map.c 135 KB

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