map.cpp 162 KB

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