map.cpp 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "map.hpp"
  4. #include <stdlib.h>
  5. #include <math.h>
  6. #include "../common/cbasetypes.h"
  7. #include "../common/core.h"
  8. #include "../common/timer.h"
  9. #include "../common/grfio.h"
  10. #include "../common/malloc.h"
  11. #include "../common/socket.h" // WFIFO*()
  12. #include "../common/showmsg.h"
  13. #include "../common/nullpo.h"
  14. #include "../common/random.h"
  15. #include "../common/strlib.h"
  16. #include "../common/utils.h"
  17. #include "../common/cli.h"
  18. #include "../common/ers.h"
  19. #include "path.hpp"
  20. #include "chrif.hpp"
  21. #include "clan.hpp"
  22. #include "clif.hpp"
  23. #include "duel.hpp"
  24. #include "intif.hpp"
  25. #include "npc.hpp"
  26. #include "pc.hpp"
  27. #include "chat.hpp"
  28. #include "storage.hpp"
  29. #include "trade.hpp"
  30. #include "party.hpp"
  31. #include "battleground.hpp"
  32. #include "quest.hpp"
  33. #include "mapreg.hpp"
  34. #include "pet.hpp"
  35. #include "homunculus.hpp"
  36. #include "instance.hpp"
  37. #include "mercenary.hpp"
  38. #include "elemental.hpp"
  39. #include "cashshop.hpp"
  40. #include "channel.hpp"
  41. #include "achievement.hpp"
  42. #include "guild.hpp"
  43. #include "atcommand.hpp"
  44. #include "battle.hpp"
  45. #include "log.hpp"
  46. #include "mob.hpp"
  47. char default_codepage[32] = "";
  48. int map_server_port = 3306;
  49. char map_server_ip[32] = "127.0.0.1";
  50. char map_server_id[32] = "ragnarok";
  51. char map_server_pw[32] = "";
  52. char map_server_db[32] = "ragnarok";
  53. Sql* mmysql_handle;
  54. Sql* qsmysql_handle; /// For query_sql
  55. int db_use_sqldbs = 0;
  56. char buyingstores_table[32] = "buyingstores";
  57. char buyingstore_items_table[32] = "buyingstore_items";
  58. char item_cash_table[32] = "item_cash_db";
  59. char item_cash2_table[32] = "item_cash_db2";
  60. #ifdef RENEWAL
  61. char item_table[32] = "item_db_re";
  62. char item2_table[32] = "item_db2_re";
  63. char mob_table[32] = "mob_db_re";
  64. char mob2_table[32] = "mob_db2_re";
  65. char mob_skill_table[32] = "mob_skill_db_re";
  66. char mob_skill2_table[32] = "mob_skill_db2_re";
  67. #else
  68. char item_table[32] = "item_db";
  69. char item2_table[32] = "item_db2";
  70. char mob_table[32] = "mob_db";
  71. char mob2_table[32] = "mob_db2";
  72. char mob_skill_table[32] = "mob_skill_db";
  73. char mob_skill2_table[32] = "mob_skill_db2";
  74. #endif
  75. char sales_table[32] = "sales";
  76. char vendings_table[32] = "vendings";
  77. char vending_items_table[32] = "vending_items";
  78. char market_table[32] = "market";
  79. char roulette_table[32] = "db_roulette";
  80. // log database
  81. char log_db_ip[32] = "127.0.0.1";
  82. int log_db_port = 3306;
  83. char log_db_id[32] = "ragnarok";
  84. char log_db_pw[32] = "ragnarok";
  85. char log_db_db[32] = "log";
  86. Sql* logmysql_handle;
  87. // DBMap declaration
  88. static DBMap* id_db=NULL; /// int id -> struct block_list*
  89. static DBMap* pc_db=NULL; /// int id -> struct map_session_data*
  90. static DBMap* mobid_db=NULL; /// int id -> struct mob_data*
  91. static DBMap* bossid_db=NULL; /// int id -> struct mob_data* (MVP db)
  92. static DBMap* map_db=NULL; /// unsigned int mapindex -> struct map_data*
  93. static DBMap* nick_db=NULL; /// uint32 char_id -> struct charid2nick* (requested names of offline characters)
  94. static DBMap* charid_db=NULL; /// uint32 char_id -> struct map_session_data*
  95. static DBMap* regen_db=NULL; /// int id -> struct block_list* (status_natural_heal processing)
  96. static DBMap* map_msg_db=NULL;
  97. static int map_users=0;
  98. #define BLOCK_SIZE 8
  99. #define block_free_max 1048576
  100. struct block_list *block_free[block_free_max];
  101. static int block_free_count = 0, block_free_lock = 0;
  102. #define BL_LIST_MAX 1048576
  103. static struct block_list *bl_list[BL_LIST_MAX];
  104. static int bl_list_count = 0;
  105. #ifndef MAP_MAX_MSG
  106. #define MAP_MAX_MSG 1550
  107. #endif
  108. struct map_data map[MAX_MAP_PER_SERVER];
  109. int map_num = 0;
  110. int map_port=0;
  111. int autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  112. int minsave_interval = 100;
  113. unsigned char save_settings = CHARSAVE_ALL;
  114. bool agit_flag = false;
  115. bool agit2_flag = false;
  116. bool agit3_flag = false;
  117. int night_flag = 0; // 0=day, 1=night [Yor]
  118. #ifdef ADJUST_SKILL_DAMAGE
  119. struct eri *map_skill_damage_ers = NULL;
  120. #endif
  121. struct charid_request {
  122. struct charid_request* next;
  123. int charid;// who want to be notified of the nick
  124. };
  125. struct charid2nick {
  126. char nick[NAME_LENGTH];
  127. struct charid_request* requests;// requests of notification on this nick
  128. };
  129. // This is the main header found at the very beginning of the map cache
  130. struct map_cache_main_header {
  131. uint32 file_size;
  132. uint16 map_count;
  133. };
  134. // This is the header appended before every compressed map cells info in the map cache
  135. struct map_cache_map_info {
  136. char name[MAP_NAME_LENGTH];
  137. int16 xs;
  138. int16 ys;
  139. int32 len;
  140. };
  141. char motd_txt[256] = "conf/motd.txt";
  142. char help_txt[256] = "conf/help.txt";
  143. char help2_txt[256] = "conf/help2.txt";
  144. char charhelp_txt[256] = "conf/charhelp.txt";
  145. char channel_conf[256] = "conf/channels.conf";
  146. const char *MSG_CONF_NAME_RUS;
  147. const char *MSG_CONF_NAME_SPN;
  148. const char *MSG_CONF_NAME_GRM;
  149. const char *MSG_CONF_NAME_CHN;
  150. const char *MSG_CONF_NAME_MAL;
  151. const char *MSG_CONF_NAME_IDN;
  152. const char *MSG_CONF_NAME_FRN;
  153. const char *MSG_CONF_NAME_POR;
  154. const char *MSG_CONF_NAME_THA;
  155. char wisp_server_name[NAME_LENGTH] = "Server"; // can be modified in char-server configuration file
  156. struct s_map_default map_default;
  157. int console = 0;
  158. int enable_spy = 0; //To enable/disable @spy commands, which consume too much cpu time when sending packets. [Skotlex]
  159. int enable_grf = 0; //To enable/disable reading maps from GRF files, bypassing mapcache [blackhole89]
  160. /*==========================================
  161. * server player count (of all mapservers)
  162. *------------------------------------------*/
  163. void map_setusers(int users)
  164. {
  165. map_users = users;
  166. }
  167. int map_getusers(void)
  168. {
  169. return map_users;
  170. }
  171. /*==========================================
  172. * server player count (this mapserver only)
  173. *------------------------------------------*/
  174. int map_usercount(void)
  175. {
  176. return pc_db->size(pc_db);
  177. }
  178. /*==========================================
  179. * Attempt to free a map blocklist
  180. *------------------------------------------*/
  181. int map_freeblock (struct block_list *bl)
  182. {
  183. nullpo_retr(block_free_lock, bl);
  184. if (block_free_lock == 0 || block_free_count >= block_free_max)
  185. {
  186. aFree(bl);
  187. bl = NULL;
  188. if (block_free_count >= block_free_max)
  189. ShowWarning("map_freeblock: too many free block! %d %d\n", block_free_count, block_free_lock);
  190. } else
  191. block_free[block_free_count++] = bl;
  192. return block_free_lock;
  193. }
  194. /*==========================================
  195. * Lock blocklist, (prevent map_freeblock usage)
  196. *------------------------------------------*/
  197. int map_freeblock_lock (void)
  198. {
  199. return ++block_free_lock;
  200. }
  201. /*==========================================
  202. * Remove the lock on map_bl
  203. *------------------------------------------*/
  204. int map_freeblock_unlock (void)
  205. {
  206. if ((--block_free_lock) == 0) {
  207. int i;
  208. for (i = 0; i < block_free_count; i++)
  209. {
  210. aFree(block_free[i]);
  211. block_free[i] = NULL;
  212. }
  213. block_free_count = 0;
  214. } else if (block_free_lock < 0) {
  215. ShowError("map_freeblock_unlock: lock count < 0 !\n");
  216. block_free_lock = 0;
  217. }
  218. return block_free_lock;
  219. }
  220. // Timer function to check if there some remaining lock and remove them if so.
  221. // Called each 1s
  222. int map_freeblock_timer(int tid, unsigned int tick, int id, intptr_t data)
  223. {
  224. if (block_free_lock > 0) {
  225. ShowError("map_freeblock_timer: block_free_lock(%d) is invalid.\n", block_free_lock);
  226. block_free_lock = 1;
  227. map_freeblock_unlock();
  228. }
  229. return 0;
  230. }
  231. //
  232. // blocklist
  233. //
  234. /*==========================================
  235. * Handling of map_bl[]
  236. * The address of bl_heal is set in bl->prev
  237. *------------------------------------------*/
  238. static struct block_list bl_head;
  239. #ifdef CELL_NOSTACK
  240. /*==========================================
  241. * These pair of functions update the counter of how many objects
  242. * lie on a tile.
  243. *------------------------------------------*/
  244. static void map_addblcell(struct block_list *bl)
  245. {
  246. if( bl->m<0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  247. return;
  248. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl++;
  249. return;
  250. }
  251. static void map_delblcell(struct block_list *bl)
  252. {
  253. if( bl->m <0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  254. return;
  255. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl--;
  256. }
  257. #endif
  258. /*==========================================
  259. * Adds a block to the map.
  260. * Returns 0 on success, 1 on failure (illegal coordinates).
  261. *------------------------------------------*/
  262. int map_addblock(struct block_list* bl)
  263. {
  264. int16 m, x, y;
  265. int pos;
  266. nullpo_ret(bl);
  267. if (bl->prev != NULL) {
  268. ShowError("map_addblock: bl->prev != NULL\n");
  269. return 1;
  270. }
  271. m = bl->m;
  272. x = bl->x;
  273. y = bl->y;
  274. if( m < 0 || m >= map_num )
  275. {
  276. ShowError("map_addblock: invalid map id (%d), only %d are loaded.\n", m, map_num);
  277. return 1;
  278. }
  279. if( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  280. {
  281. ShowError("map_addblock: out-of-bounds coordinates (\"%s\",%d,%d), map is %dx%d\n", map[m].name, x, y, map[m].xs, map[m].ys);
  282. return 1;
  283. }
  284. pos = x/BLOCK_SIZE+(y/BLOCK_SIZE)*map[m].bxs;
  285. if (bl->type == BL_MOB) {
  286. bl->next = map[m].block_mob[pos];
  287. bl->prev = &bl_head;
  288. if (bl->next) bl->next->prev = bl;
  289. map[m].block_mob[pos] = bl;
  290. } else {
  291. bl->next = map[m].block[pos];
  292. bl->prev = &bl_head;
  293. if (bl->next) bl->next->prev = bl;
  294. map[m].block[pos] = bl;
  295. }
  296. #ifdef CELL_NOSTACK
  297. map_addblcell(bl);
  298. #endif
  299. return 0;
  300. }
  301. /*==========================================
  302. * Removes a block from the map.
  303. *------------------------------------------*/
  304. int map_delblock(struct block_list* bl)
  305. {
  306. int pos;
  307. nullpo_ret(bl);
  308. // blocklist (2ways chainlist)
  309. if (bl->prev == NULL) {
  310. if (bl->next != NULL) {
  311. // can't delete block (already at the beginning of the chain)
  312. ShowError("map_delblock error : bl->next!=NULL\n");
  313. }
  314. return 0;
  315. }
  316. #ifdef CELL_NOSTACK
  317. map_delblcell(bl);
  318. #endif
  319. pos = bl->x/BLOCK_SIZE+(bl->y/BLOCK_SIZE)*map[bl->m].bxs;
  320. if (bl->next)
  321. bl->next->prev = bl->prev;
  322. if (bl->prev == &bl_head) {
  323. //Since the head of the list, update the block_list map of []
  324. if (bl->type == BL_MOB) {
  325. map[bl->m].block_mob[pos] = bl->next;
  326. } else {
  327. map[bl->m].block[pos] = bl->next;
  328. }
  329. } else {
  330. bl->prev->next = bl->next;
  331. }
  332. bl->next = NULL;
  333. bl->prev = NULL;
  334. return 0;
  335. }
  336. /**
  337. * Moves a block a x/y target position. [Skotlex]
  338. * Pass flag as 1 to prevent doing skill_unit_move checks
  339. * (which are executed by default on BL_CHAR types)
  340. * @param bl : block(object) to move
  341. * @param x1 : new x position
  342. * @param y1 : new y position
  343. * @param tick : when this was scheduled
  344. * @return 0:success, 1:fail
  345. */
  346. int map_moveblock(struct block_list *bl, int x1, int y1, unsigned int tick)
  347. {
  348. int x0 = bl->x, y0 = bl->y;
  349. struct status_change *sc = NULL;
  350. int moveblock = ( x0/BLOCK_SIZE != x1/BLOCK_SIZE || y0/BLOCK_SIZE != y1/BLOCK_SIZE);
  351. if (!bl->prev) {
  352. //Block not in map, just update coordinates, but do naught else.
  353. bl->x = x1;
  354. bl->y = y1;
  355. return 0;
  356. }
  357. //TODO: Perhaps some outs of bounds checking should be placed here?
  358. if (bl->type&BL_CHAR) {
  359. sc = status_get_sc(bl);
  360. skill_unit_move(bl,tick,2);
  361. if ( sc && sc->count ) //at least one to cancel
  362. {
  363. status_change_end(bl, SC_ROLLINGCUTTER, INVALID_TIMER); // If you move, you lose your counters. [malufett]
  364. status_change_end(bl, SC_CLOSECONFINE, INVALID_TIMER);
  365. status_change_end(bl, SC_CLOSECONFINE2, INVALID_TIMER);
  366. status_change_end(bl, SC_TINDER_BREAKER, INVALID_TIMER);
  367. status_change_end(bl, SC_TINDER_BREAKER2, INVALID_TIMER);
  368. // status_change_end(bl, SC_BLADESTOP, INVALID_TIMER); //Won't stop when you are knocked away, go figure...
  369. status_change_end(bl, SC_TATAMIGAESHI, INVALID_TIMER);
  370. status_change_end(bl, SC_MAGICROD, INVALID_TIMER);
  371. status_change_end(bl, SC_SU_STOOP, INVALID_TIMER);
  372. if (sc->data[SC_PROPERTYWALK] &&
  373. sc->data[SC_PROPERTYWALK]->val3 >= skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2) )
  374. status_change_end(bl,SC_PROPERTYWALK,INVALID_TIMER);
  375. }
  376. } else
  377. if (bl->type == BL_NPC)
  378. npc_unsetcells((TBL_NPC*)bl);
  379. if (moveblock) map_delblock(bl);
  380. #ifdef CELL_NOSTACK
  381. else map_delblcell(bl);
  382. #endif
  383. bl->x = x1;
  384. bl->y = y1;
  385. if (moveblock) {
  386. if(map_addblock(bl))
  387. return 1;
  388. }
  389. #ifdef CELL_NOSTACK
  390. else map_addblcell(bl);
  391. #endif
  392. if (bl->type&BL_CHAR) {
  393. skill_unit_move(bl,tick,3);
  394. if( bl->type == BL_PC && ((TBL_PC*)bl)->shadowform_id ) {//Shadow Form Target Moving
  395. struct block_list *d_bl;
  396. if( (d_bl = map_id2bl(((TBL_PC*)bl)->shadowform_id)) == NULL || !check_distance_bl(bl,d_bl,10) ) {
  397. if( d_bl )
  398. status_change_end(d_bl,SC__SHADOWFORM,INVALID_TIMER);
  399. ((TBL_PC*)bl)->shadowform_id = 0;
  400. }
  401. }
  402. if (sc && sc->count) {
  403. if (sc->data[SC_DANCING])
  404. skill_unit_move_unit_group(skill_id2group(sc->data[SC_DANCING]->val2), bl->m, x1-x0, y1-y0);
  405. else {
  406. if (sc->data[SC_CLOAKING] && sc->data[SC_CLOAKING]->val1 < 3 && !skill_check_cloaking(bl, NULL))
  407. status_change_end(bl, SC_CLOAKING, INVALID_TIMER);
  408. if (sc->data[SC_WARM])
  409. skill_unit_move_unit_group(skill_id2group(sc->data[SC_WARM]->val4), bl->m, x1-x0, y1-y0);
  410. if (sc->data[SC_BANDING])
  411. skill_unit_move_unit_group(skill_id2group(sc->data[SC_BANDING]->val4), bl->m, x1-x0, y1-y0);
  412. if (sc->data[SC_NEUTRALBARRIER_MASTER])
  413. skill_unit_move_unit_group(skill_id2group(sc->data[SC_NEUTRALBARRIER_MASTER]->val2), bl->m, x1-x0, y1-y0);
  414. else if (sc->data[SC_STEALTHFIELD_MASTER])
  415. skill_unit_move_unit_group(skill_id2group(sc->data[SC_STEALTHFIELD_MASTER]->val2), bl->m, x1-x0, y1-y0);
  416. if( sc->data[SC__SHADOWFORM] ) {//Shadow Form Caster Moving
  417. struct block_list *d_bl;
  418. if( (d_bl = map_id2bl(sc->data[SC__SHADOWFORM]->val2)) == NULL || !check_distance_bl(bl,d_bl,10) )
  419. status_change_end(bl,SC__SHADOWFORM,INVALID_TIMER);
  420. }
  421. if (sc->data[SC_PROPERTYWALK]
  422. && sc->data[SC_PROPERTYWALK]->val3 < skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2)
  423. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_ELECTRICWALK,NULL,0) == NULL
  424. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_FIREWALK,NULL,0) == NULL
  425. && skill_unitsetting(bl,sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2,x0, y0,0)) {
  426. sc->data[SC_PROPERTYWALK]->val3++;
  427. }
  428. }
  429. /* Guild Aura Moving */
  430. if( bl->type == BL_PC && ((TBL_PC*)bl)->state.gmaster_flag ) {
  431. if (sc->data[SC_LEADERSHIP])
  432. skill_unit_move_unit_group(skill_id2group(sc->data[SC_LEADERSHIP]->val4), bl->m, x1-x0, y1-y0);
  433. if (sc->data[SC_GLORYWOUNDS])
  434. skill_unit_move_unit_group(skill_id2group(sc->data[SC_GLORYWOUNDS]->val4), bl->m, x1-x0, y1-y0);
  435. if (sc->data[SC_SOULCOLD])
  436. skill_unit_move_unit_group(skill_id2group(sc->data[SC_SOULCOLD]->val4), bl->m, x1-x0, y1-y0);
  437. if (sc->data[SC_HAWKEYES])
  438. skill_unit_move_unit_group(skill_id2group(sc->data[SC_HAWKEYES]->val4), bl->m, x1-x0, y1-y0);
  439. }
  440. }
  441. } else
  442. if (bl->type == BL_NPC)
  443. npc_setcells((TBL_NPC*)bl);
  444. return 0;
  445. }
  446. /*==========================================
  447. * Counts specified number of objects on given cell.
  448. * flag:
  449. * 0x1 - only count standing units
  450. *------------------------------------------*/
  451. int map_count_oncell(int16 m, int16 x, int16 y, int type, int flag)
  452. {
  453. int bx,by;
  454. struct block_list *bl;
  455. int count = 0;
  456. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  457. return 0;
  458. bx = x/BLOCK_SIZE;
  459. by = y/BLOCK_SIZE;
  460. if (type&~BL_MOB)
  461. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  462. if(bl->x == x && bl->y == y && bl->type&type) {
  463. if(flag&1) {
  464. struct unit_data *ud = unit_bl2ud(bl);
  465. if(!ud || ud->walktimer == INVALID_TIMER)
  466. count++;
  467. } else {
  468. count++;
  469. }
  470. }
  471. if (type&BL_MOB)
  472. for( bl = map[m].block_mob[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  473. if(bl->x == x && bl->y == y) {
  474. if(flag&1) {
  475. struct unit_data *ud = unit_bl2ud(bl);
  476. if(!ud || ud->walktimer == INVALID_TIMER)
  477. count++;
  478. } else {
  479. count++;
  480. }
  481. }
  482. return count;
  483. }
  484. /*
  485. * Looks for a skill unit on a given cell
  486. * flag&1: runs battle_check_target check based on unit->group->target_flag
  487. */
  488. struct skill_unit* map_find_skill_unit_oncell(struct block_list* target,int16 x,int16 y,uint16 skill_id,struct skill_unit* out_unit, int flag) {
  489. int16 m,bx,by;
  490. struct block_list *bl;
  491. struct skill_unit *unit;
  492. m = target->m;
  493. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  494. return NULL;
  495. bx = x/BLOCK_SIZE;
  496. by = y/BLOCK_SIZE;
  497. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  498. {
  499. if (bl->x != x || bl->y != y || bl->type != BL_SKILL)
  500. continue;
  501. unit = (struct skill_unit *) bl;
  502. if( unit == out_unit || !unit->alive || !unit->group || unit->group->skill_id != skill_id )
  503. continue;
  504. if( !(flag&1) || battle_check_target(&unit->bl,target,unit->group->target_flag) > 0 )
  505. return unit;
  506. }
  507. return NULL;
  508. }
  509. /*==========================================
  510. * Adapted from foreachinarea for an easier invocation. [Skotlex]
  511. *------------------------------------------*/
  512. int map_foreachinrangeV(int (*func)(struct block_list*,va_list),struct block_list* center, int16 range, int type, va_list ap, bool wall_check)
  513. {
  514. int bx, by, m;
  515. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  516. struct block_list *bl;
  517. int blockcount = bl_list_count, i;
  518. int x0, x1, y0, y1;
  519. va_list ap_copy;
  520. m = center->m;
  521. if( m < 0 )
  522. return 0;
  523. x0 = i16max(center->x - range, 0);
  524. y0 = i16max(center->y - range, 0);
  525. x1 = i16min(center->x + range, map[m].xs - 1);
  526. y1 = i16min(center->y + range, map[m].ys - 1);
  527. if ( type&~BL_MOB ) {
  528. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  529. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  530. for(bl = map[m].block[ bx + by * map[m].bxs ]; bl != NULL; bl = bl->next ) {
  531. if( bl->type&type
  532. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  533. #ifdef CIRCULAR_AREA
  534. && check_distance_bl(center, bl, range)
  535. #endif
  536. && ( !wall_check || path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL) )
  537. && bl_list_count < BL_LIST_MAX )
  538. bl_list[ bl_list_count++ ] = bl;
  539. }
  540. }
  541. }
  542. }
  543. if ( type&BL_MOB ) {
  544. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  545. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  546. for(bl = map[m].block_mob[ bx + by * map[m].bxs ]; bl != NULL; bl = bl->next ) {
  547. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  548. #ifdef CIRCULAR_AREA
  549. && check_distance_bl(center, bl, range)
  550. #endif
  551. && ( !wall_check || path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL) )
  552. && bl_list_count < BL_LIST_MAX )
  553. bl_list[ bl_list_count++ ] = bl;
  554. }
  555. }
  556. }
  557. }
  558. if( bl_list_count >= BL_LIST_MAX )
  559. ShowWarning("map_foreachinrange: block count too many!\n");
  560. map_freeblock_lock();
  561. for( i = blockcount; i < bl_list_count; i++ ) {
  562. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  563. va_copy(ap_copy, ap);
  564. returnCount += func(bl_list[i], ap_copy);
  565. va_end(ap_copy);
  566. }
  567. }
  568. map_freeblock_unlock();
  569. bl_list_count = blockcount;
  570. return returnCount; //[Skotlex]
  571. }
  572. int map_foreachinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int type, ...)
  573. {
  574. int returnCount = 0;
  575. va_list ap;
  576. va_start(ap,type);
  577. returnCount = map_foreachinrangeV(func,center,range,type,ap,battle_config.skill_wall_check>0);
  578. va_end(ap);
  579. return returnCount;
  580. }
  581. int map_foreachinallrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int type, ...)
  582. {
  583. int returnCount = 0;
  584. va_list ap;
  585. va_start(ap,type);
  586. returnCount = map_foreachinrangeV(func,center,range,type,ap,false);
  587. va_end(ap);
  588. return returnCount;
  589. }
  590. /*==========================================
  591. * Same as foreachinrange, but there must be a shoot-able range between center and target to be counted in. [Skotlex]
  592. *------------------------------------------*/
  593. int map_foreachinshootrange(int (*func)(struct block_list*,va_list),struct block_list* center, int16 range, int type,...)
  594. {
  595. int returnCount = 0;
  596. va_list ap;
  597. va_start(ap,type);
  598. returnCount = map_foreachinrangeV(func,center,range,type,ap,true);
  599. va_end(ap);
  600. return returnCount;
  601. }
  602. /*========================================== [Playtester]
  603. * range = map m (x0,y0)-(x1,y1)
  604. * Apply *func with ... arguments for the range.
  605. * @param m: ID of map
  606. * @param x0: West end of area
  607. * @param y0: South end of area
  608. * @param x1: East end of area
  609. * @param y1: North end of area
  610. * @param type: Type of bl to search for
  611. *------------------------------------------*/
  612. int map_foreachinareaV(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, va_list ap, bool wall_check)
  613. {
  614. int bx, by, cx, cy;
  615. int returnCount = 0; //total sum of returned values of func()
  616. struct block_list *bl;
  617. int blockcount = bl_list_count, i;
  618. va_list ap_copy;
  619. if (m < 0 || m >= map_num)
  620. return 0;
  621. if (x1 < x0)
  622. SWAP(x0, x1);
  623. if (y1 < y0)
  624. SWAP(y0, y1);
  625. x0 = i16max(x0, 0);
  626. y0 = i16max(y0, 0);
  627. x1 = i16min(x1, map[m].xs - 1);
  628. y1 = i16min(y1, map[m].ys - 1);
  629. if( wall_check ) {
  630. cx = x0 + (x1 - x0) / 2;
  631. cy = y0 + (y1 - y0) / 2;
  632. }
  633. if( type&~BL_MOB ) {
  634. for (by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++) {
  635. for (bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++) {
  636. for(bl = map[m].block[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  637. if ( bl->type&type
  638. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  639. && ( !wall_check || path_search_long(NULL, m, cx, cy, bl->x, bl->y, CELL_CHKWALL) )
  640. && bl_list_count < BL_LIST_MAX )
  641. bl_list[bl_list_count++] = bl;
  642. }
  643. }
  644. }
  645. }
  646. if( type&BL_MOB ) {
  647. for (by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++) {
  648. for (bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++) {
  649. for(bl = map[m].block_mob[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  650. if ( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  651. && ( !wall_check || path_search_long(NULL, m, cx, cy, bl->x, bl->y, CELL_CHKWALL) )
  652. && bl_list_count < BL_LIST_MAX )
  653. bl_list[bl_list_count++] = bl;
  654. }
  655. }
  656. }
  657. }
  658. if (bl_list_count >= BL_LIST_MAX)
  659. ShowWarning("map_foreachinarea: block count too many!\n");
  660. map_freeblock_lock();
  661. for (i = blockcount; i < bl_list_count; i++) {
  662. if (bl_list[i]->prev) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  663. va_copy(ap_copy, ap);
  664. returnCount += func(bl_list[i], ap_copy);
  665. va_end(ap_copy);
  666. }
  667. }
  668. map_freeblock_unlock();
  669. bl_list_count = blockcount;
  670. return returnCount;
  671. }
  672. int map_foreachinallarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  673. {
  674. int returnCount = 0;
  675. va_list ap;
  676. va_start(ap,type);
  677. returnCount = map_foreachinareaV(func,m,x0,y0,x1,y1,type,ap,false);
  678. va_end(ap);
  679. return returnCount;
  680. }
  681. int map_foreachinshootarea(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  682. {
  683. int returnCount = 0;
  684. va_list ap;
  685. va_start(ap,type);
  686. returnCount = map_foreachinareaV(func,m,x0,y0,x1,y1,type,ap,true);
  687. va_end(ap);
  688. return returnCount;
  689. }
  690. int map_foreachinarea(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  691. {
  692. int returnCount = 0;
  693. va_list ap;
  694. va_start(ap,type);
  695. returnCount = map_foreachinareaV(func,m,x0,y0,x1,y1,type,ap,battle_config.skill_wall_check>0);
  696. va_end(ap);
  697. return returnCount;
  698. }
  699. /*==========================================
  700. * Adapted from forcountinarea for an easier invocation. [pakpil]
  701. *------------------------------------------*/
  702. int map_forcountinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int count, int type, ...)
  703. {
  704. int bx, by, m;
  705. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  706. struct block_list *bl;
  707. int blockcount = bl_list_count, i;
  708. int x0, x1, y0, y1;
  709. va_list ap;
  710. m = center->m;
  711. x0 = i16max(center->x - range, 0);
  712. y0 = i16max(center->y - range, 0);
  713. x1 = i16min(center->x + range, map[ m ].xs - 1);
  714. y1 = i16min(center->y + range, map[ m ].ys - 1);
  715. if ( type&~BL_MOB )
  716. for ( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  717. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  718. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  719. if( bl->type&type
  720. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  721. #ifdef CIRCULAR_AREA
  722. && check_distance_bl(center, bl, range)
  723. #endif
  724. && bl_list_count < BL_LIST_MAX )
  725. bl_list[ bl_list_count++ ] = bl;
  726. }
  727. }
  728. }
  729. if( type&BL_MOB )
  730. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  731. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ){
  732. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  733. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  734. #ifdef CIRCULAR_AREA
  735. && check_distance_bl(center, bl, range)
  736. #endif
  737. && bl_list_count < BL_LIST_MAX )
  738. bl_list[ bl_list_count++ ] = bl;
  739. }
  740. }
  741. }
  742. if( bl_list_count >= BL_LIST_MAX )
  743. ShowWarning("map_forcountinrange: block count too many!\n");
  744. map_freeblock_lock();
  745. for( i = blockcount; i < bl_list_count; i++ )
  746. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  747. va_start(ap, type);
  748. returnCount += func(bl_list[ i ], ap);
  749. va_end(ap);
  750. if( count && returnCount >= count )
  751. break;
  752. }
  753. map_freeblock_unlock();
  754. bl_list_count = blockcount;
  755. return returnCount; //[Skotlex]
  756. }
  757. int map_forcountinarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int count, int type, ...)
  758. {
  759. int bx, by;
  760. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  761. struct block_list *bl;
  762. int blockcount = bl_list_count, i;
  763. va_list ap;
  764. if ( m < 0 )
  765. return 0;
  766. if ( x1 < x0 )
  767. SWAP(x0, x1);
  768. if ( y1 < y0 )
  769. SWAP(y0, y1);
  770. x0 = i16max(x0, 0);
  771. y0 = i16max(y0, 0);
  772. x1 = i16min(x1, map[ m ].xs - 1);
  773. y1 = i16min(y1, map[ m ].ys - 1);
  774. if ( type&~BL_MOB )
  775. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  776. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  777. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  778. if( bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  779. bl_list[ bl_list_count++ ] = bl;
  780. if( type&BL_MOB )
  781. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  782. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  783. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  784. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  785. bl_list[ bl_list_count++ ] = bl;
  786. if( bl_list_count >= BL_LIST_MAX )
  787. ShowWarning("map_forcountinarea: block count too many!\n");
  788. map_freeblock_lock();
  789. for( i = blockcount; i < bl_list_count; i++ )
  790. if(bl_list[ i ]->prev) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  791. va_start(ap, type);
  792. returnCount += func(bl_list[ i ], ap);
  793. va_end(ap);
  794. if( count && returnCount >= count )
  795. break;
  796. }
  797. map_freeblock_unlock();
  798. bl_list_count = blockcount;
  799. return returnCount; //[Skotlex]
  800. }
  801. /*==========================================
  802. * Move bl and do func* with va_list while moving.
  803. * Movement is set by dx dy which are distance in x and y
  804. *------------------------------------------*/
  805. int map_foreachinmovearea(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int16 dx, int16 dy, int type, ...)
  806. {
  807. int bx, by, m;
  808. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  809. struct block_list *bl;
  810. int blockcount = bl_list_count, i;
  811. int16 x0, x1, y0, y1;
  812. va_list ap;
  813. if ( !range ) return 0;
  814. if ( !dx && !dy ) return 0; //No movement.
  815. m = center->m;
  816. x0 = center->x - range;
  817. x1 = center->x + range;
  818. y0 = center->y - range;
  819. y1 = center->y + range;
  820. if ( x1 < x0 )
  821. SWAP(x0, x1);
  822. if ( y1 < y0 )
  823. SWAP(y0, y1);
  824. if( dx == 0 || dy == 0 ) {
  825. //Movement along one axis only.
  826. if( dx == 0 ){
  827. if( dy < 0 ) //Moving south
  828. y0 = y1 + dy + 1;
  829. else //North
  830. y1 = y0 + dy - 1;
  831. } else { //dy == 0
  832. if( dx < 0 ) //West
  833. x0 = x1 + dx + 1;
  834. else //East
  835. x1 = x0 + dx - 1;
  836. }
  837. x0 = i16max(x0, 0);
  838. y0 = i16max(y0, 0);
  839. x1 = i16min(x1, map[ m ].xs - 1);
  840. y1 = i16min(y1, map[ m ].ys - 1);
  841. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  842. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  843. if ( type&~BL_MOB ) {
  844. for( bl = map[m].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  845. if( bl->type&type &&
  846. bl->x >= x0 && bl->x <= x1 &&
  847. bl->y >= y0 && bl->y <= y1 &&
  848. bl_list_count < BL_LIST_MAX )
  849. bl_list[ bl_list_count++ ] = bl;
  850. }
  851. }
  852. if ( type&BL_MOB ) {
  853. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  854. if( bl->x >= x0 && bl->x <= x1 &&
  855. bl->y >= y0 && bl->y <= y1 &&
  856. bl_list_count < BL_LIST_MAX )
  857. bl_list[ bl_list_count++ ] = bl;
  858. }
  859. }
  860. }
  861. }
  862. } else { // Diagonal movement
  863. x0 = i16max(x0, 0);
  864. y0 = i16max(y0, 0);
  865. x1 = i16min(x1, map[ m ].xs - 1);
  866. y1 = i16min(y1, map[ m ].ys - 1);
  867. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  868. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  869. if ( type & ~BL_MOB ) {
  870. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  871. if( bl->type&type &&
  872. bl->x >= x0 && bl->x <= x1 &&
  873. bl->y >= y0 && bl->y <= y1 &&
  874. bl_list_count < BL_LIST_MAX )
  875. if( ( dx > 0 && bl->x < x0 + dx) ||
  876. ( dx < 0 && bl->x > x1 + dx) ||
  877. ( dy > 0 && bl->y < y0 + dy) ||
  878. ( dy < 0 && bl->y > y1 + dy) )
  879. bl_list[ bl_list_count++ ] = bl;
  880. }
  881. }
  882. if ( type&BL_MOB ) {
  883. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  884. if( bl->x >= x0 && bl->x <= x1 &&
  885. bl->y >= y0 && bl->y <= y1 &&
  886. bl_list_count < BL_LIST_MAX)
  887. if( ( dx > 0 && bl->x < x0 + dx) ||
  888. ( dx < 0 && bl->x > x1 + dx) ||
  889. ( dy > 0 && bl->y < y0 + dy) ||
  890. ( dy < 0 && bl->y > y1 + dy) )
  891. bl_list[ bl_list_count++ ] = bl;
  892. }
  893. }
  894. }
  895. }
  896. }
  897. if( bl_list_count >= BL_LIST_MAX )
  898. ShowWarning("map_foreachinmovearea: block count too many!\n");
  899. map_freeblock_lock(); // Prohibit the release from memory
  900. for( i = blockcount; i < bl_list_count; i++ )
  901. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  902. va_start(ap, type);
  903. returnCount += func(bl_list[ i ], ap);
  904. va_end(ap);
  905. }
  906. map_freeblock_unlock(); // Allow Free
  907. bl_list_count = blockcount;
  908. return returnCount;
  909. }
  910. // -- moonsoul (added map_foreachincell which is a rework of map_foreachinarea but
  911. // which only checks the exact single x/y passed to it rather than an
  912. // area radius - may be more useful in some instances)
  913. //
  914. int map_foreachincell(int (*func)(struct block_list*,va_list), int16 m, int16 x, int16 y, int type, ...)
  915. {
  916. int bx, by;
  917. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  918. struct block_list *bl;
  919. int blockcount = bl_list_count, i;
  920. va_list ap;
  921. if ( x < 0 || y < 0 || x >= map[ m ].xs || y >= map[ m ].ys ) return 0;
  922. by = y / BLOCK_SIZE;
  923. bx = x / BLOCK_SIZE;
  924. if( type&~BL_MOB )
  925. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  926. if( bl->type&type && bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX )
  927. bl_list[ bl_list_count++ ] = bl;
  928. if( type&BL_MOB )
  929. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs]; bl != NULL; bl = bl->next )
  930. if( bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX)
  931. bl_list[ bl_list_count++ ] = bl;
  932. if( bl_list_count >= BL_LIST_MAX )
  933. ShowWarning("map_foreachincell: block count too many!\n");
  934. map_freeblock_lock();
  935. for( i = blockcount; i < bl_list_count; i++ )
  936. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  937. va_start(ap, type);
  938. returnCount += func(bl_list[ i ], ap);
  939. va_end(ap);
  940. }
  941. map_freeblock_unlock();
  942. bl_list_count = blockcount;
  943. return returnCount;
  944. }
  945. /*============================================================
  946. * For checking a path between two points (x0, y0) and (x1, y1)
  947. *------------------------------------------------------------*/
  948. int map_foreachinpath(int (*func)(struct block_list*,va_list),int16 m,int16 x0,int16 y0,int16 x1,int16 y1,int16 range,int length, int type,...)
  949. {
  950. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  951. //////////////////////////////////////////////////////////////
  952. //
  953. // sharp shooting 3 [Skotlex]
  954. //
  955. //////////////////////////////////////////////////////////////
  956. // problem:
  957. // Same as Sharp Shooting 1. Hits all targets within range of
  958. // the line.
  959. // (t1,t2 t3 and t4 get hit)
  960. //
  961. // target 1
  962. // x t4
  963. // t2
  964. // t3 x
  965. // x
  966. // S
  967. //////////////////////////////////////////////////////////////
  968. // Methodology:
  969. // My trigonometrics and math are a little rusty... so the approach I am writing
  970. // here is basically do a double for to check for all targets in the square that
  971. // contains the initial and final positions (area range increased to match the
  972. // radius given), then for each object to test, calculate the distance to the
  973. // path and include it if the range fits and the target is in the line (0<k<1,
  974. // as they call it).
  975. // The implementation I took as reference is found at
  976. // http://astronomy.swin.edu.au/~pbourke/geometry/pointline/
  977. // (they have a link to a C implementation, too)
  978. // This approach is a lot like #2 commented on this function, which I have no
  979. // idea why it was commented. I won't use doubles/floats, but pure int math for
  980. // speed purposes. The range considered is always the same no matter how
  981. // close/far the target is because that's how SharpShooting works currently in
  982. // kRO.
  983. //Generic map_foreach* variables.
  984. int i, blockcount = bl_list_count;
  985. struct block_list *bl;
  986. int bx, by;
  987. //method specific variables
  988. int magnitude2, len_limit; //The square of the magnitude
  989. int k, xi, yi, xu, yu;
  990. int mx0 = x0, mx1 = x1, my0 = y0, my1 = y1;
  991. va_list ap;
  992. //Avoid needless calculations by not getting the sqrt right away.
  993. #define MAGNITUDE2(x0, y0, x1, y1) ( ( ( x1 ) - ( x0 ) ) * ( ( x1 ) - ( x0 ) ) + ( ( y1 ) - ( y0 ) ) * ( ( y1 ) - ( y0 ) ) )
  994. if ( m < 0 )
  995. return 0;
  996. len_limit = magnitude2 = MAGNITUDE2(x0, y0, x1, y1);
  997. if ( magnitude2 < 1 ) //Same begin and ending point, can't trace path.
  998. return 0;
  999. if ( length ) { //Adjust final position to fit in the given area.
  1000. //TODO: Find an alternate method which does not requires a square root calculation.
  1001. k = (int)sqrt((float)magnitude2);
  1002. mx1 = x0 + (x1 - x0) * length / k;
  1003. my1 = y0 + (y1 - y0) * length / k;
  1004. len_limit = MAGNITUDE2(x0, y0, mx1, my1);
  1005. }
  1006. //Expand target area to cover range.
  1007. if ( mx0 > mx1 ) {
  1008. mx0 += range;
  1009. mx1 -= range;
  1010. } else {
  1011. mx0 -= range;
  1012. mx1 += range;
  1013. }
  1014. if (my0 > my1) {
  1015. my0 += range;
  1016. my1 -= range;
  1017. } else {
  1018. my0 -= range;
  1019. my1 += range;
  1020. }
  1021. //The two fors assume mx0 < mx1 && my0 < my1
  1022. if ( mx0 > mx1 )
  1023. SWAP(mx0, mx1);
  1024. if ( my0 > my1 )
  1025. SWAP(my0, my1);
  1026. mx0 = max(mx0, 0);
  1027. my0 = max(my0, 0);
  1028. mx1 = min(mx1, map[ m ].xs - 1);
  1029. my1 = min(my1, map[ m ].ys - 1);
  1030. range *= range << 8; //Values are shifted later on for higher precision using int math.
  1031. if ( type&~BL_MOB )
  1032. for ( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  1033. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  1034. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  1035. if( bl->prev && bl->type&type && bl_list_count < BL_LIST_MAX ) {
  1036. xi = bl->x;
  1037. yi = bl->y;
  1038. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  1039. if ( k < 0 || k > len_limit ) //Since more skills use this, check for ending point as well.
  1040. continue;
  1041. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  1042. continue; //Targets beyond the initial ending point need the wall check.
  1043. //All these shifts are to increase the precision of the intersection point and distance considering how it's
  1044. //int math.
  1045. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  1046. xi <<= 4;
  1047. yi <<= 4;
  1048. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  1049. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  1050. k = MAGNITUDE2(xi, yi, xu, yu);
  1051. //If all dot coordinates were <<4 the square of the magnitude is <<8
  1052. if ( k > range )
  1053. continue;
  1054. bl_list[ bl_list_count++ ] = bl;
  1055. }
  1056. }
  1057. }
  1058. }
  1059. if( type&BL_MOB )
  1060. for( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  1061. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  1062. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  1063. if( bl->prev && bl_list_count < BL_LIST_MAX ) {
  1064. xi = bl->x;
  1065. yi = bl->y;
  1066. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  1067. if ( k < 0 || k > len_limit )
  1068. continue;
  1069. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  1070. continue; //Targets beyond the initial ending point need the wall check.
  1071. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  1072. xi <<= 4;
  1073. yi <<= 4;
  1074. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  1075. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  1076. k = MAGNITUDE2(xi, yi, xu, yu);
  1077. //If all dot coordinates were <<4 the square of the magnitude is <<8
  1078. if ( k > range )
  1079. continue;
  1080. bl_list[ bl_list_count++ ] = bl;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. if( bl_list_count >= BL_LIST_MAX )
  1086. ShowWarning("map_foreachinpath: block count too many!\n");
  1087. map_freeblock_lock();
  1088. for( i = blockcount; i < bl_list_count; i++ )
  1089. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1090. va_start(ap, type);
  1091. returnCount += func(bl_list[ i ], ap);
  1092. va_end(ap);
  1093. }
  1094. map_freeblock_unlock();
  1095. bl_list_count = blockcount;
  1096. return returnCount; //[Skotlex]
  1097. }
  1098. /*========================================== [Playtester]
  1099. * Calls the given function for every object of a type that is on a path.
  1100. * The path goes into one of the eight directions and the direction is determined by the given coordinates.
  1101. * The path has a length, a width and an offset.
  1102. * The cost for diagonal movement is the same as for horizontal/vertical movement.
  1103. * @param m: ID of map
  1104. * @param x0: Start X
  1105. * @param y0: Start Y
  1106. * @param x1: X to calculate direction against
  1107. * @param y1: Y to calculate direction against
  1108. * @param range: Determines width of the path (width = range*2+1 cells)
  1109. * @param length: Length of the path
  1110. * @param offset: Moves the whole path, half-length for diagonal paths
  1111. * @param type: Type of bl to search for
  1112. *------------------------------------------*/
  1113. int map_foreachindir(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int16 range, int length, int offset, int type, ...)
  1114. {
  1115. int returnCount = 0; //Total sum of returned values of func()
  1116. int i, blockcount = bl_list_count;
  1117. struct block_list *bl;
  1118. int bx, by;
  1119. int mx0, mx1, my0, my1, rx, ry;
  1120. uint8 dir = map_calc_dir_xy(x0, y0, x1, y1, 6);
  1121. short dx = dirx[dir];
  1122. short dy = diry[dir];
  1123. va_list ap;
  1124. if (m < 0)
  1125. return 0;
  1126. if (range < 0)
  1127. return 0;
  1128. if (length < 1)
  1129. return 0;
  1130. if (offset < 0)
  1131. return 0;
  1132. //Special offset handling for diagonal paths
  1133. if (offset && (dir % 2)) {
  1134. //So that diagonal paths can attach to each other, we have to work with half-tile offsets
  1135. offset = (2 * offset) - 1;
  1136. //To get the half-tiles we need to increase length by one
  1137. length++;
  1138. }
  1139. //Get area that needs to be checked
  1140. mx0 = x0 + dx*(offset / ((dir % 2) + 1));
  1141. my0 = y0 + dy*(offset / ((dir % 2) + 1));
  1142. mx1 = x0 + dx*(offset / ((dir % 2) + 1) + length - 1);
  1143. my1 = y0 + dy*(offset / ((dir % 2) + 1) + length - 1);
  1144. //The following assumes mx0 < mx1 && my0 < my1
  1145. if (mx0 > mx1)
  1146. SWAP(mx0, mx1);
  1147. if (my0 > my1)
  1148. SWAP(my0, my1);
  1149. //Apply width to the path by turning 90 degrees
  1150. mx0 -= abs(range*dirx[(dir + 2) % 8]);
  1151. my0 -= abs(range*diry[(dir + 2) % 8]);
  1152. mx1 += abs(range*dirx[(dir + 2) % 8]);
  1153. my1 += abs(range*diry[(dir + 2) % 8]);
  1154. mx0 = max(mx0, 0);
  1155. my0 = max(my0, 0);
  1156. mx1 = min(mx1, map[m].xs - 1);
  1157. my1 = min(my1, map[m].ys - 1);
  1158. if (type&~BL_MOB) {
  1159. for (by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++) {
  1160. for (bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++) {
  1161. for (bl = map[m].block[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  1162. if (bl->prev && bl->type&type && bl_list_count < BL_LIST_MAX) {
  1163. //Check if inside search area
  1164. if (bl->x < mx0 || bl->x > mx1 || bl->y < my0 || bl->y > my1)
  1165. continue;
  1166. //What matters now is the relative x and y from the start point
  1167. rx = (bl->x - x0);
  1168. ry = (bl->y - y0);
  1169. //Do not hit source cell
  1170. if (rx == 0 && ry == 0)
  1171. continue;
  1172. //This turns it so that the area that is hit is always with positive rx and ry
  1173. rx *= dx;
  1174. ry *= dy;
  1175. //These checks only need to be done for diagonal paths
  1176. if (dir % 2) {
  1177. //Check for length
  1178. if ((rx + ry < offset) || (rx + ry > 2 * (length + (offset/2) - 1)))
  1179. continue;
  1180. //Check for width
  1181. if (abs(rx - ry) > 2 * range)
  1182. continue;
  1183. }
  1184. //Everything else ok, check for line of sight from source
  1185. if (!path_search_long(NULL, m, x0, y0, bl->x, bl->y, CELL_CHKWALL))
  1186. continue;
  1187. //All checks passed, add to list
  1188. bl_list[bl_list_count++] = bl;
  1189. }
  1190. }
  1191. }
  1192. }
  1193. }
  1194. if (type&BL_MOB) {
  1195. for (by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++) {
  1196. for (bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++) {
  1197. for (bl = map[m].block_mob[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  1198. if (bl->prev && bl_list_count < BL_LIST_MAX) {
  1199. //Check if inside search area
  1200. if (bl->x < mx0 || bl->x > mx1 || bl->y < my0 || bl->y > my1)
  1201. continue;
  1202. //What matters now is the relative x and y from the start point
  1203. rx = (bl->x - x0);
  1204. ry = (bl->y - y0);
  1205. //Do not hit source cell
  1206. if (rx == 0 && ry == 0)
  1207. continue;
  1208. //This turns it so that the area that is hit is always with positive rx and ry
  1209. rx *= dx;
  1210. ry *= dy;
  1211. //These checks only need to be done for diagonal paths
  1212. if (dir % 2) {
  1213. //Check for length
  1214. if ((rx + ry < offset) || (rx + ry > 2 * (length + (offset / 2) - 1)))
  1215. continue;
  1216. //Check for width
  1217. if (abs(rx - ry) > 2 * range)
  1218. continue;
  1219. }
  1220. //Everything else ok, check for line of sight from source
  1221. if (!path_search_long(NULL, m, x0, y0, bl->x, bl->y, CELL_CHKWALL))
  1222. continue;
  1223. //All checks passed, add to list
  1224. bl_list[bl_list_count++] = bl;
  1225. }
  1226. }
  1227. }
  1228. }
  1229. }
  1230. if( bl_list_count >= BL_LIST_MAX )
  1231. ShowWarning("map_foreachindir: block count too many!\n");
  1232. map_freeblock_lock();
  1233. for( i = blockcount; i < bl_list_count; i++ )
  1234. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1235. va_start(ap, type);
  1236. returnCount += func(bl_list[ i ], ap);
  1237. va_end(ap);
  1238. }
  1239. map_freeblock_unlock();
  1240. bl_list_count = blockcount;
  1241. return returnCount;
  1242. }
  1243. // Copy of map_foreachincell, but applied to the whole map. [Skotlex]
  1244. int map_foreachinmap(int (*func)(struct block_list*,va_list), int16 m, int type,...)
  1245. {
  1246. int b, bsize;
  1247. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  1248. struct block_list *bl;
  1249. int blockcount = bl_list_count, i;
  1250. va_list ap;
  1251. bsize = map[ m ].bxs * map[ m ].bys;
  1252. if( type&~BL_MOB )
  1253. for( b = 0; b < bsize; b++ )
  1254. for( bl = map[ m ].block[ b ]; bl != NULL; bl = bl->next )
  1255. if( bl->type&type && bl_list_count < BL_LIST_MAX )
  1256. bl_list[ bl_list_count++ ] = bl;
  1257. if( type&BL_MOB )
  1258. for( b = 0; b < bsize; b++ )
  1259. for( bl = map[ m ].block_mob[ b ]; bl != NULL; bl = bl->next )
  1260. if( bl_list_count < BL_LIST_MAX )
  1261. bl_list[ bl_list_count++ ] = bl;
  1262. if( bl_list_count >= BL_LIST_MAX )
  1263. ShowWarning("map_foreachinmap: block count too many!\n");
  1264. map_freeblock_lock();
  1265. for( i = blockcount; i < bl_list_count ; i++ )
  1266. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1267. va_start(ap, type);
  1268. returnCount += func(bl_list[ i ], ap);
  1269. va_end(ap);
  1270. }
  1271. map_freeblock_unlock();
  1272. bl_list_count = blockcount;
  1273. return returnCount;
  1274. }
  1275. /// Generates a new flooritem object id from the interval [MIN_FLOORITEM, MAX_FLOORITEM).
  1276. /// Used for floor items, skill units and chatroom objects.
  1277. /// @return The new object id
  1278. int map_get_new_object_id(void)
  1279. {
  1280. static int last_object_id = MIN_FLOORITEM - 1;
  1281. int i;
  1282. // find a free id
  1283. i = last_object_id + 1;
  1284. while( i != last_object_id ) {
  1285. if( i == MAX_FLOORITEM )
  1286. i = MIN_FLOORITEM;
  1287. if( !idb_exists(id_db, i) )
  1288. break;
  1289. ++i;
  1290. }
  1291. if( i == last_object_id ) {
  1292. ShowError("map_addobject: no free object id!\n");
  1293. return 0;
  1294. }
  1295. // update cursor
  1296. last_object_id = i;
  1297. return i;
  1298. }
  1299. /*==========================================
  1300. * Timered function to clear the floor (remove remaining item)
  1301. * Called each flooritem_lifetime ms
  1302. *------------------------------------------*/
  1303. int map_clearflooritem_timer(int tid, unsigned int tick, int id, intptr_t data)
  1304. {
  1305. struct flooritem_data* fitem = (struct flooritem_data*)idb_get(id_db, id);
  1306. if (fitem == NULL || fitem->bl.type != BL_ITEM || (fitem->cleartimer != tid)) {
  1307. ShowError("map_clearflooritem_timer : error\n");
  1308. return 1;
  1309. }
  1310. if (search_petDB_index(fitem->item.nameid, PET_EGG) >= 0)
  1311. intif_delete_petdata(MakeDWord(fitem->item.card[1], fitem->item.card[2]));
  1312. clif_clearflooritem(fitem, 0);
  1313. map_deliddb(&fitem->bl);
  1314. map_delblock(&fitem->bl);
  1315. map_freeblock(&fitem->bl);
  1316. return 0;
  1317. }
  1318. /*
  1319. * clears a single bl item out of the map.
  1320. */
  1321. void map_clearflooritem(struct block_list *bl) {
  1322. struct flooritem_data* fitem = (struct flooritem_data*)bl;
  1323. if( fitem->cleartimer != INVALID_TIMER )
  1324. delete_timer(fitem->cleartimer,map_clearflooritem_timer);
  1325. clif_clearflooritem(fitem, 0);
  1326. map_deliddb(&fitem->bl);
  1327. map_delblock(&fitem->bl);
  1328. map_freeblock(&fitem->bl);
  1329. }
  1330. /*==========================================
  1331. * (m,x,y) locates a random available free cell around the given coordinates
  1332. * to place an BL_ITEM object. Scan area is 9x9, returns 1 on success.
  1333. * x and y are modified with the target cell when successful.
  1334. *------------------------------------------*/
  1335. int map_searchrandfreecell(int16 m,int16 *x,int16 *y,int stack) {
  1336. int free_cell,i,j;
  1337. int free_cells[9][2];
  1338. for(free_cell=0,i=-1;i<=1;i++){
  1339. if(i+*y<0 || i+*y>=map[m].ys)
  1340. continue;
  1341. for(j=-1;j<=1;j++){
  1342. if(j+*x<0 || j+*x>=map[m].xs)
  1343. continue;
  1344. if(map_getcell(m,j+*x,i+*y,CELL_CHKNOPASS) && !map_getcell(m,j+*x,i+*y,CELL_CHKICEWALL))
  1345. continue;
  1346. //Avoid item stacking to prevent against exploits. [Skotlex]
  1347. if(stack && map_count_oncell(m,j+*x,i+*y, BL_ITEM, 0) > stack)
  1348. continue;
  1349. free_cells[free_cell][0] = j+*x;
  1350. free_cells[free_cell++][1] = i+*y;
  1351. }
  1352. }
  1353. if(free_cell==0)
  1354. return 0;
  1355. free_cell = rnd()%free_cell;
  1356. *x = free_cells[free_cell][0];
  1357. *y = free_cells[free_cell][1];
  1358. return 1;
  1359. }
  1360. static int map_count_sub(struct block_list *bl,va_list ap)
  1361. {
  1362. return 1;
  1363. }
  1364. /*==========================================
  1365. * Locates a random spare cell around the object given, using range as max
  1366. * distance from that spot. Used for warping functions. Use range < 0 for
  1367. * whole map range.
  1368. * Returns 1 on success. when it fails and src is available, x/y are set to src's
  1369. * src can be null as long as flag&1
  1370. * when ~flag&1, m is not needed.
  1371. * Flag values:
  1372. * &1 = random cell must be around given m,x,y, not around src
  1373. * &2 = the target should be able to walk to the target tile.
  1374. * &4 = there shouldn't be any players around the target tile (use the no_spawn_on_player setting)
  1375. *------------------------------------------*/
  1376. int map_search_freecell(struct block_list *src, int16 m, int16 *x,int16 *y, int16 rx, int16 ry, int flag)
  1377. {
  1378. int tries, spawn=0;
  1379. int bx, by;
  1380. int rx2 = 2*rx+1;
  1381. int ry2 = 2*ry+1;
  1382. if( !src && (!(flag&1) || flag&2) )
  1383. {
  1384. ShowDebug("map_search_freecell: Incorrect usage! When src is NULL, flag has to be &1 and can't have &2\n");
  1385. return 0;
  1386. }
  1387. if (flag&1) {
  1388. bx = *x;
  1389. by = *y;
  1390. } else {
  1391. bx = src->x;
  1392. by = src->y;
  1393. m = src->m;
  1394. }
  1395. if (!rx && !ry) {
  1396. //No range? Return the target cell then....
  1397. *x = bx;
  1398. *y = by;
  1399. return map_getcell(m,*x,*y,CELL_CHKREACH);
  1400. }
  1401. if (rx >= 0 && ry >= 0) {
  1402. tries = rx2*ry2;
  1403. if (tries > 100) tries = 100;
  1404. } else {
  1405. tries = map[m].xs*map[m].ys;
  1406. if (tries > 500) tries = 500;
  1407. }
  1408. while(tries--) {
  1409. *x = (rx >= 0)?(rnd()%rx2-rx+bx):(rnd()%(map[m].xs-2)+1);
  1410. *y = (ry >= 0)?(rnd()%ry2-ry+by):(rnd()%(map[m].ys-2)+1);
  1411. if (*x == bx && *y == by)
  1412. continue; //Avoid picking the same target tile.
  1413. if (map_getcell(m,*x,*y,CELL_CHKREACH))
  1414. {
  1415. if(flag&2 && !unit_can_reach_pos(src, *x, *y, 1))
  1416. continue;
  1417. if(flag&4) {
  1418. if (spawn >= 100) return 0; //Limit of retries reached.
  1419. if (spawn++ < battle_config.no_spawn_on_player &&
  1420. map_foreachinallarea(map_count_sub, m,
  1421. *x-AREA_SIZE, *y-AREA_SIZE,
  1422. *x+AREA_SIZE, *y+AREA_SIZE, BL_PC)
  1423. )
  1424. continue;
  1425. }
  1426. return 1;
  1427. }
  1428. }
  1429. *x = bx;
  1430. *y = by;
  1431. return 0;
  1432. }
  1433. /*==========================================
  1434. * Locates the closest, walkable cell with no blocks of a certain type on it
  1435. * Returns true on success and sets x and y to cell found.
  1436. * Otherwise returns false and x and y are not changed.
  1437. * type: Types of block to count
  1438. * flag:
  1439. * 0x1 - only count standing units
  1440. *------------------------------------------*/
  1441. bool map_closest_freecell(int16 m, int16 *x, int16 *y, int type, int flag)
  1442. {
  1443. uint8 dir = 6;
  1444. int16 tx = *x;
  1445. int16 ty = *y;
  1446. int costrange = 10;
  1447. if(!map_count_oncell(m, tx, ty, type, flag))
  1448. return true; //Current cell is free
  1449. //Algorithm only works up to costrange of 34
  1450. while(costrange <= 34) {
  1451. short dx = dirx[dir];
  1452. short dy = diry[dir];
  1453. //Linear search
  1454. if(dir%2 == 0 && costrange%MOVE_COST == 0) {
  1455. tx = *x+dx*(costrange/MOVE_COST);
  1456. ty = *y+dy*(costrange/MOVE_COST);
  1457. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1458. *x = tx;
  1459. *y = ty;
  1460. return true;
  1461. }
  1462. }
  1463. //Full diagonal search
  1464. else if(dir%2 == 1 && costrange%MOVE_DIAGONAL_COST == 0) {
  1465. tx = *x+dx*(costrange/MOVE_DIAGONAL_COST);
  1466. ty = *y+dy*(costrange/MOVE_DIAGONAL_COST);
  1467. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1468. *x = tx;
  1469. *y = ty;
  1470. return true;
  1471. }
  1472. }
  1473. //One cell diagonal, rest linear (TODO: Find a better algorithm for this)
  1474. else if(dir%2 == 1 && costrange%MOVE_COST == 4) {
  1475. tx = *x+dx*((dir%4==3)?(costrange/MOVE_COST):1);
  1476. ty = *y+dy*((dir%4==1)?(costrange/MOVE_COST):1);
  1477. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1478. *x = tx;
  1479. *y = ty;
  1480. return true;
  1481. }
  1482. tx = *x+dx*((dir%4==1)?(costrange/MOVE_COST):1);
  1483. ty = *y+dy*((dir%4==3)?(costrange/MOVE_COST):1);
  1484. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1485. *x = tx;
  1486. *y = ty;
  1487. return true;
  1488. }
  1489. }
  1490. //Get next direction
  1491. if (dir == 5) {
  1492. //Diagonal search complete, repeat with higher cost range
  1493. if(costrange == 14) costrange += 6;
  1494. else if(costrange == 28 || costrange >= 38) costrange += 2;
  1495. else costrange += 4;
  1496. dir = 6;
  1497. } else if (dir == 4) {
  1498. //Linear search complete, switch to diagonal directions
  1499. dir = 7;
  1500. } else {
  1501. dir = (dir+2)%8;
  1502. }
  1503. }
  1504. return false;
  1505. }
  1506. /*==========================================
  1507. * Add an item in floor to location (m,x,y) and add restriction for those who could pickup later
  1508. * NB : If charids are null their no restriction for pickup
  1509. * @param item_data : item attributes
  1510. * @param amount : items quantity
  1511. * @param m : mapid
  1512. * @param x : x coordinates
  1513. * @param y : y coordinates
  1514. * @param first_charid : 1st player that could loot the item (only charid that could loot for first_get_tick duration)
  1515. * @param second_charid : 2nd player that could loot the item (2nd charid that could loot for second_get_charid duration)
  1516. * @param third_charid : 3rd player that could loot the item (3rd charid that could loot for third_get_charid duration)
  1517. * @param flag: &1 MVP item. &2 do stacking check. &4 bypass droppable check.
  1518. * @param mob_id: Monster ID if dropped by monster
  1519. * @return 0:failure, x:item_gid [MIN_FLOORITEM;MAX_FLOORITEM]==[2;START_ACCOUNT_NUM]
  1520. *------------------------------------------*/
  1521. int map_addflooritem(struct item *item, int amount, int16 m, int16 x, int16 y, int first_charid, int second_charid, int third_charid, int flags, unsigned short mob_id)
  1522. {
  1523. int r;
  1524. struct flooritem_data *fitem = NULL;
  1525. nullpo_ret(item);
  1526. if (!(flags&4) && battle_config.item_onfloor && (itemdb_traderight(item->nameid)&1))
  1527. return 0; //can't be dropped
  1528. if (!map_searchrandfreecell(m,&x,&y,flags&2?1:0))
  1529. return 0;
  1530. r = rnd();
  1531. CREATE(fitem, struct flooritem_data, 1);
  1532. fitem->bl.type=BL_ITEM;
  1533. fitem->bl.prev = fitem->bl.next = NULL;
  1534. fitem->bl.m=m;
  1535. fitem->bl.x=x;
  1536. fitem->bl.y=y;
  1537. fitem->bl.id = map_get_new_object_id();
  1538. if (fitem->bl.id==0) {
  1539. aFree(fitem);
  1540. return 0;
  1541. }
  1542. fitem->first_get_charid = first_charid;
  1543. fitem->first_get_tick = gettick() + (flags&1 ? battle_config.mvp_item_first_get_time : battle_config.item_first_get_time);
  1544. fitem->second_get_charid = second_charid;
  1545. fitem->second_get_tick = fitem->first_get_tick + (flags&1 ? battle_config.mvp_item_second_get_time : battle_config.item_second_get_time);
  1546. fitem->third_get_charid = third_charid;
  1547. fitem->third_get_tick = fitem->second_get_tick + (flags&1 ? battle_config.mvp_item_third_get_time : battle_config.item_third_get_time);
  1548. fitem->mob_id = mob_id;
  1549. memcpy(&fitem->item,item,sizeof(*item));
  1550. fitem->item.amount = amount;
  1551. fitem->subx = (r&3)*3+3;
  1552. fitem->suby = ((r>>2)&3)*3+3;
  1553. fitem->cleartimer = add_timer(gettick()+battle_config.flooritem_lifetime,map_clearflooritem_timer,fitem->bl.id,0);
  1554. map_addiddb(&fitem->bl);
  1555. if (map_addblock(&fitem->bl))
  1556. return 0;
  1557. clif_dropflooritem(fitem);
  1558. return fitem->bl.id;
  1559. }
  1560. /**
  1561. * @see DBCreateData
  1562. */
  1563. static DBData create_charid2nick(DBKey key, va_list args)
  1564. {
  1565. struct charid2nick *p;
  1566. CREATE(p, struct charid2nick, 1);
  1567. return db_ptr2data(p);
  1568. }
  1569. /// Adds(or replaces) the nick of charid to nick_db and fulfils pending requests.
  1570. /// Does nothing if the character is online.
  1571. void map_addnickdb(int charid, const char* nick)
  1572. {
  1573. struct charid2nick* p;
  1574. if( map_charid2sd(charid) )
  1575. return;// already online
  1576. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1577. safestrncpy(p->nick, nick, sizeof(p->nick));
  1578. while( p->requests ) {
  1579. struct map_session_data* sd;
  1580. struct charid_request* req;
  1581. req = p->requests;
  1582. p->requests = req->next;
  1583. sd = map_charid2sd(req->charid);
  1584. if( sd )
  1585. clif_solved_charname(sd->fd, charid, p->nick);
  1586. aFree(req);
  1587. }
  1588. }
  1589. /// Removes the nick of charid from nick_db.
  1590. /// Sends name to all pending requests on charid.
  1591. void map_delnickdb(int charid, const char* name)
  1592. {
  1593. struct charid2nick* p;
  1594. DBData data;
  1595. if (!nick_db->remove(nick_db, db_i2key(charid), &data) || (p = (struct charid2nick*)db_data2ptr(&data)) == NULL)
  1596. return;
  1597. while( p->requests ) {
  1598. struct charid_request* req;
  1599. struct map_session_data* sd;
  1600. req = p->requests;
  1601. p->requests = req->next;
  1602. sd = map_charid2sd(req->charid);
  1603. if( sd )
  1604. clif_solved_charname(sd->fd, charid, name);
  1605. aFree(req);
  1606. }
  1607. aFree(p);
  1608. }
  1609. /// Notifies sd of the nick of charid.
  1610. /// Uses the name in the character if online.
  1611. /// Uses the name in nick_db if offline.
  1612. void map_reqnickdb(struct map_session_data * sd, int charid)
  1613. {
  1614. struct charid2nick* p;
  1615. struct charid_request* req;
  1616. struct map_session_data* tsd;
  1617. nullpo_retv(sd);
  1618. tsd = map_charid2sd(charid);
  1619. if( tsd )
  1620. {
  1621. clif_solved_charname(sd->fd, charid, tsd->status.name);
  1622. return;
  1623. }
  1624. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1625. if( *p->nick )
  1626. {
  1627. clif_solved_charname(sd->fd, charid, p->nick);
  1628. return;
  1629. }
  1630. // not in cache, request it
  1631. CREATE(req, struct charid_request, 1);
  1632. req->next = p->requests;
  1633. p->requests = req;
  1634. chrif_searchcharid(charid);
  1635. }
  1636. /*==========================================
  1637. * add bl to id_db
  1638. *------------------------------------------*/
  1639. void map_addiddb(struct block_list *bl)
  1640. {
  1641. nullpo_retv(bl);
  1642. if( bl->type == BL_PC )
  1643. {
  1644. TBL_PC* sd = (TBL_PC*)bl;
  1645. idb_put(pc_db,sd->bl.id,sd);
  1646. uidb_put(charid_db,sd->status.char_id,sd);
  1647. }
  1648. else if( bl->type == BL_MOB )
  1649. {
  1650. TBL_MOB* md = (TBL_MOB*)bl;
  1651. idb_put(mobid_db,bl->id,bl);
  1652. if( md->state.boss )
  1653. idb_put(bossid_db, bl->id, bl);
  1654. }
  1655. if( bl->type & BL_REGEN )
  1656. idb_put(regen_db, bl->id, bl);
  1657. idb_put(id_db,bl->id,bl);
  1658. }
  1659. /*==========================================
  1660. * remove bl from id_db
  1661. *------------------------------------------*/
  1662. void map_deliddb(struct block_list *bl)
  1663. {
  1664. nullpo_retv(bl);
  1665. if( bl->type == BL_PC )
  1666. {
  1667. TBL_PC* sd = (TBL_PC*)bl;
  1668. idb_remove(pc_db,sd->bl.id);
  1669. uidb_remove(charid_db,sd->status.char_id);
  1670. }
  1671. else if( bl->type == BL_MOB )
  1672. {
  1673. idb_remove(mobid_db,bl->id);
  1674. idb_remove(bossid_db,bl->id);
  1675. }
  1676. if( bl->type & BL_REGEN )
  1677. idb_remove(regen_db,bl->id);
  1678. idb_remove(id_db,bl->id);
  1679. }
  1680. /*==========================================
  1681. * Standard call when a player connection is closed.
  1682. *------------------------------------------*/
  1683. int map_quit(struct map_session_data *sd) {
  1684. int i;
  1685. if (sd->state.keepshop == false) { // Close vending/buyingstore
  1686. if (sd->state.vending)
  1687. vending_closevending(sd);
  1688. else if (sd->state.buyingstore)
  1689. buyingstore_close(sd);
  1690. }
  1691. if(!sd->state.active) { //Removing a player that is not active.
  1692. struct auth_node *node = chrif_search(sd->status.account_id);
  1693. if (node && node->char_id == sd->status.char_id &&
  1694. node->state != ST_LOGOUT)
  1695. //Except when logging out, clear the auth-connect data immediately.
  1696. chrif_auth_delete(node->account_id, node->char_id, node->state);
  1697. //Non-active players should not have loaded any data yet (or it was cleared already) so no additional cleanups are needed.
  1698. return 0;
  1699. }
  1700. if (sd->expiration_tid != INVALID_TIMER)
  1701. delete_timer(sd->expiration_tid, pc_expiration_timer);
  1702. if (sd->npc_timer_id != INVALID_TIMER) //Cancel the event timer.
  1703. npc_timerevent_quit(sd);
  1704. if (sd->autotrade_tid != INVALID_TIMER)
  1705. delete_timer(sd->autotrade_tid, pc_autotrade_timer);
  1706. if (sd->npc_id)
  1707. npc_event_dequeue(sd);
  1708. if( sd->bg_id )
  1709. bg_team_leave(sd,1);
  1710. if( sd->status.clan_id )
  1711. clan_member_left(sd);
  1712. pc_itemcd_do(sd,false);
  1713. npc_script_event(sd, NPCE_LOGOUT);
  1714. //Unit_free handles clearing the player related data,
  1715. //map_quit handles extra specific data which is related to quitting normally
  1716. //(changing map-servers invokes unit_free but bypasses map_quit)
  1717. if( sd->sc.count ) {
  1718. //Status that are not saved...
  1719. status_change_end(&sd->bl, SC_BOSSMAPINFO, INVALID_TIMER);
  1720. status_change_end(&sd->bl, SC_AUTOTRADE, INVALID_TIMER);
  1721. status_change_end(&sd->bl, SC_SPURT, INVALID_TIMER);
  1722. status_change_end(&sd->bl, SC_BERSERK, INVALID_TIMER);
  1723. status_change_end(&sd->bl, SC__BLOODYLUST, INVALID_TIMER);
  1724. status_change_end(&sd->bl, SC_TRICKDEAD, INVALID_TIMER);
  1725. status_change_end(&sd->bl, SC_LEADERSHIP, INVALID_TIMER);
  1726. status_change_end(&sd->bl, SC_GLORYWOUNDS, INVALID_TIMER);
  1727. status_change_end(&sd->bl, SC_SOULCOLD, INVALID_TIMER);
  1728. status_change_end(&sd->bl, SC_HAWKEYES, INVALID_TIMER);
  1729. status_change_end(&sd->bl, SC_CHASEWALK2, INVALID_TIMER);
  1730. if(sd->sc.data[SC_ENDURE] && sd->sc.data[SC_ENDURE]->val4)
  1731. status_change_end(&sd->bl, SC_ENDURE, INVALID_TIMER); //No need to save infinite endure.
  1732. if(sd->sc.data[SC_PROVOKE] && sd->sc.data[SC_PROVOKE]->timer == INVALID_TIMER)
  1733. status_change_end(&sd->bl, SC_PROVOKE, INVALID_TIMER); //Infinite provoke ends on logout
  1734. status_change_end(&sd->bl, SC_WEIGHT50, INVALID_TIMER);
  1735. status_change_end(&sd->bl, SC_WEIGHT90, INVALID_TIMER);
  1736. status_change_end(&sd->bl, SC_SATURDAYNIGHTFEVER, INVALID_TIMER);
  1737. status_change_end(&sd->bl, SC_KYOUGAKU, INVALID_TIMER);
  1738. status_change_end(&sd->bl, SC_C_MARKER, INVALID_TIMER);
  1739. status_change_end(&sd->bl, SC_READYSTORM, INVALID_TIMER);
  1740. status_change_end(&sd->bl, SC_READYDOWN, INVALID_TIMER);
  1741. status_change_end(&sd->bl, SC_READYTURN, INVALID_TIMER);
  1742. status_change_end(&sd->bl, SC_READYCOUNTER, INVALID_TIMER);
  1743. status_change_end(&sd->bl, SC_DODGE, INVALID_TIMER);
  1744. status_change_end(&sd->bl, SC_CBC, INVALID_TIMER);
  1745. status_change_end(&sd->bl, SC_EQC, INVALID_TIMER);
  1746. status_change_end(&sd->bl, SC_SPRITEMABLE, INVALID_TIMER);
  1747. status_change_end(&sd->bl, SC_SV_ROOTTWIST, INVALID_TIMER);
  1748. // Remove visuals effect from headgear
  1749. status_change_end(&sd->bl, SC_MOONSTAR, INVALID_TIMER);
  1750. status_change_end(&sd->bl, SC_SUPER_STAR, INVALID_TIMER);
  1751. status_change_end(&sd->bl, SC_STRANGELIGHTS, INVALID_TIMER);
  1752. status_change_end(&sd->bl, SC_DECORATION_OF_MUSIC, INVALID_TIMER);
  1753. if (battle_config.debuff_on_logout&1) { //Remove negative buffs
  1754. status_change_end(&sd->bl, SC_ORCISH, INVALID_TIMER);
  1755. status_change_end(&sd->bl, SC_STRIPWEAPON, INVALID_TIMER);
  1756. status_change_end(&sd->bl, SC_STRIPARMOR, INVALID_TIMER);
  1757. status_change_end(&sd->bl, SC_STRIPSHIELD, INVALID_TIMER);
  1758. status_change_end(&sd->bl, SC_STRIPHELM, INVALID_TIMER);
  1759. status_change_end(&sd->bl, SC_EXTREMITYFIST, INVALID_TIMER);
  1760. status_change_end(&sd->bl, SC_EXPLOSIONSPIRITS, INVALID_TIMER);
  1761. if(sd->sc.data[SC_REGENERATION] && sd->sc.data[SC_REGENERATION]->val4)
  1762. status_change_end(&sd->bl, SC_REGENERATION, INVALID_TIMER);
  1763. //TO-DO Probably there are way more NPC_type negative status that are removed
  1764. status_change_end(&sd->bl, SC_CHANGEUNDEAD, INVALID_TIMER);
  1765. // Both these statuses are removed on logout. [L0ne_W0lf]
  1766. status_change_end(&sd->bl, SC_SLOWCAST, INVALID_TIMER);
  1767. status_change_end(&sd->bl, SC_CRITICALWOUND, INVALID_TIMER);
  1768. status_change_end(&sd->bl, SC_H_MINE, INVALID_TIMER);
  1769. status_change_end(&sd->bl, SC_ANTI_M_BLAST, INVALID_TIMER);
  1770. status_change_end(&sd->bl, SC_B_TRAP, INVALID_TIMER);
  1771. }
  1772. if (battle_config.debuff_on_logout&2) { //Remove positive buffs
  1773. status_change_end(&sd->bl, SC_MAXIMIZEPOWER, INVALID_TIMER);
  1774. status_change_end(&sd->bl, SC_MAXOVERTHRUST, INVALID_TIMER);
  1775. status_change_end(&sd->bl, SC_STEELBODY, INVALID_TIMER);
  1776. status_change_end(&sd->bl, SC_PRESERVE, INVALID_TIMER);
  1777. status_change_end(&sd->bl, SC_KAAHI, INVALID_TIMER);
  1778. status_change_end(&sd->bl, SC_SPIRIT, INVALID_TIMER);
  1779. status_change_end(&sd->bl, SC_HEAT_BARREL, INVALID_TIMER);
  1780. status_change_end(&sd->bl, SC_P_ALTER, INVALID_TIMER);
  1781. status_change_end(&sd->bl, SC_E_CHAIN, INVALID_TIMER);
  1782. status_change_end(&sd->bl, SC_SIGHTBLASTER, INVALID_TIMER);
  1783. }
  1784. }
  1785. for (i = 0; i < EQI_MAX; i++) {
  1786. if (sd->equip_index[i] >= 0)
  1787. if (pc_isequip(sd,sd->equip_index[i]))
  1788. pc_unequipitem(sd,sd->equip_index[i],2);
  1789. }
  1790. // Return loot to owner
  1791. if( sd->pd ) pet_lootitem_drop(sd->pd, sd);
  1792. if (sd->ed) // Remove effects here rather than unit_remove_map_pc so we don't clear on Teleport/map change.
  1793. elemental_clean_effect(sd->ed);
  1794. if (sd->state.permanent_speed == 1) sd->state.permanent_speed = 0; // Remove lock so speed is set back to normal at login.
  1795. if( map[sd->bl.m].instance_id )
  1796. instance_delusers(map[sd->bl.m].instance_id);
  1797. unit_remove_map_pc(sd,CLR_RESPAWN);
  1798. if( map[sd->bl.m].instance_id ) { // Avoid map conflicts and warnings on next login
  1799. int16 m;
  1800. struct point *pt;
  1801. if( map[sd->bl.m].save.map )
  1802. pt = &map[sd->bl.m].save;
  1803. else
  1804. pt = &sd->status.save_point;
  1805. if( (m=map_mapindex2mapid(pt->map)) >= 0 )
  1806. {
  1807. sd->bl.m = m;
  1808. sd->bl.x = pt->x;
  1809. sd->bl.y = pt->y;
  1810. sd->mapindex = pt->map;
  1811. }
  1812. }
  1813. if (sd->state.vending)
  1814. idb_remove(vending_getdb(), sd->status.char_id);
  1815. if (sd->state.buyingstore)
  1816. idb_remove(buyingstore_getdb(), sd->status.char_id);
  1817. pc_damage_log_clear(sd,0);
  1818. party_booking_delete(sd); // Party Booking [Spiria]
  1819. pc_makesavestatus(sd);
  1820. pc_clean_skilltree(sd);
  1821. pc_crimson_marker_clear(sd);
  1822. chrif_save(sd, CSAVE_QUIT|CSAVE_INVENTORY|CSAVE_CART);
  1823. unit_free_pc(sd);
  1824. return 0;
  1825. }
  1826. /*==========================================
  1827. * Lookup, id to session (player,mob,npc,homon,merc..)
  1828. *------------------------------------------*/
  1829. struct map_session_data * map_id2sd(int id){
  1830. if (id <= 0) return NULL;
  1831. return (struct map_session_data*)idb_get(pc_db,id);
  1832. }
  1833. struct mob_data * map_id2md(int id){
  1834. if (id <= 0) return NULL;
  1835. return (struct mob_data*)idb_get(mobid_db,id);
  1836. }
  1837. struct npc_data * map_id2nd(int id){
  1838. struct block_list* bl = map_id2bl(id);
  1839. return BL_CAST(BL_NPC, bl);
  1840. }
  1841. struct homun_data* map_id2hd(int id){
  1842. struct block_list* bl = map_id2bl(id);
  1843. return BL_CAST(BL_HOM, bl);
  1844. }
  1845. struct mercenary_data* map_id2mc(int id){
  1846. struct block_list* bl = map_id2bl(id);
  1847. return BL_CAST(BL_MER, bl);
  1848. }
  1849. struct pet_data* map_id2pd(int id){
  1850. struct block_list* bl = map_id2bl(id);
  1851. return BL_CAST(BL_PET, bl);
  1852. }
  1853. struct elemental_data* map_id2ed(int id) {
  1854. struct block_list* bl = map_id2bl(id);
  1855. return BL_CAST(BL_ELEM, bl);
  1856. }
  1857. struct chat_data* map_id2cd(int id){
  1858. struct block_list* bl = map_id2bl(id);
  1859. return BL_CAST(BL_CHAT, bl);
  1860. }
  1861. /// Returns the nick of the target charid or NULL if unknown (requests the nick to the char server).
  1862. const char* map_charid2nick(int charid)
  1863. {
  1864. struct charid2nick *p;
  1865. struct map_session_data* sd;
  1866. sd = map_charid2sd(charid);
  1867. if( sd )
  1868. return sd->status.name;// character is online, return it's name
  1869. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1870. if( *p->nick )
  1871. return p->nick;// name in nick_db
  1872. chrif_searchcharid(charid);// request the name
  1873. return NULL;
  1874. }
  1875. /// Returns the struct map_session_data of the charid or NULL if the char is not online.
  1876. struct map_session_data* map_charid2sd(int charid)
  1877. {
  1878. return (struct map_session_data*)uidb_get(charid_db, charid);
  1879. }
  1880. /*==========================================
  1881. * Search session data from a nick name
  1882. * (without sensitive case if necessary)
  1883. * return map_session_data pointer or NULL
  1884. *------------------------------------------*/
  1885. struct map_session_data * map_nick2sd(const char *nick, bool allow_partial)
  1886. {
  1887. struct map_session_data* sd;
  1888. struct map_session_data* found_sd;
  1889. struct s_mapiterator* iter;
  1890. size_t nicklen;
  1891. int qty = 0;
  1892. if( nick == NULL )
  1893. return NULL;
  1894. nicklen = strlen(nick);
  1895. iter = mapit_getallusers();
  1896. found_sd = NULL;
  1897. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  1898. {
  1899. if( allow_partial && battle_config.partial_name_scan )
  1900. {// partial name search
  1901. if( strnicmp(sd->status.name, nick, nicklen) == 0 )
  1902. {
  1903. found_sd = sd;
  1904. if( strcmp(sd->status.name, nick) == 0 )
  1905. {// Perfect Match
  1906. qty = 1;
  1907. break;
  1908. }
  1909. qty++;
  1910. }
  1911. }
  1912. else if( strcasecmp(sd->status.name, nick) == 0 )
  1913. {// exact search only
  1914. found_sd = sd;
  1915. qty = 1;
  1916. break;
  1917. }
  1918. }
  1919. mapit_free(iter);
  1920. if( battle_config.partial_name_scan && qty != 1 )
  1921. found_sd = NULL;
  1922. return found_sd;
  1923. }
  1924. /*==========================================
  1925. * Looksup id_db DBMap and returns BL pointer of 'id' or NULL if not found
  1926. *------------------------------------------*/
  1927. struct block_list * map_id2bl(int id) {
  1928. return (struct block_list*)idb_get(id_db,id);
  1929. }
  1930. /**
  1931. * Same as map_id2bl except it only checks for its existence
  1932. **/
  1933. bool map_blid_exists( int id ) {
  1934. return (idb_exists(id_db,id));
  1935. }
  1936. /*==========================================
  1937. * Convex Mirror
  1938. *------------------------------------------*/
  1939. struct mob_data * map_getmob_boss(int16 m)
  1940. {
  1941. DBIterator* iter;
  1942. struct mob_data *md = NULL;
  1943. bool found = false;
  1944. iter = db_iterator(bossid_db);
  1945. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1946. {
  1947. if( md->bl.m == m )
  1948. {
  1949. found = true;
  1950. break;
  1951. }
  1952. }
  1953. dbi_destroy(iter);
  1954. return (found)? md : NULL;
  1955. }
  1956. struct mob_data * map_id2boss(int id)
  1957. {
  1958. if (id <= 0) return NULL;
  1959. return (struct mob_data*)idb_get(bossid_db,id);
  1960. }
  1961. /// Applies func to all the players in the db.
  1962. /// Stops iterating if func returns -1.
  1963. void map_foreachpc(int (*func)(struct map_session_data* sd, va_list args), ...)
  1964. {
  1965. DBIterator* iter;
  1966. struct map_session_data* sd;
  1967. iter = db_iterator(pc_db);
  1968. for( sd = (struct map_session_data*)dbi_first(iter); dbi_exists(iter); sd = (struct map_session_data*)dbi_next(iter) )
  1969. {
  1970. va_list args;
  1971. int ret;
  1972. va_start(args, func);
  1973. ret = func(sd, args);
  1974. va_end(args);
  1975. if( ret == -1 )
  1976. break;// stop iterating
  1977. }
  1978. dbi_destroy(iter);
  1979. }
  1980. /// Applies func to all the mobs in the db.
  1981. /// Stops iterating if func returns -1.
  1982. void map_foreachmob(int (*func)(struct mob_data* md, va_list args), ...)
  1983. {
  1984. DBIterator* iter;
  1985. struct mob_data* md;
  1986. iter = db_iterator(mobid_db);
  1987. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1988. {
  1989. va_list args;
  1990. int ret;
  1991. va_start(args, func);
  1992. ret = func(md, args);
  1993. va_end(args);
  1994. if( ret == -1 )
  1995. break;// stop iterating
  1996. }
  1997. dbi_destroy(iter);
  1998. }
  1999. /// Applies func to all the npcs in the db.
  2000. /// Stops iterating if func returns -1.
  2001. void map_foreachnpc(int (*func)(struct npc_data* nd, va_list args), ...)
  2002. {
  2003. DBIterator* iter;
  2004. struct block_list* bl;
  2005. iter = db_iterator(id_db);
  2006. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2007. {
  2008. if( bl->type == BL_NPC )
  2009. {
  2010. struct npc_data* nd = (struct npc_data*)bl;
  2011. va_list args;
  2012. int ret;
  2013. va_start(args, func);
  2014. ret = func(nd, args);
  2015. va_end(args);
  2016. if( ret == -1 )
  2017. break;// stop iterating
  2018. }
  2019. }
  2020. dbi_destroy(iter);
  2021. }
  2022. /// Applies func to everything in the db.
  2023. /// Stops iterating if func returns -1.
  2024. void map_foreachregen(int (*func)(struct block_list* bl, va_list args), ...)
  2025. {
  2026. DBIterator* iter;
  2027. struct block_list* bl;
  2028. iter = db_iterator(regen_db);
  2029. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2030. {
  2031. va_list args;
  2032. int ret;
  2033. va_start(args, func);
  2034. ret = func(bl, args);
  2035. va_end(args);
  2036. if( ret == -1 )
  2037. break;// stop iterating
  2038. }
  2039. dbi_destroy(iter);
  2040. }
  2041. /// Applies func to everything in the db.
  2042. /// Stops iterating if func returns -1.
  2043. void map_foreachiddb(int (*func)(struct block_list* bl, va_list args), ...)
  2044. {
  2045. DBIterator* iter;
  2046. struct block_list* bl;
  2047. iter = db_iterator(id_db);
  2048. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2049. {
  2050. va_list args;
  2051. int ret;
  2052. va_start(args, func);
  2053. ret = func(bl, args);
  2054. va_end(args);
  2055. if( ret == -1 )
  2056. break;// stop iterating
  2057. }
  2058. dbi_destroy(iter);
  2059. }
  2060. /// Iterator.
  2061. /// Can filter by bl type.
  2062. struct s_mapiterator
  2063. {
  2064. enum e_mapitflags flags;// flags for special behaviour
  2065. enum bl_type types;// what bl types to return
  2066. DBIterator* dbi;// database iterator
  2067. };
  2068. /// Returns true if the block_list matches the description in the iterator.
  2069. ///
  2070. /// @param _mapit_ Iterator
  2071. /// @param _bl_ block_list
  2072. /// @return true if it matches
  2073. #define MAPIT_MATCHES(_mapit_,_bl_) \
  2074. ( \
  2075. ( (_bl_)->type & (_mapit_)->types /* type matches */ ) \
  2076. )
  2077. /// Allocates a new iterator.
  2078. /// Returns the new iterator.
  2079. /// types can represent several BL's as a bit field.
  2080. /// TODO should this be expanded to allow filtering of map/guild/party/chat/cell/area/...?
  2081. ///
  2082. /// @param flags Flags of the iterator
  2083. /// @param type Target types
  2084. /// @return Iterator
  2085. struct s_mapiterator* mapit_alloc(enum e_mapitflags flags, enum bl_type types)
  2086. {
  2087. struct s_mapiterator* mapit;
  2088. CREATE(mapit, struct s_mapiterator, 1);
  2089. mapit->flags = flags;
  2090. mapit->types = types;
  2091. if( types == BL_PC ) mapit->dbi = db_iterator(pc_db);
  2092. else if( types == BL_MOB ) mapit->dbi = db_iterator(mobid_db);
  2093. else mapit->dbi = db_iterator(id_db);
  2094. return mapit;
  2095. }
  2096. /// Frees the iterator.
  2097. ///
  2098. /// @param mapit Iterator
  2099. void mapit_free(struct s_mapiterator* mapit)
  2100. {
  2101. nullpo_retv(mapit);
  2102. dbi_destroy(mapit->dbi);
  2103. aFree(mapit);
  2104. }
  2105. /// Returns the first block_list that matches the description.
  2106. /// Returns NULL if not found.
  2107. ///
  2108. /// @param mapit Iterator
  2109. /// @return first block_list or NULL
  2110. struct block_list* mapit_first(struct s_mapiterator* mapit)
  2111. {
  2112. struct block_list* bl;
  2113. nullpo_retr(NULL,mapit);
  2114. for( bl = (struct block_list*)dbi_first(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_next(mapit->dbi) )
  2115. {
  2116. if( MAPIT_MATCHES(mapit,bl) )
  2117. break;// found match
  2118. }
  2119. return bl;
  2120. }
  2121. /// Returns the last block_list that matches the description.
  2122. /// Returns NULL if not found.
  2123. ///
  2124. /// @param mapit Iterator
  2125. /// @return last block_list or NULL
  2126. struct block_list* mapit_last(struct s_mapiterator* mapit)
  2127. {
  2128. struct block_list* bl;
  2129. nullpo_retr(NULL,mapit);
  2130. for( bl = (struct block_list*)dbi_last(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_prev(mapit->dbi) )
  2131. {
  2132. if( MAPIT_MATCHES(mapit,bl) )
  2133. break;// found match
  2134. }
  2135. return bl;
  2136. }
  2137. /// Returns the next block_list that matches the description.
  2138. /// Returns NULL if not found.
  2139. ///
  2140. /// @param mapit Iterator
  2141. /// @return next block_list or NULL
  2142. struct block_list* mapit_next(struct s_mapiterator* mapit)
  2143. {
  2144. struct block_list* bl;
  2145. nullpo_retr(NULL,mapit);
  2146. for( ; ; )
  2147. {
  2148. bl = (struct block_list*)dbi_next(mapit->dbi);
  2149. if( bl == NULL )
  2150. break;// end
  2151. if( MAPIT_MATCHES(mapit,bl) )
  2152. break;// found a match
  2153. // try next
  2154. }
  2155. return bl;
  2156. }
  2157. /// Returns the previous block_list that matches the description.
  2158. /// Returns NULL if not found.
  2159. ///
  2160. /// @param mapit Iterator
  2161. /// @return previous block_list or NULL
  2162. struct block_list* mapit_prev(struct s_mapiterator* mapit)
  2163. {
  2164. struct block_list* bl;
  2165. nullpo_retr(NULL,mapit);
  2166. for( ; ; )
  2167. {
  2168. bl = (struct block_list*)dbi_prev(mapit->dbi);
  2169. if( bl == NULL )
  2170. break;// end
  2171. if( MAPIT_MATCHES(mapit,bl) )
  2172. break;// found a match
  2173. // try prev
  2174. }
  2175. return bl;
  2176. }
  2177. /// Returns true if the current block_list exists in the database.
  2178. ///
  2179. /// @param mapit Iterator
  2180. /// @return true if it exists
  2181. bool mapit_exists(struct s_mapiterator* mapit)
  2182. {
  2183. nullpo_retr(false,mapit);
  2184. return dbi_exists(mapit->dbi);
  2185. }
  2186. /*==========================================
  2187. * Add npc-bl to id_db, basically register npc to map
  2188. *------------------------------------------*/
  2189. bool map_addnpc(int16 m,struct npc_data *nd)
  2190. {
  2191. nullpo_ret(nd);
  2192. if( m < 0 || m >= map_num )
  2193. return false;
  2194. if( map[m].npc_num == MAX_NPC_PER_MAP )
  2195. {
  2196. ShowWarning("too many NPCs in one map %s\n",map[m].name);
  2197. return false;
  2198. }
  2199. map[m].npc[map[m].npc_num]=nd;
  2200. map[m].npc_num++;
  2201. idb_put(id_db,nd->bl.id,nd);
  2202. return true;
  2203. }
  2204. /*==========================================
  2205. * Add an instance map
  2206. *------------------------------------------*/
  2207. int map_addinstancemap(const char *name, unsigned short instance_id)
  2208. {
  2209. int src_m = map_mapname2mapid(name);
  2210. int dst_m = -1, i;
  2211. char iname[MAP_NAME_LENGTH];
  2212. size_t num_cell, size;
  2213. if(src_m < 0)
  2214. return -1;
  2215. if(strlen(name) > 20) {
  2216. // against buffer overflow
  2217. ShowError("map_addisntancemap: can't add long map name \"%s\"\n", name);
  2218. return -2;
  2219. }
  2220. for(i = instance_start; i < MAX_MAP_PER_SERVER; i++) {
  2221. if(!map[i].name[0])
  2222. break;
  2223. }
  2224. if(i < map_num) // Destination map value overwrites another
  2225. dst_m = i;
  2226. else if(i < MAX_MAP_PER_SERVER) // Destination map value increments to new map
  2227. dst_m = map_num++;
  2228. else {
  2229. // Out of bounds
  2230. ShowError("map_addinstancemap failed. map_num(%d) > map_max(%d)\n",map_num, MAX_MAP_PER_SERVER);
  2231. return -3;
  2232. }
  2233. // Copy the map
  2234. memcpy(&map[dst_m], &map[src_m], sizeof(struct map_data));
  2235. strcpy(iname,name);
  2236. // Alter the name
  2237. // Due to this being custom we only worry about preserving as many characters as necessary for accurate map distinguishing
  2238. // This also allows us to maintain complete independence with main map functions
  2239. if((strchr(iname,'@') == NULL) && strlen(iname) > 8) {
  2240. memmove(iname, iname+(strlen(iname)-9), strlen(iname));
  2241. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%hu#%s", instance_id, iname);
  2242. } else
  2243. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%.3hu%s", instance_id, iname);
  2244. map[dst_m].name[MAP_NAME_LENGTH-1] = '\0';
  2245. // Mimic questinfo
  2246. if( map[src_m].qi_count ) {
  2247. map[dst_m].qi_count = map[src_m].qi_count;
  2248. CREATE( map[dst_m].qi_data, struct questinfo, map[dst_m].qi_count );
  2249. memcpy( map[dst_m].qi_data, map[src_m].qi_data, map[dst_m].qi_count * sizeof(struct questinfo) );
  2250. }
  2251. map[dst_m].m = dst_m;
  2252. map[dst_m].instance_id = instance_id;
  2253. map[dst_m].instance_src_map = src_m;
  2254. map[dst_m].users = 0;
  2255. memset(map[dst_m].npc, 0, sizeof(map[dst_m].npc));
  2256. map[dst_m].npc_num = 0;
  2257. // Reallocate cells
  2258. num_cell = map[dst_m].xs * map[dst_m].ys;
  2259. CREATE( map[dst_m].cell, struct mapcell, num_cell );
  2260. memcpy( map[dst_m].cell, map[src_m].cell, num_cell * sizeof(struct mapcell) );
  2261. size = map[dst_m].bxs * map[dst_m].bys * sizeof(struct block_list*);
  2262. map[dst_m].block = (struct block_list **)aCalloc(1,size);
  2263. map[dst_m].block_mob = (struct block_list **)aCalloc(1,size);
  2264. map[dst_m].index = mapindex_addmap(-1, map[dst_m].name);
  2265. map[dst_m].channel = NULL;
  2266. map[dst_m].mob_delete_timer = INVALID_TIMER;
  2267. map_addmap2db(&map[dst_m]);
  2268. return dst_m;
  2269. }
  2270. /*==========================================
  2271. * Set player to save point when they leave
  2272. *------------------------------------------*/
  2273. static int map_instancemap_leave(struct block_list *bl, va_list ap)
  2274. {
  2275. struct map_session_data* sd;
  2276. nullpo_retr(0, bl);
  2277. nullpo_retr(0, sd = (struct map_session_data *)bl);
  2278. pc_setpos(sd, sd->status.save_point.map, sd->status.save_point.x, sd->status.save_point.y, CLR_TELEPORT);
  2279. return 1;
  2280. }
  2281. /*==========================================
  2282. * Remove all units from instance
  2283. *------------------------------------------*/
  2284. static int map_instancemap_clean(struct block_list *bl, va_list ap)
  2285. {
  2286. nullpo_retr(0, bl);
  2287. switch(bl->type) {
  2288. /*case BL_PC:
  2289. // BL_PET, BL_HOM, BL_MER, and BL_ELEM are moved when BL_PC warped out in map_instancemap_leave
  2290. map_quit((struct map_session_data *) bl);
  2291. break;*/
  2292. case BL_NPC:
  2293. npc_unload((struct npc_data *)bl,true);
  2294. break;
  2295. case BL_MOB:
  2296. unit_free(bl,CLR_OUTSIGHT);
  2297. break;
  2298. case BL_ITEM:
  2299. map_clearflooritem(bl);
  2300. break;
  2301. case BL_SKILL:
  2302. skill_delunit((struct skill_unit *) bl);
  2303. break;
  2304. }
  2305. return 1;
  2306. }
  2307. static void map_free_questinfo(int m);
  2308. /*==========================================
  2309. * Deleting an instance map
  2310. *------------------------------------------*/
  2311. int map_delinstancemap(int m)
  2312. {
  2313. if(m < 0 || !map[m].instance_id)
  2314. return 0;
  2315. // Kick everyone out
  2316. map_foreachinmap(map_instancemap_leave, m, BL_PC);
  2317. // Do the unit cleanup
  2318. map_foreachinmap(map_instancemap_clean, m, BL_ALL);
  2319. if( map[m].mob_delete_timer != INVALID_TIMER )
  2320. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2321. // Free memory
  2322. aFree(map[m].cell);
  2323. aFree(map[m].block);
  2324. aFree(map[m].block_mob);
  2325. map_free_questinfo(m);
  2326. mapindex_removemap( map[m].index );
  2327. map_removemapdb(&map[m]);
  2328. memset(&map[m], 0x00, sizeof(map[0]));
  2329. map[m].mob_delete_timer = INVALID_TIMER;
  2330. return 1;
  2331. }
  2332. /*=========================================
  2333. * Dynamic Mobs [Wizputer]
  2334. *-----------------------------------------*/
  2335. // Stores the spawn data entry in the mob list.
  2336. // Returns the index of successful, or -1 if the list was full.
  2337. int map_addmobtolist(unsigned short m, struct spawn_data *spawn)
  2338. {
  2339. size_t i;
  2340. ARR_FIND( 0, MAX_MOB_LIST_PER_MAP, i, map[m].moblist[i] == NULL );
  2341. if( i < MAX_MOB_LIST_PER_MAP )
  2342. {
  2343. map[m].moblist[i] = spawn;
  2344. return i;
  2345. }
  2346. return -1;
  2347. }
  2348. void map_spawnmobs(int16 m)
  2349. {
  2350. int i, k=0;
  2351. if (map[m].mob_delete_timer != INVALID_TIMER)
  2352. { //Mobs have not been removed yet [Skotlex]
  2353. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2354. map[m].mob_delete_timer = INVALID_TIMER;
  2355. return;
  2356. }
  2357. for(i=0; i<MAX_MOB_LIST_PER_MAP; i++)
  2358. if(map[m].moblist[i]!=NULL)
  2359. {
  2360. k+=map[m].moblist[i]->num;
  2361. npc_parse_mob2(map[m].moblist[i]);
  2362. }
  2363. if (battle_config.etc_log && k > 0)
  2364. {
  2365. ShowStatus("Map %s: Spawned '" CL_WHITE "%d" CL_RESET "' mobs.\n",map[m].name, k);
  2366. }
  2367. }
  2368. int map_removemobs_sub(struct block_list *bl, va_list ap)
  2369. {
  2370. struct mob_data *md = (struct mob_data *)bl;
  2371. nullpo_ret(md);
  2372. //When not to remove mob:
  2373. // doesn't respawn and is not a slave
  2374. if( !md->spawn && !md->master_id )
  2375. return 0;
  2376. // respawn data is not in cache
  2377. if( md->spawn && !md->spawn->state.dynamic )
  2378. return 0;
  2379. // hasn't spawned yet
  2380. if( md->spawn_timer != INVALID_TIMER )
  2381. return 0;
  2382. // is damaged and mob_remove_damaged is off
  2383. if( !battle_config.mob_remove_damaged && md->status.hp < md->status.max_hp )
  2384. return 0;
  2385. // is a mvp
  2386. if( md->db->mexp > 0 )
  2387. return 0;
  2388. unit_free(&md->bl,CLR_OUTSIGHT);
  2389. return 1;
  2390. }
  2391. int map_removemobs_timer(int tid, unsigned int tick, int id, intptr_t data)
  2392. {
  2393. int count;
  2394. const int16 m = id;
  2395. if (m < 0 || m >= MAX_MAP_PER_SERVER)
  2396. { //Incorrect map id!
  2397. ShowError("map_removemobs_timer error: timer %d points to invalid map %d\n",tid, m);
  2398. return 0;
  2399. }
  2400. if (map[m].mob_delete_timer != tid)
  2401. { //Incorrect timer call!
  2402. ShowError("map_removemobs_timer mismatch: %d != %d (map %s)\n",map[m].mob_delete_timer, tid, map[m].name);
  2403. return 0;
  2404. }
  2405. map[m].mob_delete_timer = INVALID_TIMER;
  2406. if (map[m].users > 0) //Map not empty!
  2407. return 1;
  2408. count = map_foreachinmap(map_removemobs_sub, m, BL_MOB);
  2409. if (battle_config.etc_log && count > 0)
  2410. ShowStatus("Map %s: Removed '" CL_WHITE "%d" CL_RESET "' mobs.\n",map[m].name, count);
  2411. return 1;
  2412. }
  2413. void map_removemobs(int16 m)
  2414. {
  2415. if (map[m].mob_delete_timer != INVALID_TIMER) // should never happen
  2416. return; //Mobs are already scheduled for removal
  2417. // Don't remove mobs on instance map
  2418. if (map[m].instance_id)
  2419. return;
  2420. map[m].mob_delete_timer = add_timer(gettick()+battle_config.mob_remove_delay, map_removemobs_timer, m, 0);
  2421. }
  2422. /*==========================================
  2423. * Check for map_name from map_id
  2424. *------------------------------------------*/
  2425. const char* map_mapid2mapname(int m)
  2426. {
  2427. if (map[m].instance_id) { // Instance map check
  2428. struct instance_data *im = &instance_data[map[m].instance_id];
  2429. if (!im) // This shouldn't happen but if it does give them the map we intended to give
  2430. return map[m].name;
  2431. else {
  2432. uint8 i;
  2433. for (i = 0; i < im->cnt_map; i++) { // Loop to find the src map we want
  2434. if (im->map[i]->m == m)
  2435. return map[im->map[i]->src_m].name;
  2436. }
  2437. }
  2438. }
  2439. return map[m].name;
  2440. }
  2441. /*==========================================
  2442. * Hookup, get map_id from map_name
  2443. *------------------------------------------*/
  2444. int16 map_mapname2mapid(const char* name)
  2445. {
  2446. unsigned short map_index;
  2447. map_index = mapindex_name2id(name);
  2448. if (!map_index)
  2449. return -1;
  2450. return map_mapindex2mapid(map_index);
  2451. }
  2452. /*==========================================
  2453. * Returns the map of the given mapindex. [Skotlex]
  2454. *------------------------------------------*/
  2455. int16 map_mapindex2mapid(unsigned short mapindex)
  2456. {
  2457. struct map_data *md=NULL;
  2458. if (!mapindex)
  2459. return -1;
  2460. md = (struct map_data*)uidb_get(map_db,(unsigned int)mapindex);
  2461. if(md==NULL || md->cell==NULL)
  2462. return -1;
  2463. return md->m;
  2464. }
  2465. /*==========================================
  2466. * Switching Ip, port ? (like changing map_server) get ip/port from map_name
  2467. *------------------------------------------*/
  2468. int map_mapname2ipport(unsigned short name, uint32* ip, uint16* port)
  2469. {
  2470. struct map_data_other_server *mdos;
  2471. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)name);
  2472. if(mdos==NULL || mdos->cell) //If gat isn't null, this is a local map.
  2473. return -1;
  2474. *ip=mdos->ip;
  2475. *port=mdos->port;
  2476. return 0;
  2477. }
  2478. /*==========================================
  2479. * Checks if both dirs point in the same direction.
  2480. *------------------------------------------*/
  2481. int map_check_dir(int s_dir,int t_dir)
  2482. {
  2483. if(s_dir == t_dir)
  2484. return 0;
  2485. switch(s_dir) {
  2486. case 0: if(t_dir == 7 || t_dir == 1 || t_dir == 0) return 0; break;
  2487. case 1: if(t_dir == 0 || t_dir == 2 || t_dir == 1) return 0; break;
  2488. case 2: if(t_dir == 1 || t_dir == 3 || t_dir == 2) return 0; break;
  2489. case 3: if(t_dir == 2 || t_dir == 4 || t_dir == 3) return 0; break;
  2490. case 4: if(t_dir == 3 || t_dir == 5 || t_dir == 4) return 0; break;
  2491. case 5: if(t_dir == 4 || t_dir == 6 || t_dir == 5) return 0; break;
  2492. case 6: if(t_dir == 5 || t_dir == 7 || t_dir == 6) return 0; break;
  2493. case 7: if(t_dir == 6 || t_dir == 0 || t_dir == 7) return 0; break;
  2494. }
  2495. return 1;
  2496. }
  2497. /*==========================================
  2498. * Returns the direction of the given cell, relative to 'src'
  2499. *------------------------------------------*/
  2500. uint8 map_calc_dir(struct block_list* src, int16 x, int16 y)
  2501. {
  2502. uint8 dir = 0;
  2503. nullpo_ret(src);
  2504. dir = map_calc_dir_xy(src->x, src->y, x, y, unit_getdir(src));
  2505. return dir;
  2506. }
  2507. /*==========================================
  2508. * Returns the direction of the given cell, relative to source cell
  2509. * Use this if you don't have a block list available to check against
  2510. *------------------------------------------*/
  2511. uint8 map_calc_dir_xy(int16 srcx, int16 srcy, int16 x, int16 y, uint8 srcdir) {
  2512. uint8 dir = 0;
  2513. int dx, dy;
  2514. dx = x-srcx;
  2515. dy = y-srcy;
  2516. if( dx == 0 && dy == 0 )
  2517. { // both are standing on the same spot
  2518. // aegis-style, makes knockback default to the left
  2519. // athena-style, makes knockback default to behind 'src'
  2520. dir = (battle_config.knockback_left ? 6 : srcdir);
  2521. }
  2522. else if( dx >= 0 && dy >=0 )
  2523. { // upper-right
  2524. if( dx >= dy*3 ) dir = 6; // right
  2525. else if( dx*3 < dy ) dir = 0; // up
  2526. else dir = 7; // up-right
  2527. }
  2528. else if( dx >= 0 && dy <= 0 )
  2529. { // lower-right
  2530. if( dx >= -dy*3 ) dir = 6; // right
  2531. else if( dx*3 < -dy ) dir = 4; // down
  2532. else dir = 5; // down-right
  2533. }
  2534. else if( dx <= 0 && dy <= 0 )
  2535. { // lower-left
  2536. if( dx*3 >= dy ) dir = 4; // down
  2537. else if( dx < dy*3 ) dir = 2; // left
  2538. else dir = 3; // down-left
  2539. }
  2540. else
  2541. { // upper-left
  2542. if( -dx*3 <= dy ) dir = 0; // up
  2543. else if( -dx > dy*3 ) dir = 2; // left
  2544. else dir = 1; // up-left
  2545. }
  2546. return dir;
  2547. }
  2548. /*==========================================
  2549. * Randomizes target cell x,y to a random walkable cell that
  2550. * has the same distance from object as given coordinates do. [Skotlex]
  2551. *------------------------------------------*/
  2552. int map_random_dir(struct block_list *bl, int16 *x, int16 *y)
  2553. {
  2554. short xi = *x-bl->x;
  2555. short yi = *y-bl->y;
  2556. short i=0;
  2557. int dist2 = xi*xi + yi*yi;
  2558. short dist = (short)sqrt((float)dist2);
  2559. if (dist < 1) dist =1;
  2560. do {
  2561. short j = 1 + 2*(rnd()%4); //Pick a random diagonal direction
  2562. short segment = 1+(rnd()%dist); //Pick a random interval from the whole vector in that direction
  2563. xi = bl->x + segment*dirx[j];
  2564. segment = (short)sqrt((float)(dist2 - segment*segment)); //The complement of the previously picked segment
  2565. yi = bl->y + segment*diry[j];
  2566. } while (
  2567. (map_getcell(bl->m,xi,yi,CELL_CHKNOPASS) || !path_search(NULL,bl->m,bl->x,bl->y,xi,yi,1,CELL_CHKNOREACH))
  2568. && (++i)<100 );
  2569. if (i < 100) {
  2570. *x = xi;
  2571. *y = yi;
  2572. return 1;
  2573. }
  2574. return 0;
  2575. }
  2576. // gat system
  2577. inline static struct mapcell map_gat2cell(int gat) {
  2578. struct mapcell cell;
  2579. memset(&cell,0,sizeof(struct mapcell));
  2580. switch( gat ) {
  2581. case 0: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // walkable ground
  2582. case 1: cell.walkable = 0; cell.shootable = 0; cell.water = 0; break; // non-walkable ground
  2583. case 2: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2584. case 3: cell.walkable = 1; cell.shootable = 1; cell.water = 1; break; // walkable water
  2585. case 4: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2586. case 5: cell.walkable = 0; cell.shootable = 1; cell.water = 0; break; // gap (snipable)
  2587. case 6: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2588. default:
  2589. ShowWarning("map_gat2cell: unrecognized gat type '%d'\n", gat);
  2590. break;
  2591. }
  2592. return cell;
  2593. }
  2594. static int map_cell2gat(struct mapcell cell)
  2595. {
  2596. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 0 ) return 0;
  2597. if( cell.walkable == 0 && cell.shootable == 0 && cell.water == 0 ) return 1;
  2598. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 1 ) return 3;
  2599. if( cell.walkable == 0 && cell.shootable == 1 && cell.water == 0 ) return 5;
  2600. ShowWarning("map_cell2gat: cell has no matching gat type\n");
  2601. return 1; // default to 'wall'
  2602. }
  2603. /*==========================================
  2604. * Confirm if celltype in (m,x,y) match the one given in cellchk
  2605. *------------------------------------------*/
  2606. int map_getcell(int16 m,int16 x,int16 y,cell_chk cellchk)
  2607. {
  2608. return (m < 0 || m >= MAX_MAP_PER_SERVER) ? 0 : map_getcellp(&map[m],x,y,cellchk);
  2609. }
  2610. int map_getcellp(struct map_data* m,int16 x,int16 y,cell_chk cellchk)
  2611. {
  2612. struct mapcell cell;
  2613. nullpo_ret(m);
  2614. //NOTE: this intentionally overrides the last row and column
  2615. if(x<0 || x>=m->xs-1 || y<0 || y>=m->ys-1)
  2616. return( cellchk == CELL_CHKNOPASS );
  2617. cell = m->cell[x + y*m->xs];
  2618. switch(cellchk)
  2619. {
  2620. // gat type retrieval
  2621. case CELL_GETTYPE:
  2622. return map_cell2gat(cell);
  2623. // base gat type checks
  2624. case CELL_CHKWALL:
  2625. return (!cell.walkable && !cell.shootable);
  2626. case CELL_CHKWATER:
  2627. return (cell.water);
  2628. case CELL_CHKCLIFF:
  2629. return (!cell.walkable && cell.shootable);
  2630. // base cell type checks
  2631. case CELL_CHKNPC:
  2632. return (cell.npc);
  2633. case CELL_CHKBASILICA:
  2634. return (cell.basilica);
  2635. case CELL_CHKLANDPROTECTOR:
  2636. return (cell.landprotector);
  2637. case CELL_CHKNOVENDING:
  2638. return (cell.novending);
  2639. case CELL_CHKNOCHAT:
  2640. return (cell.nochat);
  2641. case CELL_CHKMAELSTROM:
  2642. return (cell.maelstrom);
  2643. case CELL_CHKICEWALL:
  2644. return (cell.icewall);
  2645. // special checks
  2646. case CELL_CHKPASS:
  2647. #ifdef CELL_NOSTACK
  2648. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 0;
  2649. #endif
  2650. case CELL_CHKREACH:
  2651. return (cell.walkable);
  2652. case CELL_CHKNOPASS:
  2653. #ifdef CELL_NOSTACK
  2654. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 1;
  2655. #endif
  2656. case CELL_CHKNOREACH:
  2657. return (!cell.walkable);
  2658. case CELL_CHKSTACK:
  2659. #ifdef CELL_NOSTACK
  2660. return (cell.cell_bl >= battle_config.custom_cell_stack_limit);
  2661. #else
  2662. return 0;
  2663. #endif
  2664. default:
  2665. return 0;
  2666. }
  2667. }
  2668. /*==========================================
  2669. * Change the type/flags of a map cell
  2670. * 'cell' - which flag to modify
  2671. * 'flag' - true = on, false = off
  2672. *------------------------------------------*/
  2673. void map_setcell(int16 m, int16 x, int16 y, cell_t cell, bool flag)
  2674. {
  2675. int j;
  2676. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2677. return;
  2678. j = x + y*map[m].xs;
  2679. switch( cell ) {
  2680. case CELL_WALKABLE: map[m].cell[j].walkable = flag; break;
  2681. case CELL_SHOOTABLE: map[m].cell[j].shootable = flag; break;
  2682. case CELL_WATER: map[m].cell[j].water = flag; break;
  2683. case CELL_NPC: map[m].cell[j].npc = flag; break;
  2684. case CELL_BASILICA: map[m].cell[j].basilica = flag; break;
  2685. case CELL_LANDPROTECTOR: map[m].cell[j].landprotector = flag; break;
  2686. case CELL_NOVENDING: map[m].cell[j].novending = flag; break;
  2687. case CELL_NOCHAT: map[m].cell[j].nochat = flag; break;
  2688. case CELL_MAELSTROM: map[m].cell[j].maelstrom = flag; break;
  2689. case CELL_ICEWALL: map[m].cell[j].icewall = flag; break;
  2690. default:
  2691. ShowWarning("map_setcell: invalid cell type '%d'\n", (int)cell);
  2692. break;
  2693. }
  2694. }
  2695. void map_setgatcell(int16 m, int16 x, int16 y, int gat)
  2696. {
  2697. int j;
  2698. struct mapcell cell;
  2699. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2700. return;
  2701. j = x + y*map[m].xs;
  2702. cell = map_gat2cell(gat);
  2703. map[m].cell[j].walkable = cell.walkable;
  2704. map[m].cell[j].shootable = cell.shootable;
  2705. map[m].cell[j].water = cell.water;
  2706. }
  2707. /*==========================================
  2708. * Invisible Walls
  2709. *------------------------------------------*/
  2710. static DBMap* iwall_db;
  2711. void map_iwall_nextxy(int16 x, int16 y, int8 dir, int pos, int16 *x1, int16 *y1)
  2712. {
  2713. if( dir == 0 || dir == 4 )
  2714. *x1 = x; // Keep X
  2715. else if( dir > 0 && dir < 4 )
  2716. *x1 = x - pos; // Going left
  2717. else
  2718. *x1 = x + pos; // Going right
  2719. if( dir == 2 || dir == 6 )
  2720. *y1 = y;
  2721. else if( dir > 2 && dir < 6 )
  2722. *y1 = y - pos;
  2723. else
  2724. *y1 = y + pos;
  2725. }
  2726. bool map_iwall_set(int16 m, int16 x, int16 y, int size, int8 dir, bool shootable, const char* wall_name)
  2727. {
  2728. struct iwall_data *iwall;
  2729. int i;
  2730. int16 x1 = 0, y1 = 0;
  2731. if( size < 1 || !wall_name )
  2732. return false;
  2733. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) != NULL )
  2734. return false; // Already Exists
  2735. if( map_getcell(m, x, y, CELL_CHKNOREACH) )
  2736. return false; // Starting cell problem
  2737. CREATE(iwall, struct iwall_data, 1);
  2738. iwall->m = m;
  2739. iwall->x = x;
  2740. iwall->y = y;
  2741. iwall->size = size;
  2742. iwall->dir = dir;
  2743. iwall->shootable = shootable;
  2744. safestrncpy(iwall->wall_name, wall_name, sizeof(iwall->wall_name));
  2745. for( i = 0; i < size; i++ )
  2746. {
  2747. map_iwall_nextxy(x, y, dir, i, &x1, &y1);
  2748. if( map_getcell(m, x1, y1, CELL_CHKNOREACH) )
  2749. break; // Collision
  2750. map_setcell(m, x1, y1, CELL_WALKABLE, false);
  2751. map_setcell(m, x1, y1, CELL_SHOOTABLE, shootable);
  2752. clif_changemapcell(0, m, x1, y1, map_getcell(m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2753. }
  2754. iwall->size = i;
  2755. strdb_put(iwall_db, iwall->wall_name, iwall);
  2756. map[m].iwall_num++;
  2757. return true;
  2758. }
  2759. void map_iwall_get(struct map_session_data *sd) {
  2760. struct iwall_data *iwall;
  2761. DBIterator* iter;
  2762. int16 x1, y1;
  2763. int i;
  2764. if( map[sd->bl.m].iwall_num < 1 )
  2765. return;
  2766. iter = db_iterator(iwall_db);
  2767. for( iwall = (struct iwall_data *)dbi_first(iter); dbi_exists(iter); iwall = (struct iwall_data *)dbi_next(iter) ) {
  2768. if( iwall->m != sd->bl.m )
  2769. continue;
  2770. for( i = 0; i < iwall->size; i++ ) {
  2771. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2772. clif_changemapcell(sd->fd, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), SELF);
  2773. }
  2774. }
  2775. dbi_destroy(iter);
  2776. }
  2777. void map_iwall_remove(const char *wall_name)
  2778. {
  2779. struct iwall_data *iwall;
  2780. int16 i, x1, y1;
  2781. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) == NULL )
  2782. return; // Nothing to do
  2783. for( i = 0; i < iwall->size; i++ ) {
  2784. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2785. map_setcell(iwall->m, x1, y1, CELL_SHOOTABLE, true);
  2786. map_setcell(iwall->m, x1, y1, CELL_WALKABLE, true);
  2787. clif_changemapcell(0, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2788. }
  2789. map[iwall->m].iwall_num--;
  2790. strdb_remove(iwall_db, iwall->wall_name);
  2791. }
  2792. /**
  2793. * @see DBCreateData
  2794. */
  2795. static DBData create_map_data_other_server(DBKey key, va_list args)
  2796. {
  2797. struct map_data_other_server *mdos;
  2798. unsigned short mapindex = (unsigned short)key.ui;
  2799. mdos=(struct map_data_other_server *)aCalloc(1,sizeof(struct map_data_other_server));
  2800. mdos->index = mapindex;
  2801. memcpy(mdos->name, mapindex_id2name(mapindex), MAP_NAME_LENGTH);
  2802. return db_ptr2data(mdos);
  2803. }
  2804. /*==========================================
  2805. * Add mapindex to db of another map server
  2806. *------------------------------------------*/
  2807. int map_setipport(unsigned short mapindex, uint32 ip, uint16 port)
  2808. {
  2809. struct map_data_other_server *mdos;
  2810. mdos= (struct map_data_other_server *)uidb_ensure(map_db,(unsigned int)mapindex, create_map_data_other_server);
  2811. if(mdos->cell) //Local map,Do nothing. Give priority to our own local maps over ones from another server. [Skotlex]
  2812. return 0;
  2813. if(ip == clif_getip() && port == clif_getport()) {
  2814. //That's odd, we received info that we are the ones with this map, but... we don't have it.
  2815. ShowFatalError("map_setipport : received info that this map-server SHOULD have map '%s', but it is not loaded.\n",mapindex_id2name(mapindex));
  2816. exit(EXIT_FAILURE);
  2817. }
  2818. mdos->ip = ip;
  2819. mdos->port = port;
  2820. return 1;
  2821. }
  2822. /**
  2823. * Delete all the other maps server management
  2824. * @see DBApply
  2825. */
  2826. int map_eraseallipport_sub(DBKey key, DBData *data, va_list va)
  2827. {
  2828. struct map_data_other_server *mdos = (struct map_data_other_server *)db_data2ptr(data);
  2829. if(mdos->cell == NULL) {
  2830. db_remove(map_db,key);
  2831. aFree(mdos);
  2832. }
  2833. return 0;
  2834. }
  2835. int map_eraseallipport(void)
  2836. {
  2837. map_db->foreach(map_db,map_eraseallipport_sub);
  2838. return 1;
  2839. }
  2840. /*==========================================
  2841. * Delete mapindex from db of another map server
  2842. *------------------------------------------*/
  2843. int map_eraseipport(unsigned short mapindex, uint32 ip, uint16 port)
  2844. {
  2845. struct map_data_other_server *mdos;
  2846. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)mapindex);
  2847. if(!mdos || mdos->cell) //Map either does not exists or is a local map.
  2848. return 0;
  2849. if(mdos->ip==ip && mdos->port == port) {
  2850. uidb_remove(map_db,(unsigned int)mapindex);
  2851. aFree(mdos);
  2852. return 1;
  2853. }
  2854. return 0;
  2855. }
  2856. /*==========================================
  2857. * [Shinryo]: Init the mapcache
  2858. *------------------------------------------*/
  2859. static char *map_init_mapcache(FILE *fp)
  2860. {
  2861. size_t size = 0;
  2862. char *buffer;
  2863. // No file open? Return..
  2864. nullpo_ret(fp);
  2865. // Get file size
  2866. fseek(fp, 0, SEEK_END);
  2867. size = ftell(fp);
  2868. fseek(fp, 0, SEEK_SET);
  2869. // Allocate enough space
  2870. CREATE(buffer, char, size);
  2871. // No memory? Return..
  2872. nullpo_ret(buffer);
  2873. // Read file into buffer..
  2874. if(fread(buffer, 1, size, fp) != size) {
  2875. ShowError("map_init_mapcache: Could not read entire mapcache file\n");
  2876. return NULL;
  2877. }
  2878. return buffer;
  2879. }
  2880. /*==========================================
  2881. * Map cache reading
  2882. * [Shinryo]: Optimized some behaviour to speed this up
  2883. *==========================================*/
  2884. int map_readfromcache(struct map_data *m, char *buffer, char *decode_buffer)
  2885. {
  2886. int i;
  2887. struct map_cache_main_header *header = (struct map_cache_main_header *)buffer;
  2888. struct map_cache_map_info *info = NULL;
  2889. char *p = buffer + sizeof(struct map_cache_main_header);
  2890. for(i = 0; i < header->map_count; i++) {
  2891. info = (struct map_cache_map_info *)p;
  2892. if( strcmp(m->name, info->name) == 0 )
  2893. break; // Map found
  2894. // Jump to next entry..
  2895. p += sizeof(struct map_cache_map_info) + info->len;
  2896. }
  2897. if( info && i < header->map_count ) {
  2898. unsigned long size, xy;
  2899. if( info->xs <= 0 || info->ys <= 0 )
  2900. return 0;// Invalid
  2901. m->xs = info->xs;
  2902. m->ys = info->ys;
  2903. size = (unsigned long)info->xs*(unsigned long)info->ys;
  2904. if(size > MAX_MAP_SIZE) {
  2905. ShowWarning("map_readfromcache: %s exceeded MAX_MAP_SIZE of %d\n", info->name, MAX_MAP_SIZE);
  2906. return 0; // Say not found to remove it from list.. [Shinryo]
  2907. }
  2908. // TO-DO: Maybe handle the scenario, if the decoded buffer isn't the same size as expected? [Shinryo]
  2909. decode_zip(decode_buffer, &size, p+sizeof(struct map_cache_map_info), info->len);
  2910. CREATE(m->cell, struct mapcell, size);
  2911. for( xy = 0; xy < size; ++xy )
  2912. m->cell[xy] = map_gat2cell(decode_buffer[xy]);
  2913. return 1;
  2914. }
  2915. return 0; // Not found
  2916. }
  2917. int map_addmap(char* mapname)
  2918. {
  2919. if( strcmpi(mapname,"clear")==0 )
  2920. {
  2921. map_num = 0;
  2922. instance_start = 0;
  2923. return 0;
  2924. }
  2925. if( map_num >= MAX_MAP_PER_SERVER - 1 )
  2926. {
  2927. ShowError("Could not add map '" CL_WHITE "%s" CL_RESET "', the limit of maps has been reached.\n",mapname);
  2928. return 1;
  2929. }
  2930. mapindex_getmapname(mapname, map[map_num].name);
  2931. map_num++;
  2932. return 0;
  2933. }
  2934. static void map_delmapid(int id)
  2935. {
  2936. ShowNotice("Removing map [ %s ] from maplist" CL_CLL "\n",map[id].name);
  2937. memmove(map+id, map+id+1, sizeof(map[0])*(map_num-id-1));
  2938. map_num--;
  2939. }
  2940. int map_delmap(char* mapname)
  2941. {
  2942. int i;
  2943. char map_name[MAP_NAME_LENGTH];
  2944. if (strcmpi(mapname, "all") == 0) {
  2945. map_num = 0;
  2946. return 0;
  2947. }
  2948. mapindex_getmapname(mapname, map_name);
  2949. for(i = 0; i < map_num; i++) {
  2950. if (strcmp(map[i].name, map_name) == 0) {
  2951. map_delmapid(i);
  2952. return 1;
  2953. }
  2954. }
  2955. return 0;
  2956. }
  2957. /// Initializes map flags and adjusts them depending on configuration.
  2958. void map_flags_init(void)
  2959. {
  2960. int i;
  2961. for( i = 0; i < map_num; i++ )
  2962. {
  2963. // mapflags
  2964. memset(&map[i].flag, 0, sizeof(map[i].flag));
  2965. // additional mapflag data
  2966. map[i].zone = 0; // restricted mapflag zone
  2967. map[i].nocommand = 0; // nocommand mapflag level
  2968. map[i].adjust.bexp = 100; // per map base exp multiplicator
  2969. map[i].adjust.jexp = 100; // per map job exp multiplicator
  2970. memset(map[i].drop_list, 0, sizeof(map[i].drop_list)); // pvp nightmare drop list
  2971. // skill damage
  2972. #ifdef ADJUST_SKILL_DAMAGE
  2973. memset(&map[i].adjust.damage, 0, sizeof(map[i].adjust.damage));
  2974. if (map[i].skill_damage.count)
  2975. map_skill_damage_free(&map[i]);
  2976. #endif
  2977. // adjustments
  2978. if( battle_config.pk_mode )
  2979. map[i].flag.pvp = 1; // make all maps pvp for pk_mode [Valaris]
  2980. map_free_questinfo(i);
  2981. }
  2982. }
  2983. #define NO_WATER 1000000
  2984. /*
  2985. * Reads from the .rsw for each map
  2986. * Returns water height (or NO_WATER if file doesn't exist) or other error is encountered.
  2987. * Assumed path for file is data/mapname.rsw
  2988. * Credits to LittleWolf
  2989. */
  2990. int map_waterheight(char* mapname)
  2991. {
  2992. char fn[256];
  2993. char *rsw, *found;
  2994. //Look up for the rsw
  2995. sprintf(fn, "data\\%s.rsw", mapname);
  2996. found = grfio_find_file(fn);
  2997. if (found) strcpy(fn, found); // replace with real name
  2998. // read & convert fn
  2999. rsw = (char *) grfio_read (fn);
  3000. if (rsw)
  3001. { //Load water height from file
  3002. int wh = (int) *(float*)(rsw+166); //FIXME Casting between integer* and float* which have an incompatible binary data representation.
  3003. aFree(rsw);
  3004. return wh;
  3005. }
  3006. ShowWarning("Failed to find water level for (%s)\n", mapname, fn);
  3007. return NO_WATER;
  3008. }
  3009. /*==================================
  3010. * .GAT format
  3011. *----------------------------------*/
  3012. int map_readgat (struct map_data* m)
  3013. {
  3014. char filename[256];
  3015. uint8* gat;
  3016. int water_height;
  3017. size_t xy, off, num_cells;
  3018. sprintf(filename, "data\\%s.gat", m->name);
  3019. gat = (uint8 *) grfio_read(filename);
  3020. if (gat == NULL)
  3021. return 0;
  3022. m->xs = *(int32*)(gat+6);
  3023. m->ys = *(int32*)(gat+10);
  3024. num_cells = m->xs * m->ys;
  3025. CREATE(m->cell, struct mapcell, num_cells);
  3026. water_height = map_waterheight(m->name);
  3027. // Set cell properties
  3028. off = 14;
  3029. for( xy = 0; xy < num_cells; ++xy )
  3030. {
  3031. // read cell data
  3032. float height = *(float*)( gat + off );
  3033. uint32 type = *(uint32*)( gat + off + 16 );
  3034. off += 20;
  3035. if( type == 0 && water_height != NO_WATER && height > water_height )
  3036. type = 3; // Cell is 0 (walkable) but under water level, set to 3 (walkable water)
  3037. m->cell[xy] = map_gat2cell(type);
  3038. }
  3039. aFree(gat);
  3040. return 1;
  3041. }
  3042. /*======================================
  3043. * Add/Remove map to the map_db
  3044. *--------------------------------------*/
  3045. void map_addmap2db(struct map_data *m)
  3046. {
  3047. uidb_put(map_db, (unsigned int)m->index, m);
  3048. }
  3049. void map_removemapdb(struct map_data *m)
  3050. {
  3051. uidb_remove(map_db, (unsigned int)m->index);
  3052. }
  3053. /*======================================
  3054. * Initiate maps loading stage
  3055. *--------------------------------------*/
  3056. int map_readallmaps (void)
  3057. {
  3058. int i;
  3059. FILE* fp=NULL;
  3060. int maps_removed = 0;
  3061. // Has the uncompressed gat data of all maps, so just one allocation has to be made
  3062. char *map_cache_buffer[2] = {
  3063. NULL,
  3064. NULL
  3065. };
  3066. char map_cache_decode_buffer[MAX_MAP_SIZE];
  3067. if( enable_grf )
  3068. ShowStatus("Loading maps (using GRF files)...\n");
  3069. else {
  3070. const char* mapcachefilepath[] = {
  3071. "db/" DBPATH "map_cache.dat",
  3072. "db/import/map_cache.dat"
  3073. };
  3074. for( i = 0; i < 2; i++ ){
  3075. ShowStatus( "Loading maps (using %s as map cache)...\n", mapcachefilepath[i] );
  3076. if( ( fp = fopen(mapcachefilepath[i], "rb") ) == NULL ){
  3077. if( i == 0 ){
  3078. ShowFatalError( "Unable to open map cache file " CL_WHITE "%s" CL_RESET "\n", mapcachefilepath[i] );
  3079. exit(EXIT_FAILURE); //No use launching server if maps can't be read.
  3080. }else{
  3081. ShowWarning( "Unable to open map cache file " CL_WHITE "%s" CL_RESET "\n", mapcachefilepath[i] );
  3082. break;
  3083. }
  3084. }
  3085. // Init mapcache data. [Shinryo]
  3086. map_cache_buffer[i] = map_init_mapcache(fp);
  3087. if( !map_cache_buffer[i] ) {
  3088. ShowFatalError( "Failed to initialize mapcache data (%s)..\n", mapcachefilepath );
  3089. exit(EXIT_FAILURE);
  3090. }
  3091. fclose(fp);
  3092. }
  3093. }
  3094. for(i = 0; i < map_num; i++) {
  3095. size_t size;
  3096. bool success = false;
  3097. unsigned short idx = 0;
  3098. if( enable_grf ){
  3099. // show progress
  3100. ShowStatus("Loading maps [%i/%i]: %s" CL_CLL "\r", i, map_num, map[i].name);
  3101. // try to load the map
  3102. success = map_readgat(&map[i]) != 0;
  3103. }else{
  3104. // try to load the map
  3105. // Read from import first, in case of override
  3106. if( map_cache_buffer[1] != NULL ){
  3107. success = map_readfromcache( &map[i], map_cache_buffer[1], map_cache_decode_buffer ) != 0;
  3108. }
  3109. // Nothing was found in import - try to find it in the main file
  3110. if( !success ){
  3111. success = map_readfromcache( &map[i], map_cache_buffer[0], map_cache_decode_buffer ) != 0;
  3112. }
  3113. }
  3114. // The map was not found - remove it
  3115. if( !(idx = mapindex_name2id(map[i].name)) || !success ){
  3116. map_delmapid(i);
  3117. maps_removed++;
  3118. i--;
  3119. continue;
  3120. }
  3121. map[i].index = idx;
  3122. if (uidb_get(map_db,(unsigned int)map[i].index) != NULL)
  3123. {
  3124. ShowWarning("Map %s already loaded!" CL_CLL "\n", map[i].name);
  3125. if (map[i].cell) {
  3126. aFree(map[i].cell);
  3127. map[i].cell = NULL;
  3128. }
  3129. map_delmapid(i);
  3130. maps_removed++;
  3131. i--;
  3132. continue;
  3133. }
  3134. map_addmap2db(&map[i]);
  3135. map[i].m = i;
  3136. memset(map[i].moblist, 0, sizeof(map[i].moblist)); //Initialize moblist [Skotlex]
  3137. map[i].mob_delete_timer = INVALID_TIMER; //Initialize timer [Skotlex]
  3138. map[i].bxs = (map[i].xs + BLOCK_SIZE - 1) / BLOCK_SIZE;
  3139. map[i].bys = (map[i].ys + BLOCK_SIZE - 1) / BLOCK_SIZE;
  3140. size = map[i].bxs * map[i].bys * sizeof(struct block_list*);
  3141. map[i].block = (struct block_list**)aCalloc(size, 1);
  3142. map[i].block_mob = (struct block_list**)aCalloc(size, 1);
  3143. }
  3144. // intialization and configuration-dependent adjustments of mapflags
  3145. map_flags_init();
  3146. if( !enable_grf ) {
  3147. // The cache isn't needed anymore, so free it. [Shinryo]
  3148. if( map_cache_buffer[1] != NULL ){
  3149. aFree(map_cache_buffer[1]);
  3150. }
  3151. aFree(map_cache_buffer[0]);
  3152. }
  3153. // finished map loading
  3154. ShowInfo("Successfully loaded '" CL_WHITE "%d" CL_RESET "' maps." CL_CLL "\n",map_num);
  3155. instance_start = map_num; // Next Map Index will be instances
  3156. if (maps_removed)
  3157. ShowNotice("Maps removed: '" CL_WHITE "%d" CL_RESET "'\n",maps_removed);
  3158. return 0;
  3159. }
  3160. ////////////////////////////////////////////////////////////////////////
  3161. static int map_ip_set = 0;
  3162. static int char_ip_set = 0;
  3163. /*==========================================
  3164. * Console Command Parser [Wizputer]
  3165. *------------------------------------------*/
  3166. int parse_console(const char* buf){
  3167. char type[64];
  3168. char command[64];
  3169. char mapname[64];
  3170. int16 x = 0;
  3171. int16 y = 0;
  3172. int n;
  3173. struct map_session_data sd;
  3174. memset(&sd, 0, sizeof(struct map_session_data));
  3175. strcpy(sd.status.name, "console");
  3176. if( ( n = sscanf(buf, "%63[^:]:%63[^:]:%63s %6hd %6hd[^\n]", type, command, mapname, &x, &y) ) < 5 ){
  3177. if( ( n = sscanf(buf, "%63[^:]:%63[^\n]", type, command) ) < 2 ) {
  3178. if((n = sscanf(buf, "%63[^\n]", type))<1) return -1; //nothing to do no arg
  3179. }
  3180. }
  3181. if( n != 5 ){ //end string and display
  3182. if( n < 2 ) {
  3183. ShowNotice("Type of command: '%s'\n", type);
  3184. command[0] = '\0';
  3185. mapname[0] = '\0';
  3186. }
  3187. else {
  3188. ShowNotice("Type of command: '%s' || Command: '%s'\n", type, command);
  3189. mapname[0] = '\0';
  3190. }
  3191. }
  3192. else
  3193. ShowNotice("Type of command: '%s' || Command: '%s' || Map: '%s' Coords: %d %d\n", type, command, mapname, x, y);
  3194. if(strcmpi("admin",type) == 0 ) {
  3195. if(strcmpi("map",command) == 0){
  3196. int16 m = map_mapname2mapid(mapname);
  3197. if( m < 0 ){
  3198. ShowWarning("Console: Unknown map.\n");
  3199. return 0;
  3200. }
  3201. sd.bl.m = m;
  3202. map_search_freecell(&sd.bl, m, &sd.bl.x, &sd.bl.y, -1, -1, 0);
  3203. if( x > 0 )
  3204. sd.bl.x = x;
  3205. if( y > 0 )
  3206. sd.bl.y = y;
  3207. ShowNotice("Now at: '%s' Coords: %d %d\n", mapname, x, y);
  3208. }
  3209. else if( !is_atcommand(sd.fd, &sd, command, 2) )
  3210. ShowInfo("Console: Invalid atcommand.\n");
  3211. }
  3212. else if( n == 2 && strcmpi("server", type) == 0 ){
  3213. if( strcmpi("shutdown", command) == 0 || strcmpi("exit", command) == 0 || strcmpi("quit", command) == 0 ){
  3214. runflag = 0;
  3215. }
  3216. }
  3217. else if( strcmpi("ers_report", type) == 0 ){
  3218. ers_report();
  3219. }
  3220. else if( strcmpi("help", type) == 0 ) {
  3221. ShowInfo("Available commands:\n");
  3222. ShowInfo("\t admin:@<atcommand> => Uses an atcommand. Do NOT use commands requiring an attached player.\n");
  3223. ShowInfo("\t admin:map:<map> <x> <y> => Changes the map from which console commands are executed.\n");
  3224. ShowInfo("\t server:shutdown => Stops the server.\n");
  3225. ShowInfo("\t ers_report => Displays database usage.\n");
  3226. }
  3227. return 0;
  3228. }
  3229. /*==========================================
  3230. * Read map server configuration files (conf/map_athena.conf...)
  3231. *------------------------------------------*/
  3232. int map_config_read(const char *cfgName)
  3233. {
  3234. char line[1024], w1[32], w2[1024];
  3235. FILE *fp;
  3236. fp = fopen(cfgName,"r");
  3237. if( fp == NULL )
  3238. {
  3239. ShowError("Map configuration file not found at: %s\n", cfgName);
  3240. return 1;
  3241. }
  3242. while( fgets(line, sizeof(line), fp) )
  3243. {
  3244. char* ptr;
  3245. if( line[0] == '/' && line[1] == '/' )
  3246. continue;
  3247. if( (ptr = strstr(line, "//")) != NULL )
  3248. *ptr = '\n'; //Strip comments
  3249. if( sscanf(line, "%31[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3250. continue;
  3251. //Strip trailing spaces
  3252. ptr = w2 + strlen(w2);
  3253. while (--ptr >= w2 && *ptr == ' ');
  3254. ptr++;
  3255. *ptr = '\0';
  3256. if(strcmpi(w1,"timestamp_format")==0)
  3257. safestrncpy(timestamp_format, w2, 20);
  3258. else if(strcmpi(w1,"stdout_with_ansisequence")==0)
  3259. stdout_with_ansisequence = config_switch(w2);
  3260. else if(strcmpi(w1,"console_silent")==0) {
  3261. msg_silent = atoi(w2);
  3262. if( msg_silent ) // only bother if its actually enabled
  3263. ShowInfo("Console Silent Setting: %d\n", atoi(w2));
  3264. } else if (strcmpi(w1, "userid")==0)
  3265. chrif_setuserid(w2);
  3266. else if (strcmpi(w1, "passwd") == 0)
  3267. chrif_setpasswd(w2);
  3268. else if (strcmpi(w1, "char_ip") == 0)
  3269. char_ip_set = chrif_setip(w2);
  3270. else if (strcmpi(w1, "char_port") == 0)
  3271. chrif_setport(atoi(w2));
  3272. else if (strcmpi(w1, "map_ip") == 0)
  3273. map_ip_set = clif_setip(w2);
  3274. else if (strcmpi(w1, "bind_ip") == 0)
  3275. clif_setbindip(w2);
  3276. else if (strcmpi(w1, "map_port") == 0) {
  3277. clif_setport(atoi(w2));
  3278. map_port = (atoi(w2));
  3279. } else if (strcmpi(w1, "map") == 0)
  3280. map_addmap(w2);
  3281. else if (strcmpi(w1, "delmap") == 0)
  3282. map_delmap(w2);
  3283. else if (strcmpi(w1, "npc") == 0)
  3284. npc_addsrcfile(w2, false);
  3285. else if (strcmpi(w1, "delnpc") == 0)
  3286. npc_delsrcfile(w2);
  3287. else if (strcmpi(w1, "autosave_time") == 0) {
  3288. autosave_interval = atoi(w2);
  3289. if (autosave_interval < 1) //Revert to default saving.
  3290. autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  3291. else
  3292. autosave_interval *= 1000; //Pass from sec to ms
  3293. } else if (strcmpi(w1, "minsave_time") == 0) {
  3294. minsave_interval= atoi(w2);
  3295. if (minsave_interval < 1)
  3296. minsave_interval = 1;
  3297. } else if (strcmpi(w1, "save_settings") == 0)
  3298. save_settings = cap_value(atoi(w2),CHARSAVE_NONE,CHARSAVE_ALL);
  3299. else if (strcmpi(w1, "motd_txt") == 0)
  3300. strcpy(motd_txt, w2);
  3301. else if (strcmpi(w1, "help_txt") == 0)
  3302. strcpy(help_txt, w2);
  3303. else if (strcmpi(w1, "help2_txt") == 0)
  3304. strcpy(help2_txt, w2);
  3305. else if (strcmpi(w1, "charhelp_txt") == 0)
  3306. strcpy(charhelp_txt, w2);
  3307. else if (strcmpi(w1, "channel_conf") == 0)
  3308. safestrncpy(channel_conf, w2, sizeof(channel_conf));
  3309. else if(strcmpi(w1,"db_path") == 0)
  3310. safestrncpy(db_path,w2,ARRAYLENGTH(db_path));
  3311. else if (strcmpi(w1, "console") == 0) {
  3312. console = config_switch(w2);
  3313. if (console)
  3314. ShowNotice("Console Commands are enabled.\n");
  3315. } else if (strcmpi(w1, "enable_spy") == 0)
  3316. enable_spy = config_switch(w2);
  3317. else if (strcmpi(w1, "use_grf") == 0)
  3318. enable_grf = config_switch(w2);
  3319. else if (strcmpi(w1, "console_msg_log") == 0)
  3320. console_msg_log = atoi(w2);//[Ind]
  3321. else if (strcmpi(w1, "console_log_filepath") == 0)
  3322. safestrncpy(console_log_filepath, w2, sizeof(console_log_filepath));
  3323. else if (strcmpi(w1, "import") == 0)
  3324. map_config_read(w2);
  3325. else
  3326. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3327. }
  3328. fclose(fp);
  3329. return 0;
  3330. }
  3331. void map_reloadnpc_sub(const char *cfgName)
  3332. {
  3333. char line[1024], w1[1024], w2[1024];
  3334. FILE *fp;
  3335. fp = fopen(cfgName,"r");
  3336. if( fp == NULL )
  3337. {
  3338. ShowError("Map configuration file not found at: %s\n", cfgName);
  3339. return;
  3340. }
  3341. while( fgets(line, sizeof(line), fp) )
  3342. {
  3343. char* ptr;
  3344. if( line[0] == '/' && line[1] == '/' )
  3345. continue;
  3346. if( (ptr = strstr(line, "//")) != NULL )
  3347. *ptr = '\n'; //Strip comments
  3348. if( sscanf(line, "%1023[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3349. continue;
  3350. //Strip trailing spaces
  3351. ptr = w2 + strlen(w2);
  3352. while (--ptr >= w2 && *ptr == ' ');
  3353. ptr++;
  3354. *ptr = '\0';
  3355. if (strcmpi(w1, "npc") == 0)
  3356. npc_addsrcfile(w2, false);
  3357. else if (strcmpi(w1, "delnpc") == 0)
  3358. npc_delsrcfile(w2);
  3359. else if (strcmpi(w1, "import") == 0)
  3360. map_reloadnpc_sub(w2);
  3361. else
  3362. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3363. }
  3364. fclose(fp);
  3365. }
  3366. void map_reloadnpc(bool clear)
  3367. {
  3368. if (clear)
  3369. npc_addsrcfile("clear", false); // this will clear the current script list
  3370. #ifdef RENEWAL
  3371. map_reloadnpc_sub("npc/re/scripts_main.conf");
  3372. #else
  3373. map_reloadnpc_sub("npc/pre-re/scripts_main.conf");
  3374. #endif
  3375. }
  3376. int inter_config_read(const char *cfgName)
  3377. {
  3378. char line[1024],w1[1024],w2[1024];
  3379. FILE *fp;
  3380. fp=fopen(cfgName,"r");
  3381. if(fp==NULL){
  3382. ShowError("File not found: %s\n",cfgName);
  3383. return 1;
  3384. }
  3385. while(fgets(line, sizeof(line), fp))
  3386. {
  3387. if(line[0] == '/' && line[1] == '/')
  3388. continue;
  3389. if( sscanf(line,"%1023[^:]: %1023[^\r\n]",w1,w2) < 2 )
  3390. continue;
  3391. #define RENEWALPREFIX "renewal-"
  3392. if (!strncmpi(w1, RENEWALPREFIX, strlen(RENEWALPREFIX))) {
  3393. #ifdef RENEWAL
  3394. // Move the original name to the beginning of the string
  3395. memmove(w1, w1 + strlen(RENEWALPREFIX), strlen(w1) - strlen(RENEWALPREFIX) + 1);
  3396. #else
  3397. // In Pre-Renewal the Renewal specific configurations can safely be ignored
  3398. continue;
  3399. #endif
  3400. }
  3401. #undef RENEWALPREFIX
  3402. if( strcmpi( w1, "buyingstore_db" ) == 0 )
  3403. strcpy( buyingstores_table, w2 );
  3404. else if( strcmpi( w1, "buyingstore_items_table" ) == 0 )
  3405. strcpy( buyingstore_items_table, w2 );
  3406. else if(strcmpi(w1,"item_table")==0)
  3407. strcpy(item_table,w2);
  3408. else if(strcmpi(w1,"item2_table")==0)
  3409. strcpy(item2_table,w2);
  3410. else if(strcmpi(w1,"mob_table")==0)
  3411. strcpy(mob_table,w2);
  3412. else if(strcmpi(w1,"mob2_table")==0)
  3413. strcpy(mob2_table,w2);
  3414. else if(strcmpi(w1,"mob_skill_table")==0)
  3415. strcpy(mob_skill_table,w2);
  3416. else if(strcmpi(w1,"mob_skill2_table")==0)
  3417. strcpy(mob_skill2_table,w2);
  3418. else if( strcmpi( w1, "item_cash_table" ) == 0 )
  3419. strcpy( item_cash_table, w2 );
  3420. else if( strcmpi( w1, "item_cash2_table" ) == 0 )
  3421. strcpy( item_cash2_table, w2 );
  3422. else if( strcmpi( w1, "vending_db" ) == 0 )
  3423. strcpy( vendings_table, w2 );
  3424. else if( strcmpi( w1, "vending_items_table" ) == 0 )
  3425. strcpy(vending_items_table, w2);
  3426. else if( strcmpi(w1, "roulette_table") == 0)
  3427. strcpy(roulette_table, w2);
  3428. else if (strcmpi(w1, "market_table") == 0)
  3429. strcpy(market_table, w2);
  3430. else if (strcmpi(w1, "sales_table") == 0)
  3431. strcpy(sales_table, w2);
  3432. else
  3433. //Map Server SQL DB
  3434. if(strcmpi(w1,"map_server_ip")==0)
  3435. strcpy(map_server_ip, w2);
  3436. else
  3437. if(strcmpi(w1,"map_server_port")==0)
  3438. map_server_port=atoi(w2);
  3439. else
  3440. if(strcmpi(w1,"map_server_id")==0)
  3441. strcpy(map_server_id, w2);
  3442. else
  3443. if(strcmpi(w1,"map_server_pw")==0)
  3444. strcpy(map_server_pw, w2);
  3445. else
  3446. if(strcmpi(w1,"map_server_db")==0)
  3447. strcpy(map_server_db, w2);
  3448. else
  3449. if(strcmpi(w1,"default_codepage")==0)
  3450. strcpy(default_codepage, w2);
  3451. else
  3452. if(strcmpi(w1,"use_sql_db")==0) {
  3453. db_use_sqldbs = config_switch(w2);
  3454. ShowStatus ("Using SQL dbs: %s\n",w2);
  3455. } else
  3456. if(strcmpi(w1,"log_db_ip")==0)
  3457. strcpy(log_db_ip, w2);
  3458. else
  3459. if(strcmpi(w1,"log_db_id")==0)
  3460. strcpy(log_db_id, w2);
  3461. else
  3462. if(strcmpi(w1,"log_db_pw")==0)
  3463. strcpy(log_db_pw, w2);
  3464. else
  3465. if(strcmpi(w1,"log_db_port")==0)
  3466. log_db_port = atoi(w2);
  3467. else
  3468. if(strcmpi(w1,"log_db_db")==0)
  3469. strcpy(log_db_db, w2);
  3470. else
  3471. if( mapreg_config_read(w1,w2) )
  3472. continue;
  3473. //support the import command, just like any other config
  3474. else
  3475. if(strcmpi(w1,"import")==0)
  3476. inter_config_read(w2);
  3477. }
  3478. fclose(fp);
  3479. return 0;
  3480. }
  3481. /*=======================================
  3482. * MySQL Init
  3483. *---------------------------------------*/
  3484. int map_sql_init(void)
  3485. {
  3486. // main db connection
  3487. mmysql_handle = Sql_Malloc();
  3488. qsmysql_handle = Sql_Malloc();
  3489. ShowInfo("Connecting to the Map DB Server....\n");
  3490. if( SQL_ERROR == Sql_Connect(mmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) ||
  3491. SQL_ERROR == Sql_Connect(qsmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) )
  3492. {
  3493. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3494. map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db);
  3495. Sql_ShowDebug(mmysql_handle);
  3496. Sql_Free(mmysql_handle);
  3497. Sql_ShowDebug(qsmysql_handle);
  3498. Sql_Free(qsmysql_handle);
  3499. exit(EXIT_FAILURE);
  3500. }
  3501. ShowStatus("Connect success! (Map Server Connection)\n");
  3502. if( strlen(default_codepage) > 0 ) {
  3503. if ( SQL_ERROR == Sql_SetEncoding(mmysql_handle, default_codepage) )
  3504. Sql_ShowDebug(mmysql_handle);
  3505. if ( SQL_ERROR == Sql_SetEncoding(qsmysql_handle, default_codepage) )
  3506. Sql_ShowDebug(qsmysql_handle);
  3507. }
  3508. return 0;
  3509. }
  3510. int map_sql_close(void)
  3511. {
  3512. ShowStatus("Close Map DB Connection....\n");
  3513. Sql_Free(mmysql_handle);
  3514. Sql_Free(qsmysql_handle);
  3515. mmysql_handle = NULL;
  3516. qsmysql_handle = NULL;
  3517. #ifndef BETA_THREAD_TEST
  3518. if (log_config.sql_logs)
  3519. {
  3520. ShowStatus("Close Log DB Connection....\n");
  3521. Sql_Free(logmysql_handle);
  3522. logmysql_handle = NULL;
  3523. }
  3524. #endif
  3525. return 0;
  3526. }
  3527. int log_sql_init(void)
  3528. {
  3529. #ifndef BETA_THREAD_TEST
  3530. // log db connection
  3531. logmysql_handle = Sql_Malloc();
  3532. ShowInfo("" CL_WHITE "[SQL]" CL_RESET ": Connecting to the Log Database " CL_WHITE "%s" CL_RESET " At " CL_WHITE "%s" CL_RESET "...\n",log_db_db,log_db_ip);
  3533. if ( SQL_ERROR == Sql_Connect(logmysql_handle, log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db) ){
  3534. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3535. log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db);
  3536. Sql_ShowDebug(logmysql_handle);
  3537. Sql_Free(logmysql_handle);
  3538. exit(EXIT_FAILURE);
  3539. }
  3540. ShowStatus("" CL_WHITE "[SQL]" CL_RESET ": Successfully '" CL_GREEN "connected" CL_RESET "' to Database '" CL_WHITE "%s" CL_RESET "'.\n", log_db_db);
  3541. if( strlen(default_codepage) > 0 )
  3542. if ( SQL_ERROR == Sql_SetEncoding(logmysql_handle, default_codepage) )
  3543. Sql_ShowDebug(logmysql_handle);
  3544. #endif
  3545. return 0;
  3546. }
  3547. struct questinfo *map_add_questinfo(int m, struct questinfo *qi) {
  3548. unsigned short i;
  3549. /* duplicate, override */
  3550. for(i = 0; i < map[m].qi_count; i++) {
  3551. if( &map[m].qi_data[i] && map[m].qi_data[i].nd == qi->nd && map[m].qi_data[i].quest_id == qi->quest_id)
  3552. break;
  3553. }
  3554. if( i == map[m].qi_count )
  3555. RECREATE(map[m].qi_data, struct questinfo, ++map[m].qi_count);
  3556. else { // clear previous criteria on override
  3557. if (map[m].qi_data[i].jobid)
  3558. aFree(map[m].qi_data[i].jobid);
  3559. map[m].qi_data[i].jobid = NULL;
  3560. map[m].qi_data[i].jobid_count = 0;
  3561. if (map[m].qi_data[i].req)
  3562. aFree(map[m].qi_data[i].req);
  3563. map[m].qi_data[i].req = NULL;
  3564. map[m].qi_data[i].req_count = 0;
  3565. }
  3566. memcpy(&map[m].qi_data[i], qi, sizeof(struct questinfo));
  3567. return &map[m].qi_data[i];
  3568. }
  3569. bool map_remove_questinfo(int m, struct npc_data *nd) {
  3570. unsigned short i, c;
  3571. for(i = 0; i < map[m].qi_count; i++) {
  3572. struct questinfo *qi = &map[m].qi_data[i];
  3573. if( qi->nd == nd ) {
  3574. if (qi->jobid)
  3575. aFree(qi->jobid);
  3576. qi->jobid = NULL;
  3577. qi->jobid_count = 0;
  3578. if (qi->req)
  3579. aFree(qi->req);
  3580. qi->req = NULL;
  3581. qi->req_count = 0;
  3582. memset(&map[m].qi_data[i], 0, sizeof(map[m].qi_data[i]));
  3583. }
  3584. }
  3585. // Move next data to empty slot
  3586. for(i = 0, c = 0; i < map[m].qi_count; i++) {
  3587. struct questinfo *qi = &map[m].qi_data[i];
  3588. if (!qi || !qi->nd)
  3589. continue;
  3590. if (i != c) {
  3591. map[m].qi_data[c] = map[m].qi_data[i];
  3592. memset(&map[m].qi_data[i], 0, sizeof(map[m].qi_data[i]));
  3593. }
  3594. c++;
  3595. }
  3596. if (!(map[m].qi_count = c)) {
  3597. aFree(map[m].qi_data);
  3598. map[m].qi_data = NULL;
  3599. }
  3600. else
  3601. RECREATE(map[m].qi_data, struct questinfo, map[m].qi_count);
  3602. return true;
  3603. }
  3604. static void map_free_questinfo(int m) {
  3605. unsigned short i;
  3606. for(i = 0; i < map[m].qi_count; i++) {
  3607. if (map[m].qi_data[i].jobid)
  3608. aFree(map[m].qi_data[i].jobid);
  3609. map[m].qi_data[i].jobid = NULL;
  3610. map[m].qi_data[i].jobid_count = 0;
  3611. if (map[m].qi_data[i].req)
  3612. aFree(map[m].qi_data[i].req);
  3613. map[m].qi_data[i].req = NULL;
  3614. map[m].qi_data[i].req_count = 0;
  3615. }
  3616. aFree(map[m].qi_data);
  3617. map[m].qi_data = NULL;
  3618. map[m].qi_count = 0;
  3619. }
  3620. struct questinfo *map_has_questinfo(int m, struct npc_data *nd, int quest_id) {
  3621. unsigned short i;
  3622. for (i = 0; i < map[m].qi_count; i++) {
  3623. struct questinfo *qi = &map[m].qi_data[i];
  3624. if (qi->nd == nd && qi->quest_id == quest_id) {
  3625. return qi;
  3626. }
  3627. }
  3628. return NULL;
  3629. }
  3630. /**
  3631. * @see DBApply
  3632. */
  3633. int map_db_final(DBKey key, DBData *data, va_list ap)
  3634. {
  3635. struct map_data_other_server *mdos = (struct map_data_other_server *)db_data2ptr(data);
  3636. if(mdos && mdos->cell == NULL)
  3637. aFree(mdos);
  3638. return 0;
  3639. }
  3640. /**
  3641. * @see DBApply
  3642. */
  3643. int nick_db_final(DBKey key, DBData *data, va_list args)
  3644. {
  3645. struct charid2nick* p = (struct charid2nick*)db_data2ptr(data);
  3646. struct charid_request* req;
  3647. if( p == NULL )
  3648. return 0;
  3649. while( p->requests )
  3650. {
  3651. req = p->requests;
  3652. p->requests = req->next;
  3653. aFree(req);
  3654. }
  3655. aFree(p);
  3656. return 0;
  3657. }
  3658. int cleanup_sub(struct block_list *bl, va_list ap)
  3659. {
  3660. nullpo_ret(bl);
  3661. switch(bl->type) {
  3662. case BL_PC:
  3663. map_quit((struct map_session_data *) bl);
  3664. break;
  3665. case BL_NPC:
  3666. npc_unload((struct npc_data *)bl,false);
  3667. break;
  3668. case BL_MOB:
  3669. unit_free(bl,CLR_OUTSIGHT);
  3670. break;
  3671. case BL_PET:
  3672. //There is no need for this, the pet is removed together with the player. [Skotlex]
  3673. break;
  3674. case BL_ITEM:
  3675. map_clearflooritem(bl);
  3676. break;
  3677. case BL_SKILL:
  3678. skill_delunit((struct skill_unit *) bl);
  3679. break;
  3680. }
  3681. return 1;
  3682. }
  3683. #ifdef ADJUST_SKILL_DAMAGE
  3684. /**
  3685. * Free all skill damage entries for a map
  3686. * @param m Map data
  3687. **/
  3688. void map_skill_damage_free(struct map_data *m) {
  3689. uint8 i;
  3690. for (i = 0; i < m->skill_damage.count; i++) {
  3691. ers_free(map_skill_damage_ers, m->skill_damage.entries[i]);
  3692. m->skill_damage.entries[i] = NULL;
  3693. }
  3694. aFree(m->skill_damage.entries);
  3695. m->skill_damage.entries = NULL;
  3696. m->skill_damage.count = 0;
  3697. }
  3698. /**
  3699. * Add new skill damage adjustment entry for a map
  3700. * @param m Map data
  3701. * @param skill_id Skill
  3702. * @param pc Rate to PC
  3703. * @param mobs Rate to Monster
  3704. * @param boss Rate to Boss-monster
  3705. * @param other Rate to Other target
  3706. * @param caster Caster type
  3707. **/
  3708. void map_skill_damage_add(struct map_data *m, uint16 skill_id, int pc, int mob, int boss, int other, uint8 caster) {
  3709. struct s_skill_damage *entry;
  3710. int i = 0;
  3711. if (m->skill_damage.count >= UINT8_MAX)
  3712. return;
  3713. for (i = 0; i < m->skill_damage.count; i++) {
  3714. if (m->skill_damage.entries[i]->skill_id == skill_id) {
  3715. m->skill_damage.entries[i]->pc = pc;
  3716. m->skill_damage.entries[i]->mob = mob;
  3717. m->skill_damage.entries[i]->boss = boss;
  3718. m->skill_damage.entries[i]->other = other;
  3719. m->skill_damage.entries[i]->caster = caster;
  3720. return;
  3721. }
  3722. }
  3723. entry = ers_alloc(map_skill_damage_ers, struct s_skill_damage);
  3724. entry->skill_id = skill_id;
  3725. entry->pc = pc;
  3726. entry->mob = mob;
  3727. entry->boss = boss;
  3728. entry->other = other;
  3729. entry->caster = caster;
  3730. RECREATE(m->skill_damage.entries, struct s_skill_damage *, m->skill_damage.count+1);
  3731. m->skill_damage.entries[m->skill_damage.count++] = entry;
  3732. }
  3733. #endif
  3734. /**
  3735. * @see DBApply
  3736. */
  3737. static int cleanup_db_sub(DBKey key, DBData *data, va_list va)
  3738. {
  3739. return cleanup_sub((struct block_list *)db_data2ptr(data), va);
  3740. }
  3741. /*==========================================
  3742. * map destructor
  3743. *------------------------------------------*/
  3744. void do_final(void)
  3745. {
  3746. int i, j;
  3747. struct map_session_data* sd;
  3748. struct s_mapiterator* iter;
  3749. ShowStatus("Terminating...\n");
  3750. channel_config.closing = true;
  3751. //Ladies and babies first.
  3752. iter = mapit_getallusers();
  3753. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3754. map_quit(sd);
  3755. mapit_free(iter);
  3756. /* prepares npcs for a faster shutdown process */
  3757. do_clear_npc();
  3758. // remove all objects on maps
  3759. for (i = 0; i < map_num; i++) {
  3760. ShowStatus("Cleaning up maps [%d/%d]: %s..." CL_CLL "\r", i+1, map_num, map[i].name);
  3761. if (map[i].m >= 0) {
  3762. map_foreachinmap(cleanup_sub, i, BL_ALL);
  3763. channel_delete(map[i].channel,false);
  3764. }
  3765. }
  3766. ShowStatus("Cleaned up %d maps." CL_CLL "\n", map_num);
  3767. id_db->foreach(id_db,cleanup_db_sub);
  3768. chrif_char_reset_offline();
  3769. chrif_flush_fifo();
  3770. do_final_atcommand();
  3771. do_final_battle();
  3772. do_final_chrif();
  3773. do_final_clan();
  3774. do_final_clif();
  3775. do_final_npc();
  3776. do_final_quest();
  3777. do_final_achievement();
  3778. do_final_script();
  3779. do_final_instance();
  3780. do_final_itemdb();
  3781. do_final_storage();
  3782. do_final_guild();
  3783. do_final_party();
  3784. do_final_pc();
  3785. do_final_pet();
  3786. do_final_homunculus();
  3787. do_final_mercenary();
  3788. do_final_mob(false);
  3789. do_final_msg();
  3790. do_final_skill();
  3791. do_final_status();
  3792. do_final_unit();
  3793. do_final_battleground();
  3794. do_final_duel();
  3795. do_final_elemental();
  3796. do_final_cashshop();
  3797. do_final_channel(); //should be called after final guild
  3798. do_final_vending();
  3799. do_final_buyingstore();
  3800. do_final_path();
  3801. map_db->destroy(map_db, map_db_final);
  3802. for (i=0; i<map_num; i++) {
  3803. if(map[i].cell) aFree(map[i].cell);
  3804. if(map[i].block) aFree(map[i].block);
  3805. if(map[i].block_mob) aFree(map[i].block_mob);
  3806. if(battle_config.dynamic_mobs) { //Dynamic mobs flag by [random]
  3807. if(map[i].mob_delete_timer != INVALID_TIMER)
  3808. delete_timer(map[i].mob_delete_timer, map_removemobs_timer);
  3809. for (j=0; j<MAX_MOB_LIST_PER_MAP; j++)
  3810. if (map[i].moblist[j]) aFree(map[i].moblist[j]);
  3811. }
  3812. map_free_questinfo(i);
  3813. #ifdef ADJUST_SKILL_DAMAGE
  3814. if (map[i].skill_damage.count)
  3815. map_skill_damage_free(&map[i]);
  3816. #endif
  3817. }
  3818. mapindex_final();
  3819. if(enable_grf)
  3820. grfio_final();
  3821. id_db->destroy(id_db, NULL);
  3822. pc_db->destroy(pc_db, NULL);
  3823. mobid_db->destroy(mobid_db, NULL);
  3824. bossid_db->destroy(bossid_db, NULL);
  3825. nick_db->destroy(nick_db, nick_db_final);
  3826. charid_db->destroy(charid_db, NULL);
  3827. iwall_db->destroy(iwall_db, NULL);
  3828. regen_db->destroy(regen_db, NULL);
  3829. #ifdef ADJUST_SKILL_DAMAGE
  3830. ers_destroy(map_skill_damage_ers);
  3831. #endif
  3832. map_sql_close();
  3833. ShowStatus("Finished.\n");
  3834. }
  3835. static int map_abort_sub(struct map_session_data* sd, va_list ap)
  3836. {
  3837. chrif_save(sd, CSAVE_QUIT|CSAVE_INVENTORY|CSAVE_CART);
  3838. return 1;
  3839. }
  3840. //------------------------------
  3841. // Function called when the server
  3842. // has received a crash signal.
  3843. //------------------------------
  3844. void do_abort(void)
  3845. {
  3846. static int run = 0;
  3847. //Save all characters and then flush the inter-connection.
  3848. if (run) {
  3849. ShowFatalError("Server has crashed while trying to save characters. Character data can't be saved!\n");
  3850. return;
  3851. }
  3852. run = 1;
  3853. if (!chrif_isconnected())
  3854. {
  3855. if (pc_db->size(pc_db))
  3856. ShowFatalError("Server has crashed without a connection to the char-server, %u characters can't be saved!\n", pc_db->size(pc_db));
  3857. return;
  3858. }
  3859. ShowError("Server received crash signal! Attempting to save all online characters!\n");
  3860. map_foreachpc(map_abort_sub);
  3861. chrif_flush_fifo();
  3862. }
  3863. /*======================================================
  3864. * Map-Server help options screen
  3865. *------------------------------------------------------*/
  3866. void display_helpscreen(bool do_exit)
  3867. {
  3868. ShowInfo("Usage: %s [options]\n", SERVER_NAME);
  3869. ShowInfo("\n");
  3870. ShowInfo("Options:\n");
  3871. ShowInfo(" -?, -h [--help]\t\tDisplays this help screen.\n");
  3872. ShowInfo(" -v [--version]\t\tDisplays the server's version.\n");
  3873. ShowInfo(" --run-once\t\t\tCloses server after loading (testing).\n");
  3874. ShowInfo(" --map-config <file>\t\tAlternative map-server configuration.\n");
  3875. ShowInfo(" --battle-config <file>\tAlternative battle configuration.\n");
  3876. ShowInfo(" --atcommand-config <file>\tAlternative atcommand configuration.\n");
  3877. ShowInfo(" --script-config <file>\tAlternative script configuration.\n");
  3878. ShowInfo(" --msg-config <file>\t\tAlternative message configuration.\n");
  3879. ShowInfo(" --grf-path <file>\t\tAlternative GRF path configuration.\n");
  3880. ShowInfo(" --inter-config <file>\t\tAlternative inter-server configuration.\n");
  3881. ShowInfo(" --log-config <file>\t\tAlternative logging configuration.\n");
  3882. if( do_exit )
  3883. exit(EXIT_SUCCESS);
  3884. }
  3885. /*======================================================
  3886. * Map-Server Init and Command-line Arguments [Valaris]
  3887. *------------------------------------------------------*/
  3888. void set_server_type(void)
  3889. {
  3890. SERVER_TYPE = ATHENA_SERVER_MAP;
  3891. }
  3892. /*======================================================
  3893. * Message System
  3894. *------------------------------------------------------*/
  3895. struct msg_data {
  3896. char* msg[MAP_MAX_MSG];
  3897. };
  3898. struct msg_data *map_lang2msgdb(uint8 lang){
  3899. return (struct msg_data*)idb_get(map_msg_db, lang);
  3900. }
  3901. void map_do_init_msg(void){
  3902. int test=0, i=0, size;
  3903. const char * listelang[] = {
  3904. MSG_CONF_NAME_EN, //default
  3905. MSG_CONF_NAME_RUS,
  3906. MSG_CONF_NAME_SPN,
  3907. MSG_CONF_NAME_GRM,
  3908. MSG_CONF_NAME_CHN,
  3909. MSG_CONF_NAME_MAL,
  3910. MSG_CONF_NAME_IDN,
  3911. MSG_CONF_NAME_FRN,
  3912. MSG_CONF_NAME_POR,
  3913. MSG_CONF_NAME_THA
  3914. };
  3915. map_msg_db = idb_alloc(DB_OPT_BASE);
  3916. size = ARRAYLENGTH(listelang); //avoid recalc
  3917. while(test!=-1 && size>i){ //for all enable lang +(English default)
  3918. test = msg_checklangtype(i,false);
  3919. if(test == 1) msg_config_read(listelang[i],i); //if enabled read it and assign i to langtype
  3920. i++;
  3921. }
  3922. }
  3923. void map_do_final_msg(void){
  3924. DBIterator *iter = db_iterator(map_msg_db);
  3925. struct msg_data *mdb;
  3926. for (mdb = (struct msg_data *)dbi_first(iter); dbi_exists(iter); mdb = (struct msg_data *)dbi_next(iter)) {
  3927. _do_final_msg(MAP_MAX_MSG,mdb->msg);
  3928. aFree(mdb);
  3929. }
  3930. dbi_destroy(iter);
  3931. map_msg_db->destroy(map_msg_db, NULL);
  3932. }
  3933. void map_msg_reload(void){
  3934. map_do_final_msg(); //clear data
  3935. map_do_init_msg();
  3936. }
  3937. int map_msg_config_read(const char *cfgName, int lang){
  3938. struct msg_data *mdb;
  3939. if( (mdb = map_lang2msgdb(lang)) == NULL )
  3940. CREATE(mdb, struct msg_data, 1);
  3941. else
  3942. idb_remove(map_msg_db, lang);
  3943. idb_put(map_msg_db, lang, mdb);
  3944. if(_msg_config_read(cfgName,MAP_MAX_MSG,mdb->msg)!=0){ //an error occur
  3945. idb_remove(map_msg_db, lang); //@TRYME
  3946. aFree(mdb);
  3947. }
  3948. return 0;
  3949. }
  3950. const char* map_msg_txt(struct map_session_data *sd, int msg_number){
  3951. struct msg_data *mdb;
  3952. uint8 lang = 0; //default
  3953. if(sd && sd->langtype) lang = sd->langtype;
  3954. if( (mdb = map_lang2msgdb(lang)) != NULL){
  3955. const char *tmp = _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3956. if(strcmp(tmp,"??")) //to verify result
  3957. return tmp;
  3958. ShowDebug("Message #%d not found for langtype %d.\n",msg_number,lang);
  3959. }
  3960. ShowDebug("Selected langtype %d not loaded, trying fallback...\n",lang);
  3961. if(lang != 0 && (mdb = map_lang2msgdb(0)) != NULL) //fallback
  3962. return _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3963. return "??";
  3964. }
  3965. /// Called when a terminate signal is received.
  3966. void do_shutdown(void)
  3967. {
  3968. if( runflag != MAPSERVER_ST_SHUTDOWN )
  3969. {
  3970. runflag = MAPSERVER_ST_SHUTDOWN;
  3971. ShowStatus("Shutting down...\n");
  3972. {
  3973. struct map_session_data* sd;
  3974. struct s_mapiterator* iter = mapit_getallusers();
  3975. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3976. clif_GM_kick(NULL, sd);
  3977. mapit_free(iter);
  3978. flush_fifos();
  3979. }
  3980. chrif_check_shutdown();
  3981. }
  3982. }
  3983. int do_init(int argc, char *argv[])
  3984. {
  3985. runflag = MAPSERVER_ST_STARTING;
  3986. #ifdef GCOLLECT
  3987. GC_enable_incremental();
  3988. #endif
  3989. INTER_CONF_NAME="conf/inter_athena.conf";
  3990. LOG_CONF_NAME="conf/log_athena.conf";
  3991. MAP_CONF_NAME = "conf/map_athena.conf";
  3992. BATTLE_CONF_FILENAME = "conf/battle_athena.conf";
  3993. ATCOMMAND_CONF_FILENAME = "conf/atcommand_athena.conf";
  3994. SCRIPT_CONF_NAME = "conf/script_athena.conf";
  3995. GRF_PATH_FILENAME = "conf/grf-files.txt";
  3996. safestrncpy(console_log_filepath, "./log/map-msg_log.log", sizeof(console_log_filepath));
  3997. /* Multilanguage */
  3998. MSG_CONF_NAME_EN = "conf/msg_conf/map_msg.conf"; // English (default)
  3999. MSG_CONF_NAME_RUS = "conf/msg_conf/map_msg_rus.conf"; // Russian
  4000. MSG_CONF_NAME_SPN = "conf/msg_conf/map_msg_spn.conf"; // Spanish
  4001. MSG_CONF_NAME_GRM = "conf/msg_conf/map_msg_grm.conf"; // German
  4002. MSG_CONF_NAME_CHN = "conf/msg_conf/map_msg_chn.conf"; // Chinese
  4003. MSG_CONF_NAME_MAL = "conf/msg_conf/map_msg_mal.conf"; // Malaysian
  4004. MSG_CONF_NAME_IDN = "conf/msg_conf/map_msg_idn.conf"; // Indonesian
  4005. MSG_CONF_NAME_FRN = "conf/msg_conf/map_msg_frn.conf"; // French
  4006. MSG_CONF_NAME_POR = "conf/msg_conf/map_msg_por.conf"; // Brazilian Portuguese
  4007. MSG_CONF_NAME_THA = "conf/msg_conf/map_msg_tha.conf"; // Thai
  4008. /* Multilanguage */
  4009. // Default map
  4010. safestrncpy(map_default.mapname, "prontera", MAP_NAME_LENGTH);
  4011. map_default.x = 156;
  4012. map_default.y = 191;
  4013. cli_get_options(argc,argv);
  4014. rnd_init();
  4015. map_config_read(MAP_CONF_NAME);
  4016. if (save_settings == CHARSAVE_NONE)
  4017. ShowWarning("Value of 'save_settings' is not set, player's data only will be saved every 'autosave_time' (%d seconds).\n", autosave_interval/1000);
  4018. // loads npcs
  4019. map_reloadnpc(false);
  4020. chrif_checkdefaultlogin();
  4021. if (!map_ip_set || !char_ip_set) {
  4022. char ip_str[16];
  4023. ip2str(addr_[0], ip_str);
  4024. // Skip this warning if the server is run with run-once flag
  4025. if( runflag != CORE_ST_STOP ){
  4026. ShowWarning("Not all IP addresses in map_athena.conf configured, autodetecting...\n");
  4027. }
  4028. if (naddr_ == 0)
  4029. ShowError("Unable to determine your IP address...\n");
  4030. else if (naddr_ > 1)
  4031. ShowNotice("Multiple interfaces detected...\n");
  4032. ShowInfo("Defaulting to %s as our IP address\n", ip_str);
  4033. if (!map_ip_set)
  4034. clif_setip(ip_str);
  4035. if (!char_ip_set)
  4036. chrif_setip(ip_str);
  4037. }
  4038. battle_config_read(BATTLE_CONF_FILENAME);
  4039. script_config_read(SCRIPT_CONF_NAME);
  4040. inter_config_read(INTER_CONF_NAME);
  4041. log_config_read(LOG_CONF_NAME);
  4042. id_db = idb_alloc(DB_OPT_BASE);
  4043. pc_db = idb_alloc(DB_OPT_BASE); //Added for reliable map_id2sd() use. [Skotlex]
  4044. mobid_db = idb_alloc(DB_OPT_BASE); //Added to lower the load of the lazy mob ai. [Skotlex]
  4045. bossid_db = idb_alloc(DB_OPT_BASE); // Used for Convex Mirror quick MVP search
  4046. map_db = uidb_alloc(DB_OPT_BASE);
  4047. nick_db = idb_alloc(DB_OPT_BASE);
  4048. charid_db = uidb_alloc(DB_OPT_BASE);
  4049. regen_db = idb_alloc(DB_OPT_BASE); // efficient status_natural_heal processing
  4050. iwall_db = strdb_alloc(DB_OPT_RELEASE_DATA,2*NAME_LENGTH+2+1); // [Zephyrus] Invisible Walls
  4051. #ifdef ADJUST_SKILL_DAMAGE
  4052. map_skill_damage_ers = ers_new(sizeof(struct s_skill_damage), "map.cpp:map_skill_damage_ers", ERS_OPT_NONE);
  4053. #endif
  4054. map_sql_init();
  4055. if (log_config.sql_logs)
  4056. log_sql_init();
  4057. mapindex_init();
  4058. if(enable_grf)
  4059. grfio_init(GRF_PATH_FILENAME);
  4060. map_readallmaps();
  4061. add_timer_func_list(map_freeblock_timer, "map_freeblock_timer");
  4062. add_timer_func_list(map_clearflooritem_timer, "map_clearflooritem_timer");
  4063. add_timer_func_list(map_removemobs_timer, "map_removemobs_timer");
  4064. add_timer_interval(gettick()+1000, map_freeblock_timer, 0, 0, 60*1000);
  4065. map_do_init_msg();
  4066. do_init_path();
  4067. do_init_atcommand();
  4068. do_init_battle();
  4069. do_init_instance();
  4070. do_init_chrif();
  4071. do_init_clan();
  4072. do_init_clif();
  4073. do_init_script();
  4074. do_init_itemdb();
  4075. do_init_channel();
  4076. do_init_cashshop();
  4077. do_init_skill();
  4078. do_init_mob();
  4079. do_init_pc();
  4080. do_init_status();
  4081. do_init_party();
  4082. do_init_guild();
  4083. do_init_storage();
  4084. do_init_pet();
  4085. do_init_homunculus();
  4086. do_init_mercenary();
  4087. do_init_elemental();
  4088. do_init_quest();
  4089. do_init_achievement();
  4090. do_init_npc();
  4091. do_init_unit();
  4092. do_init_battleground();
  4093. do_init_duel();
  4094. do_init_vending();
  4095. do_init_buyingstore();
  4096. npc_event_do_oninit(); // Init npcs (OnInit)
  4097. if (battle_config.pk_mode)
  4098. ShowNotice("Server is running on '" CL_WHITE "PK Mode" CL_RESET "'.\n");
  4099. ShowStatus("Server is '" CL_GREEN "ready" CL_RESET "' and listening on port '" CL_WHITE "%d" CL_RESET "'.\n\n", map_port);
  4100. if( runflag != CORE_ST_STOP )
  4101. {
  4102. shutdown_callback = do_shutdown;
  4103. runflag = MAPSERVER_ST_RUNNING;
  4104. }
  4105. if( console ){ //start listening
  4106. add_timer_func_list(parse_console_timer, "parse_console_timer");
  4107. add_timer_interval(gettick()+1000, parse_console_timer, 0, 0, 1000); //start in 1s each 1sec
  4108. }
  4109. return 0;
  4110. }