map.cpp 147 KB

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