NPC_AI.cpp 28 KB

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