World.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535
  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 <assert.h>
  17. #include "World.h"
  18. #include "Items/Items.h"
  19. #include "Items/Items_ToV.h"
  20. #include "Items/Items_DoV.h"
  21. #include "Spells.h"
  22. #include "client.h"
  23. #include "WorldDatabase.h"
  24. #include "../common/debug.h"
  25. #include "races.h"
  26. #include "classes.h"
  27. #include "VisualStates.h"
  28. #include "Appearances.h"
  29. #include "Skills.h"
  30. #include "LoginServer.h"
  31. #include "Quests.h"
  32. #include "Factions.h"
  33. #include "Guilds/Guild.h"
  34. #include "Collections/Collections.h"
  35. #include "Achievements/Achievements.h"
  36. #include "Recipes/Recipe.h"
  37. #include "Rules/Rules.h"
  38. #include "../common/Log.h"
  39. #include "Traits/Traits.h"
  40. #include "Chat/Chat.h"
  41. #include "Tradeskills/Tradeskills.h"
  42. #include "AltAdvancement/AltAdvancement.h"
  43. #include "LuaInterface.h"
  44. #include "HeroicOp/HeroicOp.h"
  45. #include "RaceTypes/RaceTypes.h"
  46. #include "LuaInterface.h"
  47. #include "../common/version.h"
  48. #include "Player.h"
  49. #include "Web/PeerManager.h"
  50. #include "Web/HTTPSClientPool.h"
  51. #include <boost/algorithm/string.hpp>
  52. #include <string>
  53. #include <iostream>
  54. MasterQuestList master_quest_list;
  55. MasterItemList master_item_list;
  56. MasterSpellList master_spell_list;
  57. MasterTraitList master_trait_list;
  58. MasterHeroicOPList master_ho_list;
  59. MasterSkillList master_skill_list;
  60. MasterFactionList master_faction_list;
  61. MasterCollectionList master_collection_list;
  62. MasterAchievementList master_achievement_list;
  63. MasterRecipeList master_recipe_list;
  64. MasterRecipeBookList master_recipebook_list;
  65. MasterTradeskillEventsList master_tradeskillevent_list;
  66. MasterAAList master_aa_list;
  67. MasterRaceTypeList race_types_list;
  68. MasterAANodeList master_tree_nodes;
  69. ClientList client_list;
  70. ZoneList zone_list;
  71. ZoneAuth zone_auth;
  72. int32 Spawn::next_id = 1;
  73. int32 WorldDatabase::next_id = 0;
  74. Commands commands;
  75. Variables variables;
  76. VisualStates visual_states;
  77. Appearances master_appearance_list;
  78. Classes classes;
  79. Races races;
  80. map<int16,OpcodeManager*>EQOpcodeManager;
  81. map<int16, int16> EQOpcodeVersions;
  82. WorldDatabase database;
  83. GuildList guild_list;
  84. Chat chat;
  85. Player player;
  86. extern ConfigReader configReader;
  87. extern LoginServer loginserver;
  88. extern World world;
  89. extern ZoneList zone_list;
  90. extern RuleManager rule_manager;
  91. extern LuaInterface* lua_interface;
  92. extern PeerManager peer_manager;
  93. extern sint32 numclients;
  94. extern PeerManager peer_manager;
  95. extern HTTPSClientPool peer_https_pool;
  96. World::World() : save_time_timer(300000), time_tick_timer(3000), vitality_timer(3600000), player_stats_timer(60000), server_stats_timer(60000), /*remove_grouped_player(30000),*/ guilds_timer(60000), lotto_players_timer(500), watchdog_timer(10000) {
  97. save_time_timer.Start();
  98. time_tick_timer.Start();
  99. vitality_timer.Start();
  100. player_stats_timer.Start();
  101. server_stats_timer.Start();
  102. //remove_grouped_player.Start();
  103. guilds_timer.Start();
  104. lotto_players_timer.Start();
  105. watchdog_timer.Start();
  106. xp_rate = -1;
  107. ts_xp_rate = -1;
  108. vitality_frequency = 0xFFFFFFFF;
  109. vitality_amount = -1;
  110. last_checked_time = 0;
  111. items_loaded = false;
  112. spells_loaded = false;
  113. achievments_loaded = false;
  114. merchant_inventory_items.clear();
  115. MHouseZones.SetName("World::m_houseZones");
  116. MPlayerHouses.SetName("World::m_playerHouses");
  117. MWorldMaps.SetName("World::MWorldMaps");
  118. MWorldRegionMaps.SetName("World::MWorldRegionMaps");
  119. world_webserver = nullptr;
  120. world_loaded = false;
  121. world_uptime = getCurrentTimestamp();
  122. }
  123. World::~World(){
  124. // At this point the log system is already shut down so no calls to LogWrite are allowed in any of the functions called by this deconstructor
  125. DeleteSpawns();
  126. if(database.GetStatus() == database.Connected)
  127. WriteServerStatistics();
  128. RemoveServerStatistics();
  129. DeleteMerchantsInfo();
  130. MutexMap<int32, LottoPlayer*>::iterator itr = lotto_players.begin();
  131. while (itr.Next())
  132. safe_delete(itr->second);
  133. map<int32, HouseZone*>::iterator itr2;
  134. for (itr2 = m_houseZones.begin(); itr2 != m_houseZones.end(); itr2++)
  135. safe_delete(itr2->second);
  136. m_houseZones.clear();
  137. tov_itemstat_conversion.clear();
  138. PurgeStartingLists();
  139. PurgeVoiceOvers();
  140. map<std::string, RegionMapRange*>::iterator itr3;
  141. for (itr3 = region_maps.begin(); itr3 != region_maps.end(); itr3++)
  142. safe_delete(itr3->second);
  143. map<std::string, MapRange*>::iterator itr4;
  144. for (itr4 = maps.begin(); itr4 != maps.end(); itr4++)
  145. safe_delete(itr4->second);
  146. PurgeNPCSpells();
  147. safe_delete(world_webserver);
  148. }
  149. void World::init(std::string web_ipaddr, int16 web_port, std::string cert_file, std::string key_file, std::string key_password, std::string hardcode_user, std::string hardcode_password){
  150. WorldDatabase::next_id = database.GetMaxHotBarID();
  151. LogWrite(COMMAND__DEBUG, 1, "Command", "-Loading Commands...");
  152. database.LoadCommandList();
  153. LogWrite(COMMAND__DEBUG, 1, "Command", "-Load Commands complete!");
  154. LogWrite(FACTION__DEBUG, 1, "Faction", "-Loading Factions...");
  155. database.LoadFactionList();
  156. LogWrite(FACTION__DEBUG, 1, "Faction", "-Load Factions complete!...");
  157. LogWrite(SKILL__DEBUG, 1, "Skill", "-Loading Skills...");
  158. database.LoadSkills();
  159. LogWrite(SKILL__DEBUG, 1, "Skill", "-Load Skills complete...");
  160. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `variables`...");
  161. database.LoadGlobalVariables();
  162. LogWrite(WORLD__DEBUG, 1, "World", "-Load `variables` complete!");
  163. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `appearances`...");
  164. database.LoadAppearanceMasterList();
  165. LogWrite(WORLD__DEBUG, 1, "World", "-Load `appearances` complete!");
  166. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `visual_states`...");
  167. database.LoadVisualStates();
  168. LogWrite(WORLD__DEBUG, 1, "World", "-Load `visual states` complete!");
  169. LoadStartingLists();
  170. LoadVoiceOvers();
  171. LogWrite(WORLD__DEBUG, 1, "World", "-Loading EXP Curve From DB...");
  172. player.InitXPTable();
  173. LogWrite(WORLD__DEBUG, 1, "World", "-Loading EXP Curve From DB Complete!");
  174. LogWrite(WORLD__DEBUG, 1, "World", "-Setting system parameters...");
  175. Variable* var = variables.FindVariable("gametime");
  176. const char* time_string = 0;
  177. char default_time[] = "0/0/3800 8:30";
  178. if(var)
  179. time_string = var->GetValue();
  180. if(!time_string)
  181. time_string = default_time;
  182. int year, month, day, hour, minute;
  183. sscanf (time_string, "%d/%d/%d %d:%d", &month, &day, &year, &hour, &minute);
  184. LogWrite(WORLD__DEBUG, 3, "World", "--Setting World Time to %s...", time_string);
  185. world_time.month = month;
  186. world_time.day = day;
  187. world_time.year = year;
  188. world_time.hour = hour;
  189. world_time.minute = minute;
  190. LogWrite(WORLD__DEBUG, 3, "World", "--Loading Vitality Information...");
  191. LoadVitalityInformation();
  192. LogWrite(WORLD__DEBUG, 3, "World", "--Loading Server Statistics...");
  193. database.LoadServerStatistics();
  194. LogWrite(WORLD__DEBUG, 3, "World", "--Setting Server Start Time...");
  195. UpdateServerStatistic(STAT_SERVER_START_TIME, Timer::GetUnixTimeStamp(), true);
  196. LogWrite(WORLD__DEBUG, 3, "World", "--Resetting Accepted Connections to 0...");
  197. UpdateServerStatistic(STAT_SERVER_ACCEPTED_CONNECTION, 0, true);
  198. LogWrite(WORLD__DEBUG, 3, "World", "--Resetting Active Zones to 0...");
  199. UpdateServerStatistic(STAT_SERVER_NUM_ACTIVE_ZONES, 0, true);
  200. // Clear all online players at server startup
  201. LogWrite(WORLD__DEBUG, 3, "World", "--Resetting characters online flags...");
  202. database.ToggleCharacterOnline();
  203. LogWrite(WORLD__DEBUG, 1, "World", "-Set system parameters complete!");
  204. LogWrite(RULESYS__DEBUG, 1, "Rules", "-Loading Rule Sets...");
  205. database.LoadRuleSets();
  206. LogWrite(RULESYS__DEBUG, 1, "Rules", "-Load Rule Sets complete!");
  207. LoadItemBlueStats();
  208. //PopulateTOVStatMap();
  209. group_buff_updates.Start(rule_manager.GetGlobalRule(R_Client, GroupSpellsTimer)->GetInt32());
  210. bool web_success = false;
  211. if(web_ipaddr.size() > 0 && web_port > 0) {
  212. try {
  213. world_webserver = new WebServer(web_ipaddr, web_port, cert_file, key_file, key_password, hardcode_user, hardcode_password);
  214. // status providers
  215. world_webserver->register_route("/status", World::Web_worldhandle_status);
  216. world_webserver->register_route("/clients", World::Web_worldhandle_clients);
  217. world_webserver->register_route("/zones", World::Web_worldhandle_zones);
  218. // administrative commands
  219. world_webserver->register_route("/setadminstatus", World::Web_worldhandle_setadminstatus);
  220. world_webserver->register_route("/reloadrules", World::Web_worldhandle_reloadrules);
  221. world_webserver->register_route("/reloadcommand", World::Web_worldhandle_reloadcommand);
  222. // peering capabilities
  223. world_webserver->register_route("/addpeer", World::Web_worldhandle_addpeer);
  224. world_webserver->register_route("/addcharauth", World::Web_worldhandle_addcharauth);
  225. world_webserver->register_route("/startzone", World::Web_worldhandle_startzone);
  226. world_webserver->register_route("/sendglobalmessage", World::Web_worldhandle_sendglobalmessage);
  227. world_webserver->register_route("/newgroup", World::Web_worldhandle_newgroup);
  228. world_webserver->register_route("/addgroupmember", World::Web_worldhandle_addgroupmember);
  229. world_webserver->register_route("/removegroupmember", World::Web_worldhandle_removegroupmember);
  230. world_webserver->register_route("/disbandgroup", World::Web_worldhandle_disbandgroup);
  231. world_webserver->register_route("/createguild", World::Web_worldhandle_createguild);
  232. world_webserver->register_route("/addguildmember", World::Web_worldhandle_addguildmember);
  233. world_webserver->register_route("/removeguildmember", World::Web_worldhandle_removeguildmember);
  234. world_webserver->register_route("/setguildpermission", World::Web_worldhandle_setguildpermission);
  235. world_webserver->register_route("/setguildeventfilter", World::Web_worldhandle_setguildeventfilter);
  236. world_webserver->run();
  237. LogWrite(INIT__INFO, 0, "Init", "World Web Server is listening on %s:%u..", web_ipaddr.c_str(), web_port);
  238. web_success = true;
  239. }
  240. catch (const std::exception& e) {
  241. LogWrite(INIT__ERROR, 0, "Init", "World Web Server failed to listen on %s:%u due to reason %s", web_ipaddr.c_str(), web_port, e.what());
  242. }
  243. }
  244. if(!web_success) {
  245. LogWrite(INIT__WARNING, 0, "Init", "World Web Server not started/configured, cannot attempt peering.");
  246. return;
  247. }
  248. try {
  249. std::map<std::string, int16> peers = net.GetWebPeers();
  250. std::map<std::string, int16>::iterator peer_itr;
  251. if(peers.size() > 0) {
  252. net.is_primary = false;
  253. for(peer_itr = peers.begin(); peer_itr != peers.end(); peer_itr++) {
  254. if(net.GetWebWorldAddress() == peer_itr->first && net.GetWebWorldPort() == peer_itr->second)
  255. continue; // no good you can't add yourself
  256. std::string portNum = std::to_string(peer_itr->second);
  257. std::string peerName = "eq2emu_" + peer_itr->first + "_" + portNum;
  258. peer_manager.addPeer(peerName, PeeringStatus::SECONDARY, "", "", 0, peer_itr->first, peer_itr->second);
  259. peer_https_pool.addPeerClient(peerName, peer_itr->first, std::to_string(peer_itr->second), "/addpeer");
  260. }
  261. }
  262. }
  263. catch (const std::exception& e) {
  264. LogWrite(INIT__ERROR, 0, "Init", "World Web Server failed to listen on %s:%u due to reason %s", web_ipaddr.c_str(), web_port, e.what());
  265. }
  266. }
  267. PacketStruct* World::GetWorldTime(int16 version){
  268. MWorldTime.readlock(__FUNCTION__, __LINE__);
  269. PacketStruct* packet = configReader.getStruct("WS_GameWorldTime", version);
  270. if(packet){
  271. packet->setDataByName("year", world_time.year);
  272. packet->setDataByName("month", world_time.month);
  273. packet->setDataByName("day", world_time.day);
  274. packet->setDataByName("hour", world_time.hour);
  275. packet->setDataByName("minute", world_time.minute);
  276. packet->setDataByName("unknown", 250);
  277. packet->setDataByName("unix_time", Timer::GetUnixTimeStamp());
  278. packet->setDataByName("unknown2", 1);
  279. }
  280. MWorldTime.releasereadlock(__FUNCTION__, __LINE__);
  281. return packet;
  282. }
  283. float World::GetXPRate(){
  284. xp_rate = rule_manager.GetGlobalRule(R_Player, XPMultiplier)->GetFloat();
  285. LogWrite(WORLD__DEBUG, 0, "World", "Setting Global XP Rate to: %.2f", xp_rate);
  286. return xp_rate;
  287. }
  288. float World::GetTSXPRate(){
  289. ts_xp_rate = rule_manager.GetGlobalRule(R_Player, TSXPMultiplier)->GetFloat();
  290. LogWrite(WORLD__DEBUG, 0, "World", "Setting Global Tradeskill XP Rate to: %.2f", ts_xp_rate);
  291. return ts_xp_rate;
  292. }
  293. void World::Process(){
  294. if(last_checked_time > Timer::GetCurrentTime2())
  295. return;
  296. last_checked_time = Timer::GetCurrentTime2() + 1000;
  297. if(save_time_timer.Check())
  298. {
  299. MWorldTime.readlock(__FUNCTION__, __LINE__);
  300. database.SaveWorldTime(&world_time);
  301. MWorldTime.releasereadlock(__FUNCTION__, __LINE__);
  302. }
  303. if(time_tick_timer.Check())
  304. {
  305. MWorldTime.writelock(__FUNCTION__, __LINE__);
  306. WorldTimeTick();
  307. MWorldTime.releasewritelock(__FUNCTION__, __LINE__);
  308. }
  309. if(lua_interface)
  310. lua_interface->Process();
  311. if(vitality_timer.Check())
  312. UpdateVitality();
  313. if (player_stats_timer.Check())
  314. WritePlayerStatistics();
  315. if (server_stats_timer.Check())
  316. WriteServerStatistics();
  317. /*if(remove_grouped_player.Check())
  318. CheckRemoveGroupedPlayer();*/
  319. if (group_buff_updates.Check())
  320. GetGroupManager()->UpdateGroupBuffs();
  321. if (guilds_timer.Check())
  322. SaveGuilds();
  323. if (lotto_players_timer.Check())
  324. CheckLottoPlayers();
  325. if(watchdog_timer.Check())
  326. zone_list.WatchdogHeartbeat();
  327. }
  328. vector<Variable*>* World::GetClientVariables(){
  329. return variables.GetVariables("cl_");
  330. }
  331. void World::LoadVitalityInformation()
  332. {
  333. int32 timestamp = Timer::GetUnixTimeStamp();
  334. int32 diff = 0;
  335. // fetch vitalitytimer value from `variables` table
  336. Variable* timer_var = variables.FindVariable("vitalitytimer");
  337. if(timer_var)
  338. {
  339. try
  340. {
  341. diff = timestamp - atoul(timer_var->GetValue());
  342. diff *= 1000; //convert seconds to milliseconds
  343. }
  344. catch(...)
  345. {
  346. LogWrite(WORLD__ERROR, 0, "World", "Error parsing vitalitytimer, value: %s", timer_var->GetValue());
  347. }
  348. }
  349. // Now using Rules System to set vitality parameters
  350. vitality_amount = rule_manager.GetGlobalRule(R_Player, VitalityAmount)->GetFloat();
  351. vitality_frequency = rule_manager.GetGlobalRule(R_Player, VitalityFrequency)->GetInt32();
  352. vitality_frequency *= 1000; //convert seconds to milliseconds
  353. if(diff >= vitality_frequency)
  354. UpdateVitality(); //update now
  355. else
  356. vitality_timer.SetTimer(vitality_frequency - diff);
  357. }
  358. void World::UpdateVitality()
  359. {
  360. // push new vitalitytimer to `variables` table
  361. database.UpdateVitality(Timer::GetUnixTimeStamp(), vitality_amount);
  362. if(vitality_timer.GetDuration() != vitality_frequency)
  363. vitality_timer.SetTimer(vitality_frequency);
  364. zone_list.UpdateVitality(vitality_amount);
  365. }
  366. void ZoneList::UpdateVitality(float amount)
  367. {
  368. list<ZoneServer*>::iterator zone_iter;
  369. ZoneServer* tmp = 0;
  370. MZoneList.readlock(__FUNCTION__, __LINE__);
  371. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++)
  372. {
  373. tmp = *zone_iter;
  374. if(tmp)
  375. tmp->UpdateVitality(amount);
  376. }
  377. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  378. }
  379. void ZoneList::SendTimeUpdate()
  380. {
  381. list<ZoneServer*>::iterator zone_iter;
  382. ZoneServer* tmp = 0;
  383. MZoneList.readlock(__FUNCTION__, __LINE__);
  384. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++)
  385. {
  386. tmp = *zone_iter;
  387. if(tmp && !tmp->isZoneShuttingDown())
  388. tmp->WorldTimeUpdateTrigger();
  389. }
  390. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  391. }
  392. // should already be ran inside MWorldTime
  393. void World::WorldTimeTick(){
  394. world_time.minute++;
  395. //I know it looks complicated, but the nested ifs are to avoid checking all of them every 3 seconds
  396. if(world_time.minute >= 60){ // >= in case of bad time from db
  397. world_time.minute = 0;
  398. world_time.hour++;
  399. if(world_time.hour >= 24){
  400. world_time.hour = 0;
  401. world_time.day++;
  402. if(world_time.day>=30){
  403. world_time.day = 0;
  404. world_time.month++;
  405. if(world_time.month >= 12){
  406. world_time.month = 0;
  407. world_time.year++;
  408. }
  409. }
  410. }
  411. }
  412. }
  413. ZoneList::ZoneList() {
  414. MZoneList.SetName("ZoneList::MZoneList");
  415. }
  416. ZoneList::~ZoneList() {
  417. list<ZoneServer*>::iterator zone_iter;
  418. ZoneServer* zs = 0;
  419. for(zone_iter=zlist.begin(); zone_iter!=zlist.end();){
  420. zs = *zone_iter;
  421. zone_iter = zlist.erase(zone_iter);
  422. safe_delete(zs);
  423. }
  424. }
  425. void ZoneList::CheckFriendList(Client* client) {
  426. LogWrite(WORLD__DEBUG, 0, "World", "Sending FriendList...");
  427. MClientList.lock();
  428. map<string,Client*>::iterator itr;
  429. for(itr = client_map.begin(); itr != client_map.end(); itr++){
  430. if(itr->second != client && itr->second){
  431. if(itr->second->GetPlayer()->IsFriend(client->GetPlayer()->GetName())){
  432. itr->second->SendFriendList();
  433. itr->second->Message(CHANNEL_COLOR_CHAT_RELATIONSHIP, "Friend: %s has logged in.", client->GetPlayer()->GetName());
  434. }
  435. }
  436. }
  437. MClientList.unlock();
  438. }
  439. void ZoneList::CheckFriendZoned(Client* client){
  440. MClientList.lock();
  441. map<string,Client*>::iterator itr;
  442. for(itr = client_map.begin(); itr != client_map.end(); itr++){
  443. if(itr->second != client && itr->second){
  444. if(itr->second->GetPlayer()->IsFriend(client->GetPlayer()->GetName())){
  445. itr->second->SendFriendList();
  446. }
  447. }
  448. }
  449. MClientList.unlock();
  450. }
  451. bool ZoneList::HandleGlobalChatMessage(Client* from, char* to, int16 channel, const char* message, const char* channel_name, int32 current_language_id){
  452. if (!from) {
  453. LogWrite(WORLD__ERROR, 0, "World", "HandleGlobalChatMessage() called with an invalid client");
  454. return false;
  455. }
  456. if(channel == CHANNEL_PRIVATE_TELL){
  457. Client* find_client = zone_list.GetClientByCharName(to);
  458. if(find_client && find_client->GetPlayer()->IsIgnored(from->GetPlayer()->GetName()))
  459. return false;
  460. std::string peerId = peer_manager.GetCharacterPeerId(std::string(to));
  461. if(peerId.size() > 0) {
  462. std::shared_ptr<Peer> peer = peer_manager.getPeerById(peerId);
  463. if(peer != nullptr) {
  464. boost::property_tree::ptree root;
  465. root.put("from_name", from->GetPlayer()->GetName());
  466. root.put("to_name", to);
  467. root.put("message", message);
  468. root.put("from_language", current_language_id);
  469. root.put("channel", channel);
  470. std::ostringstream jsonStream;
  471. boost::property_tree::write_json(jsonStream, root);
  472. std::string jsonPayload = jsonStream.str();
  473. LogWrite(PEERING__DEBUG, 0, "Peering", "%s: Notify Peer %s of Tell from %s to %s", __FUNCTION__, peerId.c_str(), from->GetPlayer()->GetName(), to);
  474. peer_https_pool.sendPostRequestToPeerAsync(peer->id, peer->webAddr, std::to_string(peer->webPort), "/sendglobalmessage", jsonPayload);
  475. return true;
  476. }
  477. }
  478. if(!find_client) {
  479. return false;
  480. }
  481. if(find_client == from)
  482. {
  483. from->Message(CHANNEL_COLOR_RED,"You must be very lonely...(ERROR: Cannot send tell to self)");
  484. }
  485. else
  486. {
  487. const char* whoto = find_client->GetPlayer()->GetName();
  488. find_client->HandleTellMessage(from->GetPlayer()->GetName(), message, whoto, from->GetPlayer()->GetCurrentLanguage());
  489. from->HandleTellMessage(from->GetPlayer()->GetName(), message, whoto, from->GetPlayer()->GetCurrentLanguage());
  490. if (find_client->GetPlayer()->get_character_flag(CF_AFK)) {
  491. find_client->HandleTellMessage(find_client->GetPlayer()->GetName(), find_client->GetPlayer()->GetAwayMessage().c_str(),whoto, from->GetPlayer()->GetCurrentLanguage());
  492. from->HandleTellMessage(find_client->GetPlayer()->GetName(), find_client->GetPlayer()->GetAwayMessage().c_str(),whoto, from->GetPlayer()->GetCurrentLanguage());
  493. }
  494. }
  495. }
  496. else if(channel == CHANNEL_GROUP_SAY) {
  497. GroupMemberInfo* gmi = from->GetPlayer()->GetGroupMemberInfo();
  498. if(gmi) {
  499. world.GetGroupManager()->GroupMessage(gmi->group_id, message);
  500. peer_manager.SendPeersChannelMessage(gmi->group_id, "", std::string(message), CHANNEL_GROUP_SAY, from->GetPlayer()->GetCurrentLanguage());
  501. }
  502. }
  503. else{
  504. if(channel == CHANNEL_OUT_OF_CHARACTER) {
  505. peer_manager.SendPeersChannelMessage(0, std::string(from->GetPlayer()->GetName()), std::string(message), CHANNEL_OUT_OF_CHARACTER, from->GetPlayer()->GetCurrentLanguage());
  506. }
  507. list<ZoneServer*>::iterator zone_iter;
  508. ZoneServer* zs = 0;
  509. MZoneList.readlock(__FUNCTION__, __LINE__);
  510. for(zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  511. zs = *zone_iter;
  512. if(zs)
  513. zs->HandleChatMessage(from->GetPlayer(), to, channel, message, 0, channel_name, true, current_language_id);
  514. }
  515. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  516. }
  517. return true;
  518. }
  519. void ZoneList::SendZoneWideChannelMessage(std::string fromName, const char* to, int16 channel, const char* message, float distance, const char* channel_name, int32 language) {
  520. list<ZoneServer*>::iterator zone_iter;
  521. ZoneServer* zs = 0;
  522. MZoneList.readlock(__FUNCTION__, __LINE__);
  523. for(zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  524. zs = *zone_iter;
  525. if(zs)
  526. zs->HandleChatMessage(fromName, to, channel, message, distance, channel_name, language);
  527. }
  528. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  529. }
  530. void ZoneList::LoadSpellProcess(){
  531. list<ZoneServer*>::iterator zone_iter;
  532. ZoneServer* zone = 0;
  533. MZoneList.readlock(__FUNCTION__, __LINE__);
  534. for (zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  535. zone = *zone_iter;
  536. if (zone)
  537. zone->LoadSpellProcess();
  538. }
  539. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  540. }
  541. void ZoneList::DeleteSpellProcess(){
  542. list<ZoneServer*>::iterator zone_iter;
  543. ZoneServer* zone = 0;
  544. MZoneList.readlock(__FUNCTION__, __LINE__);
  545. for (zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  546. zone = *zone_iter;
  547. if (zone)
  548. zone->DeleteSpellProcess();
  549. }
  550. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  551. }
  552. void ZoneList::HandleGlobalBroadcast(const char* message) {
  553. list<ZoneServer*>::iterator zone_iter;
  554. ZoneServer* zone = 0;
  555. MZoneList.readlock(__FUNCTION__, __LINE__);
  556. for (zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  557. zone = *zone_iter;
  558. if (zone)
  559. zone->HandleBroadcast(message);
  560. }
  561. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  562. }
  563. void ZoneList::HandleGlobalAnnouncement(const char* message) {
  564. list<ZoneServer*>::iterator zone_iter;
  565. ZoneServer* zone = 0;
  566. MZoneList.readlock(__FUNCTION__, __LINE__);
  567. for (zone_iter=zlist.begin(); zone_iter!=zlist.end();zone_iter++){
  568. zone = *zone_iter;
  569. if (zone)
  570. zone->HandleAnnouncement(message);
  571. }
  572. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  573. }
  574. int32 ZoneList::Count(){
  575. return zlist.size();
  576. }
  577. void ZoneList::Add(ZoneServer* zone) {
  578. MZoneList.writelock(__FUNCTION__, __LINE__);
  579. zlist.push_back(zone);
  580. MZoneList.releasewritelock(__FUNCTION__, __LINE__);
  581. }
  582. void ZoneList::Remove(ZoneServer* zone) {
  583. const char* zoneName = zone->GetZoneName();
  584. MZoneList.writelock(__FUNCTION__, __LINE__);
  585. zlist.remove(zone);
  586. MZoneList.releasewritelock(__FUNCTION__, __LINE__);
  587. bool alternativeZone = GetZone(nullptr, 0, std::string(zoneName), false, false, false, false, true);
  588. if(!alternativeZone && !rule_manager.GetZoneRule(zone->GetZoneID(), R_World, MemoryCacheZoneMaps)->GetBool()) {
  589. world.RemoveMaps(std::string(zoneName));
  590. }
  591. }
  592. bool ZoneList::GetZone(ZoneChangeDetails* zone_details, int32 opt_zone_id, std::string opt_zone_name, bool loadZone, bool skip_existing_zones, bool increment_zone, bool check_peers, bool check_instances, bool only_always_loaded, bool skip_self) {
  593. list<ZoneServer*>::iterator zone_iter;
  594. ZoneServer* tmp = 0;
  595. ZoneServer* ret = 0;
  596. if(!skip_existing_zones) {
  597. if(!skip_self) {
  598. MZoneList.readlock(__FUNCTION__, __LINE__);
  599. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  600. tmp = *zone_iter;
  601. if(!check_instances && tmp->IsInstanceZone())
  602. continue;
  603. if(!tmp->isZoneShuttingDown() && ((opt_zone_id > 0 && tmp->GetZoneID() == opt_zone_id) || (opt_zone_name.length() > 0 && strncasecmp(tmp->GetZoneName(), opt_zone_name.c_str(), opt_zone_name.length())==0))){
  604. if(tmp->NumPlayers() < 30 || tmp->IsCityZone()) {
  605. ret = tmp;
  606. if(increment_zone) {
  607. ret->IncrementIncomingClients();
  608. }
  609. break;
  610. }
  611. }
  612. }
  613. tmp = nullptr;
  614. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  615. }
  616. if(!ret && check_peers) {
  617. std::string peerId = peer_manager.getZonePeerId(opt_zone_name, opt_zone_id, 0, zone_details, only_always_loaded);
  618. if(peerId.size() > 0) {
  619. LogWrite(WORLD__ERROR, 0, "World", "Peer %s is providing zone %s for zone %s id %u", peerId.c_str(), zone_details->zoneName.c_str(), opt_zone_name.c_str(), opt_zone_id);
  620. return true;
  621. }
  622. }
  623. }
  624. if(ret) {
  625. tmp = ret;
  626. }
  627. else if (loadZone) {
  628. if(opt_zone_name.length() < 1) {
  629. opt_zone_name = database.GetZoneName(opt_zone_id);
  630. }
  631. if(opt_zone_name.length() > 0){
  632. std::shared_ptr<Peer> peer = peer_manager.getHealthyPeerWithLeastClients();
  633. if(check_peers && peer != nullptr) {
  634. tmp = new ZoneServer(opt_zone_name.c_str());
  635. database.LoadZoneInfo(tmp);
  636. boost::property_tree::ptree root;
  637. root.put("instance_id", 0);
  638. root.put("zone_name", opt_zone_name);
  639. root.put("zone_id", std::to_string(opt_zone_id));
  640. root.put("always_loaded", only_always_loaded);
  641. std::ostringstream jsonStream;
  642. boost::property_tree::write_json(jsonStream, root);
  643. std::string jsonPayload = jsonStream.str();
  644. LogWrite(PEERING__DEBUG, 0, "Peering", "%s: Notify Peer %s StartZone %s (%u), always loaded %u", __FUNCTION__, peer->id.c_str(), opt_zone_name.c_str(), opt_zone_id, only_always_loaded);
  645. peer_https_pool.sendPostRequestToPeerAsync(peer->id, peer->webAddr, std::to_string(peer->webPort), "/startzone", jsonPayload);
  646. peer_manager.setZonePeerData(zone_details, peer->id, peer->worldAddr, peer->internalWorldAddr, peer->worldPort, peer->webAddr, peer->webPort, std::string(tmp->GetZoneFile()), std::string(tmp->GetZoneName()), tmp->GetZoneID(),
  647. tmp->GetInstanceID(), tmp->GetSafeX(), tmp->GetSafeY(), tmp->GetSafeZ(), tmp->GetSafeHeading(),
  648. tmp->GetZoneLockState(), tmp->GetMinimumStatus(), tmp->GetMinimumLevel(), tmp->GetMaximumLevel(),
  649. tmp->GetMinimumVersion(), tmp->GetDefaultLockoutTime(), tmp->GetDefaultReenterTime(),
  650. tmp->GetInstanceType(), tmp->NumPlayers());
  651. safe_delete(tmp);
  652. return true;
  653. }
  654. else {
  655. tmp = new ZoneServer(opt_zone_name.c_str());
  656. database.LoadZoneInfo(tmp);
  657. tmp->Init();
  658. tmp->SetAlwaysLoaded(only_always_loaded);
  659. }
  660. }
  661. }
  662. if(tmp) {
  663. peer_manager.setZonePeerDataSelf(zone_details, std::string(tmp->GetZoneFile()), std::string(tmp->GetZoneName()), tmp->GetZoneID(),
  664. tmp->GetInstanceID(), tmp->GetSafeX(), tmp->GetSafeY(), tmp->GetSafeZ(), tmp->GetSafeHeading(),
  665. tmp->GetZoneLockState(), tmp->GetMinimumStatus(), tmp->GetMinimumLevel(), tmp->GetMaximumLevel(),
  666. tmp->GetMinimumVersion(), tmp->GetDefaultLockoutTime(), tmp->GetDefaultReenterTime(),
  667. tmp->GetInstanceType(), tmp->NumPlayers(), tmp);
  668. if(zone_details) {
  669. zone_details->zonePtr = (void*)tmp;
  670. }
  671. }
  672. return (tmp != nullptr) ? true : false;
  673. }
  674. bool ZoneList::GetZoneByInstance(ZoneChangeDetails* zone_details, int32 instance_id, int32 zone_id, bool loadZone, bool skip_existing_zones, bool increment_zone, bool check_peers) {
  675. list<ZoneServer*>::iterator zone_iter;
  676. ZoneServer* tmp = 0;
  677. ZoneServer* ret = 0;
  678. if(!skip_existing_zones) {
  679. MZoneList.readlock(__FUNCTION__, __LINE__);
  680. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  681. tmp = *zone_iter;
  682. if(!tmp->isZoneShuttingDown() && tmp->IsInstanceZone() && tmp->GetInstanceID() == instance_id){
  683. ret = tmp;
  684. if(increment_zone) {
  685. ret->IncrementIncomingClients();
  686. }
  687. break;
  688. }
  689. }
  690. tmp = nullptr;
  691. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  692. if(!ret && check_peers) {
  693. std::string peerId = peer_manager.getZonePeerId("", 0, instance_id, zone_details);
  694. if(peerId.size() > 0) {
  695. LogWrite(WORLD__ERROR, 0, "World", "Peer %s is providing instanced zone %s for zone id %u instance id %u", peerId.c_str(), zone_details->zoneName, zone_id, instance_id);
  696. return true;
  697. }
  698. }
  699. }
  700. if(ret) {
  701. tmp = ret;
  702. }
  703. else if ( loadZone && zone_id > 0 ){
  704. string zonename = database.GetZoneName(zone_id);
  705. if(zonename.length() > 0){
  706. std::shared_ptr<Peer> peer = peer_manager.getHealthyPeerWithLeastClients();
  707. if(check_peers && peer != nullptr && instance_id > 0) {
  708. tmp = new ZoneServer(zonename.c_str());
  709. database.LoadZoneInfo(tmp);
  710. boost::property_tree::ptree root;
  711. root.put("instance_id", instance_id);
  712. root.put("zone_name", zonename);
  713. root.put("zone_id", std::to_string(zone_id));
  714. root.put("always_loaded", false);
  715. std::ostringstream jsonStream;
  716. boost::property_tree::write_json(jsonStream, root);
  717. std::string jsonPayload = jsonStream.str();
  718. LogWrite(PEERING__DEBUG, 0, "Peering", "%s: Notify Peer %s StartZone %s (%u), instance %u", __FUNCTION__, peer->id.c_str(), zonename.c_str(), zone_id, instance_id);
  719. peer_https_pool.sendPostRequestToPeerAsync(peer->id, peer->webAddr, std::to_string(peer->webPort), "/startzone", jsonPayload);
  720. peer_manager.setZonePeerData(zone_details, peer->id, peer->worldAddr, peer->internalWorldAddr, peer->worldPort, peer->webAddr, peer->webPort, std::string(tmp->GetZoneFile()), std::string(tmp->GetZoneName()), tmp->GetZoneID(),
  721. instance_id, tmp->GetSafeX(), tmp->GetSafeY(), tmp->GetSafeZ(), tmp->GetSafeHeading(),
  722. tmp->GetZoneLockState(), tmp->GetMinimumStatus(), tmp->GetMinimumLevel(), tmp->GetMaximumLevel(),
  723. tmp->GetMinimumVersion(), tmp->GetDefaultLockoutTime(), tmp->GetDefaultReenterTime(),
  724. tmp->GetInstanceType(), tmp->NumPlayers());
  725. safe_delete(tmp);
  726. return true;
  727. }
  728. else {
  729. tmp = new ZoneServer(zonename.c_str());
  730. // the player is trying to preload an already existing instance but it isn't loaded
  731. if ( instance_id > 0 )
  732. tmp->SetupInstance(instance_id);
  733. database.LoadZoneInfo(tmp);
  734. tmp->Init();
  735. }
  736. }
  737. }
  738. if(tmp) {
  739. peer_manager.setZonePeerDataSelf(zone_details, std::string(tmp->GetZoneFile()), std::string(tmp->GetZoneName()), tmp->GetZoneID(),
  740. tmp->GetInstanceID(), tmp->GetSafeX(), tmp->GetSafeY(), tmp->GetSafeZ(), tmp->GetSafeHeading(),
  741. tmp->GetZoneLockState(), tmp->GetMinimumStatus(), tmp->GetMinimumLevel(),
  742. tmp->GetMaximumLevel(), tmp->GetMinimumVersion(), tmp->GetDefaultLockoutTime(), tmp->GetDefaultReenterTime(),
  743. tmp->GetInstanceType(), tmp->NumPlayers(), tmp);
  744. zone_details->zonePtr = (void*)tmp;
  745. }
  746. return (tmp != nullptr) ? true : false;
  747. }
  748. bool PeerManager::IsClientConnectedPeer(int32 account_id) {
  749. for (auto& [peerId, peer] : peers) {
  750. if(peer->healthCheck.status != HealthStatus::OK)
  751. continue;
  752. try {
  753. std::lock_guard<std::mutex> lock(peer->dataMutex);
  754. for (const auto& zone : peer->client_tree->get_child("Clients")) {
  755. // Access each field within the current zone
  756. int32 client_acct_id = zone.second.get<int32>("account_id");
  757. bool is_linkdead = zone.second.get<bool>("is_linkdead");
  758. bool is_zoning = zone.second.get<bool>("is_zoning");
  759. bool in_zone = zone.second.get<bool>("in_zone");
  760. if(client_acct_id == account_id) {
  761. if(is_zoning)
  762. return true;
  763. else if(is_linkdead)
  764. return false;
  765. else if(in_zone)
  766. return true;
  767. }
  768. }
  769. } catch (const std::exception& e) {
  770. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  771. }
  772. }
  773. return false;
  774. }
  775. std::string PeerManager::GetCharacterPeerId(std::string charName) {
  776. for (auto& [peerId, peer] : peers) {
  777. if(peer->healthCheck.status != HealthStatus::OK)
  778. continue;
  779. try {
  780. std::lock_guard<std::mutex> lock(peer->dataMutex);
  781. for (const auto& zone : peer->client_tree->get_child("Clients")) {
  782. // Access each field within the current zone
  783. std::string character_name = zone.second.get<std::string>("character_name");
  784. if(strncasecmp(character_name.c_str(), charName.c_str(), charName.length())==0) {
  785. return peer->id;
  786. }
  787. }
  788. } catch (const std::exception& e) {
  789. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  790. }
  791. }
  792. return "";
  793. }
  794. void PeerManager::SendPeersChannelMessage(int32 group_id, std::string fromName, std::string message, int16 channel, int32 language_id) {
  795. boost::property_tree::ptree root;
  796. root.put("message", message);
  797. root.put("channel", channel);
  798. root.put("group_id", group_id);
  799. root.put("from_language", language_id);
  800. root.put("from_name", fromName);
  801. std::ostringstream jsonStream;
  802. boost::property_tree::write_json(jsonStream, root);
  803. std::string jsonPayload = jsonStream.str();
  804. std::vector<int32> raidGroups;
  805. world.GetGroupManager()->GetRaidGroups(group_id, &raidGroups);
  806. for (auto& [peerId, peer] : peers) {
  807. if(peer->healthCheck.status != HealthStatus::OK)
  808. continue;
  809. try {
  810. std::lock_guard<std::mutex> lock(peer->dataMutex);
  811. for (const auto& zone : peer->client_tree->get_child("Clients")) {
  812. // Access each field within the current zone
  813. int32 player_group_id = zone.second.get<int32>("group_id");
  814. if(group_id == 0 || group_id == player_group_id || (std::find(raidGroups.begin(), raidGroups.end(), player_group_id) != raidGroups.end())) {
  815. peer_https_pool.sendPostRequestToPeerAsync(peer->id, peer->webAddr, std::to_string(peer->webPort), "/sendglobalmessage", jsonPayload);
  816. break;
  817. }
  818. }
  819. } catch (const std::exception& e) {
  820. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  821. }
  822. }
  823. }
  824. void PeerManager::SendPeersGuildChannelMessage(int32 guild_id, std::string fromName, std::string message, int16 channel, int32 language_id) {
  825. boost::property_tree::ptree root;
  826. root.put("message", message);
  827. root.put("channel", channel);
  828. root.put("guild_id", guild_id);
  829. root.put("from_language", language_id);
  830. root.put("from_name", fromName);
  831. std::ostringstream jsonStream;
  832. boost::property_tree::write_json(jsonStream, root);
  833. std::string jsonPayload = jsonStream.str();
  834. for (auto& [peerId, peer] : peers) {
  835. if(peer->healthCheck.status != HealthStatus::OK)
  836. continue;
  837. try {
  838. std::lock_guard<std::mutex> lock(peer->dataMutex);
  839. for (const auto& zone : peer->client_tree->get_child("Clients")) {
  840. // Access each field within the current zone
  841. int32 player_guild_id = zone.second.get<int32>("guild_id");
  842. if(guild_id == 0 || guild_id == player_guild_id) {
  843. peer_https_pool.sendPostRequestToPeerAsync(peer->id, peer->webAddr, std::to_string(peer->webPort), "/sendglobalmessage", jsonPayload);
  844. break;
  845. }
  846. }
  847. }
  848. catch (const std::exception& e) {
  849. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  850. }
  851. }
  852. }
  853. void PeerManager::sendZonePeerList(Client* client) {
  854. for (auto& [peerId, peer] : peers) {
  855. if(peer->healthCheck.status != HealthStatus::OK)
  856. continue;
  857. try {
  858. std::lock_guard<std::mutex> lock(peer->dataMutex);
  859. for (const auto& zone : peer->zone_tree->get_child("Zones")) {
  860. // Access each field within the current zone
  861. std::string zone_name = zone.second.get<std::string>("zone_name");
  862. std::string zone_file_name = zone.second.get<std::string>("zone_file_name");
  863. int32 zone_id = zone.second.get<int32>("zone_id");
  864. int32 instance_id = zone.second.get<int32>("instance_id");
  865. bool shutting_down = zone.second.get<std::string>("shutting_down") == "true";
  866. bool instance_zone = zone.second.get<std::string>("instance_zone") == "true";
  867. int32 num_players = zone.second.get<int32>("num_players");
  868. bool city_zone = zone.second.get<std::string>("city_zone") == "true";
  869. float safe_x = zone.second.get<float>("safe_x");
  870. float safe_y = zone.second.get<float>("safe_y");
  871. float safe_z = zone.second.get<float>("safe_z");
  872. float safe_heading = zone.second.get<float>("safe_heading");
  873. bool lock_state = zone.second.get<bool>("lock_state");
  874. sint16 min_status = zone.second.get<sint16>("min_status");
  875. int16 min_level = zone.second.get<int16>("min_level");
  876. int16 max_level = zone.second.get<int16>("max_level");
  877. int16 min_version = zone.second.get<int16>("min_version");
  878. int32 default_lockout_time = zone.second.get<int32>("default_lockout_time");
  879. int32 default_reenter_time = zone.second.get<int32>("default_reenter_time");
  880. int8 instance_type = zone.second.get<int8>("instance_type");
  881. client->Message(CHANNEL_COLOR_YELLOW,"Zone (ID) (InstanceID): %s (%u) (%u), Peer: %s, NumPlayers: %u, Locked: %s, ShuttingDown: %s.",zone_name.c_str(),zone_id,
  882. instance_id,peer->id.c_str(), num_players, lock_state ? "true" : "false", shutting_down ? "true" : "false");
  883. }
  884. } catch (const std::exception& e) {
  885. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Zones Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  886. }
  887. }
  888. }
  889. void PeerManager::sendZonePlayerList(std::vector<string>* queries, std::vector<WhoAllPeerPlayer>* peer_list, bool isGM) {
  890. for (auto& [peerId, peer] : peers) {
  891. if(peer->healthCheck.status != HealthStatus::OK)
  892. continue;
  893. try {
  894. bool add_player = true;
  895. bool found_match = false;
  896. int8 lower = 0;
  897. int8 upper = 0;
  898. std::lock_guard<std::mutex> lock(peer->dataMutex);
  899. for (const auto& player : peer->client_tree->get_child("Clients")) {
  900. std::string char_name = player.second.get<std::string>("character_name");
  901. std::string subtitle = player.second.get<std::string>("subtitle");
  902. std::string zone_name = player.second.get<std::string>("zonedescription");
  903. int8 adventure_class = player.second.get<int8>("adventure_class");
  904. int8 tradeskill_class = player.second.get<int8>("tradeskill_class");
  905. int8 deity = player.second.get<int8>("deity");
  906. int8 race = player.second.get<int8>("race");
  907. sint16 status = player.second.get<sint16>("status");
  908. int flags = player.second.get<int>("flags");
  909. int flags2 = player.second.get<int>("flags2");
  910. int16 level = player.second.get<int16>("level");
  911. found_match = false;
  912. add_player = true;
  913. for(int32 i=0;add_player && queries && i<queries->size();i++){
  914. if(queries->at(i) == "ALL")
  915. continue;
  916. if(queries->at(i).length() > 3 && classes.GetClassID(queries->at(i).c_str()) > 0){
  917. if(adventure_class != classes.GetClassID(queries->at(i).c_str()))
  918. add_player = false;
  919. found_match = true;
  920. }
  921. else if(queries->at(i).length() > 2 && races.GetRaceID(queries->at(i).c_str()) > 0){
  922. if(race != races.GetRaceID(queries->at(i).c_str()))
  923. add_player = false;
  924. found_match = true;
  925. }
  926. if(!found_match && queries->at(i) == "GOOD"){
  927. if(deity != 1)
  928. add_player = false;
  929. found_match = true;
  930. }
  931. else if(!found_match && queries->at(i) == "EVIL"){
  932. if(deity == 1)
  933. add_player = false;
  934. found_match = true;
  935. }
  936. if((queries->at(i) == "GUIDE") && (status > 0) && ((status >> 4) < 5))
  937. found_match = true;
  938. else if((queries->at(i) == "GM") && ((status >> 4) > 4))
  939. found_match = true;
  940. else if((queries->at(i) == "LFG") && (flags & (1 << CF_LFG)))
  941. found_match = true;
  942. else if((queries->at(i) == "LFW") && (flags & (1 << CF_LFW)))
  943. found_match = true;
  944. else if((queries->at(i) == "ROLEPLAYING") && (flags & (1 << CF_ROLEPLAYING)))
  945. found_match = true;
  946. else if(strspn(queries->at(i).c_str(),"0123456789") == queries->at(i).length()){
  947. try{
  948. if(lower == 0)
  949. lower = atoi(queries->at(i).c_str());
  950. else
  951. upper = atoi(queries->at(i).c_str());
  952. }
  953. catch(...){}
  954. found_match = true;
  955. }
  956. if(!found_match){
  957. std::string name = ToUpper(char_name);
  958. if(name.find(queries->at(i)) == name.npos)
  959. add_player = false;
  960. }
  961. }
  962. if(lower > 0 && upper > 0){
  963. if(level < lower || level > upper)
  964. add_player = false;
  965. }
  966. else if(lower > 0){
  967. if(level != lower)
  968. add_player = false;
  969. }
  970. if((flags2 & (1 << (CF_GM_HIDDEN - 32))) && !isGM) {
  971. add_player = false;
  972. found_match = true;
  973. }
  974. if(add_player)
  975. peer_list->push_back(WhoAllPeerPlayer(char_name, subtitle, zone_name, adventure_class, tradeskill_class, deity, race,
  976. status, flags, flags2, level));
  977. }
  978. }
  979. catch (const std::exception& e) {
  980. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  981. }
  982. }
  983. }
  984. bool PeerManager::GetClientGuildDetails(int32 matchCharID, GuildMember* member_details) {
  985. if(!member_details)
  986. return false;
  987. for (auto& [peerId, peer] : peers) {
  988. if(peer->healthCheck.status != HealthStatus::OK)
  989. continue;
  990. try {
  991. std::lock_guard<std::mutex> lock(peer->dataMutex);
  992. for (const auto& player : peer->client_tree->get_child("Clients")) {
  993. std::string char_name = player.second.get<std::string>("character_name");
  994. std::string subtitle = player.second.get<std::string>("subtitle");
  995. std::string zone_name = player.second.get<std::string>("zonedescription");
  996. int8 adventure_class = player.second.get<int8>("adventure_class");
  997. int8 tradeskill_class = player.second.get<int8>("tradeskill_class");
  998. int8 deity = player.second.get<int8>("deity");
  999. int8 race = player.second.get<int8>("race");
  1000. sint16 status = player.second.get<sint16>("status");
  1001. int flags = player.second.get<int>("flags");
  1002. int flags2 = player.second.get<int>("flags2");
  1003. int16 level = player.second.get<int16>("level");
  1004. int16 tradeskill_level = player.second.get<int16>("tradeskill_level");
  1005. int32 character_id = player.second.get<int32>("character_id");
  1006. int32 account_id = player.second.get<int32>("account_id");
  1007. if(character_id == matchCharID) {
  1008. member_details->account_id = account_id;
  1009. member_details->character_id = character_id;
  1010. strncpy(member_details->name, char_name.c_str(), sizeof(member_details->name));
  1011. member_details->guild_status = 0;
  1012. member_details->points = 0.0;
  1013. member_details->adventure_class = adventure_class;
  1014. member_details->adventure_level = level;
  1015. member_details->tradeskill_class = tradeskill_class;
  1016. member_details->tradeskill_level = tradeskill_level;
  1017. //gm->rank = rank; ?? not sure how yet
  1018. member_details->zone = zone_name;
  1019. //gm->join_date = Timer::GetUnixTimeStamp();
  1020. //gm->last_login_date = gm->join_date;
  1021. member_details->recruiter_id = 0;
  1022. member_details->member_flags = GUILD_MEMBER_FLAGS_NOTIFY_LOGINS;
  1023. member_details->recruiting_show_adventure_class = 1;
  1024. member_details->recruiter_picture_data_size = 0;
  1025. member_details->recruiter_picture_data = 0;
  1026. return true;
  1027. }
  1028. }
  1029. }
  1030. catch (const std::exception& e) {
  1031. LogWrite(PEERING__ERROR, 0, "Peering", "%s: Clients Parsing Error %s for %s:%u/%s", __FUNCTION__, e.what() ? e.what() : "??", peer->webAddr.c_str(), peer->webPort);
  1032. }
  1033. }
  1034. return false;
  1035. }
  1036. void ZoneList::SendZoneList(Client* client) {
  1037. list<ZoneServer*>::iterator zone_iter;
  1038. ZoneServer* tmp = 0;
  1039. MZoneList.readlock(__FUNCTION__, __LINE__);
  1040. int zonesListed = 0;
  1041. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1042. tmp = *zone_iter;
  1043. client->Message(CHANNEL_COLOR_YELLOW,"Zone (ID) (InstanceID): %s (%u) (%u), Description: %s, NumPlayers: %u, Locked: %s, ShuttingDown: %s.",tmp->GetZoneName(),tmp->GetZoneID(),
  1044. tmp->GetInstanceID(),tmp->GetZoneDescription(), tmp->NumPlayers(), tmp->GetZoneLockState() ? "true" : "false", tmp->isZoneShuttingDown() ? "true" : "false");
  1045. }
  1046. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1047. peer_manager.sendZonePeerList(client);
  1048. }
  1049. ZoneServer* ZoneList::GetByLowestPopulation(int32 zone_id) {
  1050. ZoneServer* ret = 0;
  1051. ZoneServer* zone = 0;
  1052. int32 clients = 0;
  1053. list<ZoneServer*>::iterator itr;
  1054. MZoneList.readlock(__FUNCTION__, __LINE__);
  1055. if (zone_id) {
  1056. for (itr = zlist.begin(); itr != zlist.end(); itr++) {
  1057. zone = *itr;
  1058. if (zone) {
  1059. // check the zone id's
  1060. if (zone->GetZoneID() == zone_id) {
  1061. // check this zones client count
  1062. if (clients == 0 || zone->GetClientCount() < clients) {
  1063. ret = zone;
  1064. clients = zone->GetClientCount();
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }
  1070. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1071. return ret;
  1072. }
  1073. int32 ZoneList::GetZonesPlayersCount() {
  1074. int32 ret = 0;
  1075. ZoneServer* zone = nullptr;
  1076. list<ZoneServer*>::iterator itr;
  1077. MZoneList.readlock(__FUNCTION__, __LINE__);
  1078. for (itr = zlist.begin(); itr != zlist.end(); itr++) {
  1079. zone = *itr;
  1080. if (zone) {
  1081. ret += zone->GetClientCount();
  1082. }
  1083. }
  1084. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1085. return ret;
  1086. }
  1087. bool ZoneList::ClientConnected(int32 account_id){
  1088. bool ret = false;
  1089. map<string, Client*>::iterator itr;
  1090. MClientList.lock();
  1091. for(itr=client_map.begin(); itr != client_map.end(); itr++){
  1092. if(itr->second && itr->second->GetAccountID() == account_id && itr->second->getConnection() && itr->second->getConnection()->GetState() != CLOSING && itr->second->getConnection()->GetState() != CLOSED && (itr->second->GetPlayer()->GetActivityStatus() & ACTIVITY_STATUS_LINKDEAD) == 0){
  1093. ret = true;
  1094. break;
  1095. }
  1096. else if(!itr->second){
  1097. client_map.erase(itr);
  1098. if(client_map.size() > 0){
  1099. itr=client_map.begin();
  1100. if(itr == client_map.end()){
  1101. if(itr->second && itr->second->GetAccountID() == account_id && (itr->second->GetPlayer()->GetActivityStatus() & ACTIVITY_STATUS_LINKDEAD) == 0)
  1102. ret = true;
  1103. break;
  1104. }
  1105. }
  1106. else
  1107. break;
  1108. }
  1109. }
  1110. if(!ret) {
  1111. ret = peer_manager.IsClientConnectedPeer(account_id);
  1112. }
  1113. MClientList.unlock();
  1114. return ret;
  1115. }
  1116. void ZoneList::RemoveClientZoneReference(ZoneServer* zone){
  1117. map<string, Client*>::iterator itr;
  1118. MClientList.lock();
  1119. for(itr=client_map.begin(); itr != client_map.end(); itr++){
  1120. if(itr->second) {
  1121. if(itr->second->GetCurrentZone() == zone) {
  1122. itr->second->SetCurrentZone(nullptr);
  1123. }
  1124. if(itr->second->GetZoningDestination() == zone) {
  1125. itr->second->SetZoningDestination(nullptr);
  1126. }
  1127. }
  1128. }
  1129. MClientList.unlock();
  1130. list<ZoneServer*>::iterator zone_iter;
  1131. ZoneServer* tmp = 0;
  1132. MZoneList.readlock(__FUNCTION__, __LINE__);
  1133. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1134. tmp = *zone_iter;
  1135. if(tmp)
  1136. tmp->RemoveClientsFromZone(zone);
  1137. }
  1138. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1139. }
  1140. void ZoneList::ReloadClientQuests(){
  1141. list<ZoneServer*>::iterator zone_iter;
  1142. ZoneServer* tmp = 0;
  1143. MZoneList.readlock(__FUNCTION__, __LINE__);
  1144. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1145. tmp = *zone_iter;
  1146. if(tmp)
  1147. tmp->ReloadClientQuests();
  1148. }
  1149. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1150. }
  1151. void ZoneList::ProcessWhoQuery(vector<string>* queries, ZoneServer* zone, vector<Entity*>* players, bool isGM){
  1152. Entity* player = 0;
  1153. bool add_player = true;
  1154. bool found_match = false;
  1155. int8 lower = 0;
  1156. int8 upper = 0;
  1157. vector<Entity*> tmpPlayers;
  1158. vector<Entity*>::iterator spawn_iter;
  1159. if(!zone->isZoneShuttingDown()){
  1160. tmpPlayers = zone->GetPlayers();
  1161. for(spawn_iter = tmpPlayers.begin(); spawn_iter!=tmpPlayers.end(); spawn_iter++){
  1162. player = *spawn_iter;
  1163. add_player = true;
  1164. Client* find_client = zone_list.GetClientByCharName(player->GetName());
  1165. if (find_client == NULL) continue;
  1166. int flags = find_client->GetPlayer()->GetInfoStruct()->get_flags();
  1167. int flags2 = find_client->GetPlayer()->GetInfoStruct()->get_flags2();
  1168. for(int32 i=0;add_player && queries && i<queries->size();i++){
  1169. found_match = false;
  1170. if(queries->at(i) == "ALL")
  1171. continue;
  1172. if(queries->at(i).length() > 3 && classes.GetClassID(queries->at(i).c_str()) > 0){
  1173. if(player->GetAdventureClass() != classes.GetClassID(queries->at(i).c_str()))
  1174. add_player = false;
  1175. found_match = true;
  1176. }
  1177. else if(queries->at(i).length() > 2 && races.GetRaceID(queries->at(i).c_str()) > 0){
  1178. if(player->GetRace() != races.GetRaceID(queries->at(i).c_str()))
  1179. add_player = false;
  1180. found_match = true;
  1181. }
  1182. if(!found_match && queries->at(i) == "GOOD"){
  1183. if(player->GetDeity() != 1)
  1184. add_player = false;
  1185. found_match = true;
  1186. }
  1187. else if(!found_match && queries->at(i) == "EVIL"){
  1188. if(player->GetDeity() == 1)
  1189. add_player = false;
  1190. found_match = true;
  1191. }
  1192. if((queries->at(i) == "GUIDE") && (find_client->GetAdminStatus() > 0) && ((find_client->GetAdminStatus() >> 4) < 5))
  1193. found_match = true;
  1194. else if((queries->at(i) == "GM") && ((find_client->GetAdminStatus() >> 4) > 4))
  1195. found_match = true;
  1196. else if((queries->at(i) == "LFG") && (flags & (1 << CF_LFG)))
  1197. found_match = true;
  1198. else if((queries->at(i) == "LFW") && (flags & (1 << CF_LFW)))
  1199. found_match = true;
  1200. else if((queries->at(i) == "ROLEPLAYING") && (flags & (1 << CF_ROLEPLAYING)))
  1201. found_match = true;
  1202. else if(strspn(queries->at(i).c_str(),"0123456789") == queries->at(i).length()){
  1203. try{
  1204. if(lower == 0)
  1205. lower = atoi(queries->at(i).c_str());
  1206. else
  1207. upper = atoi(queries->at(i).c_str());
  1208. }
  1209. catch(...){}
  1210. found_match = true;
  1211. }
  1212. if(!found_match){
  1213. string name = string(player->GetName());
  1214. name = ToUpper(name);
  1215. if(name.find(queries->at(i)) == name.npos)
  1216. add_player = false;
  1217. }
  1218. }
  1219. if(lower > 0 && upper > 0){
  1220. if(player->GetLevel() < lower || player->GetLevel() > upper)
  1221. add_player = false;
  1222. }
  1223. else if(lower > 0){
  1224. if(player->GetLevel() != lower)
  1225. add_player = false;
  1226. }
  1227. if((flags2 & (1 << (CF_GM_HIDDEN - 32))) && !isGM) {
  1228. add_player = false;
  1229. found_match = true;
  1230. }
  1231. if(add_player)
  1232. players->push_back(player);
  1233. }
  1234. }
  1235. }
  1236. void ZoneList::ProcessWhoQuery(const char* query, Client* client){
  1237. list<ZoneServer*>::iterator zone_iter;
  1238. vector<Entity*> players;
  1239. vector<WhoAllPeerPlayer> peer_players;
  1240. vector<WhoAllPeerPlayer>::iterator peer_iter;
  1241. vector<Entity*>::iterator spawn_iter;
  1242. Entity* player = 0;
  1243. //for now display all clients
  1244. bool all = false;
  1245. vector<string>* queries = 0;
  1246. bool isGM = ((client->GetAdminStatus() >> 4) > 4);
  1247. if(query){
  1248. string query_string = string(query);
  1249. query_string = ToUpper(query_string);
  1250. queries = SplitString(query_string, ' ');
  1251. }
  1252. if(queries && queries->size() > 0 && queries->at(0) == "ALL")
  1253. all = true;
  1254. if(all){
  1255. MZoneList.readlock(__FUNCTION__, __LINE__);
  1256. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1257. ZoneServer* tmp = *zone_iter;
  1258. ProcessWhoQuery(queries, tmp, &players, isGM);
  1259. }
  1260. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1261. if(queries) {
  1262. peer_manager.sendZonePlayerList(queries, &peer_players, isGM);
  1263. }
  1264. }
  1265. else{
  1266. ProcessWhoQuery(queries, client->GetCurrentZone(), &players, isGM);
  1267. }
  1268. PacketStruct* packet = configReader.getStruct("WS_WhoQueryReply", client->GetVersion());
  1269. if(packet){
  1270. packet->setDataByName("account_id", client->GetAccountID());
  1271. packet->setDataByName("unknown", 0xFFFFFFFF);
  1272. int16 num_characters = players.size();
  1273. int16 num_players_peers = peer_players.size();
  1274. int16 total_results = num_characters + num_players_peers;
  1275. int8 max_who_results = 10;
  1276. int8 max_who_results_status_override = 100;
  1277. Variable* var = variables.FindVariable("max_who_results_status_override");
  1278. if ( var ){
  1279. max_who_results_status_override = atoi(var->GetValue());
  1280. }
  1281. // AdnaeDMorte
  1282. if ( client->GetAdminStatus() >= max_who_results_status_override ){
  1283. client->Message(CHANNEL_COLOR_RED, "** ADMIN-MODE ** ");
  1284. }
  1285. Variable* var1 = variables.FindVariable("max_who_results");
  1286. if ( var1 ){
  1287. max_who_results = atoul(var1->GetValue());
  1288. }
  1289. if(total_results > max_who_results && client->GetAdminStatus() < max_who_results_status_override){
  1290. total_results = max_who_results;
  1291. if(num_characters > total_results)
  1292. num_characters = total_results;
  1293. if((num_characters+num_players_peers) > max_who_results) {
  1294. int16 max_num_players_peers = max_who_results - num_characters;
  1295. if(num_players_peers > max_num_players_peers)
  1296. num_players_peers = max_num_players_peers;
  1297. }
  1298. packet->setDataByName("response", 3); //response 1 = error message, 3 == capped
  1299. }
  1300. else
  1301. packet->setDataByName("response", 2);
  1302. packet->setArrayLengthByName("num_characters", (int8)total_results);
  1303. packet->setDataByName("display_zone", 1);
  1304. int i=0;
  1305. for(spawn_iter = players.begin(); spawn_iter!=players.end(); spawn_iter++, i++){
  1306. if(i == num_characters)
  1307. break;
  1308. player = *spawn_iter;
  1309. Client* find_client = zone_list.GetClientByCharName(player->GetName());
  1310. int flags = find_client->GetPlayer()->GetInfoStruct()->get_flags();
  1311. int flags2 = find_client->GetPlayer()->GetInfoStruct()->get_flags2();
  1312. packet->setArrayDataByName("char_name", player->GetName(), i);
  1313. packet->setArrayDataByName("level", player->GetLevel(), i);
  1314. packet->setArrayDataByName("admin_level", ((flags2 & (1 << (CF_HIDE_STATUS - 32))) && !isGM)?0:(find_client->GetAdminStatus() >> 4), i);
  1315. packet->setArrayDataByName("class", player->GetAdventureClass(), i);
  1316. packet->setArrayDataByName("unknown4", 0xFF, i); //probably tradeskill class
  1317. packet->setArrayDataByName("flags", (((flags >> CF_ANONYMOUS) & 1) << 0 ) |
  1318. (((flags >> CF_LFG) & 1) << 1 ) |
  1319. (((flags >> CF_ANONYMOUS) & 1) << 2 ) |
  1320. /*(((flags >> CF_HIDDEN) & 1) << 3 ) |*/
  1321. (((flags >> CF_ROLEPLAYING) & 1) << 4 ) |
  1322. (((flags >> CF_AFK) & 1) << 5 ) |
  1323. (((flags >> CF_LFW) & 1) << 6 ) /*|
  1324. (((flags >> CF_NOTA) & 1) << 7 )*/, i);
  1325. packet->setArrayDataByName("race", player->GetRace(), i);
  1326. if(player->GetZone() && player->GetZone()->GetZoneDescription())
  1327. packet->setArrayDataByName("zone", player->GetZone()->GetZoneDescription(), i);
  1328. if(player->appearance.sub_title) {
  1329. int32 sub_title_length = strlen(player->appearance.sub_title);
  1330. char tmp_title[255];
  1331. int32 index = 0;
  1332. int32 index_tmp = 0;
  1333. while (index < sub_title_length) {
  1334. if (player->appearance.sub_title[index] != '<' && player->appearance.sub_title[index] != '>') {
  1335. memcpy(tmp_title + index_tmp, player->appearance.sub_title + index, 1);
  1336. index_tmp++;
  1337. }
  1338. index++;
  1339. }
  1340. tmp_title[index_tmp] = '\0';
  1341. packet->setArrayDataByName("guild", tmp_title, i);
  1342. }
  1343. }
  1344. int8 count = 0;
  1345. for(peer_iter = peer_players.begin(); peer_iter!=peer_players.end(); peer_iter++, i++, count++){
  1346. if(count == num_players_peers)
  1347. break;
  1348. int flags = (*peer_iter).flags;
  1349. int flags2 = (*peer_iter).flags2;
  1350. sint16 status = (*peer_iter).status;
  1351. packet->setArrayDataByName("char_name", (*peer_iter).name.c_str(), i);
  1352. packet->setArrayDataByName("level", (*peer_iter).level, i);
  1353. packet->setArrayDataByName("admin_level", ((flags2 & (1 << (CF_HIDE_STATUS - 32))) && !isGM)?0:(status >> 4), i);
  1354. packet->setArrayDataByName("class", (*peer_iter).adventureClass, i);
  1355. packet->setArrayDataByName("unknown4", 0xFF, i); //probably tradeskill class
  1356. packet->setArrayDataByName("flags", (((flags >> CF_ANONYMOUS) & 1) << 0 ) |
  1357. (((flags >> CF_LFG) & 1) << 1 ) |
  1358. (((flags >> CF_ANONYMOUS) & 1) << 2 ) |
  1359. /*(((flags >> CF_HIDDEN) & 1) << 3 ) |*/
  1360. (((flags >> CF_ROLEPLAYING) & 1) << 4 ) |
  1361. (((flags >> CF_AFK) & 1) << 5 ) |
  1362. (((flags >> CF_LFW) & 1) << 6 ) /*|
  1363. (((flags >> CF_NOTA) & 1) << 7 )*/, i);
  1364. packet->setArrayDataByName("race", (*peer_iter).race, i);
  1365. packet->setArrayDataByName("zone", (*peer_iter).zoneName.c_str(), i);
  1366. if((*peer_iter).subtitle.size() > 0) {
  1367. size_t start = (*peer_iter).subtitle.find('<');
  1368. size_t end = (*peer_iter).subtitle.find('>');
  1369. std::string result = (*peer_iter).subtitle;
  1370. // Check if both '<' and '>' are found and in the correct order
  1371. if (start != std::string::npos && end != std::string::npos && start < end) {
  1372. result = (*peer_iter).subtitle.substr(start + 1, end - start - 1);
  1373. }
  1374. packet->setArrayDataByName("guild", result.c_str(), i);
  1375. }
  1376. }
  1377. client->QueuePacket(packet->serialize());
  1378. safe_delete(packet);
  1379. }
  1380. }
  1381. bool ZoneList::DepopFinished(){
  1382. list<ZoneServer*>::iterator zone_iter;
  1383. MZoneList.readlock(__FUNCTION__, __LINE__);
  1384. bool finished_depop = true;
  1385. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1386. if(!(*zone_iter)->FinishedDepop())
  1387. finished_depop = false;
  1388. }
  1389. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1390. return finished_depop;
  1391. }
  1392. void ZoneList::Depop(){
  1393. list<ZoneServer*>::iterator zone_iter;
  1394. MZoneList.readlock(__FUNCTION__, __LINE__);
  1395. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1396. (*zone_iter)->Depop();
  1397. }
  1398. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1399. }
  1400. void ZoneList::Repop(){
  1401. list<ZoneServer*>::iterator zone_iter;
  1402. MZoneList.readlock(__FUNCTION__, __LINE__);
  1403. for(zone_iter=zlist.begin(); zone_iter!=zlist.end(); zone_iter++){
  1404. (*zone_iter)->Depop(false, true);
  1405. }
  1406. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1407. }
  1408. void ZoneList::ReloadSpawns() {
  1409. MZoneList.readlock(__FUNCTION__, __LINE__);
  1410. list<ZoneServer*>::iterator itr;
  1411. for (itr = zlist.begin(); itr != zlist.end(); itr++)
  1412. (*itr)->ReloadSpawns();
  1413. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1414. }
  1415. bool World::ReportBug(string data, char* player_name, int32 account_id, const char* spawn_name, int32 spawn_id, int32 zone_id){
  1416. //loginserver
  1417. vector<string> list;
  1418. int32 offset = 0;
  1419. int32 old_offset = 0;
  1420. while((offset = data.find(7, old_offset+1)) < 0xFFFFFFFF){
  1421. if(old_offset > 0)
  1422. list.push_back(data.substr(old_offset+1, offset-old_offset-1));
  1423. else
  1424. list.push_back(data.substr(old_offset, offset));
  1425. old_offset = offset;
  1426. }
  1427. if(list.size() > 0 && list.size() < 7){
  1428. string output = "Invalid bug list:\n";
  1429. for(int32 i=0;i<list.size();i++)
  1430. output = output.append("\t").append(list[i]).append("\n");
  1431. LogWrite(WORLD__ERROR, 0, "World", "%s", output.c_str());
  1432. return false;
  1433. }
  1434. ServerPacket* outpack = new ServerPacket(ServerOP_BugReport, sizeof(BugReport));
  1435. BugReport* report = (BugReport*)outpack->pBuffer;
  1436. if (list.size() < 7) {
  1437. strncpy(report->category, "AutoBug", 7);
  1438. strncpy(report->subcategory, "AutoGenerate", 12);
  1439. strncpy(report->causes_crash, "N", 1);
  1440. strncpy(report->reproducible, "Y", 1);
  1441. strncpy(report->summary, data.c_str(), data.length() > 127 ? 127 : data.length());
  1442. strncpy(report->description, data.c_str(), data.length() > 1999 ? 1999 : data.length());
  1443. strncpy(report->version, "CUR", 3);
  1444. }
  1445. else
  1446. {
  1447. strncpy(report->category, list[0].c_str(), list[0].length() > 63 ? 63 : list[0].length());
  1448. strncpy(report->subcategory, list[1].c_str(), list[1].length() > 63 ? 63 : list[1].length());
  1449. strncpy(report->causes_crash, list[2].c_str(), list[2].length() > 63 ? 63 : list[2].length());
  1450. strncpy(report->reproducible, list[3].c_str(), list[3].length() > 63 ? 63 : list[3].length());
  1451. strncpy(report->summary, list[4].c_str(), list[4].length() > 127 ? 127 : list[4].length());
  1452. strncpy(report->description, list[5].c_str(), list[5].length() > 1999 ? 1999 : list[5].length());
  1453. strncpy(report->version, list[6].c_str(), list[6].length() > 31 ? 31 : list[6].length());
  1454. }
  1455. strncpy(report->player, player_name, strlen(player_name) > 63 ? 63 : strlen(player_name));
  1456. strncpy(report->spawn_name, spawn_name, strlen(spawn_name) > 63 ? 63 : strlen(spawn_name));
  1457. report->spawn_id = spawn_id;
  1458. report->account_id = account_id;
  1459. report->zone_id = zone_id;
  1460. loginserver.SendPacket(outpack);
  1461. database.SaveBugReport(report->category, report->subcategory, report->causes_crash, report->reproducible, report->summary, report->description, report->version, report->player, account_id, spawn_name, spawn_id, zone_id);
  1462. safe_delete(outpack);
  1463. return true;
  1464. }
  1465. void ZoneList::WritePlayerStatistics() {
  1466. list<ZoneServer*>::iterator zone_itr;
  1467. MZoneList.readlock(__FUNCTION__, __LINE__);
  1468. for (zone_itr = zlist.begin(); zone_itr != zlist.end(); zone_itr++)
  1469. (*zone_itr)->WritePlayerStatistics();
  1470. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1471. }
  1472. void ZoneList::ShutDownZones(){
  1473. LogWrite(WORLD__INFO, 0, "World", "Shutting down all zones, please wait...");
  1474. list<ZoneServer*>::iterator zone_itr;
  1475. int32 size = 0;
  1476. MZoneList.readlock(__FUNCTION__, __LINE__);
  1477. for (zone_itr = zlist.begin(); zone_itr != zlist.end(); zone_itr++){
  1478. (*zone_itr)->Shutdown();
  1479. }
  1480. size = zlist.size();
  1481. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1482. while(size > 0){
  1483. Sleep(10);
  1484. MZoneList.readlock(__FUNCTION__, __LINE__);
  1485. size = zlist.size();
  1486. MZoneList.releasereadlock(__FUNCTION__, __LINE__);
  1487. }
  1488. LogWrite(WORLD__INFO, 0, "World", "Zone shutdown complete");
  1489. }
  1490. void ZoneList::ReloadMail() {
  1491. map<string, Client*>::iterator itr;
  1492. MClientList.writelock(__FUNCTION__, __LINE__);
  1493. for (itr = client_map.begin(); itr != client_map.end(); itr++) {
  1494. itr->second->GetPlayer()->DeleteMail();
  1495. database.LoadPlayerMail(itr->second);
  1496. }
  1497. MClientList.releasewritelock(__FUNCTION__, __LINE__);
  1498. }
  1499. void World::AddSpawnScript(int32 id, const char* name){
  1500. MSpawnScripts.lock();
  1501. if(name)
  1502. spawn_scripts[id] = string(name);
  1503. MSpawnScripts.unlock();
  1504. }
  1505. void World::AddSpawnEntryScript(int32 id, const char* name){
  1506. MSpawnScripts.lock();
  1507. if(name)
  1508. spawnentry_scripts[id] = string(name);
  1509. MSpawnScripts.unlock();
  1510. }
  1511. void World::AddSpawnLocationScript(int32 id, const char* name){
  1512. MSpawnScripts.lock();
  1513. if(name)
  1514. spawnlocation_scripts[id] = string(name);
  1515. MSpawnScripts.unlock();
  1516. }
  1517. void World::AddZoneScript(int32 id, const char* name) {
  1518. MZoneScripts.lock();
  1519. if (name)
  1520. zone_scripts[id] = string(name);
  1521. MZoneScripts.unlock();
  1522. }
  1523. const char* World::GetSpawnScript(int32 id){
  1524. LogWrite(SPAWN__TRACE, 1, "Spawn", "Enter %s", __FUNCTION__);
  1525. const char* ret = 0;
  1526. MSpawnScripts.lock();
  1527. if(spawn_scripts.count(id) > 0)
  1528. ret = spawn_scripts[id].c_str();
  1529. MSpawnScripts.unlock();
  1530. LogWrite(SPAWN__TRACE, 1, "Spawn", "Exit %s", __FUNCTION__);
  1531. return ret;
  1532. }
  1533. const char* World::GetSpawnEntryScript(int32 id){
  1534. LogWrite(SPAWN__TRACE, 1, "Spawn", "Enter %s", __FUNCTION__);
  1535. const char* ret = 0;
  1536. MSpawnScripts.lock();
  1537. if(spawnentry_scripts.count(id) > 0)
  1538. ret = spawnentry_scripts[id].c_str();
  1539. MSpawnScripts.unlock();
  1540. LogWrite(SPAWN__TRACE, 1, "Spawn", "Exit %s", __FUNCTION__);
  1541. return ret;
  1542. }
  1543. const char* World::GetSpawnLocationScript(int32 id){
  1544. LogWrite(SPAWN__TRACE, 1, "Spawn", "Enter %s", __FUNCTION__);
  1545. const char* ret = 0;
  1546. MSpawnScripts.lock();
  1547. if(spawnlocation_scripts.count(id) > 0)
  1548. ret = spawnlocation_scripts[id].c_str();
  1549. MSpawnScripts.unlock();
  1550. LogWrite(SPAWN__TRACE, 1, "Spawn", "Exit %s", __FUNCTION__);
  1551. return ret;
  1552. }
  1553. const char* World::GetZoneScript(int32 id) {
  1554. const char* ret = 0;
  1555. MZoneScripts.lock();
  1556. if (zone_scripts.count(id) > 0)
  1557. ret = zone_scripts[id].c_str();
  1558. MZoneScripts.unlock();
  1559. return ret;
  1560. }
  1561. void World::ResetSpawnScripts(){
  1562. MSpawnScripts.lock();
  1563. spawn_scripts.clear();
  1564. spawnentry_scripts.clear();
  1565. spawnlocation_scripts.clear();
  1566. MSpawnScripts.unlock();
  1567. }
  1568. void World::ResetZoneScripts() {
  1569. MZoneScripts.lock();
  1570. zone_scripts.clear();
  1571. MZoneScripts.unlock();
  1572. }
  1573. vector<MerchantItemInfo>* World::GetMerchantItemList(int32 merchant_id, int8 merchant_type, Player* player)
  1574. {
  1575. vector<MerchantItemInfo>* ret = 0;
  1576. MMerchantList.lock();
  1577. if(merchant_info.count(merchant_id) > 0)
  1578. {
  1579. MerchantInfo* info = merchant_info[merchant_id];
  1580. vector<MerchantItemInfo>::iterator itr;
  1581. int32 inventory_id = 0;
  1582. Item* item = 0;
  1583. for(int i=info->inventory_ids.size()-1;i>=0;i--)
  1584. {
  1585. inventory_id = info->inventory_ids[i];
  1586. if(merchant_inventory_items.count(inventory_id) > 0)
  1587. {
  1588. for(itr = merchant_inventory_items[inventory_id].begin(); itr != merchant_inventory_items[inventory_id].end(); itr++)
  1589. {
  1590. if(!ret)
  1591. ret = new vector<MerchantItemInfo>;
  1592. item = master_item_list.GetItem((*itr).item_id);
  1593. // if NOT spell merchant, OR
  1594. // skill req is any skill, OR player has the skill, AND
  1595. // skill req2 is any skill, OR player has the skill2
  1596. if(item && ( (merchant_type & MERCHANT_TYPE_SPELLS) == 0 || ( (item->generic_info.skill_req1 == 0xFFFFFFFF || player->GetSkills()->HasSkill(item->generic_info.skill_req1)) && (item->generic_info.skill_req2 == 0xFFFFFFFF || player->GetSkills()->HasSkill(item->generic_info.skill_req2)) ) ) )
  1597. (*ret).push_back(*itr);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. MMerchantList.unlock();
  1603. return ret;
  1604. }
  1605. vector<MerchantItemInfo>* World::GetMerchantList(int32 merchant_id){
  1606. vector<MerchantItemInfo>* ret = 0;
  1607. MMerchantList.lock();
  1608. if(merchant_info.count(merchant_id) > 0){
  1609. MerchantInfo* info = merchant_info[merchant_id];
  1610. map<int32, int16>::iterator itr;
  1611. int32 inventory_id = 0;
  1612. for(int i=info->inventory_ids.size()-1;i>=0;i--){
  1613. inventory_id = info->inventory_ids[i];
  1614. if(merchant_inventory_items.count(inventory_id) > 0){
  1615. ret = &merchant_inventory_items[inventory_id];
  1616. }
  1617. }
  1618. }
  1619. MMerchantList.unlock();
  1620. return ret;
  1621. }
  1622. void World::AddMerchantItem(int32 inventory_id, MerchantItemInfo ItemInfo){
  1623. MMerchantList.lock();
  1624. merchant_inventory_items[inventory_id].push_back(ItemInfo);
  1625. MMerchantList.unlock();
  1626. }
  1627. void World::DeleteMerchantItems(){
  1628. MMerchantList.lock();
  1629. merchant_inventory_items.clear();
  1630. MMerchantList.unlock();
  1631. }
  1632. void World::RemoveMerchantItem(int32 inventory_id, int32 item_id){
  1633. MMerchantList.lock();
  1634. if(merchant_inventory_items.count(inventory_id) > 0) {
  1635. vector<MerchantItemInfo>::iterator itr;
  1636. for(itr = merchant_inventory_items[inventory_id].begin(); itr != merchant_inventory_items[inventory_id].end(); itr++){
  1637. if ((*itr).item_id == item_id) {
  1638. merchant_inventory_items[inventory_id].erase(itr);
  1639. break;
  1640. }
  1641. }
  1642. }
  1643. MMerchantList.unlock();
  1644. }
  1645. int16 World::GetMerchantItemQuantity(int32 merchant_id, int32 item_id){
  1646. int16 amount = 0;
  1647. int32 inventory_id = GetInventoryID(merchant_id, item_id);
  1648. if(inventory_id > 0){
  1649. MMerchantList.lock();
  1650. vector<MerchantItemInfo>::iterator itr;
  1651. for(itr = merchant_inventory_items[inventory_id].begin(); itr != merchant_inventory_items[inventory_id].end(); itr++){
  1652. if ((*itr).item_id == item_id)
  1653. amount = (*itr).quantity;
  1654. }
  1655. MMerchantList.unlock();
  1656. }
  1657. return amount;
  1658. }
  1659. int32 World::GetInventoryID(int32 merchant_id, int32 item_id){
  1660. int32 ret = 0;
  1661. MMerchantList.lock();
  1662. if(merchant_info.count(merchant_id) > 0){
  1663. MerchantInfo* info = merchant_info[merchant_id];
  1664. vector<MerchantItemInfo>::iterator itr;
  1665. int32 inventory_id = 0;
  1666. for(int i=info->inventory_ids.size()-1;i>=0;i--){
  1667. inventory_id = info->inventory_ids[i];
  1668. if(merchant_inventory_items.count(inventory_id) > 0){
  1669. for(itr = merchant_inventory_items[inventory_id].begin(); itr != merchant_inventory_items[inventory_id].end(); itr++){
  1670. if((*itr).item_id == item_id){
  1671. ret = inventory_id;
  1672. break;
  1673. }
  1674. }
  1675. if(ret > 0)
  1676. break;
  1677. }
  1678. }
  1679. }
  1680. MMerchantList.unlock();
  1681. return ret;
  1682. }
  1683. void World::DecreaseMerchantQuantity(int32 merchant_id, int32 item_id, int16 amount){
  1684. int16 total_left = GetMerchantItemQuantity(merchant_id, item_id);
  1685. if(total_left > 0 && total_left < 0xFF){
  1686. int32 inventory_id = GetInventoryID(merchant_id, item_id);
  1687. if(inventory_id > 0){
  1688. MMerchantList.lock();
  1689. vector<MerchantItemInfo>::iterator itr;
  1690. for(itr = merchant_inventory_items[inventory_id].begin(); itr != merchant_inventory_items[inventory_id].end(); itr++){
  1691. if ((*itr).item_id == item_id) {
  1692. if(total_left <= amount) {
  1693. merchant_inventory_items[inventory_id].erase(itr);
  1694. amount = 0;
  1695. break;
  1696. }
  1697. else
  1698. (*itr).quantity -= amount;
  1699. amount = (*itr).quantity;
  1700. }
  1701. }
  1702. MMerchantList.unlock();
  1703. }
  1704. }
  1705. }
  1706. MerchantInfo* World::GetMerchantInfo(int32 merchant_id){
  1707. MerchantInfo* ret = 0;
  1708. MMerchantList.lock();
  1709. if(merchant_info.count(merchant_id) > 0)
  1710. ret = merchant_info[merchant_id];
  1711. MMerchantList.unlock();
  1712. return ret;
  1713. }
  1714. void World::AddMerchantInfo(int32 merchant_id, MerchantInfo* info){
  1715. MMerchantList.lock();
  1716. if(merchant_info.count(merchant_id) > 0){
  1717. safe_delete(merchant_info[merchant_id]);
  1718. }
  1719. merchant_info[merchant_id] = info;
  1720. MMerchantList.unlock();
  1721. }
  1722. map<int32, MerchantInfo*>* World::GetMerchantInfo() {
  1723. return &merchant_info;
  1724. }
  1725. void World::DeleteMerchantsInfo(){
  1726. MMerchantList.lock();
  1727. map<int32, MerchantInfo*>::iterator itr;
  1728. for(itr = merchant_info.begin(); itr != merchant_info.end(); itr++){
  1729. safe_delete(itr->second);
  1730. }
  1731. merchant_info.clear();
  1732. MMerchantList.unlock();
  1733. }
  1734. void World::DeleteSpawns(){
  1735. //reloading = true;
  1736. //ClearLootTables();
  1737. /*
  1738. map<int32, NPC*>::iterator npc_list_iter;
  1739. for(npc_list_iter=npc_list.begin();npc_list_iter!=npc_list.end();npc_list_iter++) {
  1740. safe_delete(npc_list_iter->second);
  1741. }
  1742. npc_list.clear();
  1743. map<int32, Object*>::iterator object_list_iter;
  1744. for(object_list_iter=object_list.begin();object_list_iter!=object_list.end();object_list_iter++) {
  1745. safe_delete(object_list_iter->second);
  1746. }
  1747. object_list.clear();
  1748. map<int32, GroundSpawn*>::iterator groundspawn_list_iter;
  1749. for(groundspawn_list_iter=groundspawn_list.begin();groundspawn_list_iter!=groundspawn_list.end();groundspawn_list_iter++) {
  1750. safe_delete(groundspawn_list_iter->second);
  1751. }
  1752. groundspawn_list.clear();
  1753. map<int32, Widget*>::iterator widget_list_iter;
  1754. for(widget_list_iter=widget_list.begin();widget_list_iter!=widget_list.end();widget_list_iter++) {
  1755. safe_delete(widget_list_iter->second);
  1756. }
  1757. widget_list.clear();
  1758. map<int32, Sign*>::iterator sign_list_iter;
  1759. for(sign_list_iter=sign_list.begin();sign_list_iter!=sign_list.end();sign_list_iter++) {
  1760. safe_delete(sign_list_iter->second);
  1761. }
  1762. sign_list.clear();*/
  1763. map<int32, AppearanceData*>::iterator appearance_list_iter;
  1764. for(appearance_list_iter=npc_appearance_list.begin();appearance_list_iter!=npc_appearance_list.end();appearance_list_iter++) {
  1765. safe_delete(appearance_list_iter->second);
  1766. }
  1767. npc_appearance_list.clear();
  1768. /*
  1769. map<int32, vector<EntityCommand*>* >::iterator command_list_iter;
  1770. for(command_list_iter=entity_command_list.begin();command_list_iter!=entity_command_list.end();command_list_iter++) {
  1771. vector<EntityCommand*>* v = command_list_iter->second;
  1772. if(v){
  1773. for(int32 i=0;i<v->size();i++){
  1774. safe_delete(v->at(i));
  1775. }
  1776. safe_delete(v);
  1777. }
  1778. }
  1779. entity_command_list.clear();
  1780. */
  1781. //DeleteGroundSpawnItems();
  1782. //DeleteTransporters();
  1783. //DeleteTransporterMaps();
  1784. }
  1785. void World::ReloadGuilds() {
  1786. guild_list.GetGuilds()->clear(true);
  1787. database.LoadGuilds();
  1788. }
  1789. int8 World::GetClassID(const char* name){
  1790. return classes.GetClassID(name);
  1791. }
  1792. void World::WritePlayerStatistics() {
  1793. zone_list.WritePlayerStatistics();
  1794. }
  1795. void World::WriteServerStatistics() {
  1796. map<int32, Statistic*>::iterator itr;
  1797. Statistic* stat = 0;
  1798. for (itr = server_statistics.begin(); itr != server_statistics.end(); itr++) {
  1799. stat = itr->second;
  1800. if (stat->save_needed) {
  1801. stat->save_needed = false;
  1802. database.WriteServerStatistic(stat);
  1803. }
  1804. }
  1805. database.WriteServerStatisticsNeededQueries();
  1806. }
  1807. void World::AddServerStatistic(int32 stat_id, sint32 stat_value, int32 stat_date) {
  1808. if (server_statistics.count(stat_id) == 0) {
  1809. Statistic* stat = new Statistic;
  1810. stat->stat_id = stat_id;
  1811. stat->stat_value = stat_value;
  1812. stat->stat_date = stat_date;
  1813. stat->save_needed = false;
  1814. server_statistics[stat_id] = stat;
  1815. }
  1816. }
  1817. void World::UpdateServerStatistic(int32 stat_id, sint32 stat_value, bool overwrite) {
  1818. if (server_statistics.count(stat_id) == 0)
  1819. AddServerStatistic(stat_id, stat_value, 0);
  1820. Statistic* stat = server_statistics[stat_id];
  1821. overwrite == true ? stat->stat_value = stat_value : stat->stat_value += stat_value;
  1822. stat->stat_date = Timer::GetUnixTimeStamp();
  1823. stat->save_needed = true;
  1824. }
  1825. sint32 World::GetServerStatisticValue(int32 stat_id) {
  1826. if (server_statistics.count(stat_id) > 0)
  1827. return server_statistics[stat_id]->stat_value;
  1828. return 0;
  1829. }
  1830. void World::RemoveServerStatistics() {
  1831. map<int32, Statistic*>::iterator stat_itr;
  1832. for (stat_itr = server_statistics.begin(); stat_itr != server_statistics.end(); stat_itr++)
  1833. safe_delete(stat_itr->second);
  1834. server_statistics.clear();
  1835. }
  1836. void World::SendGroupQuests(PlayerGroup* group, Client* client){
  1837. return;
  1838. /*if(!group)
  1839. return;
  1840. GroupMemberInfo* info = 0;
  1841. MGroups.readlock(__FUNCTION__, __LINE__);
  1842. deque<GroupMemberInfo*>::iterator itr;
  1843. for(itr = group->members.begin(); itr != group->members.end(); itr++){
  1844. info = *itr;
  1845. if(info->client){
  1846. LogWrite(PLAYER__DEBUG, 0, "Player", "Send Quest Journal...");
  1847. info->client->SendQuestJournal(false, client);
  1848. client->SendQuestJournal(false, info->client);
  1849. }
  1850. }
  1851. MGroups.releasereadlock(__FUNCTION__, __LINE__);*/
  1852. }
  1853. /*void World::CheckRemoveGroupedPlayer(){
  1854. map<GroupMemberInfo*, int32>::iterator itr;
  1855. GroupMemberInfo* found = 0;
  1856. MGroups.readlock(__FUNCTION__, __LINE__);
  1857. for(itr = group_removal_pending.begin(); itr != group_removal_pending.end(); itr++){
  1858. if(itr->second < Timer::GetCurrentTime2()){
  1859. found = itr->first;
  1860. break;
  1861. }
  1862. }
  1863. MGroups.releasereadlock(__FUNCTION__, __LINE__);
  1864. if(found){
  1865. if(!found->client || (found->client && found->client->IsConnected() == false))
  1866. DeleteGroupMember(found);
  1867. else{
  1868. MGroups.writelock(__FUNCTION__, __LINE__);
  1869. group_removal_pending.erase(found);
  1870. MGroups.releasewritelock(__FUNCTION__, __LINE__);
  1871. }
  1872. }
  1873. }*/
  1874. bool World::RejoinGroup(Client* client, int32 group_id){
  1875. if (!group_id) // no need if no group id!
  1876. return false;
  1877. world.GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  1878. PlayerGroup* group = world.GetGroupManager()->GetGroup(group_id);
  1879. deque<GroupMemberInfo*>* members = 0;
  1880. if (group)
  1881. members = group->GetMembers();
  1882. string name = string(client->GetPlayer()->GetName());
  1883. if (!members)
  1884. {
  1885. // group does not exist!
  1886. Query query;
  1887. query.AddQueryAsync(client->GetCharacterID(), &database, Q_INSERT, "UPDATE characters set group_id = 0 where id = %u",
  1888. client->GetCharacterID());
  1889. LogWrite(PLAYER__ERROR, 0, "Player", "Group did not exist for player %s to group id %i, async query to group_id = 0.", name.c_str(), group_id);
  1890. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  1891. return false;
  1892. }
  1893. deque<GroupMemberInfo*>::iterator itr;
  1894. GroupMemberInfo* info = 0;
  1895. bool match = false;
  1896. group->MGroupMembers.writelock();
  1897. for (itr = members->begin(); itr != members->end(); itr++) {
  1898. info = *itr;
  1899. if (info && info->name == name && info->is_client)
  1900. {
  1901. info->client = client;
  1902. info->member = client->GetPlayer();
  1903. client->GetPlayer()->SetGroup(group);
  1904. client->GetPlayer()->SetGroupMemberInfo(info);
  1905. client->GetPlayer()->UpdateGroupMemberInfo(true, true);
  1906. LogWrite(PLAYER__DEBUG, 0, "Player", "Identified group match for player %s to group id %u", name.c_str(), group_id);
  1907. match = true;
  1908. break;
  1909. }
  1910. }
  1911. group->MGroupMembers.releasewritelock();
  1912. // must be done after cause it needs a readlock
  1913. if (match)
  1914. group->SendGroupUpdate();
  1915. if (!match)
  1916. LogWrite(PLAYER__ERROR, 0, "Player", "Identified group match for player %s to group id %u, however the player name was not present in the group! May be an old group id that has been re-used.", name.c_str(), group_id);
  1917. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  1918. return match;
  1919. }
  1920. void World::AddBonuses(Item* item, ItemStatsValues* values, int16 type, sint32 value, Entity* entity){
  1921. if(values){
  1922. if(item && entity && entity->IsPlayer())
  1923. {
  1924. int32 effective_level = entity->GetInfoStructUInt("effective_level");
  1925. if(effective_level && effective_level < entity->GetLevel() && item->details.recommended_level > effective_level)
  1926. {
  1927. int32 diff = item->details.recommended_level - effective_level;
  1928. float tmpValue = (float)value;
  1929. value = (sint32)(float)(tmpValue / (1.0f + ((float)diff * .05f)));
  1930. }
  1931. }
  1932. switch(type){
  1933. case ITEM_STAT_STR:{
  1934. values->str += value;
  1935. break;
  1936. }
  1937. case ITEM_STAT_STA:{
  1938. values->sta += value;
  1939. break;
  1940. }
  1941. case ITEM_STAT_AGI:{
  1942. values->agi += value;
  1943. break;
  1944. }
  1945. case ITEM_STAT_WIS:{
  1946. values->wis += value;
  1947. break;
  1948. }
  1949. case ITEM_STAT_INT:{
  1950. values->int_ += value;
  1951. break;
  1952. }
  1953. case ITEM_STAT_VS_SLASH:{
  1954. values->vs_slash += value;
  1955. break;
  1956. }
  1957. case ITEM_STAT_VS_CRUSH:{
  1958. values->vs_crush += value;
  1959. break;
  1960. }
  1961. case ITEM_STAT_VS_PIERCE:{
  1962. values->vs_pierce += value;
  1963. break;
  1964. }
  1965. case ITEM_STAT_VS_HEAT:{
  1966. values->vs_heat += value;
  1967. break;
  1968. }
  1969. case ITEM_STAT_VS_COLD:{
  1970. values->vs_cold += value;
  1971. break;
  1972. }
  1973. case ITEM_STAT_VS_MAGIC:{
  1974. values->vs_magic += value;
  1975. break;
  1976. }
  1977. case ITEM_STAT_VS_MENTAL:{
  1978. values->vs_mental += value;
  1979. break;
  1980. }
  1981. case ITEM_STAT_VS_DIVINE:{
  1982. values->vs_divine += value;
  1983. break;
  1984. }
  1985. case ITEM_STAT_VS_DISEASE:{
  1986. values->vs_disease += value;
  1987. break;
  1988. }
  1989. case ITEM_STAT_VS_POISON:{
  1990. values->vs_poison += value;
  1991. break;
  1992. }
  1993. case ITEM_STAT_HEALTH:{
  1994. values->health += value;
  1995. break;
  1996. }
  1997. case ITEM_STAT_POWER:{
  1998. values->power += value;
  1999. break;
  2000. }
  2001. case ITEM_STAT_CONCENTRATION:{
  2002. values->concentration += value;
  2003. break;
  2004. }
  2005. case ITEM_STAT_ABILITY_MODIFIER:{
  2006. values->ability_modifier += value;
  2007. break;
  2008. }
  2009. case ITEM_STAT_CRITICALMITIGATION:{
  2010. values->criticalmitigation += value;
  2011. break;
  2012. }
  2013. case ITEM_STAT_EXTRASHIELDBLOCKCHANCE:{
  2014. values->extrashieldblockchance += value;
  2015. break;
  2016. }
  2017. case ITEM_STAT_BENEFICIALCRITCHANCE:{
  2018. values->beneficialcritchance += value;
  2019. break;
  2020. }
  2021. case ITEM_STAT_CRITBONUS:{
  2022. values->critbonus += value;
  2023. break;
  2024. }
  2025. case ITEM_STAT_POTENCY:{
  2026. values->potency += value;
  2027. break;
  2028. }
  2029. case ITEM_STAT_HATEGAINMOD:{
  2030. values->hategainmod += value;
  2031. break;
  2032. }
  2033. case ITEM_STAT_ABILITYREUSESPEED:{
  2034. values->abilityreusespeed += value;
  2035. break;
  2036. }
  2037. case ITEM_STAT_ABILITYCASTINGSPEED:{
  2038. values->abilitycastingspeed += value;
  2039. break;
  2040. }
  2041. case ITEM_STAT_ABILITYRECOVERYSPEED:{
  2042. values->abilityrecoveryspeed += value;
  2043. break;
  2044. }
  2045. case ITEM_STAT_SPELLREUSESPEED:{
  2046. values->spellreusespeed += value;
  2047. break;
  2048. }
  2049. case ITEM_STAT_SPELLMULTIATTACKCHANCE:{
  2050. values->spellmultiattackchance += value;
  2051. break;
  2052. }
  2053. case ITEM_STAT_DPS:{
  2054. values->dps += value;
  2055. break;
  2056. }
  2057. case ITEM_STAT_ATTACKSPEED:{
  2058. values->attackspeed += value;
  2059. break;
  2060. }
  2061. case ITEM_STAT_MULTIATTACKCHANCE:{
  2062. values->multiattackchance += value;
  2063. break;
  2064. }
  2065. case ITEM_STAT_AEAUTOATTACKCHANCE:{
  2066. values->aeautoattackchance += value;
  2067. break;
  2068. }
  2069. case ITEM_STAT_STRIKETHROUGH:{
  2070. values->strikethrough += value;
  2071. break;
  2072. }
  2073. case ITEM_STAT_ACCURACY:{
  2074. values->accuracy += value;
  2075. break;
  2076. }
  2077. /*case ITEM_STAT_OFFENSIVESPEED:{
  2078. values->offensivespeed += value;
  2079. break;
  2080. }*/
  2081. default: {
  2082. if (entity) {
  2083. entity->MStats.lock();
  2084. entity->stats[type] += value;
  2085. entity->MStats.unlock();
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. }
  2092. int32 World::CreateGuild(const char* guild_name, Client* leader, int32 group_id) {
  2093. deque<GroupMemberInfo*>::iterator itr;
  2094. GroupMemberInfo* gmi;
  2095. Guild *guild;
  2096. assert(guild_name);
  2097. guild = new Guild();
  2098. guild->SetName(guild_name);
  2099. guild->SetFormedDate(Timer::GetUnixTimeStamp());
  2100. database.LoadGuildDefaultRanks(guild);
  2101. database.LoadGuildDefaultEventFilters(guild);
  2102. database.SaveGuild(guild, true); // sets the guild id
  2103. database.SaveGuildEvents(guild);
  2104. database.SaveGuildRanks(guild);
  2105. database.SaveGuildEventFilters(guild);
  2106. database.SaveGuildRecruiting(guild);
  2107. guild_list.AddGuild(guild);
  2108. if (leader && !leader->GetPlayer()->GetGuild())
  2109. guild->AddNewGuildMember(leader, 0, GUILD_RANK_LEADER);
  2110. database.SaveGuildMembers(guild);
  2111. if (leader && group_id > 0) {
  2112. GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  2113. PlayerGroup* group = world.GetGroupManager()->GetGroup(group_id);
  2114. if (group)
  2115. {
  2116. group->MGroupMembers.readlock(__FUNCTION__, __LINE__);
  2117. deque<GroupMemberInfo*>* members = group->GetMembers();
  2118. for (itr = members->begin(); itr != members->end(); itr++) {
  2119. gmi = *itr;
  2120. if (gmi->client && gmi->client != leader && !gmi->client->GetPlayer()->GetGuild())
  2121. guild->InvitePlayer(gmi->client, leader->GetPlayer()->GetName());
  2122. }
  2123. group->MGroupMembers.releasereadlock(__FUNCTION__, __LINE__);
  2124. }
  2125. GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  2126. }
  2127. return guild->GetID();
  2128. }
  2129. void World::SaveGuilds() {
  2130. MutexMap<int32, Guild*>* guilds = guild_list.GetGuilds();
  2131. MutexMap<int32, Guild*>::iterator itr = guilds->begin();
  2132. while (itr.Next()) {
  2133. Guild* guild = itr.second;
  2134. if (guild->GetSaveNeeded())
  2135. database.SaveGuild(guild);
  2136. if (guild->GetMemberSaveNeeded())
  2137. database.SaveGuildMembers(guild);
  2138. if (guild->GetEventsSaveNeeded())
  2139. database.SaveGuildEvents(guild);
  2140. if (guild->GetRanksSaveNeeded())
  2141. database.SaveGuildRanks(guild);
  2142. if (guild->GetEventFiltersSaveNeeded())
  2143. database.SaveGuildEventFilters(guild);
  2144. if (guild->GetPointsHistorySaveNeeded())
  2145. database.SaveGuildPointsHistory(guild);
  2146. if (guild->GetRecruitingSaveNeeded())
  2147. database.SaveGuildRecruiting(guild);
  2148. }
  2149. }
  2150. void World::PickRandomLottoDigits(int32* digits) {
  2151. if (digits) {
  2152. for (int32 i = 0; i < 6; i++) {
  2153. bool found = true;
  2154. int32 num = 0;
  2155. while (found) {
  2156. num = ((int32)rand() % 36) + 1;
  2157. for (int32 j = 0; j < 6; j++) {
  2158. if (digits[j] == num)
  2159. break;
  2160. if (j == 5)
  2161. found = false;
  2162. }
  2163. }
  2164. digits[i] = num;
  2165. }
  2166. }
  2167. }
  2168. void World::AddLottoPlayer(int32 character_id, int32 end_time) {
  2169. LottoPlayer* lp;
  2170. if (lotto_players.count(character_id) == 0) {
  2171. lp = new LottoPlayer;
  2172. lotto_players.Put(character_id, lp);
  2173. }
  2174. else
  2175. lp = lotto_players.Get(character_id);
  2176. lp->end_time = end_time;
  2177. lp->num_matches = 0;
  2178. lp->set = false;
  2179. }
  2180. void World::RemoveLottoPlayer(int32 character_id) {
  2181. if (lotto_players.count(character_id) > 0)
  2182. lotto_players.erase(character_id, false, true);
  2183. }
  2184. void World::SetLottoPlayerNumMatches(int32 character_id, int8 num_matches) {
  2185. if (lotto_players.count(character_id) > 0) {
  2186. lotto_players.Get(character_id)->num_matches = num_matches;
  2187. lotto_players.Get(character_id)->set = true;
  2188. }
  2189. }
  2190. void World::CheckLottoPlayers() {
  2191. MutexMap<int32, LottoPlayer*>::iterator itr = lotto_players.begin();
  2192. while (itr.Next()) {
  2193. LottoPlayer* lp = itr->second;
  2194. if (Timer::GetCurrentTime2() >= lp->end_time && lp->set) {
  2195. int8 num_matches = lp->num_matches;
  2196. LogWrite(PLAYER__DEBUG, 0, "Player", "Num matches: %u", lp->num_matches);
  2197. Client* client = zone_list.GetClientByCharID(itr->first);
  2198. if (client && num_matches >= 2) {
  2199. if (num_matches == 2) {
  2200. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You receive 10 silver.");
  2201. client->SendPopupMessage(0, "Congratulations! You have won 10 silver!", "", 2, 0xFF, 0xFF, 0x99);
  2202. client->GetPlayer()->AddCoins(1000);
  2203. client->GetPlayer()->GetZone()->SendCastSpellPacket(869, client->GetPlayer());
  2204. }
  2205. else if (num_matches == 3) {
  2206. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You receive 50 silver.");
  2207. client->SendPopupMessage(0, "Congratulations! You have won 50 silver!", "", 2, 0xFF, 0xFF, 0x99);
  2208. client->GetPlayer()->AddCoins(5000);
  2209. client->GetPlayer()->GetZone()->SendCastSpellPacket(870, client->GetPlayer());
  2210. }
  2211. else if (num_matches == 4) {
  2212. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You receive 2 gold 50 silver.");
  2213. client->SendPopupMessage(0, "Congratulations! You have won 2 gold 50 silver!", "", 2, 0xFF, 0xFF, 0x99);
  2214. client->GetPlayer()->AddCoins(25000);
  2215. client->GetPlayer()->GetZone()->SendCastSpellPacket(871, client->GetPlayer());
  2216. }
  2217. else if (num_matches == 5) {
  2218. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You receive 25 gold.");
  2219. client->SendPopupMessage(0, "Congratulations! You have won 25 gold!", "", 2, 0xFF, 0xFF, 0x99);
  2220. client->GetPlayer()->AddCoins(250000);
  2221. client->GetPlayer()->GetZone()->SendCastSpellPacket(872, client->GetPlayer());
  2222. }
  2223. else if (num_matches == 6) {
  2224. Variable* var = variables.FindVariable("gambling_current_jackpot");
  2225. if (var) {
  2226. int64 jackpot = 0;
  2227. try {
  2228. jackpot = atoul(var->GetValue());
  2229. }
  2230. catch (...) {
  2231. jackpot = 10000;
  2232. }
  2233. char coin_message[128];
  2234. char message[512];
  2235. char announcement[512];
  2236. memset(coin_message, 0, sizeof(coin_message));
  2237. memset(message, 0, sizeof(message));
  2238. memset(announcement, 0, sizeof(announcement));
  2239. sprintf(coin_message, "%s", client->GetCoinMessage(jackpot).c_str());
  2240. sprintf(message, "Congratulations! You have won %s!", coin_message);
  2241. sprintf(announcement, "%s as won the jackpot containing a total of %s!", client->GetPlayer()->GetName(), coin_message);
  2242. client->Message(CHANNEL_COLOR_YELLOW, "You receive %s.", coin_message);
  2243. client->SendPopupMessage(0, message, "", 2, 0xFF, 0xFF, 0x99);
  2244. zone_list.HandleGlobalAnnouncement(announcement);
  2245. client->GetPlayer()->AddCoins(jackpot);
  2246. client->GetPlayer()->GetZone()->SendCastSpellPacket(843, client->GetPlayer());
  2247. client->GetPlayer()->GetZone()->SendCastSpellPacket(1413, client->GetPlayer());
  2248. }
  2249. }
  2250. }
  2251. RemoveLottoPlayer(itr->first);
  2252. }
  2253. }
  2254. }
  2255. void World::AddHouseZone(int32 id, string name, int64 cost_coins, int32 cost_status, int64 upkeep_coins, int32 upkeep_status, int8 vault_slots, int8 alignment, int8 guild_level, int32 zone_id, int32 exit_zone_id, float exit_x, float exit_y, float exit_z, float exit_heading) {
  2256. MHouseZones.writelock(__FUNCTION__, __LINE__);
  2257. if (m_houseZones.count(id) == 0) {
  2258. HouseZone* hz = new HouseZone;
  2259. //ZeroMemory(hz, sizeof(HouseZone));
  2260. hz->id = id;
  2261. hz->name = name;
  2262. hz->cost_coin = cost_coins;
  2263. hz->cost_status = cost_status;
  2264. hz->upkeep_coin = upkeep_coins;
  2265. hz->upkeep_status = upkeep_status;
  2266. hz->vault_slots = vault_slots;
  2267. hz->alignment = alignment;
  2268. hz->guild_level = guild_level;
  2269. hz->zone_id = zone_id;
  2270. hz->exit_zone_id = exit_zone_id;
  2271. hz->exit_x = exit_x;
  2272. hz->exit_y = exit_y;
  2273. hz->exit_z = exit_z;
  2274. hz->exit_heading = exit_heading;
  2275. m_houseZones[id] = hz;
  2276. }
  2277. else {
  2278. LogWrite(WORLD__ERROR, 0, "Housing", "Duplicate house id (%u) for %s", id, name.c_str());
  2279. }
  2280. MHouseZones.releasewritelock(__FUNCTION__, __LINE__);
  2281. }
  2282. HouseZone* World::GetHouseZone(int32 id) {
  2283. HouseZone* ret = 0;
  2284. MHouseZones.readlock(__FUNCTION__, __LINE__);
  2285. if (m_houseZones.count(id) > 0)
  2286. ret = m_houseZones[id];
  2287. MHouseZones.releasereadlock(__FUNCTION__, __LINE__);
  2288. return ret;
  2289. }
  2290. void World::AddPlayerHouse(int32 char_id, int32 house_id, int64 unique_id, int32 instance_id, int32 upkeep_due, int64 escrow_coins, int32 escrow_status, string player_name) {
  2291. MPlayerHouses.writelock(__FUNCTION__, __LINE__);
  2292. if (m_playerHouses.count(house_id) == 0 || m_playerHouses[house_id].count(char_id) == 0) {
  2293. PlayerHouse* ph = new PlayerHouse;
  2294. ph->house_id = house_id;
  2295. ph->unique_id = unique_id;
  2296. ph->instance_id = instance_id;
  2297. ph->escrow_coins = escrow_coins;
  2298. ph->escrow_status = escrow_status;
  2299. ph->upkeep_due = upkeep_due;
  2300. ph->player_name = player_name;
  2301. ReloadHouseData(ph);
  2302. m_playerHouses[house_id][char_id] = ph;
  2303. }
  2304. MPlayerHouses.releasewritelock(__FUNCTION__, __LINE__);
  2305. }
  2306. void World::ReloadHouseData(PlayerHouse* ph)
  2307. {
  2308. database.LoadDeposits(ph);
  2309. database.LoadHistory(ph);
  2310. }
  2311. PlayerHouse* World::GetPlayerHouseByHouseID(int32 char_id, int32 house_id) {
  2312. PlayerHouse* ret = 0;
  2313. MPlayerHouses.readlock(__FUNCTION__, __LINE__);
  2314. if (m_playerHouses.count(house_id) > 0 && m_playerHouses[house_id].count(char_id) > 0)
  2315. ret = m_playerHouses[house_id][char_id];
  2316. MPlayerHouses.releasereadlock(__FUNCTION__, __LINE__);
  2317. return ret;
  2318. }
  2319. PlayerHouse* World::GetPlayerHouseByUniqueID(int64 unique_id) {
  2320. PlayerHouse* ret = 0;
  2321. MPlayerHouses.readlock(__FUNCTION__, __LINE__);
  2322. map<int32, map<int32, PlayerHouse*> >::iterator itr;
  2323. for (itr = m_playerHouses.begin(); itr != m_playerHouses.end(); itr++) {
  2324. map<int32, PlayerHouse*>::iterator itr2;
  2325. for (itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++) {
  2326. if (itr2->second->unique_id == unique_id) {
  2327. ret = itr2->second;
  2328. break;
  2329. }
  2330. }
  2331. if (ret)
  2332. break;
  2333. }
  2334. MPlayerHouses.releasereadlock(__FUNCTION__, __LINE__);
  2335. return ret;
  2336. }
  2337. PlayerHouse* World::GetPlayerHouseByInstanceID(int32 instance_id) {
  2338. PlayerHouse* ret = 0;
  2339. MPlayerHouses.readlock(__FUNCTION__, __LINE__);
  2340. map<int32, map<int32, PlayerHouse*> >::iterator itr;
  2341. for (itr = m_playerHouses.begin(); itr != m_playerHouses.end(); itr++) {
  2342. map<int32, PlayerHouse*>::iterator itr2;
  2343. for (itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++) {
  2344. if (itr2->second->instance_id == instance_id) {
  2345. ret = itr2->second;
  2346. break;
  2347. }
  2348. }
  2349. if (ret)
  2350. break;
  2351. }
  2352. MPlayerHouses.releasereadlock(__FUNCTION__, __LINE__);
  2353. return ret;
  2354. }
  2355. vector<PlayerHouse*> World::GetAllPlayerHouses(int32 char_id) {
  2356. vector<PlayerHouse*> ret;
  2357. MPlayerHouses.readlock(__FUNCTION__, __LINE__);
  2358. map<int32, map<int32, PlayerHouse*> >::iterator itr;
  2359. for (itr = m_playerHouses.begin(); itr != m_playerHouses.end(); itr++) {
  2360. if (itr->second.count(char_id) > 0)
  2361. ret.push_back(itr->second[char_id]);
  2362. }
  2363. MPlayerHouses.releasereadlock(__FUNCTION__, __LINE__);
  2364. return ret;
  2365. }
  2366. vector<PlayerHouse*> World::GetAllPlayerHousesByHouseID(int32 house_id) {
  2367. vector<PlayerHouse*> ret;
  2368. MPlayerHouses.readlock(__FUNCTION__, __LINE__);
  2369. if (m_houseZones.count(house_id) > 0) {
  2370. map<int32, PlayerHouse*>::iterator itr;
  2371. for (itr = m_playerHouses[house_id].begin(); itr != m_playerHouses[house_id].end(); itr++)
  2372. ret.push_back(itr->second);
  2373. }
  2374. MPlayerHouses.releasereadlock(__FUNCTION__, __LINE__);
  2375. return ret;
  2376. }
  2377. PlayerHouse* World::GetPlayerHouse(Client* client, int32 spawn_id, int64 unique_house_id, HouseZone** set_house_zone) {
  2378. PlayerHouse* ph = nullptr;
  2379. HouseZone* hz = nullptr;
  2380. if(spawn_id) {
  2381. Spawn* houseWidget = client->GetPlayer()->GetSpawnByIndex(spawn_id);
  2382. if(houseWidget && houseWidget->IsWidget() && ((Widget*)houseWidget)->GetHouseID()) {
  2383. hz = world.GetHouseZone(((Widget*)houseWidget)->GetHouseID());
  2384. if (hz) {
  2385. ph = world.GetPlayerHouseByHouseID(client->GetPlayer()->GetCharacterID(), hz->id);
  2386. }
  2387. }
  2388. }
  2389. if(!ph && client->GetCurrentZone()->GetInstanceID()) {
  2390. ph = world.GetPlayerHouseByInstanceID(client->GetCurrentZone()->GetInstanceID());
  2391. }
  2392. if(!ph && unique_house_id) {
  2393. ph = world.GetPlayerHouseByUniqueID(unique_house_id);
  2394. }
  2395. if (ph && !hz) {
  2396. hz = world.GetHouseZone(ph->house_id);
  2397. }
  2398. if(set_house_zone)
  2399. *set_house_zone = hz;
  2400. return ph;
  2401. }
  2402. void World::PopulateTOVStatMap() {
  2403. //This function populates a map that converts changed CoE to ToV stats
  2404. tov_itemstat_conversion[0] = TOV_ITEM_STAT_HPREGEN;
  2405. tov_itemstat_conversion[1] = TOV_ITEM_STAT_MANAREGEN;
  2406. tov_itemstat_conversion[2] = TOV_ITEM_STAT_HPREGENPPT;
  2407. tov_itemstat_conversion[3] = TOV_ITEM_STAT_MPREGENPPT;
  2408. tov_itemstat_conversion[4] = TOV_ITEM_STAT_COMBATHPREGENPPT;
  2409. tov_itemstat_conversion[5] = TOV_ITEM_STAT_COMBATMPREGENPPT;
  2410. tov_itemstat_conversion[6] = TOV_ITEM_STAT_MAXHP;
  2411. tov_itemstat_conversion[7] = TOV_ITEM_STAT_MAXHPPERC;
  2412. tov_itemstat_conversion[8] = TOV_ITEM_STAT_MAXHPPERCFINAL;
  2413. tov_itemstat_conversion[9] = TOV_ITEM_STAT_SPEED;
  2414. tov_itemstat_conversion[10] = TOV_ITEM_STAT_SLOW;
  2415. tov_itemstat_conversion[11] = TOV_ITEM_STAT_MOUNTSPEED;
  2416. tov_itemstat_conversion[12] = TOV_ITEM_STAT_MOUNTAIRSPEED;
  2417. tov_itemstat_conversion[13] = TOV_ITEM_STAT_LEAPSPEED;
  2418. tov_itemstat_conversion[14] = TOV_ITEM_STAT_LEAPTIME;
  2419. tov_itemstat_conversion[15] = TOV_ITEM_STAT_GLIDEEFFICIENCY;
  2420. tov_itemstat_conversion[16] = TOV_ITEM_STAT_OFFENSIVESPEED;
  2421. tov_itemstat_conversion[17] = TOV_ITEM_STAT_ATTACKSPEED;
  2422. tov_itemstat_conversion[18] = 698;
  2423. tov_itemstat_conversion[19] = TOV_ITEM_STAT_MAXMANA;
  2424. tov_itemstat_conversion[20] = TOV_ITEM_STAT_MAXMANAPERC;
  2425. tov_itemstat_conversion[21] = TOV_ITEM_STAT_MAXATTPERC;
  2426. tov_itemstat_conversion[22] = TOV_ITEM_STAT_BLURVISION;
  2427. tov_itemstat_conversion[23] = TOV_ITEM_STAT_MAGICLEVELIMMUNITY;
  2428. tov_itemstat_conversion[24] = TOV_ITEM_STAT_HATEGAINMOD;
  2429. tov_itemstat_conversion[25] = TOV_ITEM_STAT_COMBATEXPMOD;
  2430. tov_itemstat_conversion[26] = TOV_ITEM_STAT_TRADESKILLEXPMOD;
  2431. tov_itemstat_conversion[27] = TOV_ITEM_STAT_ACHIEVEMENTEXPMOD;
  2432. tov_itemstat_conversion[28] = TOV_ITEM_STAT_SIZEMOD;
  2433. tov_itemstat_conversion[29] = TOV_ITEM_STAT_DPS;
  2434. tov_itemstat_conversion[30] = 698;
  2435. tov_itemstat_conversion[31] = TOV_ITEM_STAT_STEALTH;
  2436. tov_itemstat_conversion[32] = TOV_ITEM_STAT_INVIS;
  2437. tov_itemstat_conversion[33] = TOV_ITEM_STAT_SEESTEALTH;
  2438. tov_itemstat_conversion[34] = TOV_ITEM_STAT_SEEINVIS;
  2439. tov_itemstat_conversion[35] = TOV_ITEM_STAT_EFFECTIVELEVELMOD;
  2440. tov_itemstat_conversion[36] = TOV_ITEM_STAT_RIPOSTECHANCE;
  2441. tov_itemstat_conversion[37] = TOV_ITEM_STAT_PARRYCHANCE;
  2442. tov_itemstat_conversion[38] = TOV_ITEM_STAT_DODGECHANCE;
  2443. tov_itemstat_conversion[39] = TOV_ITEM_STAT_AEAUTOATTACKCHANCE;
  2444. tov_itemstat_conversion[40] = 698;
  2445. tov_itemstat_conversion[41] = TOV_ITEM_STAT_MULTIATTACKCHANCE;
  2446. tov_itemstat_conversion[42] = 698;
  2447. tov_itemstat_conversion[43] = 698;
  2448. tov_itemstat_conversion[44] = 698;
  2449. tov_itemstat_conversion[45] = TOV_ITEM_STAT_SPELLMULTIATTACKCHANCE;
  2450. tov_itemstat_conversion[46] = 698;
  2451. tov_itemstat_conversion[47] = TOV_ITEM_STAT_FLURRY;
  2452. tov_itemstat_conversion[48] = 698;
  2453. tov_itemstat_conversion[49] = TOV_ITEM_STAT_MELEEDAMAGEMULTIPLIER;
  2454. tov_itemstat_conversion[50] = TOV_ITEM_STAT_EXTRAHARVESTCHANCE;
  2455. tov_itemstat_conversion[51] = TOV_ITEM_STAT_EXTRASHIELDBLOCKCHANCE;
  2456. tov_itemstat_conversion[52] = TOV_ITEM_STAT_ITEMHPREGENPPT;
  2457. tov_itemstat_conversion[53] = TOV_ITEM_STAT_ITEMPPREGENPPT;
  2458. tov_itemstat_conversion[54] = TOV_ITEM_STAT_MELEECRITCHANCE;
  2459. tov_itemstat_conversion[55] = TOV_ITEM_STAT_CRITAVOIDANCE;
  2460. tov_itemstat_conversion[56] = TOV_ITEM_STAT_BENEFICIALCRITCHANCE;
  2461. tov_itemstat_conversion[57] = TOV_ITEM_STAT_CRITBONUS;
  2462. tov_itemstat_conversion[58] = 698;
  2463. tov_itemstat_conversion[59] = TOV_ITEM_STAT_POTENCY;
  2464. tov_itemstat_conversion[60] = 698;
  2465. tov_itemstat_conversion[61] = TOV_ITEM_STAT_UNCONSCIOUSHPMOD;
  2466. tov_itemstat_conversion[62] = TOV_ITEM_STAT_ABILITYREUSESPEED;
  2467. tov_itemstat_conversion[63] = TOV_ITEM_STAT_ABILITYRECOVERYSPEED;
  2468. tov_itemstat_conversion[64] = TOV_ITEM_STAT_ABILITYCASTINGSPEED;
  2469. tov_itemstat_conversion[65] = TOV_ITEM_STAT_SPELLREUSESPEED;
  2470. tov_itemstat_conversion[66] = TOV_ITEM_STAT_MELEEWEAPONRANGE;
  2471. tov_itemstat_conversion[67] = TOV_ITEM_STAT_RANGEDWEAPONRANGE;
  2472. tov_itemstat_conversion[68] = TOV_ITEM_STAT_FALLINGDAMAGEREDUCTION;
  2473. tov_itemstat_conversion[69] = TOV_ITEM_STAT_RIPOSTEDAMAGE;
  2474. tov_itemstat_conversion[70] = TOV_ITEM_STAT_MINIMUMDEFLECTIONCHANCE;
  2475. tov_itemstat_conversion[71] = TOV_ITEM_STAT_MOVEMENTWEAVE;
  2476. tov_itemstat_conversion[72] = TOV_ITEM_STAT_COMBATHPREGEN;
  2477. tov_itemstat_conversion[73] = TOV_ITEM_STAT_COMBATMANAREGEN;
  2478. tov_itemstat_conversion[74] = TOV_ITEM_STAT_CONTESTSPEEDBOOST;
  2479. tov_itemstat_conversion[75] = TOV_ITEM_STAT_TRACKINGAVOIDANCE;
  2480. tov_itemstat_conversion[76] = TOV_ITEM_STAT_STEALTHINVISSPEEDMOD;
  2481. tov_itemstat_conversion[77] = TOV_ITEM_STAT_LOOT_COIN;
  2482. tov_itemstat_conversion[78] = TOV_ITEM_STAT_ARMORMITIGATIONINCREASE;
  2483. tov_itemstat_conversion[79] = TOV_ITEM_STAT_AMMOCONSERVATION;
  2484. tov_itemstat_conversion[80] = TOV_ITEM_STAT_STRIKETHROUGH;
  2485. tov_itemstat_conversion[81] = TOV_ITEM_STAT_STATUSBONUS;
  2486. tov_itemstat_conversion[82] = TOV_ITEM_STAT_ACCURACY;
  2487. tov_itemstat_conversion[83] = TOV_ITEM_STAT_COUNTERSTRIKE;
  2488. tov_itemstat_conversion[84] = TOV_ITEM_STAT_SHIELDBASH;
  2489. tov_itemstat_conversion[85] = TOV_ITEM_STAT_WEAPONDAMAGEBONUS;
  2490. tov_itemstat_conversion[86] = 698;
  2491. tov_itemstat_conversion[87] = TOV_ITEM_STAT_WEAPONDAMAGEBONUSMELEEONLY;
  2492. tov_itemstat_conversion[88] = TOV_ITEM_STAT_ADDITIONALRIPOSTECHANCE;
  2493. tov_itemstat_conversion[89] = TOV_ITEM_STAT_PVPTOUGHNESS;
  2494. tov_itemstat_conversion[90] = TOV_ITEM_STAT_PVPLETHALITY;
  2495. tov_itemstat_conversion[91] = TOV_ITEM_STAT_STAMINABONUS;
  2496. tov_itemstat_conversion[92] = TOV_ITEM_STAT_WISDOMMITBONUS;
  2497. tov_itemstat_conversion[93] = TOV_ITEM_STAT_HEALRECEIVE;
  2498. tov_itemstat_conversion[94] = TOV_ITEM_STAT_HEALRECEIVEPERC;
  2499. tov_itemstat_conversion[95] = TOV_ITEM_STAT_PVPCRITICALMITIGATION;
  2500. tov_itemstat_conversion[96] = TOV_ITEM_STAT_BASEAVOIDANCEBONUS;
  2501. tov_itemstat_conversion[97] = TOV_ITEM_STAT_INCOMBATSAVAGERYREGEN;
  2502. tov_itemstat_conversion[98] = TOV_ITEM_STAT_OUTOFCOMBATSAVAGERYREGEN;
  2503. tov_itemstat_conversion[99] = TOV_ITEM_STAT_SAVAGERYREGEN;
  2504. tov_itemstat_conversion[100] = TOV_ITEM_STAT_SAVAGERYGAINMOD;
  2505. tov_itemstat_conversion[101] = TOV_ITEM_STAT_MAXSAVAGERYLEVEL;
  2506. }
  2507. int32 World::LoadItemBlueStats() {
  2508. Query query;
  2509. MYSQL_ROW row;
  2510. int32 count = 0;
  2511. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT version_range1,version_range2,emu_stat,name,stat from itemstats");
  2512. if (result && mysql_num_rows(result) > 0) {
  2513. while (result && (row = mysql_fetch_row(result))) {
  2514. count++;
  2515. if (atoi(row[0]) >= 63119) //KA
  2516. ka_itemstat_conversion[atoi(row[2])] = atoi(row[4]);
  2517. else if (atoi(row[0]) >= 57101) // ToV
  2518. tov_itemstat_conversion[atoi(row[2])] = atoi(row[4]);
  2519. else if (atoi(row[0]) >= 1193) // CoE
  2520. coe_itemstat_conversion[atoi(row[2])] = atoi(row[4]);
  2521. else if (atoi(row[0]) >= 1096) // DoV
  2522. dov_itemstat_conversion[atoi(row[2])] = atoi(row[4]);
  2523. }
  2524. }
  2525. return count;
  2526. }
  2527. sint64 World::newValue = 0;
  2528. sint16 World::GetItemStatAOMValue(sint16 subtype) {
  2529. sint16 tmp_subtype = subtype;
  2530. // this is ugly for now cause I didn't want to map it all out, see a better way later but a lot of these are just slightly shifted
  2531. if(subtype > 39)
  2532. {
  2533. // 88 needs to be something else (crit mitigation)
  2534. // 19 needs to be something else (ability reuse speed) which is 62
  2535. if(subtype == 21) // ITEM_STAT_MAXATTPERC
  2536. tmp_subtype = 20;
  2537. else if(subtype == 41) // flurry
  2538. tmp_subtype = 39;
  2539. else if(subtype == 47) // flurry
  2540. tmp_subtype = 41;
  2541. else if(subtype == 49) // flurry
  2542. tmp_subtype = 42;
  2543. else if(subtype == 51) // ITEM_STAT_EXTRASHIELDBLOCKCHANCE
  2544. tmp_subtype = 44;
  2545. //tmp_subtype = 43 is bountiful harvest
  2546. else if(subtype == 54 && subtype <= 57) // ITEM_STAT_MELEECRITCHANCE
  2547. tmp_subtype = subtype - 7;
  2548. else if(subtype == 59) // ITEM_STAT_POTENCY
  2549. tmp_subtype = 51;
  2550. else if(subtype >= 61 && subtype <= 85) // ITEM_STAT_RANGEDWEAPONRANGE
  2551. tmp_subtype = subtype - 9; //
  2552. else if(subtype >= 86 && subtype <= 101) // ITEM_STAT_WEAPONDAMAGEBONUSMELEEONLY
  2553. tmp_subtype = subtype - 8; //
  2554. else if(subtype == 102) // ITEM_STAT_SPELLWEAPONDAMAGEBONUS
  2555. tmp_subtype = 77; //
  2556. else if(subtype >= 103 && subtype <= 110)
  2557. tmp_subtype = subtype - 9;
  2558. else if(subtype == 122) // ITEM_STAT_ABILITYDOUBLECASTCHANCE
  2559. tmp_subtype = 40; //
  2560. else if(subtype == 124) // ITEM_STAT_STATUSEARNED
  2561. tmp_subtype = 27; //
  2562. else
  2563. tmp_subtype += 1;
  2564. // 80 serves as ranged weapon range increase, but so does 58?
  2565. }
  2566. else if((subtype > 18 && subtype < 28) || subtype > 30) // max mana was 18
  2567. tmp_subtype = subtype - 1;
  2568. else if(subtype == 5)
  2569. tmp_subtype = 46;
  2570. else if(subtype == 4)
  2571. tmp_subtype = 45;
  2572. LogWrite(PLAYER__DEBUG, 0, "Player", "Convert type: %i -> %i", subtype, tmp_subtype);
  2573. return tmp_subtype;
  2574. }
  2575. sint16 World::GetItemStatTOVValue(sint16 subtype) {
  2576. return (tov_itemstat_conversion[subtype] - 600);
  2577. }
  2578. sint16 World::GetItemStatDOVValue(sint16 subtype) {
  2579. return (dov_itemstat_conversion[subtype] - 600);
  2580. }
  2581. sint16 World::GetItemStatCOEValue(sint16 subtype) {
  2582. return (coe_itemstat_conversion[subtype] - 600);
  2583. }
  2584. sint16 World::GetItemStatKAValue(sint16 subtype) {
  2585. return (ka_itemstat_conversion[subtype] - 600);
  2586. }
  2587. int8 World::TranslateSlotSubTypeToClient(Client* client, int8 stat_type, sint16 sub_type) {
  2588. int8 new_subtype = (int8)sub_type;
  2589. switch(stat_type) {
  2590. case 2: {
  2591. if(client->GetVersion() <= 561) {
  2592. if(sub_type == (ITEM_STAT_VS_POISON-200)) // poison
  2593. new_subtype = 9;
  2594. else if(sub_type == (ITEM_STAT_VS_DISEASE-200)) // disease
  2595. new_subtype = 8;
  2596. else if(sub_type == (ITEM_STAT_VS_COLD-200)) // cold
  2597. new_subtype = 4;
  2598. else if(sub_type == (ITEM_STAT_VS_HEAT-200) || sub_type == (ITEM_STAT_VS_MAGIC-200))
  2599. new_subtype += 2;
  2600. else if(sub_type == (ITEM_STAT_VS_MENTAL-200) || sub_type == (ITEM_STAT_VS_DIVINE-200))
  2601. new_subtype -= 2;
  2602. }
  2603. else if(client->GetVersion() >= 60085) { // AoM era since its the client we support
  2604. if(sub_type == (ITEM_STAT_VS_MENTAL-200) || sub_type == (ITEM_STAT_VS_DIVINE-200) || sub_type == (ITEM_STAT_VS_COLD-200)) {
  2605. new_subtype = 255; // omit client cannot properly display
  2606. }
  2607. }
  2608. break;
  2609. }
  2610. case 6:
  2611. case 7: {
  2612. if(stat_type == 7){
  2613. new_subtype = sub_type;
  2614. }
  2615. else if ((client->GetVersion() >= 63119) || client->GetVersion() == 61331){ //KA
  2616. new_subtype = world.GetItemStatKAValue(sub_type);
  2617. }
  2618. else if(client->GetVersion() >= 60085 ) {
  2619. new_subtype = world.GetItemStatAOMValue(sub_type);
  2620. }
  2621. else if (client->GetVersion() >= 57107){ //TOV
  2622. new_subtype = world.GetItemStatTOVValue(sub_type);
  2623. }
  2624. else if (client->GetVersion() >= 1193){ //COE
  2625. new_subtype = world.GetItemStatCOEValue(sub_type);
  2626. //tmp_subtype = stat->stat_subtype;
  2627. }
  2628. else if (client->GetVersion() >= 1096){ //DOV
  2629. new_subtype = world.GetItemStatDOVValue(sub_type); //comment out for testing
  2630. //tmp_subtype = stat->stat_subtype; //comment for normal use
  2631. }
  2632. break;
  2633. }
  2634. }
  2635. return new_subtype;
  2636. }
  2637. bool World::CheckTempBugCRC(char* msg)
  2638. {
  2639. MBugReport.writelock();
  2640. sint32 crc = GetItemNameCrc(std::string(msg));
  2641. if (bug_report_crc.count(crc) > 0)
  2642. {
  2643. MBugReport.releasewritelock();
  2644. return true;
  2645. }
  2646. else
  2647. bug_report_crc.insert(make_pair(crc, true));
  2648. MBugReport.releasewritelock();
  2649. return false;
  2650. }
  2651. #ifdef WIN32
  2652. ulong World::GetCurrentThreadID(){
  2653. return GetCurrentThreadId();
  2654. }
  2655. int64 World::GetThreadUsageCPUTime(){
  2656. HANDLE handle = GetCurrentThread();
  2657. int64 lpCreationTime;
  2658. int64 lpExitTime;
  2659. int64 lpKernelTime;
  2660. int64 lpUserTime;
  2661. if(GetThreadTimes(handle, (FILETIME*)&lpCreationTime, (FILETIME*)&lpExitTime, (FILETIME*)&lpKernelTime, (FILETIME*)&lpUserTime))
  2662. return lpKernelTime + lpUserTime;
  2663. return 0;
  2664. }
  2665. #else
  2666. #endif
  2667. void World::SyncCharacterAbilities(Client* client)
  2668. {
  2669. MStartingLists.readlock();
  2670. int8 baseClass = classes.GetBaseClass(client->GetPlayer()->GetAdventureClass());
  2671. int8 secondaryClass = classes.GetSecondaryBaseClass(client->GetPlayer()->GetAdventureClass());
  2672. int8 actualClass = client->GetPlayer()->GetAdventureClass();
  2673. int8 baseRace = client->GetPlayer()->GetRace();
  2674. multimap<int8, multimap<int8, StartingSkill>*>::iterator skill_itr = starting_skills.begin();
  2675. multimap<int8, multimap<int8, StartingSpell>*>::iterator spell_itr = starting_spells.begin();
  2676. bool isProcessing = false;
  2677. int8 wait_iterations = 0; // wait 5 iterations and give up if db takes too long
  2678. do
  2679. {
  2680. isProcessing = false;
  2681. if (skill_itr != starting_skills.end())
  2682. {
  2683. isProcessing = true;
  2684. // race = 255 is wildcard all, otherwise needs to match the race id
  2685. if (skill_itr->first == 255 || skill_itr->first == baseRace)
  2686. {
  2687. multimap<int8, StartingSkill>::iterator child_itr;
  2688. for (child_itr = skill_itr->second->begin(); child_itr != skill_itr->second->end(); child_itr++)
  2689. {
  2690. // class = 255 is wildcard all, otherwise needs to match the class id
  2691. if (child_itr->first == 255 ||
  2692. child_itr->first == baseClass ||
  2693. child_itr->first == secondaryClass ||
  2694. child_itr->first == actualClass)
  2695. {
  2696. if (!client->GetPlayer()->skill_list.HasSkill(child_itr->second.skill_id))
  2697. {
  2698. Query query;
  2699. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding skill %i for race: %i, class: %i for char_id: %u", child_itr->second.skill_id, baseRace, baseClass, client->GetCharacterID());
  2700. query.AddQueryAsync(client->GetCharacterID(), &database, Q_INSERT, "INSERT IGNORE INTO character_skills (char_id, skill_id, current_val, max_val) VALUES (%u, %u, %u, %u)",
  2701. client->GetCharacterID(), child_itr->second.skill_id, child_itr->second.current_val, child_itr->second.max_val);
  2702. client->GetPlayer()->AddSkill(child_itr->second.skill_id, child_itr->second.current_val, child_itr->second.max_val);
  2703. }
  2704. }
  2705. }
  2706. }
  2707. skill_itr++;
  2708. }
  2709. if (spell_itr != starting_spells.end())
  2710. {
  2711. isProcessing = true;
  2712. // race = 255 is wildcard all, otherwise needs to match the race id
  2713. if (spell_itr->first == 255 || spell_itr->first == baseRace)
  2714. {
  2715. multimap<int8, StartingSpell>::iterator child_itr;
  2716. for (child_itr = spell_itr->second->begin(); child_itr != spell_itr->second->end(); child_itr++)
  2717. {
  2718. // class = 255 is wildcard all, otherwise needs to match the class id
  2719. if (child_itr->first == 255 ||
  2720. child_itr->first == baseClass ||
  2721. child_itr->first == secondaryClass ||
  2722. child_itr->first == actualClass)
  2723. {
  2724. if (!client->GetPlayer()->HasSpell(child_itr->second.spell_id, child_itr->second.tier, true))
  2725. {
  2726. Query query;
  2727. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding spell %i for race: %i, class: %i for char_id: %u", child_itr->second.spell_id, baseRace, baseClass, client->GetCharacterID());
  2728. // knowledge_slot is a signed int in the DB
  2729. query.AddQueryAsync(client->GetCharacterID(), &database, Q_INSERT, "INSERT IGNORE INTO character_spells (char_id, spell_id, tier, knowledge_slot) VALUES (%u, %u, %u, %i)",
  2730. client->GetCharacterID(), child_itr->second.spell_id, child_itr->second.tier, child_itr->second.knowledge_slot);
  2731. // reload spells, we don't know the spellbook or timer info
  2732. client->GetPlayer()->GetInfoStruct()->set_reload_player_spells(1);
  2733. }
  2734. }
  2735. }
  2736. }
  2737. spell_itr++;
  2738. }
  2739. } while (isProcessing);
  2740. MStartingLists.releasereadlock();
  2741. }
  2742. void World::LoadStartingLists()
  2743. {
  2744. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `starting_skills`...");
  2745. database.LoadStartingSkills(this);
  2746. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `starting_spells`...");
  2747. database.LoadStartingSpells(this);
  2748. }
  2749. void World::PurgeStartingLists()
  2750. {
  2751. MStartingLists.writelock();
  2752. multimap<int8, multimap<int8, StartingSkill>*>::iterator skill_itr;
  2753. for (skill_itr = starting_skills.begin(); skill_itr != starting_skills.end(); skill_itr++)
  2754. {
  2755. multimap<int8, StartingSkill>* tmpMap = skill_itr->second;
  2756. safe_delete(tmpMap);
  2757. }
  2758. starting_skills.clear();
  2759. multimap<int8, multimap<int8, StartingSpell>*>::iterator spell_itr;
  2760. for (spell_itr = starting_spells.begin(); spell_itr != starting_spells.end(); spell_itr++)
  2761. {
  2762. multimap<int8, StartingSpell>* tmpMap = spell_itr->second;
  2763. safe_delete(tmpMap);
  2764. }
  2765. starting_spells.clear();
  2766. for(int type=0;type<3;type++) {
  2767. multimap<int32, multimap<int16, VoiceOverStruct>*>::iterator vos_itr;
  2768. for (vos_itr = voiceover_map[type].begin(); vos_itr != voiceover_map[type].end(); vos_itr++)
  2769. {
  2770. multimap<int16, VoiceOverStruct>* tmpMap = vos_itr->second;
  2771. safe_delete(tmpMap);
  2772. }
  2773. voiceover_map[type].clear();
  2774. }
  2775. MStartingLists.releasewritelock();
  2776. }
  2777. void World::SetReloadingSubsystem(string subsystem) {
  2778. MReloadingSubsystems.lock();
  2779. reloading_subsystems[subsystem] = Timer::GetCurrentTime2();
  2780. MReloadingSubsystems.unlock();
  2781. }
  2782. void World::RemoveReloadingSubSystem(string subsystem) {
  2783. MReloadingSubsystems.lock();
  2784. if (reloading_subsystems.count(subsystem) > 0)
  2785. reloading_subsystems.erase(subsystem);
  2786. MReloadingSubsystems.unlock();
  2787. }
  2788. bool World::IsReloadingSubsystems() {
  2789. bool result = false;
  2790. MReloadingSubsystems.lock();
  2791. result = reloading_subsystems.size() > 0;
  2792. MReloadingSubsystems.unlock();
  2793. return result;
  2794. }
  2795. map<string, int32> World::GetOldestReloadingSubsystem() {
  2796. map<string, int32> result;
  2797. MReloadingSubsystems.lock();
  2798. int32 current_time = Timer::GetCurrentTime2();
  2799. map<string, int32>::iterator itr;
  2800. int32 oldest = current_time;
  2801. string oldestname = "";
  2802. for (itr = reloading_subsystems.begin(); itr != reloading_subsystems.end(); itr++) {
  2803. if (itr->second < oldest) {
  2804. oldestname = itr->first;
  2805. result.clear();
  2806. result[oldestname] = oldest;
  2807. }
  2808. }
  2809. MReloadingSubsystems.unlock();
  2810. return result;
  2811. }
  2812. void ZoneList::WatchdogHeartbeat()
  2813. {
  2814. list<ZoneServer*>::iterator zone_iter;
  2815. ZoneServer* tmp = 0;
  2816. MZoneList.writelock(__FUNCTION__, __LINE__);
  2817. bool match = false;
  2818. for (zone_iter = zlist.begin(); zone_iter != zlist.end(); zone_iter++)
  2819. {
  2820. tmp = *zone_iter;
  2821. if (tmp)
  2822. {
  2823. int32 curTime = Timer::GetCurrentTime2();
  2824. sint64 diff = (sint64)curTime - (sint64)tmp->GetWatchdogTime();
  2825. if (diff > 120000)
  2826. {
  2827. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds.. attempting to cancel threads...", tmp->GetZoneName(), diff);
  2828. #ifndef WIN32
  2829. tmp->CancelThreads();
  2830. zlist.erase(zone_iter);
  2831. safe_delete(tmp);
  2832. #endif
  2833. MZoneList.releasewritelock(__FUNCTION__, __LINE__);
  2834. match = true;
  2835. break;
  2836. }
  2837. else if (diff > 90000 && !tmp->isZoneShuttingDown())
  2838. {
  2839. tmp->SetWatchdogTime(Timer::GetCurrentTime2()); // reset so we don't continuously flood this heartbeat
  2840. map<string, int32> oldest_process = world.GetOldestReloadingSubsystem();
  2841. if (oldest_process.size() > 0) {
  2842. map<string, int32>::iterator itr = oldest_process.begin();
  2843. if(itr != oldest_process.end())
  2844. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds.. while waiting for %s to reload...attempting shutdown", tmp->GetZoneName(), diff, itr->first);
  2845. else
  2846. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds... attempting shutdown", tmp->GetZoneName(), diff);
  2847. }
  2848. else
  2849. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds.. attempting shutdown", tmp->GetZoneName(), diff);
  2850. tmp->Shutdown();
  2851. }
  2852. else if (diff > 30000)
  2853. {
  2854. if (world.IsReloadingSubsystems()) {
  2855. if (world.GetSuppressedWarningTime() == 0) {
  2856. world.SetSuppressedWarning();
  2857. map<string, int32> oldest_process = world.GetOldestReloadingSubsystem();
  2858. if (oldest_process.size() > 0) {
  2859. map<string, int32>::iterator itr = oldest_process.begin();
  2860. if(itr != oldest_process.end())
  2861. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds.. while waiting for %s to reload...", tmp->GetZoneName(), diff, itr->first);
  2862. else
  2863. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds...", tmp->GetZoneName(), diff);
  2864. }
  2865. }
  2866. continue;
  2867. }
  2868. }
  2869. else if (diff > 60000 && !tmp->isZoneShuttingDown())
  2870. {
  2871. if (world.IsReloadingSubsystems())
  2872. continue;
  2873. LogWrite(WORLD__ERROR, 1, "World", "Zone %s is hung for %i milliseconds.. attempting shutdown", tmp->GetZoneName(), diff);
  2874. tmp->Shutdown();
  2875. }
  2876. }
  2877. }
  2878. if(!match)
  2879. MZoneList.releasewritelock(__FUNCTION__, __LINE__);
  2880. }
  2881. void World::LoadRegionMaps(std::string zoneFile)
  2882. {
  2883. string zoneToLower(zoneFile);
  2884. boost::algorithm::to_lower(zoneToLower);
  2885. MWorldRegionMaps.writelock();
  2886. std::map<std::string, RegionMapRange*>::iterator itr;
  2887. itr = region_maps.find(zoneToLower);
  2888. if (itr == region_maps.end())
  2889. {
  2890. RegionMapRange* newRange = new RegionMapRange();
  2891. newRange->AddVersionRange(zoneFile);
  2892. region_maps.insert(make_pair(zoneToLower, newRange));
  2893. }
  2894. MWorldRegionMaps.releasewritelock();
  2895. }
  2896. RegionMap* World::GetRegionMap(std::string zoneFile, int32 client_version)
  2897. {
  2898. string zoneToLower(zoneFile);
  2899. boost::algorithm::to_lower(zoneToLower);
  2900. MWorldRegionMaps.readlock();
  2901. std::map<std::string, RegionMapRange*>::iterator itr;
  2902. itr = region_maps.find(zoneToLower);
  2903. if ( itr != region_maps.end())
  2904. {
  2905. std::map<VersionRange*, RegionMap*>::iterator rmitr;
  2906. rmitr = itr->second->FindRegionByVersion(client_version);
  2907. if ( rmitr != itr->second->GetRangeEnd())
  2908. {
  2909. MWorldRegionMaps.releasereadlock();
  2910. return rmitr->second;
  2911. }
  2912. }
  2913. MWorldRegionMaps.releasereadlock();
  2914. return nullptr;
  2915. }
  2916. void World::LoadMaps(std::string zoneFile)
  2917. {
  2918. string zoneToLower(zoneFile);
  2919. boost::algorithm::to_lower(zoneToLower);
  2920. MWorldMaps.writelock();
  2921. std::map<std::string, MapRange*>::iterator itr;
  2922. itr = maps.find(zoneToLower);
  2923. if (itr == maps.end())
  2924. {
  2925. MapRange* newRange = new MapRange();
  2926. newRange->AddVersionRange(zoneFile);
  2927. maps.insert(make_pair(zoneToLower, newRange));
  2928. }
  2929. MWorldMaps.releasewritelock();
  2930. }
  2931. void World::RemoveMaps(std::string zoneFile)
  2932. {
  2933. string zoneToLower(zoneFile);
  2934. boost::algorithm::to_lower(zoneToLower);
  2935. MWorldMaps.writelock();
  2936. std::map<std::string, MapRange*>::iterator itr;
  2937. itr = maps.find(zoneToLower);
  2938. if (itr != maps.end())
  2939. {
  2940. MapRange* range = itr->second;
  2941. maps.erase(itr);
  2942. MWorldMaps.releasewritelock();
  2943. safe_delete(range);
  2944. }
  2945. else {
  2946. MWorldMaps.releasewritelock();
  2947. }
  2948. }
  2949. Map* World::GetMap(std::string zoneFile, int32 client_version)
  2950. {
  2951. string zoneToLower(zoneFile);
  2952. boost::algorithm::to_lower(zoneToLower);
  2953. MWorldMaps.readlock();
  2954. std::map<std::string, MapRange*>::iterator itr;
  2955. itr = maps.find(zoneToLower);
  2956. if ( itr != maps.end())
  2957. {
  2958. std::map<VersionRange*, Map*>::iterator rmitr;
  2959. rmitr = itr->second->FindMapByVersion(client_version);
  2960. if ( rmitr != itr->second->GetRangeEnd())
  2961. {
  2962. MWorldMaps.releasereadlock();
  2963. return rmitr->second;
  2964. }
  2965. }
  2966. MWorldMaps.releasereadlock();
  2967. return nullptr;
  2968. }
  2969. void World::SendTimeUpdate()
  2970. {
  2971. zone_list.SendTimeUpdate();
  2972. }
  2973. void World::LoadVoiceOvers()
  2974. {
  2975. LogWrite(WORLD__DEBUG, 1, "World", "-Loading `voiceovers`...");
  2976. database.LoadVoiceOvers(this);
  2977. }
  2978. void World::PurgeVoiceOvers()
  2979. {
  2980. MVoiceOvers.writelock();
  2981. for(int type=0;type<MAX_VOICEOVER_TYPE+1;type++) {
  2982. multimap<int32, multimap<int16, VoiceOverStruct>*>::iterator vos_itr;
  2983. for (vos_itr = voiceover_map[type].begin(); vos_itr != voiceover_map[type].end(); vos_itr++)
  2984. {
  2985. multimap<int16, VoiceOverStruct>* tmpMap = vos_itr->second;
  2986. safe_delete(tmpMap);
  2987. }
  2988. voiceover_map[type].clear();
  2989. }
  2990. MVoiceOvers.releasewritelock();
  2991. }
  2992. bool World::FindVoiceOver(int8 type, int32 id, int16 index, VoiceOverStruct* struct_, bool* find_garbled, VoiceOverStruct* garble_struct_) {
  2993. // if we complete both requirements, based on struct_ and garble_struct_ being passed when required by ptr not being null
  2994. bool succeed = false;
  2995. if(type > MAX_VOICEOVER_TYPE) {
  2996. LogWrite(WORLD__ERROR, 0, "World", "Voice over %u out of range, max voiceover type is %u...", type, MAX_VOICEOVER_TYPE);
  2997. return succeed;
  2998. }
  2999. MVoiceOvers.readlock();
  3000. multimap<int32, multimap<int16, VoiceOverStruct>*>::iterator itr = voiceover_map[type].find(id);
  3001. if(itr != voiceover_map[type].end()) {
  3002. std::pair<VOMapIterator, VOMapIterator> result = itr->second->equal_range(index);
  3003. int count = std::distance(result.first, result.second);
  3004. bool tries_attempt = true; // abort out the while loop
  3005. bool non_garble_found = false;
  3006. int rand = 0; // use to randomize the voiceover selection
  3007. int pos = 0;
  3008. int tries = 0;
  3009. bool has_ungarbled = false;
  3010. bool has_garbled = false;
  3011. int8 garble_link_id = 0; // used to match ungarbled to garbled when the link id is set in the DB
  3012. while(tries_attempt) {
  3013. pos = 0;
  3014. rand = MakeRandomInt(0, count);
  3015. if ( tries == 3 || non_garble_found || (find_garbled && (*find_garbled)))
  3016. rand = 0; // override, too many tries, or we otherwise found one garbled/ungarbled lets try to link it
  3017. for (VOMapIterator it = result.first; it != result.second; it++) {
  3018. if(!it->second.is_garbled) {
  3019. has_ungarbled = true;
  3020. }
  3021. else {
  3022. has_garbled = true;
  3023. }
  3024. pos++;
  3025. // if there is only 1 entry in the voiceover list we aren't going to bother skipping
  3026. if(count > 1 && pos < rand) {
  3027. continue;
  3028. }
  3029. if(!it->second.is_garbled && (garble_link_id == 0 || it->second.garble_link_id == garble_link_id)) {
  3030. garble_link_id = it->second.garble_link_id;
  3031. non_garble_found = true;
  3032. if(struct_) {
  3033. CopyVoiceOver(struct_, &it->second);
  3034. }
  3035. if(!find_garbled || ((*find_garbled))) {
  3036. if(find_garbled)
  3037. *find_garbled = true;
  3038. tries_attempt = false;
  3039. succeed = true;
  3040. break;
  3041. }
  3042. }
  3043. else if(find_garbled && !(*find_garbled) && it->second.is_garbled && (garble_link_id == 0 || it->second.garble_link_id == garble_link_id)) {
  3044. *find_garbled = true;
  3045. garble_link_id = it->second.garble_link_id;
  3046. if(garble_struct_) {
  3047. CopyVoiceOver(garble_struct_, &it->second);
  3048. if(!struct_ || non_garble_found) {
  3049. tries_attempt = false;
  3050. succeed = true;
  3051. break;
  3052. }
  3053. }
  3054. }
  3055. }
  3056. tries++;
  3057. if(!tries_attempt || (tries > 0 && !has_ungarbled && (!find_garbled || *find_garbled == true || !has_garbled)) || tries > 3)
  3058. break;
  3059. }
  3060. }
  3061. MVoiceOvers.releasereadlock();
  3062. return succeed;
  3063. }
  3064. void World::AddVoiceOver(int8 type, int32 id, int16 index, VoiceOverStruct* struct_) {
  3065. if(type > MAX_VOICEOVER_TYPE) {
  3066. LogWrite(WORLD__ERROR, 0, "World", "Voice over %u out of range, max voiceover type is %u...", type, MAX_VOICEOVER_TYPE);
  3067. return;
  3068. }
  3069. VoiceOverStruct tmpStruct;
  3070. tmpStruct.mp3_string = std::string(struct_->mp3_string);
  3071. tmpStruct.text_string = std::string(struct_->text_string);
  3072. tmpStruct.emote_string = std::string(struct_->emote_string);
  3073. tmpStruct.key1 = struct_->key1;
  3074. tmpStruct.key2 = struct_->key2;
  3075. tmpStruct.is_garbled = struct_->is_garbled;
  3076. MVoiceOvers.writelock();
  3077. if(!voiceover_map[type].count(id))
  3078. {
  3079. multimap<int16, VoiceOverStruct>* vo_struct = new multimap<int16, VoiceOverStruct>();
  3080. vo_struct->insert(make_pair(index, tmpStruct));
  3081. voiceover_map[type].insert(make_pair(id, vo_struct));
  3082. }
  3083. else
  3084. {
  3085. multimap<int32, multimap<int16, VoiceOverStruct>*>::const_iterator itr = voiceover_map[type].find(id);
  3086. itr->second->insert(make_pair(index, tmpStruct));
  3087. }
  3088. MVoiceOvers.releasewritelock();
  3089. }
  3090. void World::CopyVoiceOver(VoiceOverStruct* struct1, VoiceOverStruct* struct2) {
  3091. if(!struct1 || !struct2)
  3092. return;
  3093. struct1->mp3_string = std::string(struct2->mp3_string);
  3094. struct1->text_string = std::string(struct2->text_string);
  3095. struct1->emote_string = std::string(struct2->emote_string);
  3096. struct1->key1 = struct2->key1;
  3097. struct1->key2 = struct2->key2;
  3098. struct1->is_garbled = struct2->is_garbled;
  3099. struct1->garble_link_id = struct2->garble_link_id;
  3100. }
  3101. void World::AddNPCSpell(int32 list_id, int32 spell_id, int8 tier, bool spawn_cast, bool aggro_cast, sint8 req_hp_ratio){
  3102. std::unique_lock lock(MNPCSpells);
  3103. NPCSpell* npc_spell_struct = new NPCSpell;
  3104. npc_spell_struct->list_id = list_id;
  3105. npc_spell_struct->spell_id = spell_id;
  3106. npc_spell_struct->tier = tier;
  3107. npc_spell_struct->cast_on_spawn = spawn_cast;
  3108. npc_spell_struct->cast_on_initial_aggro = aggro_cast;
  3109. npc_spell_struct->required_hp_ratio = req_hp_ratio;
  3110. if(npc_spell_list.count(list_id) && npc_spell_list[list_id].count(spell_id)) {
  3111. map<int32, NPCSpell*>::iterator spell_itr = npc_spell_list[list_id].find(spell_id);
  3112. if(spell_itr != npc_spell_list[list_id].end()) {
  3113. safe_delete(spell_itr->second);
  3114. npc_spell_list[list_id].erase(spell_itr);
  3115. }
  3116. }
  3117. npc_spell_list[list_id].insert(make_pair(spell_id, npc_spell_struct));
  3118. }
  3119. vector<NPCSpell*>* World::GetNPCSpells(int32 primary_list, int32 secondary_list){
  3120. std::shared_lock lock(MNPCSpells);
  3121. vector<NPCSpell*>* ret = 0;
  3122. if(npc_spell_list.count(primary_list) > 0){
  3123. ret = new vector<NPCSpell*>();
  3124. map<int32, NPCSpell*>::iterator itr;
  3125. Spell* tmpSpell = 0;
  3126. for(itr = npc_spell_list[primary_list].begin(); itr != npc_spell_list[primary_list].end(); itr++){
  3127. tmpSpell = master_spell_list.GetSpell(itr->first, itr->second->tier);
  3128. if(tmpSpell) {
  3129. NPCSpell* addedSpell = new NPCSpell(itr->second);
  3130. ret->push_back(addedSpell);
  3131. }
  3132. }
  3133. }
  3134. if(npc_spell_list.count(secondary_list) > 0){
  3135. if(!ret)
  3136. ret = new vector<NPCSpell*>();
  3137. map<int32, NPCSpell*>::iterator itr;
  3138. Spell* tmpSpell = 0;
  3139. for(itr = npc_spell_list[secondary_list].begin(); itr != npc_spell_list[secondary_list].end(); itr++){
  3140. tmpSpell = master_spell_list.GetSpell(itr->first, itr->second->tier);
  3141. if(tmpSpell) {
  3142. NPCSpell* addedSpell = new NPCSpell(itr->second);
  3143. ret->push_back(addedSpell);
  3144. }
  3145. }
  3146. }
  3147. if(ret && ret->size() == 0){
  3148. safe_delete(ret);
  3149. ret = 0;
  3150. }
  3151. return ret;
  3152. }
  3153. void World::PurgeNPCSpells() {
  3154. std::unique_lock lock(MNPCSpells);
  3155. map<int32, map<int32, NPCSpell*> >::iterator list_itr;
  3156. map<int32, NPCSpell*>::iterator spell_itr;
  3157. Spell* tmpSpell = 0;
  3158. for(list_itr = npc_spell_list.begin(); list_itr != npc_spell_list.end(); list_itr++) {
  3159. for(spell_itr = npc_spell_list[list_itr->first].begin(); spell_itr != npc_spell_list[list_itr->first].end(); spell_itr++){
  3160. safe_delete(spell_itr->second);
  3161. }
  3162. }
  3163. npc_spell_list.clear();
  3164. }
  3165. void World::ClientAuthApproval(int32 success, std::string charName, int32 account_id, std::string zone_name, int32 zone_id, int32 instance_id, bool first_login) {
  3166. Client* find_client = zone_list.GetClientByCharName(charName.c_str());
  3167. if(find_client) {
  3168. if(success) {
  3169. find_client->ApproveZone();
  3170. }
  3171. else {
  3172. int32 zone_success = 0;
  3173. ZoneChangeDetails details;
  3174. if(instance_id || zone_id || zone_name.length() > 0) {
  3175. if(!instance_id) {
  3176. if((zone_list.GetZone(&details, zone_id, zone_name, true, true, false, false)))
  3177. zone_success = 1;
  3178. }
  3179. else {
  3180. if((zone_list.GetZoneByInstance(&details, instance_id, zone_id, true, true, false, false)))
  3181. zone_success = 1;
  3182. }
  3183. }
  3184. if(zone_success) {
  3185. LogWrite(CCLIENT__DEBUG, 0, "Client", "%s: Sending to zone_auth.AddAuth...", __FUNCTION__);
  3186. int32 key = static_cast<unsigned int>(MakeRandomFloat(0.01,1.0) * UINT32_MAX);
  3187. details.zoneKey = key;
  3188. details.authDispatchedTime = key;
  3189. zone_auth.AddAuth(new ZoneAuthRequest(find_client->GetAccountID(), find_client->GetPlayer()->GetName(), key));
  3190. find_client->SetZoningDetails(&details);
  3191. find_client->ApproveZone();
  3192. }
  3193. }
  3194. }
  3195. else {
  3196. // can't find client
  3197. }
  3198. }