[7717] Use more safe code in EventAI.
[AHbot.git] / src / game / CreatureEventAI.cpp
blobbeb473da5fbc7bdd2fba42c5068bf31912842f4f
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 "WorldPacket.h"
31 #include "InstanceData.h"
33 int CreatureEventAI::Permissible(const Creature *creature)
35 if( creature->GetAIName() == "EventAI" )
36 return PERMIT_BASE_SPECIAL;
37 return PERMIT_BASE_NO;
40 CreatureEventAI::CreatureEventAI(Creature *c ) : CreatureAI(c)
42 CreatureEventAI_Event_Map::const_iterator CreatureEvents = CreatureEAI_Mgr.GetCreatureEventAIMap().find(m_creature->GetEntry());
43 if (CreatureEvents != CreatureEAI_Mgr.GetCreatureEventAIMap().end())
45 std::vector<CreatureEventAI_Event>::const_iterator i;
46 for (i = (*CreatureEvents).second.begin(); i != (*CreatureEvents).second.end(); ++i)
49 //Debug check
50 #ifndef MANGOS_DEBUG
51 if ((*i).event_flags & EFLAG_DEBUG_ONLY)
52 continue;
53 #endif
54 if (m_creature->GetMap()->IsDungeon())
56 if( (m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_HEROIC) ||
57 (!m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_NORMAL))
59 //event flagged for instance mode
60 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
62 continue;
64 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
66 //EventMap had events but they were not added because they must be for instance
67 if (CreatureEventAIList.empty())
68 sLog.outError("CreatureEventAI: CreatureId has events but no events added to list because of instance flags.", m_creature->GetEntry());
70 else
71 sLog.outError("CreatureEventAI: EventMap for Creature %u is empty but creature is using CreatureEventAI.", m_creature->GetEntry());
73 bEmptyList = CreatureEventAIList.empty();
74 Phase = 0;
75 CombatMovementEnabled = true;
76 MeleeEnabled = true;
77 AttackDistance = 0;
78 AttackAngle = 0.0f;
80 //Handle Spawned Events
81 if (!bEmptyList)
83 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
85 if ((*i).Event.event_type == EVENT_T_SPAWNED)
86 ProcessEvent(*i);
89 Reset();
92 bool CreatureEventAI::ProcessEvent(CreatureEventAIHolder& pHolder, Unit* pActionInvoker)
94 if (!pHolder.Enabled || pHolder.Time)
95 return false;
97 //Check the inverse phase mask (event doesn't trigger if current phase bit is set in mask)
98 if (pHolder.Event.event_inverse_phase_mask & (1 << Phase))
99 return false;
101 //Store random here so that all random actions match up
102 uint32 rnd = rand();
104 //Return if chance for event is not met
105 if (pHolder.Event.event_chance <= rnd % 100)
106 return false;
108 union
110 uint32 param1;
111 int32 param1_s;
114 union
116 uint32 param2;
117 int32 param2_s;
120 union
122 uint32 param3;
123 int32 param3_s;
126 union
128 uint32 param4;
129 int32 param4_s;
132 param1 = pHolder.Event.event_param1;
133 param2 = pHolder.Event.event_param2;
134 param3 = pHolder.Event.event_param3;
135 param4 = pHolder.Event.event_param4;
137 //Check event conditions based on the event type, also reset events
138 switch (pHolder.Event.event_type)
140 case EVENT_T_TIMER:
142 if (!m_creature->isInCombat())
143 return false;
145 //Repeat Timers
146 if (param3 == param4)
148 pHolder.Time = param3;
150 }else if (param4 > param3)
151 pHolder.Time = urand(param3, param4);
152 else
154 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
155 pHolder.Enabled = false;
158 break;
159 case EVENT_T_TIMER_OOC:
161 if (m_creature->isInCombat())
162 return false;
164 //Repeat Timers
165 if (param3 == param4)
167 pHolder.Time = param3;
169 }else if (param4 > param3)
170 pHolder.Time = urand(param3, param4);
171 else
174 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
175 pHolder.Enabled = false;
178 break;
179 case EVENT_T_HP:
181 if (!m_creature->isInCombat() || !m_creature->GetMaxHealth())
182 return false;
184 uint32 perc = (m_creature->GetHealth()*100) / m_creature->GetMaxHealth();
186 if (perc > param1 || perc < param2)
187 return false;
189 //Repeat Timers
190 if (param3 == param4)
192 pHolder.Time = param3;
194 }else if (param4 > param3)
195 pHolder.Time = urand(param3, param4);
196 else
199 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
200 pHolder.Enabled = false;
203 break;
204 case EVENT_T_MANA:
206 if (!m_creature->isInCombat() || !m_creature->GetMaxPower(POWER_MANA))
207 return false;
209 uint32 perc = (m_creature->GetPower(POWER_MANA)*100) / m_creature->GetMaxPower(POWER_MANA);
211 if (perc > param1 || perc < param2)
212 return false;
214 //Repeat Timers
215 if (param3 == param4)
217 pHolder.Time = param3;
219 }else if (param4 > param3)
220 pHolder.Time = urand(param3, param4);
221 else
224 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
225 pHolder.Enabled = false;
228 break;
229 case EVENT_T_AGGRO:
232 break;
233 case EVENT_T_KILL:
235 //Repeat Timers
236 if (param1 == param2)
238 pHolder.Time = param1;
240 }else if (param2 > param1)
241 pHolder.Time = urand(param1, param2);
242 else
245 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
246 pHolder.Enabled = false;
249 case EVENT_T_DEATH:
252 break;
253 case EVENT_T_EVADE:
256 break;
257 case EVENT_T_SPELLHIT:
259 //Spell hit is special case, param1 and param2 handled within CreatureEventAI::SpellHit
261 //Repeat Timers
262 if (param3 == param4)
264 pHolder.Time = param3;
266 }else if (param4 > param3)
267 pHolder.Time = urand(param3, param4);
268 else
271 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
272 pHolder.Enabled = false;
275 break;
276 case EVENT_T_RANGE:
278 //Repeat Timers
279 if (param3 == param4)
281 pHolder.Time = param3;
283 }else if (param4 > param3)
284 pHolder.Time = urand(param3, param4);
285 else
288 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
289 pHolder.Enabled = false;
292 break;
293 case EVENT_T_OOC_LOS:
295 //Repeat Timers
296 if (param3 == param4)
298 pHolder.Time = param3;
300 }else if (param4 > param3)
301 pHolder.Time = urand(param3, param4);
302 else
305 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
306 pHolder.Enabled = false;
309 break;
310 case EVENT_T_SPAWNED:
313 break;
314 case EVENT_T_TARGET_HP:
316 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxHealth())
317 return false;
319 uint32 perc = (m_creature->getVictim()->GetHealth()*100) / m_creature->getVictim()->GetMaxHealth();
321 if (perc > param1 || perc < param2)
322 return false;
324 //Repeat Timers
325 if (param3 == param4)
327 pHolder.Time = param3;
329 }else if (param4 > param3)
330 pHolder.Time = urand(param3, param4);
331 else
334 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
335 pHolder.Enabled = false;
338 break;
339 case EVENT_T_TARGET_CASTING:
341 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->IsNonMeleeSpellCasted(false, false, true))
342 return false;
344 //Repeat Timers
345 if (param1 == param2)
347 pHolder.Time = param1;
349 }else if (param2 > param1)
350 pHolder.Time = urand(param1, param2);
351 else
354 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
355 pHolder.Enabled = false;
358 break;
359 case EVENT_T_FRIENDLY_HP:
361 if (!m_creature->isInCombat())
362 return false;
364 Unit* pUnit = DoSelectLowestHpFriendly(param2, param1);
366 if (!pUnit)
367 return false;
369 pActionInvoker = pUnit;
371 //Repeat Timers
372 if (param3 == param4)
374 pHolder.Time = param3;
376 }else if (param4 > param3)
377 pHolder.Time = urand(param3, param4);
378 else
381 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
382 pHolder.Enabled = false;
385 break;
386 case EVENT_T_FRIENDLY_IS_CC:
388 if (!m_creature->isInCombat())
389 return false;
391 std::list<Creature*> pList;
392 DoFindFriendlyCC(pList, param2);
394 //List is empty
395 if (pList.empty())
396 return false;
398 //We don't really care about the whole list, just return first available
399 pActionInvoker = *(pList.begin());
401 //Repeat Timers
402 if (param3 == param4)
404 pHolder.Time = param3;
406 }else if (param4 > param3)
407 pHolder.Time = urand(param3, param4);
408 else
410 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
411 pHolder.Enabled = false;
414 break;
415 case EVENT_T_FRIENDLY_MISSING_BUFF:
417 std::list<Creature*> pList;
418 DoFindFriendlyMissingBuff(pList, param2, param1);
420 //List is empty
421 if (pList.empty())
422 return false;
424 //We don't really care about the whole list, just return first available
425 pActionInvoker = *(pList.begin());
427 //Repeat Timers
428 if (param3 == param4)
430 pHolder.Time = param3;
432 }else if (param4 > param3)
433 pHolder.Time = urand(param3, param4);
434 else
437 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
438 pHolder.Enabled = false;
441 break;
442 case EVENT_T_SUMMONED_UNIT:
444 //Prevent event from occuring on no unit or non creatures
445 if (!pActionInvoker || pActionInvoker->GetTypeId()!=TYPEID_UNIT)
446 return false;
448 //Creature id doesn't match up
449 if (param1 && ((Creature*)pActionInvoker)->GetEntry() != param1)
450 return false;
452 //Repeat Timers
453 if (param2 == param3)
455 pHolder.Time = param2;
457 }else if (param3 > param2)
458 pHolder.Time = urand(param2, param3);
459 else
462 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
463 pHolder.Enabled = false;
466 break;
467 case EVENT_T_REACHED_HOME:
470 break;
471 case EVENT_T_RECEIVE_EMOTE:
474 break;
475 default:
477 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);
478 break;
481 //Disable non-repeatable events
482 if (!(pHolder.Event.event_flags & EFLAG_REPEATABLE))
483 pHolder.Enabled = false;
485 //Process actions
486 for (uint32 j = 0; j < MAX_ACTIONS; j++)
487 ProcessAction(pHolder.Event.action[j].type, pHolder.Event.action[j].param1, pHolder.Event.action[j].param2, pHolder.Event.action[j].param3, rnd, pHolder.Event.event_id, pActionInvoker);
489 return true;
492 void CreatureEventAI::ProcessAction(uint16 type, uint32 param1, uint32 param2, uint32 param3, uint32 rnd, uint32 EventId, Unit* pActionInvoker)
494 switch (type)
496 case ACTION_T_TEXT:
498 if (!param1)
499 return;
501 uint32 temp = 0;
503 if (param2 && param3)
505 switch( rand()%3 )
507 case 0: temp = param1; break;
508 case 2: temp = param2; break;
509 case 3: temp = param3; break;
511 }else if ( param2 && urand(0,1) )
513 temp = param2;
514 }else
516 temp = param1;
519 if (temp)
521 Unit* target = NULL;
522 Unit* owner = NULL;
524 if (pActionInvoker)
526 if (pActionInvoker->GetTypeId() == TYPEID_PLAYER)
527 target = pActionInvoker;
528 else if (owner = pActionInvoker->GetOwner())
530 if (owner->GetTypeId() == TYPEID_PLAYER)
531 target = owner;
534 else if (target = m_creature->getVictim())
536 if (target->GetTypeId() != TYPEID_PLAYER)
538 if (owner = target->GetOwner())
540 if (owner->GetTypeId() == TYPEID_PLAYER)
541 target = owner;
546 DoScriptText(temp, m_creature, target);
549 break;
550 case ACTION_T_SET_FACTION:
552 if (param1)
553 m_creature->setFaction(param1);
554 else
556 if (CreatureInfo const* ci = GetCreatureTemplateStore(m_creature->GetEntry()))
558 //if no id provided, assume reset and then use default
559 if (m_creature->getFaction() != ci->faction_A)
560 m_creature->setFaction(ci->faction_A);
564 break;
565 case ACTION_T_MORPH_TO_ENTRY_OR_MODEL:
567 if (param1 || param2)
569 //set model based on entry from creature_template
570 if (param1)
572 if (CreatureInfo const* ci = GetCreatureTemplateStore(param1))
574 //use default display
575 if (ci->DisplayID_A)
576 m_creature->SetDisplayId(ci->DisplayID_A);
579 //if no param1, then use value from param2 (modelId)
580 else
581 m_creature->SetDisplayId(param2);
583 else
584 m_creature->DeMorph();
586 break;
587 case ACTION_T_SOUND:
588 m_creature->PlayDirectSound(param1);
589 break;
590 case ACTION_T_EMOTE:
591 m_creature->HandleEmoteCommand(param1);
592 break;
593 case ACTION_T_RANDOM_SOUND:
595 uint32 temp = GetRandActionParam(rnd, param1, param2, param3);
597 if (temp != uint32(0xffffffff))
598 m_creature->PlayDirectSound( temp );
600 break;
601 case ACTION_T_RANDOM_EMOTE:
603 uint32 temp = GetRandActionParam(rnd, param1, param2, param3);
605 if (temp != uint32(0xffffffff))
606 m_creature->HandleEmoteCommand(temp);
608 break;
609 case ACTION_T_CAST:
611 Unit* target = GetTargetByType(param2, pActionInvoker);
612 Unit* caster = m_creature;
614 if (!target)
615 return;
617 //Cast is always triggered if target is forced to cast on self
618 if (param3 & CAST_FORCE_TARGET_SELF)
620 param3 |= CAST_TRIGGERED;
621 caster = target;
624 //Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered
625 bool canCast = !(caster->IsNonMeleeSpellCasted(false) && (param3 & (CAST_TRIGGERED | CAST_INTURRUPT_PREVIOUS)));
627 // If cast flag CAST_AURA_NOT_PRESENT is active, check if target already has aura on them
628 if(param3 & CAST_AURA_NOT_PRESENT)
630 for(uint8 i = 0; i < 3; ++i)
631 if(target->HasAura(param1, i))
632 return;
635 if (canCast)
637 const SpellEntry* tSpell = GetSpellStore()->LookupEntry(param1);
639 //Verify that spell exists
640 if (tSpell)
642 //Check if cannot cast spell
643 if (!(param3 & (CAST_FORCE_TARGET_SELF | CAST_FORCE_CAST)) &&
644 !CanCast(target, tSpell, (param3 & CAST_TRIGGERED)))
646 //Melee current victim if flag not set
647 if (!(param3 & CAST_NO_MELEE_IF_OOM))
649 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
651 AttackDistance = 0;
652 AttackAngle = 0;
654 m_creature->GetMotionMaster()->Clear(false);
655 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
660 else
662 //Interrupt any previous spell
663 if (caster->IsNonMeleeSpellCasted(false) && param3 & CAST_INTURRUPT_PREVIOUS)
664 caster->InterruptNonMeleeSpells(false);
666 caster->CastSpell(target, param1, (param3 & CAST_TRIGGERED));
669 }else
670 sLog.outErrorDb("CreatureEventAI: event %d creature %d attempt to cast spell that doesn't exist %d", EventId, m_creature->GetEntry(), param1);
673 break;
674 case ACTION_T_SUMMON:
676 Unit* target = GetTargetByType(param2, pActionInvoker);
678 Creature* pCreature = NULL;
680 if (param3)
681 pCreature = m_creature->SummonCreature(param1, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, param3);
682 else
683 pCreature = m_creature->SummonCreature(param1, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
685 if (!pCreature)
688 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Spawn event %d is on creature %d", param1, EventId, m_creature->GetEntry());
690 else if (param2 != TARGET_T_SELF && target)
691 pCreature->AI()->AttackStart(target);
693 break;
694 case ACTION_T_THREAT_SINGLE_PCT:
696 Unit* target = GetTargetByType(param2, pActionInvoker);
698 if (target)
699 m_creature->getThreatManager().modifyThreatPercent(target, param1);
701 break;
702 case ACTION_T_THREAT_ALL_PCT:
704 Unit* Temp = NULL;
706 std::list<HostilReference*>::iterator i = m_creature->getThreatManager().getThreatList().begin();
707 for (; i != m_creature->getThreatManager().getThreatList().end(); ++i)
709 Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
710 if (Temp)
711 m_creature->getThreatManager().modifyThreatPercent(Temp, param1);
714 break;
715 case ACTION_T_QUEST_EVENT:
717 Unit* target = GetTargetByType(param2, pActionInvoker);
719 if (target && target->GetTypeId() == TYPEID_PLAYER)
720 ((Player*)target)->AreaExploredOrEventHappens(param1);
722 break;
723 case ACTION_T_CASTCREATUREGO:
725 Unit* target = GetTargetByType(param3, pActionInvoker);
727 if (target && target->GetTypeId() == TYPEID_PLAYER)
728 ((Player*)target)->CastedCreatureOrGO(param1, m_creature->GetGUID(), param2);
730 break;
731 case ACTION_T_SET_UNIT_FIELD:
733 Unit* target = GetTargetByType(param3, pActionInvoker);
735 if (param1 < OBJECT_END || param1 >= UNIT_END)
736 return;
738 if (target)
739 target->SetUInt32Value(param1, param2);
741 break;
742 case ACTION_T_SET_UNIT_FLAG:
744 Unit* target = GetTargetByType(param2, pActionInvoker);
746 if (target)
747 target->SetFlag(UNIT_FIELD_FLAGS, param1);
749 break;
750 case ACTION_T_REMOVE_UNIT_FLAG:
752 Unit* target = GetTargetByType(param2, pActionInvoker);
754 if (target)
755 target->RemoveFlag(UNIT_FIELD_FLAGS, param1);
757 break;
758 case ACTION_T_AUTO_ATTACK:
760 if (param1)
761 MeleeEnabled = true;
762 else MeleeEnabled = false;
764 break;
765 case ACTION_T_COMBAT_MOVEMENT:
767 CombatMovementEnabled = param1;
769 //Allow movement (create new targeted movement gen only if idle)
770 if (CombatMovementEnabled)
772 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == IDLE_MOTION_TYPE)
774 m_creature->GetMotionMaster()->Clear(false);
775 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
778 else
779 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
781 m_creature->GetMotionMaster()->Clear(false);
782 m_creature->GetMotionMaster()->MoveIdle();
783 m_creature->StopMoving();
786 break;
787 case ACTION_T_SET_PHASE:
789 Phase = param1;
791 break;
792 case ACTION_T_INC_PHASE:
794 Phase += param1;
796 if (Phase > 31)
798 sLog.outErrorDb( "CreatureEventAI: Event %d incremented Phase above 31. Phase mask cannot be used with phases past 31. CreatureEntry = %d", EventId, m_creature->GetEntry());
800 break;
801 case ACTION_T_EVADE:
803 EnterEvadeMode();
805 break;
806 case ACTION_T_FLEE:
808 //TODO: Replace with Flee movement generator
809 m_creature->CastSpell(m_creature, SPELL_RUN_AWAY, true);
811 break;
812 case ACTION_T_QUEST_EVENT_ALL:
814 Unit* Temp = NULL;
815 if( pActionInvoker && pActionInvoker->GetTypeId() == TYPEID_PLAYER )
817 Temp = Unit::GetUnit(*m_creature,pActionInvoker->GetGUID());
818 if( Temp )
819 ((Player*)Temp)->GroupEventHappens(param1,m_creature);
822 break;
823 case ACTION_T_CASTCREATUREGO_ALL:
825 Unit* Temp = NULL;
827 std::list<HostilReference*>::iterator i = m_creature->getThreatManager().getThreatList().begin();
828 for (; i != m_creature->getThreatManager().getThreatList().end(); ++i)
830 Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
831 if (Temp && Temp->GetTypeId() == TYPEID_PLAYER)
832 ((Player*)Temp)->CastedCreatureOrGO(param1, m_creature->GetGUID(), param2);
835 break;
836 case ACTION_T_REMOVEAURASFROMSPELL:
838 Unit* target = GetTargetByType(param1, pActionInvoker);
840 if (target)
841 target->RemoveAurasDueToSpell(param2);
843 break;
844 case ACTION_T_RANGED_MOVEMENT:
846 AttackDistance = param1;
847 AttackAngle = ((float)param2/180)*M_PI;
849 if (CombatMovementEnabled)
851 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
853 //Drop current movement gen
854 m_creature->GetMotionMaster()->Clear(false);
855 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
859 break;
860 case ACTION_T_RANDOM_PHASE:
862 uint32 temp = GetRandActionParam(rnd, param1, param2, param3);
864 Phase = temp;
866 break;
867 case ACTION_T_RANDOM_PHASE_RANGE:
869 if (param2 > param1)
871 Phase = param1 + (rnd % (param2 - param1));
873 else
874 sLog.outErrorDb( "CreatureEventAI: ACTION_T_RANDOM_PHASE_RANGE cannot have Param2 <= Param1. Divide by Zero. Event = %d. CreatureEntry = %d", EventId, m_creature->GetEntry());
876 break;
877 case ACTION_T_SUMMON_ID:
879 Unit* target = GetTargetByType(param2, pActionInvoker);
881 //Duration
882 Creature* pCreature = NULL;
884 CreatureEventAI_Summon_Map::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAISummonMap().find(param3);
885 if (i == CreatureEAI_Mgr.GetCreatureEventAISummonMap().end())
888 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d", param1, param3, EventId, m_creature->GetEntry());
889 return;
892 if ((*i).second.SpawnTimeSecs)
893 pCreature = m_creature->SummonCreature(param1, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs);
894 else pCreature = m_creature->SummonCreature(param1, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
896 if (!pCreature)
899 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. EventId %d.Creature %d", param1, EventId, m_creature->GetEntry());
901 else if (param2 != TARGET_T_SELF && target)
902 pCreature->AI()->AttackStart(target);
904 break;
905 case ACTION_T_KILLED_MONSTER:
907 //first attempt player who tapped creature
908 if (Player* pPlayer = m_creature->GetLootRecipient())
909 pPlayer->RewardPlayerAndGroupAtEvent(param1, m_creature);
910 else
912 //if not available, use pActionInvoker
913 if (Unit* pTarget = GetTargetByType(param2, pActionInvoker))
915 if (Player* pPlayer2 = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself())
916 pPlayer2->RewardPlayerAndGroupAtEvent(param1, m_creature);
920 break;
921 case ACTION_T_SET_INST_DATA:
923 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
924 if (!pInst)
926 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data without instance script. Creature %d", EventId, m_creature->GetEntry());
927 return;
930 pInst->SetData(param1, param2);
932 break;
933 case ACTION_T_SET_INST_DATA64:
935 Unit* target = GetTargetByType(param2, pActionInvoker);
936 if (!target)
938 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 but Target == NULL. Creature %d", EventId, m_creature->GetEntry());
939 return;
942 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
943 if (!pInst)
945 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 without instance script. Creature %d", EventId, m_creature->GetEntry());
946 return;
949 pInst->SetData64(param1, target->GetGUID());
951 break;
952 case ACTION_T_UPDATE_TEMPLATE:
954 if (m_creature->GetEntry() == param1)
957 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d", EventId, m_creature->GetEntry());
958 return;
961 m_creature->UpdateEntry(param1, param2 ? HORDE : ALLIANCE);
963 break;
964 case ACTION_T_DIE:
966 if (m_creature->isDead())
969 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_DIE on dead creature. Creature %d", EventId, m_creature->GetEntry());
970 return;
972 m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(),NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
974 break;
975 case ACTION_T_ZONE_COMBAT_PULSE:
977 if (!m_creature->isInCombat() || !m_creature->GetMap()->IsDungeon())
980 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());
981 return;
984 DoZoneInCombat(m_creature);
986 break;
990 void CreatureEventAI::JustRespawned()
992 Reset();
994 if (bEmptyList)
995 return;
997 //Handle Spawned Events
998 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1000 if ((*i).Event.event_type == EVENT_T_SPAWNED)
1001 ProcessEvent(*i);
1005 void CreatureEventAI::Reset()
1007 EventUpdateTime = EVENT_UPDATE_TIME;
1008 EventDiff = 0;
1010 if (bEmptyList)
1011 return;
1013 //Reset all events to enabled
1014 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1016 switch ((*i).Event.event_type)
1018 //Reset all out of combat timers
1019 case EVENT_T_TIMER_OOC:
1021 if ((*i).Event.event_param2 == (*i).Event.event_param1)
1023 (*i).Time = (*i).Event.event_param1;
1024 (*i).Enabled = true;
1026 else if ((*i).Event.event_param2 > (*i).Event.event_param1)
1028 (*i).Time = urand((*i).Event.event_param1, (*i).Event.event_param2);
1029 (*i).Enabled = true;
1031 else
1032 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has InitialMax < InitialMin. Event disabled.", m_creature->GetEntry(), (*i).Event.event_id, (*i).Event.event_type);
1034 break;
1035 //default:
1036 //TODO: enable below code line / verify this is correct to enable events previously disabled (ex. aggro yell), instead of enable this in void Aggro()
1037 //(*i).Enabled = true;
1038 //(*i).Time = 0;
1039 //break;
1044 void CreatureEventAI::JustReachedHome()
1046 m_creature->LoadCreaturesAddon();
1048 if (!bEmptyList)
1050 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1052 if ((*i).Event.event_type == EVENT_T_REACHED_HOME)
1053 ProcessEvent(*i);
1057 Reset();
1060 void CreatureEventAI::EnterEvadeMode()
1062 m_creature->RemoveAllAuras();
1063 m_creature->DeleteThreatList();
1064 m_creature->CombatStop(true);
1066 if (m_creature->isAlive())
1067 m_creature->GetMotionMaster()->MoveTargetedHome();
1069 m_creature->SetLootRecipient(NULL);
1071 if (bEmptyList)
1072 return;
1074 //Handle Evade events
1075 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1077 if ((*i).Event.event_type == EVENT_T_EVADE)
1078 ProcessEvent(*i);
1082 void CreatureEventAI::JustDied(Unit* killer)
1084 Reset();
1086 if (bEmptyList)
1087 return;
1089 //Handle Evade events
1090 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1092 if ((*i).Event.event_type == EVENT_T_DEATH)
1093 ProcessEvent(*i, killer);
1097 void CreatureEventAI::KilledUnit(Unit* victim)
1099 if (bEmptyList || victim->GetTypeId() != TYPEID_PLAYER)
1100 return;
1102 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1104 if ((*i).Event.event_type == EVENT_T_KILL)
1105 ProcessEvent(*i, victim);
1109 void CreatureEventAI::JustSummoned(Creature* pUnit)
1111 if (bEmptyList || !pUnit)
1112 return;
1114 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1116 if ((*i).Event.event_type == EVENT_T_SUMMONED_UNIT)
1117 ProcessEvent(*i, pUnit);
1121 void CreatureEventAI::Aggro(Unit *who)
1123 //Check for on combat start events
1124 if (!bEmptyList)
1126 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1128 switch ((*i).Event.event_type)
1130 case EVENT_T_AGGRO:
1131 (*i).Enabled = true;
1132 ProcessEvent(*i, who);
1133 break;
1134 //Reset all in combat timers
1135 case EVENT_T_TIMER:
1136 if ((*i).Event.event_param2 == (*i).Event.event_param1)
1138 (*i).Time = (*i).Event.event_param1;
1139 (*i).Enabled = true;
1141 else if ((*i).Event.event_param2 > (*i).Event.event_param1)
1143 (*i).Time = urand((*i).Event.event_param1, (*i).Event.event_param2);
1144 (*i).Enabled = true;
1146 else
1147 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has InitialMax < InitialMin. Event disabled.", m_creature->GetEntry(), (*i).Event.event_id, (*i).Event.event_type);
1148 break;
1149 //All normal events need to be re-enabled and their time set to 0
1150 default:
1151 (*i).Enabled = true;
1152 (*i).Time = 0;
1153 break;
1158 EventUpdateTime = EVENT_UPDATE_TIME;
1159 EventDiff = 0;
1162 void CreatureEventAI::AttackStart(Unit *who)
1164 if (!who)
1165 return;
1167 bool inCombat = m_creature->isInCombat();
1169 if (m_creature->Attack(who, MeleeEnabled))
1171 m_creature->AddThreat(who, 0.0f);
1172 m_creature->SetInCombatWith(who);
1173 who->SetInCombatWith(m_creature);
1175 if (!inCombat)
1176 Aggro(who);
1178 if (CombatMovementEnabled)
1180 m_creature->GetMotionMaster()->MoveChase(who, AttackDistance, AttackAngle);
1182 else
1184 m_creature->GetMotionMaster()->MoveIdle();
1185 m_creature->StopMoving();
1190 void CreatureEventAI::MoveInLineOfSight(Unit *who)
1192 if (!who)
1193 return;
1195 //Check for OOC LOS Event
1196 if (!bEmptyList && !m_creature->getVictim())
1198 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1200 if ((*itr).Event.event_type == EVENT_T_OOC_LOS)
1202 //can trigger if closer than fMaxAllowedRange
1203 float fMaxAllowedRange = (*itr).Event.event_param2;
1205 //if range is ok and we are actually in LOS
1206 if (m_creature->IsWithinDistInMap(who, fMaxAllowedRange) && m_creature->IsWithinLOSInMap(who))
1208 //if friendly event&&who is not hostile OR hostile event&&who is hostile
1209 if (((*itr).Event.event_param1 && !m_creature->IsHostileTo(who)) ||
1210 ((!(*itr).Event.event_param1) && m_creature->IsHostileTo(who)))
1211 ProcessEvent(*itr, who);
1217 if (m_creature->isCivilian() || m_creature->IsNeutralToAll())
1218 return;
1220 if (!m_creature->hasUnitState(UNIT_STAT_STUNNED) && who->isTargetableForAttack() &&
1221 m_creature->IsHostileTo(who) && who->isInAccessablePlaceFor(m_creature))
1223 if (!m_creature->canFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
1224 return;
1226 float attackRadius = m_creature->GetAttackDistance(who);
1227 if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who))
1229 if (!m_creature->getVictim())
1231 AttackStart(who);
1232 who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1234 else if (m_creature->GetMap()->IsDungeon())
1236 who->SetInCombatWith(m_creature);
1237 m_creature->AddThreat(who, 0.0f);
1243 void CreatureEventAI::SpellHit(Unit* pUnit, const SpellEntry* pSpell)
1246 if (bEmptyList)
1247 return;
1249 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1251 if ((*i).Event.event_type == EVENT_T_SPELLHIT)
1253 //If spell id matches (or no spell id) & if spell school matches (or no spell school)
1254 if (!(*i).Event.event_param1 || pSpell->Id == (*i).Event.event_param1)
1256 if ((*i).Event.event_param2_s == -1 || pSpell->SchoolMask == (*i).Event.event_param2)
1257 ProcessEvent(*i, pUnit);
1263 void CreatureEventAI::UpdateAI(const uint32 diff)
1265 //Check if we are in combat (also updates calls threat update code)
1266 bool Combat = m_creature->SelectHostilTarget() && m_creature->getVictim();
1268 //Must return if creature isn't alive. Normally select hostil target and get victim prevent this
1269 if (!m_creature->isAlive())
1270 return;
1272 if (!bEmptyList)
1274 //Events are only updated once every EVENT_UPDATE_TIME ms to prevent lag with large amount of events
1275 if (EventUpdateTime < diff)
1277 EventDiff += diff;
1279 //Check for time based events
1280 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1282 //Decrement Timers
1283 if ((*i).Time)
1285 if ((*i).Time > EventDiff)
1287 //Do not decrement timers if event cannot trigger in this phase
1288 if (!((*i).Event.event_inverse_phase_mask & (1 << Phase)))
1289 (*i).Time -= EventDiff;
1291 //Skip processing of events that have time remaining
1292 continue;
1294 else (*i).Time = 0;
1297 //Events that are updated every EVENT_UPDATE_TIME
1298 switch ((*i).Event.event_type)
1300 case EVENT_T_TIMER_OOC:
1301 ProcessEvent(*i);
1302 break;
1303 case EVENT_T_TIMER:
1304 case EVENT_T_MANA:
1305 case EVENT_T_HP:
1306 case EVENT_T_TARGET_HP:
1307 case EVENT_T_TARGET_CASTING:
1308 case EVENT_T_FRIENDLY_HP:
1309 if (Combat)
1310 ProcessEvent(*i);
1311 break;
1312 case EVENT_T_RANGE:
1313 if (Combat)
1315 if (m_creature->IsWithinDistInMap(m_creature->getVictim(),(float)(*i).Event.event_param2))
1317 if (m_creature->GetDistance(m_creature->getVictim()) >= (float)(*i).Event.event_param1)
1318 ProcessEvent(*i);
1321 break;
1325 EventDiff = 0;
1326 EventUpdateTime = EVENT_UPDATE_TIME;
1328 else
1330 EventDiff += diff;
1331 EventUpdateTime -= diff;
1335 //Melee Auto-Attack
1336 if (Combat && MeleeEnabled)
1337 DoMeleeAttackIfReady();
1340 bool CreatureEventAI::IsVisible(Unit *pl) const
1342 return m_creature->GetDistance(pl) < sWorld.getConfig(CONFIG_SIGHT_MONSTER)
1343 && pl->isVisibleForOrDetect(m_creature,true);
1346 inline Unit* CreatureEventAI::SelectUnit(AttackingTarget target, uint32 position)
1348 //ThreatList m_threatlist;
1349 std::list<HostilReference*>& m_threatlist = m_creature->getThreatManager().getThreatList();
1350 std::list<HostilReference*>::iterator i = m_threatlist.begin();
1351 std::list<HostilReference*>::reverse_iterator r = m_threatlist.rbegin();
1353 if (position >= m_threatlist.size() || !m_threatlist.size())
1354 return NULL;
1356 switch (target)
1358 case ATTACKING_TARGET_RANDOM:
1360 advance ( i , position + (rand() % (m_threatlist.size() - position ) ));
1361 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1363 case ATTACKING_TARGET_TOPAGGRO:
1365 advance ( i , position);
1366 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1368 case ATTACKING_TARGET_BOTTOMAGGRO:
1370 advance ( r , position);
1371 return Unit::GetUnit(*m_creature,(*r)->getUnitGuid());
1374 return NULL;
1377 inline uint32 CreatureEventAI::GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3)
1379 switch (rnd % 3)
1381 case 0:
1382 return param1;
1383 break;
1384 case 1:
1385 return param2;
1386 break;
1387 case 2:
1388 return param3;
1389 break;
1391 return 0;
1394 inline Unit* CreatureEventAI::GetTargetByType(uint32 Target, Unit* pActionInvoker)
1396 switch (Target)
1398 case TARGET_T_SELF:
1399 return m_creature;
1400 break;
1401 case TARGET_T_HOSTILE:
1402 return m_creature->getVictim();
1403 break;
1404 case TARGET_T_HOSTILE_SECOND_AGGRO:
1405 return SelectUnit(ATTACKING_TARGET_TOPAGGRO,1);
1406 break;
1407 case TARGET_T_HOSTILE_LAST_AGGRO:
1408 return SelectUnit(ATTACKING_TARGET_BOTTOMAGGRO,0);
1409 break;
1410 case TARGET_T_HOSTILE_RANDOM:
1411 return SelectUnit(ATTACKING_TARGET_RANDOM,0);
1412 break;
1413 case TARGET_T_HOSTILE_RANDOM_NOT_TOP:
1414 return SelectUnit(ATTACKING_TARGET_RANDOM,1);
1415 break;
1416 case TARGET_T_ACTION_INVOKER:
1417 return pActionInvoker;
1418 break;
1419 default:
1420 return NULL;
1421 break;
1425 Unit* CreatureEventAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff)
1427 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1428 Cell cell(p);
1429 cell.data.Part.reserved = ALL_DISTRICT;
1430 cell.SetNoCreate();
1432 Unit* pUnit = NULL;
1434 MaNGOS::MostHPMissingInRange u_check(m_creature, range, MinHPDiff);
1435 MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange> searcher(m_creature, pUnit, u_check);
1438 typedef TYPELIST_4(GameObject, Creature*except pets*, DynamicObject, Corpse*Bones*) AllGridObjectTypes;
1439 This means that if we only search grid then we cannot possibly return pets or players so this is safe
1441 TypeContainerVisitor<MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange>, GridTypeMapContainer > grid_unit_searcher(searcher);
1443 CellLock<GridReadGuard> cell_lock(cell, p);
1444 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_creature->GetMap());
1445 return pUnit;
1448 void CreatureEventAI::DoFindFriendlyCC(std::list<Creature*>& _list, float range)
1450 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1451 Cell cell(p);
1452 cell.data.Part.reserved = ALL_DISTRICT;
1453 cell.SetNoCreate();
1455 MaNGOS::FriendlyCCedInRange u_check(m_creature, range);
1456 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange> searcher(m_creature, _list, u_check);
1458 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1460 CellLock<GridReadGuard> cell_lock(cell, p);
1461 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1464 void CreatureEventAI::DoFindFriendlyMissingBuff(std::list<Creature*>& _list, float range, uint32 spellid)
1466 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1467 Cell cell(p);
1468 cell.data.Part.reserved = ALL_DISTRICT;
1469 cell.SetNoCreate();
1471 MaNGOS::FriendlyMissingBuffInRange u_check(m_creature, range, spellid);
1472 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange> searcher(m_creature, _list, u_check);
1474 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1476 CellLock<GridReadGuard> cell_lock(cell, p);
1477 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1480 //*********************************
1481 //*** Functions used globally ***
1483 void CreatureEventAI::DoScriptText(int32 textEntry, WorldObject* pSource, Unit* target)
1485 if (!pSource)
1487 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i, invalid Source pointer.",textEntry);
1488 return;
1491 if (textEntry >= 0)
1493 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);
1494 return;
1497 CreatureEventAI_TextMap::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAITextMap().find(textEntry);
1499 if (i == CreatureEAI_Mgr.GetCreatureEventAITextMap().end())
1501 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);
1502 return;
1505 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);
1507 if((*i).second.SoundId)
1509 if (GetSoundEntriesStore()->LookupEntry((*i).second.SoundId))
1510 pSource->PlayDirectSound((*i).second.SoundId);
1511 else
1512 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process invalid sound id %u.",textEntry,(*i).second.SoundId);
1515 if((*i).second.Emote)
1517 if (pSource->GetTypeId() == TYPEID_UNIT || pSource->GetTypeId() == TYPEID_PLAYER)
1519 ((Unit*)pSource)->HandleEmoteCommand((*i).second.Emote);
1521 else
1522 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process emote for invalid TypeId (%u).",textEntry,pSource->GetTypeId());
1525 switch((*i).second.Type)
1527 case CHAT_TYPE_SAY:
1528 pSource->MonsterSay(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1529 break;
1530 case CHAT_TYPE_YELL:
1531 pSource->MonsterYell(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1532 break;
1533 case CHAT_TYPE_TEXT_EMOTE:
1534 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0);
1535 break;
1536 case CHAT_TYPE_BOSS_EMOTE:
1537 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0, true);
1538 break;
1539 case CHAT_TYPE_WHISPER:
1541 if (target && target->GetTypeId() == TYPEID_PLAYER)
1542 pSource->MonsterWhisper(textEntry, target->GetGUID());
1543 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1544 }break;
1545 case CHAT_TYPE_BOSS_WHISPER:
1547 if (target && target->GetTypeId() == TYPEID_PLAYER)
1548 pSource->MonsterWhisper(textEntry, target->GetGUID(), true);
1549 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1550 }break;
1551 case CHAT_TYPE_ZONE_YELL:
1552 pSource->MonsterYellToZone(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1553 break;
1557 void CreatureEventAI::DoZoneInCombat(Unit* pUnit)
1559 if (!pUnit)
1560 pUnit = m_creature;
1562 Map *map = pUnit->GetMap();
1564 if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
1566 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat call for map that isn't an instance (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1567 return;
1570 if (!pUnit->CanHaveThreatList() || pUnit->getThreatManager().isThreatListEmpty())
1572 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);
1574 return;
1577 Map::PlayerList const &PlayerList = map->GetPlayers();
1578 for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
1579 if (Player* i_pl = i->getSource())
1580 if (!i_pl->isGameMaster())
1581 pUnit->AddThreat(i_pl, 0.0f);
1584 void CreatureEventAI::DoMeleeAttackIfReady()
1586 //Make sure our attack is ready before checking distance
1587 if (m_creature->isAttackReady())
1589 //If we are within range melee the target
1590 if (m_creature->IsWithinDistInMap(m_creature->getVictim(), ATTACK_DISTANCE))
1592 m_creature->AttackerStateUpdate(m_creature->getVictim());
1593 m_creature->resetAttackTimer();
1598 bool CreatureEventAI::CanCast(Unit* Target, SpellEntry const *Spell, bool Triggered)
1600 //No target so we can't cast
1601 if (!Target || !Spell)
1602 return false;
1604 //Silenced so we can't cast
1605 if (!Triggered && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1606 return false;
1608 //Check for power
1609 if (!Triggered && m_creature->GetPower((Powers)Spell->powerType) < Spell->manaCost)
1610 return false;
1612 SpellRangeEntry const *TempRange = NULL;
1614 TempRange = GetSpellRangeStore()->LookupEntry(Spell->rangeIndex);
1616 //Spell has invalid range store so we can't use it
1617 if (!TempRange)
1618 return false;
1620 //Unit is out of range of this spell
1621 if (m_creature->GetDistance(Target) > TempRange->maxRange || m_creature->GetDistance(Target) < TempRange->minRange)
1622 return false;
1624 return true;
1627 void CreatureEventAI::ReceiveEmote(Player* pPlayer, uint32 text_emote)
1629 if (bEmptyList)
1630 return;
1632 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1634 if ((*itr).Event.event_type == EVENT_T_RECEIVE_EMOTE)
1636 if ((*itr).Event.event_param1 != text_emote)
1637 return;
1639 bool bProcess = false;
1641 switch((*itr).Event.event_param2)
1643 //enum ConditionType
1644 case CONDITION_NONE: // 0 0
1645 bProcess = true;
1646 break;
1647 case CONDITION_AURA: // spell_id effindex
1648 if (pPlayer->HasAura((*itr).Event.event_param3,(*itr).Event.event_param4))
1649 bProcess = true;
1650 break;
1651 case CONDITION_ITEM: // item_id count
1652 if (pPlayer->HasItemCount((*itr).Event.event_param3,(*itr).Event.event_param4))
1653 bProcess = true;
1654 break;
1655 case CONDITION_ITEM_EQUIPPED: // item_id count
1656 if (pPlayer->HasItemOrGemWithIdEquipped((*itr).Event.event_param3,(*itr).Event.event_param4))
1657 bProcess = true;
1658 break;
1659 case CONDITION_ZONEID: // zone_id 0
1660 if (pPlayer->GetZoneId() == (*itr).Event.event_param3)
1661 bProcess = true;
1662 break;
1663 case CONDITION_REPUTATION_RANK: // faction_id min_rank
1664 if (pPlayer->GetReputationRank((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1665 bProcess = true;
1666 break;
1667 case CONDITION_TEAM: // player_team 0, (469 - Alliance 67 - Horde)
1668 if (pPlayer->GetTeam() == (*itr).Event.event_param3)
1669 bProcess = true;
1670 break;
1671 case CONDITION_SKILL: // skill_id min skill_value
1672 if (pPlayer->HasSkill((*itr).Event.event_param3) && pPlayer->GetSkillValue((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1673 bProcess = true;
1674 break;
1675 case CONDITION_QUESTREWARDED: // quest_id 0
1676 if (pPlayer->GetQuestRewardStatus((*itr).Event.event_param3))
1677 bProcess = true;
1678 break;
1679 case CONDITION_QUESTTAKEN: // quest_id 0, for condition true while quest active.
1680 if (pPlayer->GetQuestStatus((*itr).Event.event_param3) == QUEST_STATUS_INCOMPLETE)
1681 bProcess = true;
1682 break;
1683 case CONDITION_ACTIVE_EVENT: // event_id 0
1684 if (IsHolidayActive(HolidayIds((*itr).Event.event_param3)))
1685 bProcess = true;
1686 break;
1689 if (bProcess)
1691 sLog.outDebug("CreatureEventAI: ReceiveEmote CreatureEventAI: Condition ok, processing");
1692 ProcessEvent(*itr, pPlayer);