9
3

NPC_AI.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator 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.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "NPC_AI.h"
  17. #include "Combat.h"
  18. #include "zoneserver.h"
  19. #include "Spells.h"
  20. #include "../common/Log.h"
  21. #include "LuaInterface.h"
  22. #include "World.h"
  23. #include "Rules/Rules.h"
  24. extern RuleManager rule_manager;
  25. extern LuaInterface* lua_interface;
  26. extern World world;
  27. /* The NEW AI code */
  28. Brain::Brain(NPC* npc) {
  29. // Set the npc this brain will controll
  30. m_body = npc;
  31. // Set the default time between calls to think to 250 miliseconds (1/4 a second)
  32. m_tick = 250;
  33. m_lastTick = Timer::GetCurrentTime2();
  34. m_spellRecovery = 0;
  35. m_playerInEncounter = false;
  36. // Set up the mutex for the hate list
  37. MHateList.SetName("Brain::m_hatelist");
  38. // Set up the mutex for the encounter list
  39. MEncounter.SetName("Brain::m_encounter");
  40. }
  41. Brain::~Brain() {
  42. }
  43. void Brain::Think() {
  44. if (m_body->IsPet() && m_body->GetOwner() && m_body->GetOwner()->IsPlayer()) {
  45. Player* player = (Player*)m_body->GetOwner();
  46. if(player->GetInfoStruct()->get_pet_id() == 0) {
  47. player->GetInfoStruct()->set_pet_id(player->GetIDWithPlayerSpawn(m_body));
  48. player->SetCharSheetChanged(true);
  49. }
  50. }
  51. // Get the entity this NPC hates the most,
  52. // GetMostHated() will handle dead spawns so no need to check the health in this function
  53. Entity* target = GetMostHated();
  54. // If mezzed, stunned or feared we can't do anything so skip
  55. if (!m_body->IsMezzedOrStunned()) {
  56. // Not mezzed or stunned
  57. // Get the distance to the runback location
  58. float run_back_distance = m_body->GetRunbackDistance();
  59. if (target) {
  60. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s has %s targeted.", m_body->GetName(), target->GetName());
  61. // NPC has an entity that it hates
  62. // Set the NPC's target to the most hated entity if it is not already.
  63. if (m_body->GetTarget() != target) {
  64. m_body->SetTarget(target);
  65. }
  66. m_body->FaceTarget(target, false);
  67. // target needs to be set before in combat is engaged
  68. // If the NPC is not in combat then put them in combat
  69. if (!m_body->EngagedInCombat()) {
  70. m_body->ClearRunningLocations();
  71. m_body->InCombat(true);
  72. m_body->cast_on_aggro_completed = false;
  73. m_body->GetZone()->CallSpawnScript(m_body, SPAWN_SCRIPT_AGGRO, target);
  74. }
  75. bool breakWaterPursuit = false;
  76. if (m_body->IsWaterCreature() && !m_body->IsFlyingCreature() && !target->InWater())
  77. breakWaterPursuit = true;
  78. // Check to see if the NPC has exceeded the max chase distance
  79. if (run_back_distance > MAX_CHASE_DISTANCE || breakWaterPursuit) {
  80. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Run back distance is greater then max chase distance, run_back_distance = %f", run_back_distance);
  81. // Over the max chase distance, Check to see if the target is is a client
  82. if (target->IsPlayer() && ((Player*)target)->GetClient())
  83. {
  84. // Target is a client so send encounter break messages
  85. if (m_body->HasSpawnGroup())
  86. ((Player*)target)->GetClient()->SimpleMessage(CHANNEL_NARRATIVE, "This encounter will no longer give encounter rewards.");
  87. else
  88. ((Player*)target)->GetClient()->Message(CHANNEL_NARRATIVE, "%s is no longer worth any experience or treasure.", m_body->GetName());
  89. }
  90. // Clear the hate list for this NPC
  91. ClearHate();
  92. // Clear the encounter list
  93. ClearEncounter();
  94. }
  95. else {
  96. // Still within max chase distance lets to the combat stuff now
  97. float distance = m_body->GetDistance(target);
  98. if(!m_body->IsCasting() && (!HasRecovered() || !ProcessSpell(target, distance))) {
  99. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is attempting melee on %s.", m_body->GetName(), target->GetName());
  100. m_body->FaceTarget(target, false);
  101. ProcessMelee(target, distance);
  102. }
  103. }
  104. }
  105. else {
  106. // Nothing in the hate list
  107. bool wasInCombat = m_body->EngagedInCombat();
  108. // Check to see if the NPC is still flagged as in combat for some reason
  109. if (m_body->EngagedInCombat()) {
  110. // If it is set the combat flag to false
  111. m_body->InCombat(false);
  112. // Do not set a players pet to full health once they stop combat
  113. if (!m_body->IsPet() || (m_body->IsPet() && m_body->GetOwner() && !m_body->GetOwner()->IsPlayer()))
  114. m_body->SetHP(m_body->GetTotalHP());
  115. }
  116. CheckBuffs();
  117. // If run back distance is greater then 0 then run back
  118. if(!m_body->EngagedInCombat() && !m_body->IsPauseMovementTimerActive())
  119. {
  120. if (run_back_distance > 1 || (m_body->m_call_runback && !m_body->following)) {
  121. m_body->SetLockedNoLoot(ENCOUNTER_STATE_BROKEN);
  122. m_body->UpdateEncounterState(ENCOUNTER_STATE_BROKEN);
  123. m_body->GetZone()->AddChangedSpawn(m_body);
  124. m_body->Runback(run_back_distance);
  125. m_body->m_call_runback = false;
  126. }
  127. else if (m_body->GetRunbackLocation())
  128. {
  129. switch(m_body->GetRunbackLocation()->stage)
  130. {
  131. case 0:
  132. m_body->GetZone()->movementMgr->StopNavigation((Entity*)m_body);
  133. m_body->ClearRunningLocations();
  134. m_body->SetX(m_body->GetRunbackLocation()->x,false);
  135. m_body->SetZ(m_body->GetRunbackLocation()->z,false);
  136. m_body->SetY(m_body->GetRunbackLocation()->y,false);
  137. m_body->CalculateRunningLocation(true);
  138. m_body->GetRunbackLocation()->stage = 1;
  139. m_body->GetZone()->AddChangedSpawn(m_body);
  140. break;
  141. case 6: // artificially 1500ms per 250ms Think() call
  142. if (m_body->GetRunbackLocation()->gridid > 0)
  143. m_body->SetLocation(m_body->GetRunbackLocation()->gridid);
  144. if(m_body->GetTempActionState() == 0)
  145. m_body->SetTempActionState(-1);
  146. m_body->SetHeading(m_body->m_runbackHeadingDir1,m_body->m_runbackHeadingDir2,false);
  147. if(m_body->GetRunbackLocation()->reset_hp_on_runback)
  148. m_body->SetHP(m_body->GetTotalHP());
  149. m_body->ClearRunback();
  150. if(m_body->GetLockedNoLoot() != ENCOUNTER_STATE_AVAILABLE && m_body->Alive()) {
  151. m_body->SetLockedNoLoot(ENCOUNTER_STATE_AVAILABLE);
  152. m_body->UpdateEncounterState(ENCOUNTER_STATE_AVAILABLE);
  153. }
  154. m_body->GetZone()->AddChangedSpawn(m_body);
  155. break;
  156. default: // captures case 1 up to case 5 to turn around / reset hp
  157. m_body->GetRunbackLocation()->stage++; // artificially delay
  158. break;
  159. }
  160. }
  161. }
  162. // If encounter size is greater then 0 then clear it
  163. if (GetEncounterSize() > 0)
  164. ClearEncounter();
  165. }
  166. }
  167. }
  168. sint32 Brain::GetHate(Entity* entity) {
  169. // We will use this variable to return the value, default to 0
  170. sint32 ret = 0;
  171. // Lock the hate list, not altering it so do a read lock
  172. MHateList.readlock(__FUNCTION__, __LINE__);
  173. // First check to see if the given entity is even in the hate list
  174. if (m_hatelist.count(entity->GetID()) > 0)
  175. // Entity in the hate list so get the hate value for the entity
  176. ret = m_hatelist[entity->GetID()];
  177. // Unlock the hate list
  178. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  179. // return the hate
  180. return ret;
  181. }
  182. void Brain::AddHate(Entity* entity, sint32 hate) {
  183. // do not aggro when running back, despite taking damage
  184. if (m_body->IsNPC() && ((NPC*)m_body)->m_runningBack)
  185. return;
  186. else if (m_body->IsPet() && m_body->IsEntity() && ((Entity*)m_body)->GetOwner() == entity)
  187. return;
  188. if(m_body->IsImmune(IMMUNITY_TYPE_TAUNT))
  189. {
  190. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is immune to taunt from entity %s.", m_body->GetName(), entity ? entity->GetName() : "(null)");
  191. if(entity && entity->IsPlayer())
  192. ((Player*)entity)->GetClient()->GetCurrentZone()->SendDamagePacket((Spawn*)entity, (Spawn*)m_body, DAMAGE_PACKET_TYPE_RANGE_SPELL_DMG, DAMAGE_PACKET_RESULT_IMMUNE, 0, 0, "Hate");
  193. return;
  194. }
  195. // Lock the hate list, we are altering the list so use write lock
  196. MHateList.writelock(__FUNCTION__, __LINE__);
  197. if (m_hatelist.count(entity->GetID()) > 0) {
  198. m_hatelist[entity->GetID()] += hate;
  199. // take into consideration that 0 or negative hate is not valid, we need to properly reset the value
  200. if(m_hatelist[entity->GetID()] < 1) {
  201. m_hatelist[entity->GetID()] = 1;
  202. }
  203. }
  204. else
  205. m_hatelist.insert(std::pair<int32, sint32>(entity->GetID(), hate));
  206. entity->MHatedBy.lock();
  207. if (entity->HatedBy.count(m_body->GetID()) == 0)
  208. entity->HatedBy.insert(m_body->GetID());
  209. entity->MHatedBy.unlock();
  210. // Unlock the list
  211. bool ownerExistsAddHate = false;
  212. if(entity->IsPet() && entity->GetOwner()) {
  213. map<int32, sint32>::iterator itr = m_hatelist.find(entity->GetOwner()->GetID());
  214. if(itr == m_hatelist.end()) {
  215. ownerExistsAddHate = true;
  216. }
  217. }
  218. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  219. if(ownerExistsAddHate) {
  220. AddHate(entity->GetOwner(), 0);
  221. }
  222. }
  223. void Brain::ClearHate() {
  224. // Lock the hate list, we are altering the list so use a write lock
  225. MHateList.writelock(__FUNCTION__, __LINE__);
  226. map<int32, sint32>::iterator itr;
  227. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  228. Spawn* spawn = m_body->GetZone()->GetSpawnByID(itr->first);
  229. if (spawn && spawn->IsEntity())
  230. {
  231. ((Entity*)spawn)->MHatedBy.lock();
  232. ((Entity*)spawn)->HatedBy.erase(m_body->GetID());
  233. ((Entity*)spawn)->MHatedBy.unlock();
  234. }
  235. }
  236. // Clear the list
  237. m_hatelist.clear();
  238. // Unlock the hate list
  239. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  240. }
  241. void Brain::ClearHate(Entity* entity) {
  242. // Lock the hate list, we could potentially modify the list so use write lock
  243. MHateList.writelock(__FUNCTION__, __LINE__);
  244. // Check to see if the given entity is in the hate list
  245. if (m_hatelist.count(entity->GetID()) > 0)
  246. // Erase the entity from the hate list
  247. m_hatelist.erase(entity->GetID());
  248. entity->MHatedBy.lock();
  249. entity->HatedBy.erase(m_body->GetID());
  250. entity->MHatedBy.unlock();
  251. // Unlock the hate list
  252. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  253. }
  254. Entity* Brain::GetMostHated() {
  255. map<int32, sint32>::iterator itr;
  256. int32 ret = 0;
  257. sint32 hate = 0;
  258. // Lock the hate list, not going to alter it so use a read lock
  259. MHateList.readlock(__FUNCTION__, __LINE__);
  260. if (m_hatelist.size() > 0) {
  261. // Loop through the list looking for the entity that this NPC hates the most
  262. for(itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  263. // Compare the hate value for the current iteration to our stored highest value
  264. if(itr->second > hate) {
  265. // New high value store the entity
  266. ret = itr->first;
  267. // Store the value to compare with the rest of the entities
  268. hate = itr->second;
  269. }
  270. }
  271. }
  272. // Unlock the list
  273. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  274. Entity* hated = (Entity*)GetBody()->GetZone()->GetSpawnByID(ret);
  275. // Check the reult to see if it is still alive
  276. if(hated && hated->GetHP() <= 0) {
  277. // Entity we got was dead so remove it from the list
  278. ClearHate(hated);
  279. // Call this function again now that we removed the dead entity
  280. hated = GetMostHated();
  281. }
  282. // Return our result
  283. return hated;
  284. }
  285. sint8 Brain::GetHatePercentage(Entity* entity) {
  286. float percentage = 0.0;
  287. MHateList.readlock(__FUNCTION__, __LINE__);
  288. if (entity && m_hatelist.count(entity->GetID()) > 0 && m_hatelist[entity->GetID()] > 0) {
  289. sint32 total_hate = 0;
  290. map<int32, sint32>::iterator itr;
  291. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++)
  292. total_hate += itr->second;
  293. percentage = m_hatelist[entity->GetID()] / total_hate;
  294. }
  295. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  296. return (sint8)(percentage * 100);
  297. }
  298. void Brain::SendHateList(Client* client) {
  299. MHateList.readlock(__FUNCTION__, __LINE__);
  300. client->Message(CHANNEL_COLOR_YELLOW, "%s's HateList", m_body->GetName());
  301. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  302. map<int32, sint32>::iterator itr;
  303. if (m_hatelist.size() > 0) {
  304. // Loop through the list looking for the entity that this NPC hates the most
  305. for(itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  306. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID(itr->first);
  307. // Compare the hate value for the current iteration to our stored highest value
  308. if(ent) {
  309. client->Message(CHANNEL_COLOR_YELLOW, "%s : %i", ent->GetName(), itr->second);
  310. }
  311. else {
  312. client->Message(CHANNEL_COLOR_YELLOW, "%u (cannot identity spawn id->entity) : %i", itr->first, itr->second);
  313. }
  314. }
  315. }
  316. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  317. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  318. }
  319. vector<Entity*>* Brain::GetHateList() {
  320. vector<Entity*>* ret = new vector<Entity*>;
  321. map<int32, sint32>::iterator itr;
  322. // Lock the list
  323. MHateList.readlock(__FUNCTION__, __LINE__);
  324. // Loop over the list storing the values into the new list
  325. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  326. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID(itr->first);
  327. if (ent)
  328. ret->push_back(ent);
  329. }
  330. // Unlock the list
  331. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  332. // Return the copy of the list
  333. return ret;
  334. }
  335. void Brain::MoveCloser(Spawn* target) {
  336. if (target && m_body->GetFollowTarget() != target)
  337. m_body->SetFollowTarget(target, rule_manager.GetZoneRule(m_body->GetZoneID(), R_Combat, MaxCombatRange)->GetFloat());
  338. if (m_body->GetFollowTarget() && !m_body->following) {
  339. m_body->CalculateRunningLocation(true);
  340. //m_body->ClearRunningLocations();
  341. m_body->following = true;
  342. }
  343. }
  344. bool Brain::ProcessSpell(Entity* target, float distance) {
  345. if(rand()%100 > m_body->GetCastPercentage() || m_body->IsStifled() || m_body->IsFeared())
  346. return false;
  347. Spell* spell = m_body->GetNextSpell(target, distance);
  348. if(spell){
  349. Spawn* spell_target = 0;
  350. if(spell->GetSpellData()->friendly_spell == 1){
  351. vector<Spawn*>* group = m_body->GetSpawnGroup();
  352. if(group && group->size() > 0){
  353. vector<Spawn*>::iterator itr;
  354. for(itr = group->begin(); itr != group->end(); itr++){
  355. if((!spell_target && (*itr)->GetHP() > 0 && (*itr)->GetHP() < (*itr)->GetTotalHP()) || (spell_target && (*itr)->GetHP() > 0 && spell_target->GetHP() > (*itr)->GetHP()))
  356. spell_target = *itr;
  357. }
  358. }
  359. if(!spell_target)
  360. spell_target = m_body;
  361. safe_delete(group);
  362. }
  363. else
  364. spell_target = target;
  365. BrainCastSpell(spell, spell_target, false);
  366. return true;
  367. }
  368. return false;
  369. }
  370. bool Brain::BrainCastSpell(Spell* spell, Spawn* cast_on, bool calculate_run_loc) {
  371. if (spell) {
  372. if(calculate_run_loc) {
  373. m_body->CalculateRunningLocation(true);
  374. }
  375. m_body->GetZone()->ProcessSpell(spell, m_body, cast_on);
  376. m_spellRecovery = (int32)(Timer::GetCurrentTime2() + (spell->GetSpellData()->cast_time * 10) + (spell->GetSpellData()->recovery * 10) + 2000);
  377. return true;
  378. }
  379. return false;
  380. }
  381. bool Brain::CheckBuffs() {
  382. if (!m_body->GetZone()->GetSpellProcess() || m_body->EngagedInCombat() || m_body->IsCasting() || m_body->IsMezzedOrStunned() || !m_body->Alive() || m_body->IsStifled() || !HasRecovered())
  383. return false;
  384. Spell* spell = m_body->GetNextBuffSpell(m_body);
  385. bool casted_on = false;
  386. if(!(casted_on = BrainCastSpell(spell, m_body)) && m_body->IsNPC() && ((NPC*)m_body)->HasSpells()) {
  387. Spawn* target = nullptr;
  388. vector<Spawn*>* group = m_body->GetSpawnGroup();
  389. if(group && group->size() > 0){
  390. vector<Spawn*>::iterator itr;
  391. for(itr = group->begin(); itr != group->end(); itr++){
  392. Spawn* spawn = (*itr);
  393. if(spawn->IsEntity() && spawn != m_body) {
  394. if(target) {
  395. Spell* spell = m_body->GetNextBuffSpell(spawn);
  396. SpellEffects* se = ((Entity*)spawn)->GetSpellEffect(spell->GetSpellData()->id);
  397. if(!se && BrainCastSpell(spell, spawn)) {
  398. casted_on = true;
  399. break;
  400. }
  401. }
  402. }
  403. }
  404. }
  405. safe_delete(group);
  406. }
  407. return casted_on;
  408. }
  409. void Brain::ProcessMelee(Entity* target, float distance) {
  410. if(distance > rule_manager.GetZoneRule(m_body->GetZoneID(), R_Combat, MaxCombatRange)->GetFloat())
  411. MoveCloser((Spawn*)target);
  412. else {
  413. if (target) {
  414. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is within melee range of %s.", m_body->GetName(), target->GetName());
  415. if (m_body->AttackAllowed(target)) {
  416. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is allowed to attack %s.", m_body->GetName(), target->GetName());
  417. if (m_body->PrimaryWeaponReady() && !m_body->IsDazed() && !m_body->IsFeared()) {
  418. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s swings its primary weapon at %s.", m_body->GetName(), target->GetName());
  419. m_body->SetPrimaryLastAttackTime(Timer::GetCurrentTime2());
  420. m_body->MeleeAttack(target, distance, true);
  421. m_body->GetZone()->CallSpawnScript(m_body, SPAWN_SCRIPT_AUTO_ATTACK_TICK, target);
  422. }
  423. if (m_body->SecondaryWeaponReady() && !m_body->IsDazed()) {
  424. m_body->SetSecondaryLastAttackTime(Timer::GetCurrentTime2());
  425. m_body->MeleeAttack(target, distance, false);
  426. }
  427. }
  428. }
  429. }
  430. }
  431. bool Brain::HasRecovered() {
  432. if(m_spellRecovery > Timer::GetCurrentTime2())
  433. return false;
  434. m_spellRecovery = 0;
  435. return true;
  436. }
  437. void Brain::AddToEncounter(Entity* entity) {
  438. // If player pet then set the entity to the pets owner
  439. if (entity->IsPet() && entity->GetOwner() && !entity->IsBot()) {
  440. MEncounter.writelock(__FUNCTION__, __LINE__);
  441. bool success = AddToEncounter(entity->GetID());
  442. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  443. if(!success)
  444. return;
  445. entity = entity->GetOwner();
  446. }
  447. else if(entity->HasPet() && entity->GetPet()) {
  448. MEncounter.writelock(__FUNCTION__, __LINE__);
  449. bool success = AddToEncounter(entity->GetPet()->GetID());
  450. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  451. if(!success)
  452. return;
  453. }
  454. // If player or bot then get the group
  455. int32 group_id = 0;
  456. if (entity->IsPlayer() || entity->IsBot()) {
  457. m_playerInEncounter = true;
  458. if (entity->GetGroupMemberInfo())
  459. group_id = entity->GetGroupMemberInfo()->group_id;
  460. }
  461. // Insert the entity into the encounter list, if there is a group add all group members as well
  462. // TODO: add raid members
  463. MEncounter.writelock(__FUNCTION__, __LINE__);
  464. if (group_id > 0) {
  465. world.GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  466. deque<GroupMemberInfo*>::iterator itr;
  467. PlayerGroup* group = world.GetGroupManager()->GetGroup(group_id);
  468. if (group)
  469. {
  470. std::vector<int32> raidGroups;
  471. group->GetRaidGroups(&raidGroups);
  472. if(raidGroups.size() < 1)
  473. raidGroups.push_back(group_id);
  474. std::vector<int32>::iterator group_itr;
  475. for(group_itr = raidGroups.begin(); group_itr != raidGroups.end(); group_itr++) {
  476. group = world.GetGroupManager()->GetGroup((*group_itr));
  477. if(group) {
  478. group->MGroupMembers.readlock(__FUNCTION__, __LINE__);
  479. deque<GroupMemberInfo*>* members = group->GetMembers();
  480. for (itr = members->begin(); itr != members->end(); itr++) {
  481. if ((*itr)->member)
  482. {
  483. bool success = AddToEncounter((*itr)->member->GetID());
  484. if((*itr)->client && success) {
  485. m_encounter_playerlist.insert(make_pair((*itr)->client->GetPlayer()->GetCharacterID(), (*itr)->client->GetPlayer()->GetID()));
  486. }
  487. }
  488. }
  489. group->MGroupMembers.releasereadlock(__FUNCTION__, __LINE__);
  490. }
  491. }
  492. }
  493. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  494. }
  495. else {
  496. bool success = AddToEncounter(entity->GetID());
  497. if (success && entity->IsPlayer())
  498. {
  499. Player* plyr = (Player*)entity;
  500. m_encounter_playerlist.insert(make_pair(plyr->GetCharacterID(), entity->GetID()));
  501. }
  502. }
  503. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  504. }
  505. bool Brain::CheckLootAllowed(Entity* entity) {
  506. bool ret = false;
  507. vector<int32>::iterator itr;
  508. if (m_body)
  509. {
  510. if ((m_body->GetLootMethod() != GroupLootMethod::METHOD_LOTTO && m_body->GetLootMethod() != GroupLootMethod::METHOD_NEED_BEFORE_GREED) && m_body->GetLooterSpawnID() > 0 && m_body->GetLooterSpawnID() != entity->GetID()) {
  511. LogWrite(LOOT__INFO, 0, "Loot", "%s: CheckLootAllowed failed, looter spawn id %u does not match received %s(%u)", GetBody()->GetName(), m_body->GetLooterSpawnID(), entity->GetName(), entity->GetID());
  512. return false;
  513. }
  514. if (rule_manager.GetZoneRule(m_body->GetZoneID(), R_Loot, AllowChestUnlockByDropTime)->GetInt8()
  515. && m_body->GetChestDropTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime() + (rule_manager.GetZoneRule(m_body->GetZoneID(), R_Loot, ChestUnlockedTimeDrop)->GetInt32() * 1000)) {
  516. return true;
  517. }
  518. if (rule_manager.GetZoneRule(m_body->GetZoneID(), R_Loot, AllowChestUnlockByTrapTime)->GetInt8()
  519. && m_body->GetTrapOpenedTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime() + (rule_manager.GetZoneRule(m_body->GetZoneID(), R_Loot, ChestUnlockedTimeTrap)->GetInt32() * 1000)) {
  520. return true;
  521. }
  522. if ((m_body->GetLootMethod() == GroupLootMethod::METHOD_LOTTO || m_body->GetLootMethod() == GroupLootMethod::METHOD_NEED_BEFORE_GREED) && m_body->HasSpawnLootWindowCompleted(entity->GetID())) {
  523. LogWrite(LOOT__INFO, 0, "Loot", "%s: CheckLootAllowed failed, looter %s(%u) has already completed their lotto selections.", GetBody()->GetName(), entity->GetName(), entity->GetID());
  524. return false;
  525. }
  526. }
  527. // Check the encounter list to see if the given entity is in it, if so return true.
  528. MEncounter.readlock(__FUNCTION__, __LINE__);
  529. if (entity->IsPlayer())
  530. {
  531. Player* plyr = (Player*)entity;
  532. map<int32, int32>::iterator itr = m_encounter_playerlist.find(plyr->GetCharacterID());
  533. if (itr != m_encounter_playerlist.end())
  534. {
  535. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  536. return true;
  537. }
  538. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  539. return false;
  540. }
  541. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  542. if ((*itr) == entity->GetID()) {
  543. // found the entity in the encounter list, set return value to true and break the loop
  544. ret = true;
  545. break;
  546. }
  547. }
  548. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  549. return ret;
  550. }
  551. int8 Brain::GetEncounterSize() {
  552. int8 ret = 0;
  553. MEncounter.readlock(__FUNCTION__, __LINE__);
  554. ret = (int8)m_encounter.size();
  555. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  556. return ret;
  557. }
  558. vector<int32>* Brain::GetEncounter() {
  559. vector<int32>* ret = new vector<int32>;
  560. vector<int32>::iterator itr;
  561. // Lock the list
  562. MEncounter.readlock(__FUNCTION__, __LINE__);
  563. // Loop over the list storing the values into the new list
  564. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++)
  565. ret->push_back(*itr);
  566. // Unlock the list
  567. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  568. // Return the copy of the list
  569. return ret;
  570. }
  571. bool Brain::IsPlayerInEncounter(int32 char_id) {
  572. bool ret = false;
  573. MEncounter.readlock(__FUNCTION__, __LINE__);
  574. std::map<int32,int32>::iterator itr = m_encounter_playerlist.find(char_id);
  575. if(itr != m_encounter_playerlist.end()) {
  576. ret = true;
  577. }
  578. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  579. return ret;
  580. }
  581. bool Brain::IsEntityInEncounter(int32 id, bool skip_read_lock) {
  582. bool ret = false;
  583. if(!skip_read_lock) {
  584. MEncounter.readlock(__FUNCTION__, __LINE__);
  585. }
  586. vector<int32>::iterator itr;
  587. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  588. if ((*itr) == id) {
  589. // found the entity in the encounter list, set return value to true and break the loop
  590. ret = true;
  591. break;
  592. }
  593. }
  594. if(!skip_read_lock) {
  595. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  596. }
  597. return ret;
  598. }
  599. int32 Brain::CountPlayerBotInEncounter() {
  600. int32 count = 0;
  601. vector<int32>::iterator itr;
  602. MEncounter.readlock(__FUNCTION__, __LINE__);
  603. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  604. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  605. if (ent && (ent->IsPlayer() || ent->IsBot())) {
  606. count++;
  607. }
  608. }
  609. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  610. return count;
  611. }
  612. bool Brain::AddToEncounter(int32 id) {
  613. if(!IsEntityInEncounter(id, true)) {
  614. m_encounter.push_back(id);
  615. return true;
  616. }
  617. return false;
  618. }
  619. void Brain::ClearEncounter() {
  620. MEncounter.writelock(__FUNCTION__, __LINE__);
  621. if(m_body) {
  622. m_body->RemoveSpells(true);
  623. }
  624. m_encounter.clear();
  625. m_encounter_playerlist.clear();
  626. m_playerInEncounter = false;
  627. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  628. }
  629. void Brain::SendEncounterList(Client* client) {
  630. client->Message(CHANNEL_COLOR_YELLOW, "%s's EncounterList", m_body->GetName());
  631. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  632. vector<int32>::iterator itr;
  633. // Check the encounter list to see if the given entity is in it, if so return true.
  634. MEncounter.readlock(__FUNCTION__, __LINE__);
  635. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  636. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  637. // Compare the hate value for the current iteration to our stored highest value
  638. if(ent) {
  639. client->Message(CHANNEL_COLOR_YELLOW, "%s", ent->GetName());
  640. }
  641. else {
  642. client->Message(CHANNEL_COLOR_YELLOW, "%u (cannot identity spawn id->entity)", (*itr));
  643. }
  644. }
  645. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  646. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  647. }
  648. /* Example of how to extend the default AI */
  649. CombatPetBrain::CombatPetBrain(NPC* body) : Brain(body) {
  650. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  651. // to set up the AI properly
  652. }
  653. CombatPetBrain::~CombatPetBrain() {
  654. }
  655. void CombatPetBrain::Think() {
  656. // We are extending the base brain so make sure to call the parent Think() function.
  657. // If we want to override then we could remove Brain::Think()
  658. Brain::Think();
  659. // All this Brain does is make the pet follow its owner, the combat comes from the default brain
  660. if (GetBody()->EngagedInCombat() || !GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  661. return;
  662. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  663. // If owner is a player and player has stay set then return out
  664. if (GetBody()->GetOwner() && GetBody()->GetOwner()->IsPlayer() && ((Player*)GetBody()->GetOwner())->GetInfoStruct()->get_pet_movement() == 1)
  665. return;
  666. // Set target to owner
  667. Entity* target = GetBody()->GetOwner();
  668. GetBody()->SetTarget(target);
  669. // Get distance from the owner
  670. float distance = GetBody()->GetDistance(target);
  671. // If out of melee range then move closer
  672. if (distance > rule_manager.GetZoneRule(m_body->GetZoneID(), R_Combat, MaxCombatRange)->GetFloat())
  673. MoveCloser((Spawn*)target);
  674. }
  675. /* Example of how to override the default AI */
  676. NonCombatPetBrain::NonCombatPetBrain(NPC* body) : Brain(body) {
  677. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  678. // to set up the AI properly
  679. }
  680. NonCombatPetBrain::~NonCombatPetBrain() {
  681. }
  682. void NonCombatPetBrain::Think() {
  683. // All this Brain does is make the pet follow its owner
  684. if (!GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  685. return;
  686. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  687. // Set target to owner
  688. Entity* target = GetBody()->GetOwner();
  689. GetBody()->SetTarget(target);
  690. // Get distance from the owner
  691. float distance = GetBody()->GetDistance(target);
  692. // If out of melee range then move closer
  693. if (distance > rule_manager.GetZoneRule(m_body->GetZoneID(), R_Combat, MaxCombatRange)->GetFloat())
  694. MoveCloser((Spawn*)target);
  695. }
  696. BlankBrain::BlankBrain(NPC* body) : Brain(body) {
  697. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  698. // to set up the AI properly
  699. SetTick(50000);
  700. }
  701. BlankBrain::~BlankBrain() {
  702. }
  703. void BlankBrain::Think() {
  704. }
  705. LuaBrain::LuaBrain(NPC* body) : Brain(body) {
  706. }
  707. LuaBrain::~LuaBrain() {
  708. }
  709. void LuaBrain::Think() {
  710. if (!lua_interface)
  711. return;
  712. const char* script = GetBody()->GetSpawnScript();
  713. if(script) {
  714. if (!lua_interface->RunSpawnScript(script, "Think", GetBody(), GetBody()->GetTarget())) {
  715. lua_interface->LogError("LUA LuaBrain error: was unable to call the Think function in the spawn script (%s)", script);
  716. }
  717. }
  718. else {
  719. LogWrite(NPC_AI__ERROR, 0, "NPC_AI", "Lua brain set on a spawn that doesn't have a script...");
  720. }
  721. }
  722. DumbFirePetBrain::DumbFirePetBrain(NPC* body, Entity* target, int32 expire_time) : Brain(body) {
  723. m_expireTime = Timer::GetCurrentTime2() + expire_time;
  724. AddHate(target, INT_MAX);
  725. }
  726. DumbFirePetBrain::~DumbFirePetBrain() {
  727. }
  728. void DumbFirePetBrain::AddHate(Entity* entity, sint32 hate) {
  729. if (!GetMostHated())
  730. Brain::AddHate(entity, hate);
  731. }
  732. void DumbFirePetBrain::Think() {
  733. Entity* target = GetMostHated();
  734. if (target) {
  735. if (!GetBody()->IsMezzedOrStunned()) {
  736. // Set the NPC's target to the most hated entity if it is not already.
  737. if (GetBody()->GetTarget() != target) {
  738. GetBody()->SetTarget(target);
  739. GetBody()->FaceTarget(target, false);
  740. }
  741. // target needs to be identified before combat setting
  742. // If the NPC is not in combat then put them in combat
  743. if (!GetBody()->EngagedInCombat()) {
  744. //GetBody()->ClearRunningLocations();
  745. GetBody()->CalculateRunningLocation(true);
  746. GetBody()->InCombat(true);
  747. }
  748. float distance = GetBody()->GetDistance(target);
  749. if(GetBody()->CheckLoS(target) && !GetBody()->IsCasting() && (!HasRecovered() || !ProcessSpell(target, distance))) {
  750. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is attempting melee on %s.", GetBody()->GetName(), target->GetName());
  751. GetBody()->FaceTarget(target, false);
  752. ProcessMelee(target, distance);
  753. }
  754. }
  755. }
  756. else {
  757. // No hated target or time expired, kill this mob
  758. if (GetBody()->GetHP() > 0) {
  759. GetBody()->KillSpawn(GetBody());
  760. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because there is no target.");
  761. }
  762. }
  763. if (Timer::GetCurrentTime2() > m_expireTime) {
  764. if (GetBody()->GetHP() > 0) {
  765. GetBody()->KillSpawn(GetBody());
  766. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because timer expired.");
  767. }
  768. }
  769. }