[7645] Fixed problems wit temporary unsummoned pets and cleanup code.
[AHbot.git] / src / game / CreatureEventAI.cpp
blob00b32acfe5a425b84be4a7d4218fdede0309669b
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->GetCreatureInfo()->AIName == "EventAI" )
36 return PERMIT_BASE_SPECIAL;
37 return PERMIT_BASE_NO;
40 CreatureEventAI::CreatureEventAI(Creature &c ) : m_creature(c), InCombat(false)
42 CreatureEventAI_Event_Map::iterator CreatureEvents = CreatureEAI_Mgr.GetCreatureEventAIMap().find(m_creature.GetEntry());
43 if (CreatureEvents != CreatureEAI_Mgr.GetCreatureEventAIMap().end())
45 std::vector<CreatureEventAI_Event>::iterator i;
46 for (i = (*CreatureEvents).second.begin(); i != (*CreatureEvents).second.end(); ++i)
49 //Debug check
50 #ifndef _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 (!InCombat)
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 (InCombat)
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 (!InCombat || !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 (!InCombat || !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 (!InCombat || !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 (!InCombat || !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 (!InCombat)
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 (!InCombat)
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, 0, 0, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, param3);
682 else
683 pCreature = m_creature.SummonCreature(param1, 0, 0, 0, 0, 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 Unit* pTarget = GetTargetByType(param2, pActionInvoker);
915 if (Player* pPlayer = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself())
916 pPlayer->RewardPlayerAndGroupAtEvent(param1, &m_creature);
919 break;
920 case ACTION_T_SET_INST_DATA:
922 InstanceData* pInst = (InstanceData*)m_creature.GetInstanceData();
923 if (!pInst)
925 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data without instance script. Creature %d", EventId, m_creature.GetEntry());
926 return;
929 pInst->SetData(param1, param2);
931 break;
932 case ACTION_T_SET_INST_DATA64:
934 Unit* target = GetTargetByType(param2, pActionInvoker);
935 if (!target)
937 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 but Target == NULL. Creature %d", EventId, m_creature.GetEntry());
938 return;
941 InstanceData* pInst = (InstanceData*)m_creature.GetInstanceData();
942 if (!pInst)
944 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 without instance script. Creature %d", EventId, m_creature.GetEntry());
945 return;
948 pInst->SetData64(param1, target->GetGUID());
950 break;
951 case ACTION_T_UPDATE_TEMPLATE:
953 if (m_creature.GetEntry() == param1)
956 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d", EventId, m_creature.GetEntry());
957 return;
960 m_creature.UpdateEntry(param1, param2 ? HORDE : ALLIANCE);
962 break;
963 case ACTION_T_DIE:
965 if (m_creature.isDead())
968 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_DIE on dead creature. Creature %d", EventId, m_creature.GetEntry());
969 return;
971 m_creature.DealDamage(&m_creature, m_creature.GetMaxHealth(),NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
973 break;
974 case ACTION_T_ZONE_COMBAT_PULSE:
976 if (!m_creature.isInCombat() || !m_creature.GetMap()->IsDungeon())
979 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());
980 return;
983 DoZoneInCombat(&m_creature);
985 break;
989 void CreatureEventAI::JustRespawned()
991 InCombat = false;
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.InterruptNonMeleeSpells(true);
1063 m_creature.RemoveAllAuras();
1064 m_creature.DeleteThreatList();
1065 m_creature.CombatStop();
1067 if (m_creature.isAlive())
1068 m_creature.GetMotionMaster()->MoveTargetedHome();
1070 m_creature.SetLootRecipient(NULL);
1072 InCombat = false;
1074 if (bEmptyList)
1075 return;
1077 //Handle Evade events
1078 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1080 if ((*i).Event.event_type == EVENT_T_EVADE)
1081 ProcessEvent(*i);
1085 void CreatureEventAI::JustDied(Unit* killer)
1087 InCombat = false;
1088 Reset();
1090 if (bEmptyList)
1091 return;
1093 //Handle Evade events
1094 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1096 if ((*i).Event.event_type == EVENT_T_DEATH)
1097 ProcessEvent(*i, killer);
1101 void CreatureEventAI::KilledUnit(Unit* victim)
1103 if (bEmptyList || victim->GetTypeId() != TYPEID_PLAYER)
1104 return;
1106 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1108 if ((*i).Event.event_type == EVENT_T_KILL)
1109 ProcessEvent(*i, victim);
1113 void CreatureEventAI::JustSummoned(Creature* pUnit)
1115 if (bEmptyList || !pUnit)
1116 return;
1118 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1120 if ((*i).Event.event_type == EVENT_T_SUMMONED_UNIT)
1121 ProcessEvent(*i, pUnit);
1125 void CreatureEventAI::Aggro(Unit *who)
1127 //Check for on combat start events
1128 if (!bEmptyList)
1130 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1132 switch ((*i).Event.event_type)
1134 case EVENT_T_AGGRO:
1135 (*i).Enabled = true;
1136 ProcessEvent(*i, who);
1137 break;
1138 //Reset all in combat timers
1139 case EVENT_T_TIMER:
1140 if ((*i).Event.event_param2 == (*i).Event.event_param1)
1142 (*i).Time = (*i).Event.event_param1;
1143 (*i).Enabled = true;
1145 else if ((*i).Event.event_param2 > (*i).Event.event_param1)
1147 (*i).Time = urand((*i).Event.event_param1, (*i).Event.event_param2);
1148 (*i).Enabled = true;
1150 else
1151 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);
1152 break;
1153 //All normal events need to be re-enabled and their time set to 0
1154 default:
1155 (*i).Enabled = true;
1156 (*i).Time = 0;
1157 break;
1162 EventUpdateTime = EVENT_UPDATE_TIME;
1163 EventDiff = 0;
1166 void CreatureEventAI::AttackStart(Unit *who)
1168 if (!who)
1169 return;
1171 if (m_creature.Attack(who, MeleeEnabled))
1173 m_creature.AddThreat(who, 0.0f);
1174 m_creature.SetInCombatWith(who);
1175 who->SetInCombatWith(&m_creature);
1177 if (!InCombat)
1179 InCombat = true;
1180 Aggro(who);
1183 if (CombatMovementEnabled)
1185 m_creature.GetMotionMaster()->MoveChase(who, AttackDistance, AttackAngle);
1187 else
1189 m_creature.GetMotionMaster()->MoveIdle();
1190 m_creature.StopMoving();
1195 void CreatureEventAI::MoveInLineOfSight(Unit *who)
1197 if (!who)
1198 return;
1200 //Check for OOC LOS Event
1201 if (!bEmptyList && !m_creature.getVictim())
1203 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1205 if ((*itr).Event.event_type == EVENT_T_OOC_LOS)
1207 //can trigger if closer than fMaxAllowedRange
1208 float fMaxAllowedRange = (*itr).Event.event_param2;
1210 //if range is ok and we are actually in LOS
1211 if (m_creature.IsWithinDistInMap(who, fMaxAllowedRange) && m_creature.IsWithinLOSInMap(who))
1213 //if friendly event&&who is not hostile OR hostile event&&who is hostile
1214 if (((*itr).Event.event_param1 && !m_creature.IsHostileTo(who)) ||
1215 ((!(*itr).Event.event_param1) && m_creature.IsHostileTo(who)))
1216 ProcessEvent(*itr, who);
1222 if (m_creature.isCivilian() && m_creature.IsNeutralToAll())
1223 return;
1225 if (!m_creature.hasUnitState(UNIT_STAT_STUNNED) && who->isTargetableForAttack() &&
1226 m_creature.IsHostileTo(who) && who->isInAccessablePlaceFor(&m_creature))
1228 if (!m_creature.canFly() && m_creature.GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
1229 return;
1231 float attackRadius = m_creature.GetAttackDistance(who);
1232 if (m_creature.IsWithinDistInMap(who, attackRadius) && m_creature.IsWithinLOSInMap(who))
1234 if (!m_creature.getVictim())
1236 AttackStart(who);
1237 who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1239 else if (m_creature.GetMap()->IsDungeon())
1241 who->SetInCombatWith(&m_creature);
1242 m_creature.AddThreat(who, 0.0f);
1248 void CreatureEventAI::SpellHit(Unit* pUnit, const SpellEntry* pSpell)
1251 if (bEmptyList)
1252 return;
1254 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1256 if ((*i).Event.event_type == EVENT_T_SPELLHIT)
1258 //If spell id matches (or no spell id) & if spell school matches (or no spell school)
1259 if (!(*i).Event.event_param1 || pSpell->Id == (*i).Event.event_param1)
1261 if ((*i).Event.event_param2_s == -1 || pSpell->SchoolMask == (*i).Event.event_param2)
1262 ProcessEvent(*i, pUnit);
1268 void CreatureEventAI::UpdateAI(const uint32 diff)
1270 //Check if we are in combat (also updates calls threat update code)
1271 bool Combat = InCombat ? (m_creature.SelectHostilTarget() && m_creature.getVictim()) : false;
1273 //Must return if creature isn't alive. Normally select hostil target and get victim prevent this
1274 if (!m_creature.isAlive())
1275 return;
1277 if (!bEmptyList)
1279 //Events are only updated once every EVENT_UPDATE_TIME ms to prevent lag with large amount of events
1280 if (EventUpdateTime < diff)
1282 EventDiff += diff;
1284 //Check for time based events
1285 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1287 //Decrement Timers
1288 if ((*i).Time)
1290 if ((*i).Time > EventDiff)
1292 //Do not decrement timers if event cannot trigger in this phase
1293 if (!((*i).Event.event_inverse_phase_mask & (1 << Phase)))
1294 (*i).Time -= EventDiff;
1296 //Skip processing of events that have time remaining
1297 continue;
1299 else (*i).Time = 0;
1302 //Events that are updated every EVENT_UPDATE_TIME
1303 switch ((*i).Event.event_type)
1305 case EVENT_T_TIMER_OOC:
1306 ProcessEvent(*i);
1307 break;
1308 case EVENT_T_TIMER:
1309 case EVENT_T_MANA:
1310 case EVENT_T_HP:
1311 case EVENT_T_TARGET_HP:
1312 case EVENT_T_TARGET_CASTING:
1313 case EVENT_T_FRIENDLY_HP:
1314 if (Combat)
1315 ProcessEvent(*i);
1316 break;
1317 case EVENT_T_RANGE:
1318 if (Combat)
1320 if (m_creature.IsWithinDistInMap(m_creature.getVictim(),(float)(*i).Event.event_param2))
1322 if (m_creature.GetDistance(m_creature.getVictim()) >= (float)(*i).Event.event_param1)
1323 ProcessEvent(*i);
1326 break;
1330 EventDiff = 0;
1331 EventUpdateTime = EVENT_UPDATE_TIME;
1333 else
1335 EventDiff += diff;
1336 EventUpdateTime -= diff;
1340 //Melee Auto-Attack
1341 if (Combat && MeleeEnabled)
1342 DoMeleeAttackIfReady();
1345 bool CreatureEventAI::IsVisible(Unit *pl) const
1347 return m_creature.GetDistance(pl) < sWorld.getConfig(CONFIG_SIGHT_MONSTER)
1348 && pl->isVisibleForOrDetect(&m_creature,true);
1351 inline Unit* CreatureEventAI::SelectUnit(AttackingTarget target, uint32 position)
1353 //ThreatList m_threatlist;
1354 std::list<HostilReference*>& m_threatlist = m_creature.getThreatManager().getThreatList();
1355 std::list<HostilReference*>::iterator i = m_threatlist.begin();
1356 std::list<HostilReference*>::reverse_iterator r = m_threatlist.rbegin();
1358 if (position >= m_threatlist.size() || !m_threatlist.size())
1359 return NULL;
1361 switch (target)
1363 case ATTACKING_TARGET_RANDOM:
1365 advance ( i , position + (rand() % (m_threatlist.size() - position ) ));
1366 return Unit::GetUnit(m_creature,(*i)->getUnitGuid());
1368 case ATTACKING_TARGET_TOPAGGRO:
1370 advance ( i , position);
1371 return Unit::GetUnit(m_creature,(*i)->getUnitGuid());
1373 case ATTACKING_TARGET_BOTTOMAGGRO:
1375 advance ( r , position);
1376 return Unit::GetUnit(m_creature,(*r)->getUnitGuid());
1379 return NULL;
1382 inline uint32 CreatureEventAI::GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3)
1384 switch (rnd % 3)
1386 case 0:
1387 return param1;
1388 break;
1389 case 1:
1390 return param2;
1391 break;
1392 case 2:
1393 return param3;
1394 break;
1396 return 0;
1399 inline Unit* CreatureEventAI::GetTargetByType(uint32 Target, Unit* pActionInvoker)
1401 switch (Target)
1403 case TARGET_T_SELF:
1404 return &m_creature;
1405 break;
1406 case TARGET_T_HOSTILE:
1407 return m_creature.getVictim();
1408 break;
1409 case TARGET_T_HOSTILE_SECOND_AGGRO:
1410 return SelectUnit(ATTACKING_TARGET_TOPAGGRO,1);
1411 break;
1412 case TARGET_T_HOSTILE_LAST_AGGRO:
1413 return SelectUnit(ATTACKING_TARGET_BOTTOMAGGRO,0);
1414 break;
1415 case TARGET_T_HOSTILE_RANDOM:
1416 return SelectUnit(ATTACKING_TARGET_RANDOM,0);
1417 break;
1418 case TARGET_T_HOSTILE_RANDOM_NOT_TOP:
1419 return SelectUnit(ATTACKING_TARGET_RANDOM,1);
1420 break;
1421 case TARGET_T_ACTION_INVOKER:
1422 return pActionInvoker;
1423 break;
1424 default:
1425 return NULL;
1426 break;
1430 Unit* CreatureEventAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff)
1432 CellPair p(MaNGOS::ComputeCellPair(m_creature.GetPositionX(), m_creature.GetPositionY()));
1433 Cell cell(p);
1434 cell.data.Part.reserved = ALL_DISTRICT;
1435 cell.SetNoCreate();
1437 Unit* pUnit = NULL;
1439 MaNGOS::MostHPMissingInRange u_check(&m_creature, range, MinHPDiff);
1440 MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange> searcher(&m_creature, pUnit, u_check);
1443 typedef TYPELIST_4(GameObject, Creature*except pets*, DynamicObject, Corpse*Bones*) AllGridObjectTypes;
1444 This means that if we only search grid then we cannot possibly return pets or players so this is safe
1446 TypeContainerVisitor<MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange>, GridTypeMapContainer > grid_unit_searcher(searcher);
1448 CellLock<GridReadGuard> cell_lock(cell, p);
1449 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_creature.GetMap());
1450 return pUnit;
1453 void CreatureEventAI::DoFindFriendlyCC(std::list<Creature*>& _list, float range)
1455 CellPair p(MaNGOS::ComputeCellPair(m_creature.GetPositionX(), m_creature.GetPositionY()));
1456 Cell cell(p);
1457 cell.data.Part.reserved = ALL_DISTRICT;
1458 cell.SetNoCreate();
1460 MaNGOS::FriendlyCCedInRange u_check(&m_creature, range);
1461 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange> searcher(&m_creature, _list, u_check);
1463 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1465 CellLock<GridReadGuard> cell_lock(cell, p);
1466 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature.GetMap());
1469 void CreatureEventAI::DoFindFriendlyMissingBuff(std::list<Creature*>& _list, float range, uint32 spellid)
1471 CellPair p(MaNGOS::ComputeCellPair(m_creature.GetPositionX(), m_creature.GetPositionY()));
1472 Cell cell(p);
1473 cell.data.Part.reserved = ALL_DISTRICT;
1474 cell.SetNoCreate();
1476 MaNGOS::FriendlyMissingBuffInRange u_check(&m_creature, range, spellid);
1477 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange> searcher(&m_creature, _list, u_check);
1479 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1481 CellLock<GridReadGuard> cell_lock(cell, p);
1482 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature.GetMap());
1485 //*********************************
1486 //*** Functions used globally ***
1488 void CreatureEventAI::DoScriptText(int32 textEntry, WorldObject* pSource, Unit* target)
1490 if (!pSource)
1492 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i, invalid Source pointer.",textEntry);
1493 return;
1496 if (textEntry >= 0)
1498 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);
1499 return;
1502 CreatureEventAI_TextMap::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAITextMap().find(textEntry);
1504 if (i == CreatureEAI_Mgr.GetCreatureEventAITextMap().end())
1506 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);
1507 return;
1510 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);
1512 if((*i).second.SoundId)
1514 if (GetSoundEntriesStore()->LookupEntry((*i).second.SoundId))
1515 pSource->PlayDirectSound((*i).second.SoundId);
1516 else
1517 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process invalid sound id %u.",textEntry,(*i).second.SoundId);
1520 if((*i).second.Emote)
1522 if (pSource->GetTypeId() == TYPEID_UNIT || pSource->GetTypeId() == TYPEID_PLAYER)
1524 ((Unit*)pSource)->HandleEmoteCommand((*i).second.Emote);
1526 else
1527 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process emote for invalid TypeId (%u).",textEntry,pSource->GetTypeId());
1530 switch((*i).second.Type)
1532 case CHAT_TYPE_SAY:
1533 pSource->MonsterSay(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1534 break;
1535 case CHAT_TYPE_YELL:
1536 pSource->MonsterYell(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1537 break;
1538 case CHAT_TYPE_TEXT_EMOTE:
1539 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0);
1540 break;
1541 case CHAT_TYPE_BOSS_EMOTE:
1542 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0, true);
1543 break;
1544 case CHAT_TYPE_WHISPER:
1546 if (target && target->GetTypeId() == TYPEID_PLAYER)
1547 pSource->MonsterWhisper(textEntry, target->GetGUID());
1548 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1549 }break;
1550 case CHAT_TYPE_BOSS_WHISPER:
1552 if (target && target->GetTypeId() == TYPEID_PLAYER)
1553 pSource->MonsterWhisper(textEntry, target->GetGUID(), true);
1554 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1555 }break;
1556 case CHAT_TYPE_ZONE_YELL:
1557 pSource->MonsterYellToZone(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1558 break;
1562 void CreatureEventAI::DoZoneInCombat(Unit* pUnit)
1564 if (!pUnit)
1565 pUnit = &m_creature;
1567 Map *map = pUnit->GetMap();
1569 if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
1571 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat call for map that isn't an instance (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1572 return;
1575 if (!pUnit->CanHaveThreatList() || pUnit->getThreatManager().isThreatListEmpty())
1577 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);
1579 return;
1582 Map::PlayerList const &PlayerList = map->GetPlayers();
1583 for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
1584 if (Player* i_pl = i->getSource())
1585 if (!i_pl->isGameMaster())
1586 pUnit->AddThreat(i_pl, 0.0f);
1589 void CreatureEventAI::DoMeleeAttackIfReady()
1591 //Make sure our attack is ready before checking distance
1592 if (m_creature.isAttackReady())
1594 //If we are within range melee the target
1595 if (m_creature.IsWithinDistInMap(m_creature.getVictim(), ATTACK_DISTANCE))
1597 m_creature.AttackerStateUpdate(m_creature.getVictim());
1598 m_creature.resetAttackTimer();
1603 bool CreatureEventAI::CanCast(Unit* Target, SpellEntry const *Spell, bool Triggered)
1605 //No target so we can't cast
1606 if (!Target || !Spell)
1607 return false;
1609 //Silenced so we can't cast
1610 if (!Triggered && m_creature.HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1611 return false;
1613 //Check for power
1614 if (!Triggered && m_creature.GetPower((Powers)Spell->powerType) < Spell->manaCost)
1615 return false;
1617 SpellRangeEntry const *TempRange = NULL;
1619 TempRange = GetSpellRangeStore()->LookupEntry(Spell->rangeIndex);
1621 //Spell has invalid range store so we can't use it
1622 if (!TempRange)
1623 return false;
1625 //Unit is out of range of this spell
1626 if (m_creature.GetDistance(Target) > TempRange->maxRange || m_creature.GetDistance(Target) < TempRange->minRange)
1627 return false;
1629 return true;
1632 bool CreatureEventAI::ReceiveEmote(Player* pPlayer, Creature* pCreature, uint32 uiEmote)
1634 CreatureEventAI* pTmpCreature = (CreatureEventAI*)(pCreature->AI());
1636 if (pTmpCreature->bEmptyList)
1637 return true;
1639 for (std::list<CreatureEventAIHolder>::iterator itr = pTmpCreature->CreatureEventAIList.begin(); itr != pTmpCreature->CreatureEventAIList.end(); ++itr)
1641 if ((*itr).Event.event_type == EVENT_T_RECEIVE_EMOTE)
1643 if ((*itr).Event.event_param1 != uiEmote)
1644 return true;
1646 bool bProcess = false;
1648 switch((*itr).Event.event_param2)
1650 //enum ConditionType
1651 case CONDITION_NONE: // 0 0
1652 bProcess = true;
1653 break;
1654 case CONDITION_AURA: // spell_id effindex
1655 if (pPlayer->HasAura((*itr).Event.event_param3,(*itr).Event.event_param4))
1656 bProcess = true;
1657 break;
1658 case CONDITION_ITEM: // item_id count
1659 if (pPlayer->HasItemCount((*itr).Event.event_param3,(*itr).Event.event_param4))
1660 bProcess = true;
1661 break;
1662 case CONDITION_ITEM_EQUIPPED: // item_id count
1663 if (pPlayer->HasItemOrGemWithIdEquipped((*itr).Event.event_param3,(*itr).Event.event_param4))
1664 bProcess = true;
1665 break;
1666 case CONDITION_ZONEID: // zone_id 0
1667 if (pPlayer->GetZoneId() == (*itr).Event.event_param3)
1668 bProcess = true;
1669 break;
1670 case CONDITION_REPUTATION_RANK: // faction_id min_rank
1671 if (pPlayer->GetReputationRank((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1672 bProcess = true;
1673 break;
1674 case CONDITION_TEAM: // player_team 0, (469 - Alliance 67 - Horde)
1675 if (pPlayer->GetTeam() == (*itr).Event.event_param3)
1676 bProcess = true;
1677 break;
1678 case CONDITION_SKILL: // skill_id min skill_value
1679 if (pPlayer->HasSkill((*itr).Event.event_param3) && pPlayer->GetSkillValue((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1680 bProcess = true;
1681 break;
1682 case CONDITION_QUESTREWARDED: // quest_id 0
1683 if (pPlayer->GetQuestRewardStatus((*itr).Event.event_param3))
1684 bProcess = true;
1685 break;
1686 case CONDITION_QUESTTAKEN: // quest_id 0, for condition true while quest active.
1687 if (pPlayer->GetQuestStatus((*itr).Event.event_param3) == QUEST_STATUS_INCOMPLETE)
1688 bProcess = true;
1689 break;
1690 case CONDITION_ACTIVE_EVENT: // event_id 0
1691 if (IsHolidayActive(HolidayIds((*itr).Event.event_param3)))
1692 bProcess = true;
1693 break;
1696 if (bProcess)
1698 sLog.outDebug("CreatureEventAI: ReceiveEmote CreatureEventAI: Condition ok, processing");
1699 pTmpCreature->ProcessEvent(*itr, pPlayer);
1704 return true;