[7951] Mope call for help code to function form Event AI code to allow use it from...
[getmangos.git] / src / game / CreatureEventAI.cpp
blob05b2cac1b86aa4a86a3708be9cb4c59a7f3af701
1 /*
2 * Copyright (C) 2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "CreatureEventAI.h"
21 #include "CreatureEventAIMgr.h"
22 #include "ObjectMgr.h"
23 #include "Spell.h"
24 #include "World.h"
25 #include "Cell.h"
26 #include "CellImpl.h"
27 #include "GameEventMgr.h"
28 #include "GridNotifiers.h"
29 #include "GridNotifiersImpl.h"
30 #include "InstanceData.h"
32 bool CreatureEventAIHolder::UpdateRepeatTimer( Creature* creature, uint32 repeatMin, uint32 repeatMax )
34 if (repeatMin == repeatMax)
35 Time = repeatMin;
36 else if (repeatMax > repeatMin)
37 Time = urand(repeatMin, repeatMax);
38 else
40 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", creature->GetEntry(), Event.event_id, Event.event_type);
41 Enabled = false;
42 return false;
45 return true;
48 int CreatureEventAI::Permissible(const Creature *creature)
50 if( creature->GetAIName() == "EventAI" )
51 return PERMIT_BASE_SPECIAL;
52 return PERMIT_BASE_NO;
55 CreatureEventAI::CreatureEventAI(Creature *c ) : CreatureAI(c)
57 // Need make copy for filter unneeded steps and safe in case table reload
58 CreatureEventAI_Event_Map::const_iterator CreatureEvents = CreatureEAI_Mgr.GetCreatureEventAIMap().find(m_creature->GetEntry());
59 if (CreatureEvents != CreatureEAI_Mgr.GetCreatureEventAIMap().end())
61 std::vector<CreatureEventAI_Event>::const_iterator i;
62 for (i = (*CreatureEvents).second.begin(); i != (*CreatureEvents).second.end(); ++i)
65 //Debug check
66 #ifndef MANGOS_DEBUG
67 if ((*i).event_flags & EFLAG_DEBUG_ONLY)
68 continue;
69 #endif
70 if (m_creature->GetMap()->IsDungeon())
72 if( (m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_HEROIC) ||
73 (!m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_NORMAL))
75 //event flagged for instance mode
76 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
78 continue;
80 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
82 //EventMap had events but they were not added because they must be for instance
83 if (CreatureEventAIList.empty())
84 sLog.outError("CreatureEventAI: Creature %u has events but no events added to list because of instance flags.", m_creature->GetEntry());
86 else
87 sLog.outError("CreatureEventAI: EventMap for Creature %u is empty but creature is using CreatureEventAI.", m_creature->GetEntry());
89 bEmptyList = CreatureEventAIList.empty();
90 Phase = 0;
91 CombatMovementEnabled = true;
92 MeleeEnabled = true;
93 AttackDistance = 0;
94 AttackAngle = 0.0f;
96 //Handle Spawned Events
97 if (!bEmptyList)
99 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
100 if (SpawnedEventConditionsCheck((*i).Event))
101 ProcessEvent(*i);
103 Reset();
106 bool CreatureEventAI::ProcessEvent(CreatureEventAIHolder& pHolder, Unit* pActionInvoker)
108 if (!pHolder.Enabled || pHolder.Time)
109 return false;
111 //Check the inverse phase mask (event doesn't trigger if current phase bit is set in mask)
112 if (pHolder.Event.event_inverse_phase_mask & (1 << Phase))
113 return false;
115 //Store random here so that all random actions match up
116 uint32 rnd = rand();
118 //Return if chance for event is not met
119 if (pHolder.Event.event_chance <= rnd % 100)
120 return false;
122 CreatureEventAI_Event const& event = pHolder.Event;
124 //Check event conditions based on the event type, also reset events
125 switch (event.event_type)
127 case EVENT_T_TIMER:
128 if (!m_creature->isInCombat())
129 return false;
131 //Repeat Timers
132 pHolder.UpdateRepeatTimer(m_creature,event.timer.repeatMin,event.timer.repeatMax);
133 break;
134 case EVENT_T_TIMER_OOC:
135 if (m_creature->isInCombat())
136 return false;
138 //Repeat Timers
139 pHolder.UpdateRepeatTimer(m_creature,event.timer.repeatMin,event.timer.repeatMax);
140 break;
141 case EVENT_T_HP:
143 if (!m_creature->isInCombat() || !m_creature->GetMaxHealth())
144 return false;
146 uint32 perc = (m_creature->GetHealth()*100) / m_creature->GetMaxHealth();
148 if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin)
149 return false;
151 //Repeat Timers
152 pHolder.UpdateRepeatTimer(m_creature,event.percent_range.repeatMin,event.percent_range.repeatMax);
153 break;
155 case EVENT_T_MANA:
157 if (!m_creature->isInCombat() || !m_creature->GetMaxPower(POWER_MANA))
158 return false;
160 uint32 perc = (m_creature->GetPower(POWER_MANA)*100) / m_creature->GetMaxPower(POWER_MANA);
162 if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin)
163 return false;
165 //Repeat Timers
166 pHolder.UpdateRepeatTimer(m_creature,event.percent_range.repeatMin,event.percent_range.repeatMax);
167 break;
169 case EVENT_T_AGGRO:
170 break;
171 case EVENT_T_KILL:
172 //Repeat Timers
173 pHolder.UpdateRepeatTimer(m_creature,event.kill.repeatMin,event.kill.repeatMax);
174 break;
175 case EVENT_T_DEATH:
176 case EVENT_T_EVADE:
177 break;
178 case EVENT_T_SPELLHIT:
179 //Spell hit is special case, param1 and param2 handled within CreatureEventAI::SpellHit
181 //Repeat Timers
182 pHolder.UpdateRepeatTimer(m_creature,event.spell_hit.repeatMin,event.spell_hit.repeatMax);
183 break;
184 case EVENT_T_RANGE:
185 //Repeat Timers
186 pHolder.UpdateRepeatTimer(m_creature,event.range.repeatMin,event.range.repeatMax);
187 break;
188 case EVENT_T_OOC_LOS:
189 //Repeat Timers
190 pHolder.UpdateRepeatTimer(m_creature,event.ooc_los.repeatMin,event.ooc_los.repeatMax);
191 break;
192 case EVENT_T_SPAWNED:
193 break;
194 case EVENT_T_TARGET_HP:
196 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxHealth())
197 return false;
199 uint32 perc = (m_creature->getVictim()->GetHealth()*100) / m_creature->getVictim()->GetMaxHealth();
201 if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin)
202 return false;
204 //Repeat Timers
205 pHolder.UpdateRepeatTimer(m_creature,event.percent_range.repeatMin,event.percent_range.repeatMax);
206 break;
208 case EVENT_T_TARGET_CASTING:
209 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->IsNonMeleeSpellCasted(false, false, true))
210 return false;
212 //Repeat Timers
213 pHolder.UpdateRepeatTimer(m_creature,event.target_casting.repeatMin,event.target_casting.repeatMax);
214 break;
215 case EVENT_T_FRIENDLY_HP:
217 if (!m_creature->isInCombat())
218 return false;
220 Unit* pUnit = DoSelectLowestHpFriendly(event.friendly_hp.radius, event.friendly_hp.hpDeficit);
221 if (!pUnit)
222 return false;
224 pActionInvoker = pUnit;
226 //Repeat Timers
227 pHolder.UpdateRepeatTimer(m_creature,event.friendly_hp.repeatMin,event.friendly_hp.repeatMax);
228 break;
230 case EVENT_T_FRIENDLY_IS_CC:
232 if (!m_creature->isInCombat())
233 return false;
235 std::list<Creature*> pList;
236 DoFindFriendlyCC(pList, event.friendly_is_cc.radius);
238 //List is empty
239 if (pList.empty())
240 return false;
242 //We don't really care about the whole list, just return first available
243 pActionInvoker = *(pList.begin());
245 //Repeat Timers
246 pHolder.UpdateRepeatTimer(m_creature,event.friendly_is_cc.repeatMin,event.friendly_is_cc.repeatMax);
247 break;
249 case EVENT_T_FRIENDLY_MISSING_BUFF:
251 std::list<Creature*> pList;
252 DoFindFriendlyMissingBuff(pList, event.friendly_buff.radius, event.friendly_buff.spellId);
254 //List is empty
255 if (pList.empty())
256 return false;
258 //We don't really care about the whole list, just return first available
259 pActionInvoker = *(pList.begin());
261 //Repeat Timers
262 pHolder.UpdateRepeatTimer(m_creature,event.friendly_buff.repeatMin,event.friendly_buff.repeatMax);
263 break;
265 case EVENT_T_SUMMONED_UNIT:
267 //Prevent event from occuring on no unit or non creatures
268 if (!pActionInvoker || pActionInvoker->GetTypeId()!=TYPEID_UNIT)
269 return false;
271 //Creature id doesn't match up
272 if (((Creature*)pActionInvoker)->GetEntry() != event.summon_unit.creatureId)
273 return false;
275 //Repeat Timers
276 pHolder.UpdateRepeatTimer(m_creature,event.summon_unit.repeatMin,event.summon_unit.repeatMax);
278 break;
279 case EVENT_T_TARGET_MANA:
281 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxPower(POWER_MANA))
282 return false;
284 uint32 perc = (m_creature->getVictim()->GetPower(POWER_MANA)*100) / m_creature->getVictim()->GetMaxPower(POWER_MANA);
286 if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin)
287 return false;
289 //Repeat Timers
290 pHolder.UpdateRepeatTimer(m_creature,event.percent_range.repeatMin,event.percent_range.repeatMax);
291 break;
293 case EVENT_T_REACHED_HOME:
294 case EVENT_T_RECEIVE_EMOTE:
295 break;
296 default:
297 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u has invalid Event Type(%u), missing from ProcessEvent() Switch.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
298 break;
301 //Disable non-repeatable events
302 if (!(pHolder.Event.event_flags & EFLAG_REPEATABLE))
303 pHolder.Enabled = false;
305 //Process actions
306 for (uint32 j = 0; j < MAX_ACTIONS; j++)
307 ProcessAction(pHolder.Event.action[j], rnd, pHolder.Event.event_id, pActionInvoker);
309 return true;
312 void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 rnd, uint32 EventId, Unit* pActionInvoker)
314 switch (action.type)
316 case ACTION_T_TEXT:
318 if (!action.text.TextId1)
319 return;
321 int32 temp = 0;
323 if (action.text.TextId2 && action.text.TextId3)
325 switch( rand()%3 )
327 case 0: temp = action.text.TextId1; break;
328 case 1: temp = action.text.TextId2; break;
329 case 2: temp = action.text.TextId3; break;
332 else if (action.text.TextId2 && urand(0,1))
333 temp = action.text.TextId2;
334 else
335 temp = action.text.TextId1;
337 if (temp)
339 Unit* target = NULL;
341 if (pActionInvoker)
343 if (pActionInvoker->GetTypeId() == TYPEID_PLAYER)
344 target = pActionInvoker;
345 else if (Unit* owner = pActionInvoker->GetOwner())
347 if (owner->GetTypeId() == TYPEID_PLAYER)
348 target = owner;
351 else if (target = m_creature->getVictim())
353 if (target->GetTypeId() != TYPEID_PLAYER)
354 if (Unit* owner = target->GetOwner())
355 if (owner->GetTypeId() == TYPEID_PLAYER)
356 target = owner;
359 DoScriptText(temp, m_creature, target);
361 break;
363 case ACTION_T_SET_FACTION:
365 if (action.set_faction.factionId)
366 m_creature->setFaction(action.set_faction.factionId);
367 else
369 if (CreatureInfo const* ci = GetCreatureTemplateStore(m_creature->GetEntry()))
371 //if no id provided, assume reset and then use default
372 if (m_creature->getFaction() != ci->faction_A)
373 m_creature->setFaction(ci->faction_A);
376 break;
378 case ACTION_T_MORPH_TO_ENTRY_OR_MODEL:
380 if (action.morph.creatureId || action.morph.modelId)
382 //set model based on entry from creature_template
383 if (action.morph.creatureId)
385 if (CreatureInfo const* ci = GetCreatureTemplateStore(action.morph.creatureId))
387 //use default display
388 if (ci->DisplayID_A)
389 m_creature->SetDisplayId(ci->DisplayID_A);
392 //if no param1, then use value from param2 (modelId)
393 else
394 m_creature->SetDisplayId(action.morph.modelId);
396 else
397 m_creature->DeMorph();
398 break;
400 case ACTION_T_SOUND:
401 m_creature->PlayDirectSound(action.sound.soundId);
402 break;
403 case ACTION_T_EMOTE:
404 m_creature->HandleEmoteCommand(action.emote.emoteId);
405 break;
406 case ACTION_T_RANDOM_SOUND:
408 int32 temp = GetRandActionParam(rnd, action.random_sound.soundId1, action.random_sound.soundId2, action.random_sound.soundId3);
409 if (temp >= 0)
410 m_creature->PlayDirectSound(temp);
411 break;
413 case ACTION_T_RANDOM_EMOTE:
415 int32 temp = GetRandActionParam(rnd, action.random_emote.emoteId1, action.random_emote.emoteId2, action.random_emote.emoteId3);
416 if (temp >= 0)
417 m_creature->HandleEmoteCommand(temp);
418 break;
420 case ACTION_T_CAST:
422 Unit* target = GetTargetByType(action.cast.target, pActionInvoker);
423 Unit* caster = m_creature;
425 if (!target)
426 return;
428 if (action.cast.castFlags & CAST_FORCE_TARGET_SELF)
429 caster = target;
431 //Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered
432 bool canCast = !caster->IsNonMeleeSpellCasted(false) || (action.cast.castFlags & (CAST_TRIGGERED | CAST_INTURRUPT_PREVIOUS));
434 // If cast flag CAST_AURA_NOT_PRESENT is active, check if target already has aura on them
435 if(action.cast.castFlags & CAST_AURA_NOT_PRESENT)
437 for(uint8 i = 0; i < 3; ++i)
438 if(target->HasAura(action.cast.spellId, i))
439 return;
442 if (canCast)
444 const SpellEntry* tSpell = GetSpellStore()->LookupEntry(action.cast.spellId);
446 //Verify that spell exists
447 if (tSpell)
449 //Check if cannot cast spell
450 if (!(action.cast.castFlags & (CAST_FORCE_TARGET_SELF | CAST_FORCE_CAST)) &&
451 !CanCast(target, tSpell, (action.cast.castFlags & CAST_TRIGGERED)))
453 //Melee current victim if flag not set
454 if (!(action.cast.castFlags & CAST_NO_MELEE_IF_OOM))
456 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
458 AttackDistance = 0;
459 AttackAngle = 0;
461 m_creature->GetMotionMaster()->Clear(false);
462 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
467 else
469 //Interrupt any previous spell
470 if (caster->IsNonMeleeSpellCasted(false) && action.cast.castFlags & CAST_INTURRUPT_PREVIOUS)
471 caster->InterruptNonMeleeSpells(false);
473 caster->CastSpell(target, action.cast.spellId, (action.cast.castFlags & CAST_TRIGGERED));
477 else
478 sLog.outErrorDb("CreatureEventAI: event %d creature %d attempt to cast spell that doesn't exist %d", EventId, m_creature->GetEntry(), action.cast.spellId);
480 break;
482 case ACTION_T_SUMMON:
484 Unit* target = GetTargetByType(action.summon.target, pActionInvoker);
486 Creature* pCreature = NULL;
488 if (action.summon.duration)
489 pCreature = m_creature->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, action.summon.duration);
490 else
491 pCreature = m_creature->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
493 if (!pCreature)
494 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Spawn event %d is on creature %d", action.summon.creatureId, EventId, m_creature->GetEntry());
495 else if (action.summon.target != TARGET_T_SELF && target)
496 pCreature->AI()->AttackStart(target);
497 break;
499 case ACTION_T_THREAT_SINGLE_PCT:
500 if (Unit* target = GetTargetByType(action.threat_single_pct.target, pActionInvoker))
501 m_creature->getThreatManager().modifyThreatPercent(target, action.threat_single_pct.percent);
502 break;
503 case ACTION_T_THREAT_ALL_PCT:
505 std::list<HostilReference*>& threatList = m_creature->getThreatManager().getThreatList();
506 for (std::list<HostilReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
507 if(Unit* Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid()))
508 m_creature->getThreatManager().modifyThreatPercent(Temp, action.threat_all_pct.percent);
509 break;
511 case ACTION_T_QUEST_EVENT:
512 if (Unit* target = GetTargetByType(action.quest_event.target, pActionInvoker))
513 if (target->GetTypeId() == TYPEID_PLAYER)
514 ((Player*)target)->AreaExploredOrEventHappens(action.quest_event.questId);
515 break;
516 case ACTION_T_CAST_EVENT:
517 if (Unit* target = GetTargetByType(action.cast_event.target, pActionInvoker))
518 if (target->GetTypeId() == TYPEID_PLAYER)
519 ((Player*)target)->CastedCreatureOrGO(action.cast_event.creatureId, m_creature->GetGUID(), action.cast_event.spellId);
520 break;
521 case ACTION_T_SET_UNIT_FIELD:
523 Unit* target = GetTargetByType(action.set_unit_field.target, pActionInvoker);
525 // not allow modify important for integrity object fields
526 if (action.set_unit_field.field < OBJECT_END || action.set_unit_field.field >= UNIT_END)
527 return;
529 if (target)
530 target->SetUInt32Value(action.set_unit_field.field, action.set_unit_field.value);
532 break;
534 case ACTION_T_SET_UNIT_FLAG:
535 if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker))
536 target->SetFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
537 break;
538 case ACTION_T_REMOVE_UNIT_FLAG:
539 if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker))
540 target->RemoveFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
541 break;
542 case ACTION_T_AUTO_ATTACK:
543 MeleeEnabled = action.auto_attack.state != 0;
544 break;
545 case ACTION_T_COMBAT_MOVEMENT:
546 // ignore no affect case
547 if(CombatMovementEnabled==(action.combat_movement.state!=0))
548 return;
550 CombatMovementEnabled = action.combat_movement.state != 0;
552 //Allow movement (create new targeted movement gen only if idle)
553 if (CombatMovementEnabled)
555 if(action.combat_movement.melee && m_creature->isInCombat())
556 if(Unit* victim = m_creature->getVictim())
557 m_creature->SendMeleeAttackStart(victim);
559 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == IDLE_MOTION_TYPE)
561 m_creature->GetMotionMaster()->Clear(false);
562 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
565 else
567 if(action.combat_movement.melee && m_creature->isInCombat())
568 if(Unit* victim = m_creature->getVictim())
569 m_creature->SendMeleeAttackStop(victim);
571 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
573 m_creature->GetMotionMaster()->Clear(false);
574 m_creature->GetMotionMaster()->MoveIdle();
575 m_creature->StopMoving();
578 break;
579 case ACTION_T_SET_PHASE:
580 Phase = action.set_phase.phase;
581 break;
582 case ACTION_T_INC_PHASE:
584 int32 new_phase = int32(Phase)+action.set_inc_phase.step;
585 if (new_phase < 0)
587 sLog.outErrorDb( "CreatureEventAI: Event %d decrease Phase under 0. CreatureEntry = %d", EventId, m_creature->GetEntry());
588 Phase = 0;
590 else if (new_phase >= MAX_PHASE)
592 sLog.outErrorDb( "CreatureEventAI: Event %d incremented Phase above %u. Phase mask cannot be used with phases past %u. CreatureEntry = %d", EventId, MAX_PHASE-1, MAX_PHASE-1, m_creature->GetEntry());
593 Phase = MAX_PHASE-1;
595 else
596 Phase = new_phase;
598 break;
600 case ACTION_T_EVADE:
601 EnterEvadeMode();
602 break;
603 case ACTION_T_FLEE_FOR_ASSIST:
604 m_creature->DoFleeToGetAssistance();
605 break;
606 case ACTION_T_QUEST_EVENT_ALL:
607 if (pActionInvoker && pActionInvoker->GetTypeId() == TYPEID_PLAYER)
609 if (Unit* Temp = Unit::GetUnit(*m_creature,pActionInvoker->GetGUID()))
610 if (Temp->GetTypeId() == TYPEID_PLAYER)
611 ((Player*)Temp)->GroupEventHappens(action.quest_event_all.questId,m_creature);
613 break;
614 case ACTION_T_CAST_EVENT_ALL:
616 std::list<HostilReference*>& threatList = m_creature->getThreatManager().getThreatList();
617 for (std::list<HostilReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
618 if (Unit* Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid()))
619 if (Temp->GetTypeId() == TYPEID_PLAYER)
620 ((Player*)Temp)->CastedCreatureOrGO(action.cast_event_all.creatureId, m_creature->GetGUID(), action.cast_event_all.spellId);
621 break;
623 case ACTION_T_REMOVEAURASFROMSPELL:
624 if (Unit* target = GetTargetByType(action.remove_aura.target, pActionInvoker))
625 target->RemoveAurasDueToSpell(action.remove_aura.spellId);
626 break;
627 case ACTION_T_RANGED_MOVEMENT:
628 AttackDistance = action.ranged_movement.distance;
629 AttackAngle = ((float)action.ranged_movement.angle/180)*M_PI;
631 if (CombatMovementEnabled)
633 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
635 //Drop current movement gen
636 m_creature->GetMotionMaster()->Clear(false);
637 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
640 break;
641 case ACTION_T_RANDOM_PHASE:
642 Phase = GetRandActionParam(rnd, action.random_phase.phase1, action.random_phase.phase2, action.random_phase.phase3);
643 break;
644 case ACTION_T_RANDOM_PHASE_RANGE:
645 if (action.random_phase_range.phaseMax > action.random_phase_range.phaseMin)
646 Phase = action.random_phase_range.phaseMin + (rnd % (action.random_phase_range.phaseMax - action.random_phase_range.phaseMin));
647 else
648 sLog.outErrorDb( "CreatureEventAI: ACTION_T_RANDOM_PHASE_RANGE cannot have Param2 <= Param1. Divide by Zero. Event = %d. CreatureEntry = %d", EventId, m_creature->GetEntry());
649 break;
650 case ACTION_T_SUMMON_ID:
652 Unit* target = GetTargetByType(action.summon_id.target, pActionInvoker);
654 CreatureEventAI_Summon_Map::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAISummonMap().find(action.summon_id.spawnId);
655 if (i == CreatureEAI_Mgr.GetCreatureEventAISummonMap().end())
657 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d", action.summon_id.creatureId, action.summon_id.spawnId, EventId, m_creature->GetEntry());
658 return;
661 Creature* pCreature = NULL;
662 if ((*i).second.SpawnTimeSecs)
663 pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs);
664 else
665 pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
667 if (!pCreature)
668 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. EventId %d.Creature %d", action.summon_id.creatureId, EventId, m_creature->GetEntry());
669 else if (action.summon_id.target != TARGET_T_SELF && target)
670 pCreature->AI()->AttackStart(target);
672 break;
674 case ACTION_T_KILLED_MONSTER:
675 //first attempt player who tapped creature
676 if (Player* pPlayer = m_creature->GetLootRecipient())
677 pPlayer->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature);
678 else
680 //if not available, use pActionInvoker
681 if (Unit* pTarget = GetTargetByType(action.killed_monster.target, pActionInvoker))
682 if (Player* pPlayer2 = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself())
683 pPlayer2->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature);
685 break;
686 case ACTION_T_SET_INST_DATA:
688 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
689 if (!pInst)
691 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data without instance script. Creature %d", EventId, m_creature->GetEntry());
692 return;
695 pInst->SetData(action.set_inst_data.field, action.set_inst_data.value);
696 break;
698 case ACTION_T_SET_INST_DATA64:
700 Unit* target = GetTargetByType(action.set_inst_data64.target, pActionInvoker);
701 if (!target)
703 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 but Target == NULL. Creature %d", EventId, m_creature->GetEntry());
704 return;
707 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
708 if (!pInst)
710 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 without instance script. Creature %d", EventId, m_creature->GetEntry());
711 return;
714 pInst->SetData64(action.set_inst_data64.field, target->GetGUID());
715 break;
717 case ACTION_T_UPDATE_TEMPLATE:
718 if (m_creature->GetEntry() == action.update_template.creatureId)
721 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d", EventId, m_creature->GetEntry());
722 return;
725 m_creature->UpdateEntry(action.update_template.creatureId, action.update_template.team ? HORDE : ALLIANCE);
726 break;
727 case ACTION_T_DIE:
728 if (m_creature->isDead())
731 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_DIE on dead creature. Creature %d", EventId, m_creature->GetEntry());
732 return;
734 m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(),NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
735 break;
736 case ACTION_T_ZONE_COMBAT_PULSE:
737 if (!m_creature->isInCombat() || !m_creature->GetMap()->IsDungeon())
740 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_ZONE_COMBAT_PULSE on creature out of combat or in non-dungeon map. Creature %d", EventId, m_creature->GetEntry());
741 return;
744 DoZoneInCombat(m_creature);
745 break;
746 case ACTION_T_CALL_FOR_HELP:
748 m_creature->CallForHelp(action.call_for_help.radius);
749 break;
751 case ACTION_T_SET_SHEATH:
753 m_creature->SetSheath(SheathState(action.set_sheath.sheath));
754 break;
759 void CreatureEventAI::JustRespawned()
761 Reset();
763 if (bEmptyList)
764 return;
766 //Handle Spawned Events
767 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
768 if (SpawnedEventConditionsCheck((*i).Event))
769 ProcessEvent(*i);
772 void CreatureEventAI::Reset()
774 EventUpdateTime = EVENT_UPDATE_TIME;
775 EventDiff = 0;
777 if (bEmptyList)
778 return;
780 //Reset all events to enabled
781 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
783 CreatureEventAI_Event const& event = (*i).Event;
784 switch (event.event_type)
786 //Reset all out of combat timers
787 case EVENT_T_TIMER_OOC:
789 if ((*i).UpdateRepeatTimer(m_creature,event.timer.initialMin,event.timer.initialMax))
790 (*i).Enabled = true;
791 break;
793 //default:
794 //TODO: enable below code line / verify this is correct to enable events previously disabled (ex. aggro yell), instead of enable this in void Aggro()
795 //(*i).Enabled = true;
796 //(*i).Time = 0;
797 //break;
802 void CreatureEventAI::JustReachedHome()
804 m_creature->LoadCreaturesAddon();
806 if (!bEmptyList)
808 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
810 if ((*i).Event.event_type == EVENT_T_REACHED_HOME)
811 ProcessEvent(*i);
815 Reset();
818 void CreatureEventAI::EnterEvadeMode()
820 m_creature->RemoveAllAuras();
821 m_creature->DeleteThreatList();
822 m_creature->CombatStop(true);
824 if (m_creature->isAlive())
825 m_creature->GetMotionMaster()->MoveTargetedHome();
827 m_creature->SetLootRecipient(NULL);
829 if (bEmptyList)
830 return;
832 //Handle Evade events
833 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
835 if ((*i).Event.event_type == EVENT_T_EVADE)
836 ProcessEvent(*i);
840 void CreatureEventAI::JustDied(Unit* killer)
842 Reset();
844 if (bEmptyList)
845 return;
847 //Handle Evade events
848 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
850 if ((*i).Event.event_type == EVENT_T_DEATH)
851 ProcessEvent(*i, killer);
855 void CreatureEventAI::KilledUnit(Unit* victim)
857 if (bEmptyList || victim->GetTypeId() != TYPEID_PLAYER)
858 return;
860 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
862 if ((*i).Event.event_type == EVENT_T_KILL)
863 ProcessEvent(*i, victim);
867 void CreatureEventAI::JustSummoned(Creature* pUnit)
869 if (bEmptyList || !pUnit)
870 return;
872 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
874 if ((*i).Event.event_type == EVENT_T_SUMMONED_UNIT)
875 ProcessEvent(*i, pUnit);
879 void CreatureEventAI::EnterCombat(Unit *enemy)
881 //Check for on combat start events
882 if (!bEmptyList)
884 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
886 CreatureEventAI_Event const& event = (*i).Event;
887 switch (event.event_type)
889 case EVENT_T_AGGRO:
890 (*i).Enabled = true;
891 ProcessEvent(*i, enemy);
892 break;
893 //Reset all in combat timers
894 case EVENT_T_TIMER:
895 if ((*i).UpdateRepeatTimer(m_creature,event.timer.initialMin,event.timer.initialMax))
896 (*i).Enabled = true;
897 break;
898 //All normal events need to be re-enabled and their time set to 0
899 default:
900 (*i).Enabled = true;
901 (*i).Time = 0;
902 break;
907 EventUpdateTime = EVENT_UPDATE_TIME;
908 EventDiff = 0;
911 void CreatureEventAI::AttackStart(Unit *who)
913 if (!who)
914 return;
916 if (m_creature->Attack(who, MeleeEnabled))
918 m_creature->AddThreat(who, 0.0f);
919 m_creature->SetInCombatWith(who);
920 who->SetInCombatWith(m_creature);
922 if (CombatMovementEnabled)
924 m_creature->GetMotionMaster()->MoveChase(who, AttackDistance, AttackAngle);
926 else
928 m_creature->GetMotionMaster()->MoveIdle();
929 m_creature->StopMoving();
934 void CreatureEventAI::MoveInLineOfSight(Unit *who)
936 if (!who)
937 return;
939 //Check for OOC LOS Event
940 if (!bEmptyList && !m_creature->getVictim())
942 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
944 if ((*itr).Event.event_type == EVENT_T_OOC_LOS)
946 //can trigger if closer than fMaxAllowedRange
947 float fMaxAllowedRange = (*itr).Event.ooc_los.maxRange;
949 //if range is ok and we are actually in LOS
950 if (m_creature->IsWithinDistInMap(who, fMaxAllowedRange) && m_creature->IsWithinLOSInMap(who))
952 //if friendly event&&who is not hostile OR hostile event&&who is hostile
953 if (((*itr).Event.ooc_los.noHostile && !m_creature->IsHostileTo(who)) ||
954 ((!(*itr).Event.ooc_los.noHostile) && m_creature->IsHostileTo(who)))
955 ProcessEvent(*itr, who);
961 if (m_creature->isCivilian() || m_creature->IsNeutralToAll())
962 return;
964 if (!m_creature->hasUnitState(UNIT_STAT_STUNNED) && who->isTargetableForAttack() &&
965 m_creature->IsHostileTo(who) && who->isInAccessablePlaceFor(m_creature))
967 if (!m_creature->canFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
968 return;
970 float attackRadius = m_creature->GetAttackDistance(who);
971 if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who))
973 if (!m_creature->getVictim())
975 AttackStart(who);
976 who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
978 else if (m_creature->GetMap()->IsDungeon())
980 m_creature->AddThreat(who, 0.0f);
981 who->SetInCombatWith(m_creature);
987 void CreatureEventAI::SpellHit(Unit* pUnit, const SpellEntry* pSpell)
990 if (bEmptyList)
991 return;
993 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
994 if ((*i).Event.event_type == EVENT_T_SPELLHIT)
995 //If spell id matches (or no spell id) & if spell school matches (or no spell school)
996 if (!(*i).Event.spell_hit.spellId || pSpell->Id == (*i).Event.spell_hit.spellId)
997 if (pSpell->SchoolMask & (*i).Event.spell_hit.schoolMask)
998 ProcessEvent(*i, pUnit);
1001 void CreatureEventAI::UpdateAI(const uint32 diff)
1003 //Check if we are in combat (also updates calls threat update code)
1004 bool Combat = m_creature->SelectHostilTarget() && m_creature->getVictim();
1006 //Must return if creature isn't alive. Normally select hostil target and get victim prevent this
1007 if (!m_creature->isAlive())
1008 return;
1010 if (!bEmptyList)
1012 //Events are only updated once every EVENT_UPDATE_TIME ms to prevent lag with large amount of events
1013 if (EventUpdateTime < diff)
1015 EventDiff += diff;
1017 //Check for time based events
1018 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1020 //Decrement Timers
1021 if ((*i).Time)
1023 if ((*i).Time > EventDiff)
1025 //Do not decrement timers if event cannot trigger in this phase
1026 if (!((*i).Event.event_inverse_phase_mask & (1 << Phase)))
1027 (*i).Time -= EventDiff;
1029 //Skip processing of events that have time remaining
1030 continue;
1032 else (*i).Time = 0;
1035 //Events that are updated every EVENT_UPDATE_TIME
1036 switch ((*i).Event.event_type)
1038 case EVENT_T_TIMER_OOC:
1039 ProcessEvent(*i);
1040 break;
1041 case EVENT_T_TIMER:
1042 case EVENT_T_MANA:
1043 case EVENT_T_HP:
1044 case EVENT_T_TARGET_HP:
1045 case EVENT_T_TARGET_CASTING:
1046 case EVENT_T_FRIENDLY_HP:
1047 if (Combat)
1048 ProcessEvent(*i);
1049 break;
1050 case EVENT_T_RANGE:
1051 if (Combat)
1052 if (m_creature->IsInMap(m_creature->getVictim()))
1053 if (m_creature->IsInRange(m_creature->getVictim(),(float)(*i).Event.range.minDist,(float)(*i).Event.range.maxDist))
1054 ProcessEvent(*i);
1055 break;
1059 EventDiff = 0;
1060 EventUpdateTime = EVENT_UPDATE_TIME;
1062 else
1064 EventDiff += diff;
1065 EventUpdateTime -= diff;
1069 //Melee Auto-Attack
1070 if (Combat && MeleeEnabled)
1071 DoMeleeAttackIfReady();
1074 bool CreatureEventAI::IsVisible(Unit *pl) const
1076 return m_creature->IsWithinDist(pl,sWorld.getConfig(CONFIG_SIGHT_MONSTER))
1077 && pl->isVisibleForOrDetect(m_creature,true);
1080 inline Unit* CreatureEventAI::SelectUnit(AttackingTarget target, uint32 position)
1082 //ThreatList m_threatlist;
1083 std::list<HostilReference*>& m_threatlist = m_creature->getThreatManager().getThreatList();
1084 std::list<HostilReference*>::iterator i = m_threatlist.begin();
1085 std::list<HostilReference*>::reverse_iterator r = m_threatlist.rbegin();
1087 if (position >= m_threatlist.size() || !m_threatlist.size())
1088 return NULL;
1090 switch (target)
1092 case ATTACKING_TARGET_RANDOM:
1094 advance ( i , position + (rand() % (m_threatlist.size() - position ) ));
1095 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1097 case ATTACKING_TARGET_TOPAGGRO:
1099 advance ( i , position);
1100 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1102 case ATTACKING_TARGET_BOTTOMAGGRO:
1104 advance ( r , position);
1105 return Unit::GetUnit(*m_creature,(*r)->getUnitGuid());
1108 return NULL;
1111 inline uint32 CreatureEventAI::GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3)
1113 switch (rnd % 3)
1115 case 0: return param1;
1116 case 1: return param2;
1117 case 2: return param3;
1119 return 0;
1122 inline int32 CreatureEventAI::GetRandActionParam(uint32 rnd, int32 param1, int32 param2, int32 param3)
1124 switch (rnd % 3)
1126 case 0: return param1;
1127 case 1: return param2;
1128 case 2: return param3;
1130 return 0;
1133 inline Unit* CreatureEventAI::GetTargetByType(uint32 Target, Unit* pActionInvoker)
1135 switch (Target)
1137 case TARGET_T_SELF:
1138 return m_creature;
1139 case TARGET_T_HOSTILE:
1140 return m_creature->getVictim();
1141 case TARGET_T_HOSTILE_SECOND_AGGRO:
1142 return SelectUnit(ATTACKING_TARGET_TOPAGGRO,1);
1143 case TARGET_T_HOSTILE_LAST_AGGRO:
1144 return SelectUnit(ATTACKING_TARGET_BOTTOMAGGRO,0);
1145 case TARGET_T_HOSTILE_RANDOM:
1146 return SelectUnit(ATTACKING_TARGET_RANDOM,0);
1147 case TARGET_T_HOSTILE_RANDOM_NOT_TOP:
1148 return SelectUnit(ATTACKING_TARGET_RANDOM,1);
1149 case TARGET_T_ACTION_INVOKER:
1150 return pActionInvoker;
1151 default:
1152 return NULL;
1156 Unit* CreatureEventAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff)
1158 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1159 Cell cell(p);
1160 cell.data.Part.reserved = ALL_DISTRICT;
1161 cell.SetNoCreate();
1163 Unit* pUnit = NULL;
1165 MaNGOS::MostHPMissingInRange u_check(m_creature, range, MinHPDiff);
1166 MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange> searcher(m_creature, pUnit, u_check);
1169 typedef TYPELIST_4(GameObject, Creature*except pets*, DynamicObject, Corpse*Bones*) AllGridObjectTypes;
1170 This means that if we only search grid then we cannot possibly return pets or players so this is safe
1172 TypeContainerVisitor<MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange>, GridTypeMapContainer > grid_unit_searcher(searcher);
1174 CellLock<GridReadGuard> cell_lock(cell, p);
1175 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_creature->GetMap());
1176 return pUnit;
1179 void CreatureEventAI::DoFindFriendlyCC(std::list<Creature*>& _list, float range)
1181 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1182 Cell cell(p);
1183 cell.data.Part.reserved = ALL_DISTRICT;
1184 cell.SetNoCreate();
1186 MaNGOS::FriendlyCCedInRange u_check(m_creature, range);
1187 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange> searcher(m_creature, _list, u_check);
1189 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1191 CellLock<GridReadGuard> cell_lock(cell, p);
1192 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1195 void CreatureEventAI::DoFindFriendlyMissingBuff(std::list<Creature*>& _list, float range, uint32 spellid)
1197 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1198 Cell cell(p);
1199 cell.data.Part.reserved = ALL_DISTRICT;
1200 cell.SetNoCreate();
1202 MaNGOS::FriendlyMissingBuffInRange u_check(m_creature, range, spellid);
1203 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange> searcher(m_creature, _list, u_check);
1205 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1207 CellLock<GridReadGuard> cell_lock(cell, p);
1208 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1211 //*********************************
1212 //*** Functions used globally ***
1214 void CreatureEventAI::DoScriptText(int32 textEntry, WorldObject* pSource, Unit* target)
1216 if (!pSource)
1218 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i, invalid Source pointer.",textEntry);
1219 return;
1222 if (textEntry >= 0)
1224 sLog.outErrorDb("CreatureEventAI: DoScriptText with source entry %u (TypeId=%u, guid=%u) attempts to process text entry %i, but text entry must be negative.",pSource->GetEntry(),pSource->GetTypeId(),pSource->GetGUIDLow(),textEntry);
1225 return;
1228 CreatureEventAI_TextMap::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAITextMap().find(textEntry);
1230 if (i == CreatureEAI_Mgr.GetCreatureEventAITextMap().end())
1232 sLog.outErrorDb("CreatureEventAI: DoScriptText with source entry %u (TypeId=%u, guid=%u) could not find text entry %i.",pSource->GetEntry(),pSource->GetTypeId(),pSource->GetGUIDLow(),textEntry);
1233 return;
1236 sLog.outDebug("CreatureEventAI: DoScriptText: text entry=%i, Sound=%u, Type=%u, Language=%u, Emote=%u",textEntry,(*i).second.SoundId,(*i).second.Type,(*i).second.Language,(*i).second.Emote);
1238 if((*i).second.SoundId)
1240 if (GetSoundEntriesStore()->LookupEntry((*i).second.SoundId))
1241 pSource->PlayDirectSound((*i).second.SoundId);
1242 else
1243 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process invalid sound id %u.",textEntry,(*i).second.SoundId);
1246 if((*i).second.Emote)
1248 if (pSource->GetTypeId() == TYPEID_UNIT || pSource->GetTypeId() == TYPEID_PLAYER)
1250 ((Unit*)pSource)->HandleEmoteCommand((*i).second.Emote);
1252 else
1253 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process emote for invalid TypeId (%u).",textEntry,pSource->GetTypeId());
1256 switch((*i).second.Type)
1258 case CHAT_TYPE_SAY:
1259 pSource->MonsterSay(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1260 break;
1261 case CHAT_TYPE_YELL:
1262 pSource->MonsterYell(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1263 break;
1264 case CHAT_TYPE_TEXT_EMOTE:
1265 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0);
1266 break;
1267 case CHAT_TYPE_BOSS_EMOTE:
1268 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0, true);
1269 break;
1270 case CHAT_TYPE_WHISPER:
1272 if (target && target->GetTypeId() == TYPEID_PLAYER)
1273 pSource->MonsterWhisper(textEntry, target->GetGUID());
1274 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1275 }break;
1276 case CHAT_TYPE_BOSS_WHISPER:
1278 if (target && target->GetTypeId() == TYPEID_PLAYER)
1279 pSource->MonsterWhisper(textEntry, target->GetGUID(), true);
1280 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1281 }break;
1282 case CHAT_TYPE_ZONE_YELL:
1283 pSource->MonsterYellToZone(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1284 break;
1288 void CreatureEventAI::DoZoneInCombat(Unit* pUnit)
1290 if (!pUnit)
1291 pUnit = m_creature;
1293 Map *map = pUnit->GetMap();
1295 if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
1297 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat call for map that isn't an instance (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1298 return;
1301 if (!pUnit->CanHaveThreatList() || pUnit->getThreatManager().isThreatListEmpty())
1303 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat called for creature that either cannot have threat list or has empty threat list (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1305 return;
1308 Map::PlayerList const &PlayerList = map->GetPlayers();
1309 for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
1310 if (Player* i_pl = i->getSource())
1311 if (!i_pl->isGameMaster())
1312 pUnit->AddThreat(i_pl, 0.0f);
1315 void CreatureEventAI::DoMeleeAttackIfReady()
1317 //Make sure our attack is ready before checking distance
1318 if (m_creature->isAttackReady())
1320 //If we are within range melee the target
1321 if (m_creature->IsWithinDistInMap(m_creature->getVictim(), ATTACK_DISTANCE))
1323 m_creature->AttackerStateUpdate(m_creature->getVictim());
1324 m_creature->resetAttackTimer();
1329 bool CreatureEventAI::CanCast(Unit* Target, SpellEntry const *Spell, bool Triggered)
1331 //No target so we can't cast
1332 if (!Target || !Spell)
1333 return false;
1335 //Silenced so we can't cast
1336 if (!Triggered && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1337 return false;
1339 //Check for power
1340 if (!Triggered && m_creature->GetPower((Powers)Spell->powerType) < Spell->manaCost)
1341 return false;
1343 SpellRangeEntry const *TempRange = NULL;
1345 TempRange = GetSpellRangeStore()->LookupEntry(Spell->rangeIndex);
1347 //Spell has invalid range store so we can't use it
1348 if (!TempRange)
1349 return false;
1351 //Unit is out of range of this spell
1352 if (!m_creature->IsInRange(Target,TempRange->minRange,TempRange->maxRange))
1353 return false;
1355 return true;
1358 void CreatureEventAI::ReceiveEmote(Player* pPlayer, uint32 text_emote)
1360 if (bEmptyList)
1361 return;
1363 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1365 if ((*itr).Event.event_type == EVENT_T_RECEIVE_EMOTE)
1367 if ((*itr).Event.receive_emote.emoteId != text_emote)
1368 return;
1370 PlayerCondition pcon((*itr).Event.receive_emote.condition,(*itr).Event.receive_emote.conditionValue1,(*itr).Event.receive_emote.conditionValue2);
1371 if (pcon.Meets(pPlayer))
1373 sLog.outDebug("CreatureEventAI: ReceiveEmote CreatureEventAI: Condition ok, processing");
1374 ProcessEvent(*itr, pPlayer);
1380 bool CreatureEventAI::SpawnedEventConditionsCheck(CreatureEventAI_Event const& event)
1382 if(event.event_type != EVENT_T_SPAWNED)
1383 return false;
1385 switch (event.spawned.condition)
1387 case SPAWNED_EVENT_ALWAY:
1388 // always
1389 return true;
1390 case SPAWNED_EVENT_MAP:
1391 // map ID check
1392 return m_creature->GetMapId() == event.spawned.conditionValue1;
1393 case SPAWNED_EVENT_ZONE:
1395 // zone ID check
1396 uint32 zone, area;
1397 m_creature->GetZoneAndAreaId(zone,area);
1398 return zone == event.spawned.conditionValue1 || area == event.spawned.conditionValue1;
1400 default:
1401 break;
1404 return false;