npc.cpp 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "npc.hpp"
  4. #include <errno.h>
  5. #include <map>
  6. #include <stdlib.h>
  7. #include <vector>
  8. #include "../common/cbasetypes.hpp"
  9. #include "../common/db.hpp"
  10. #include "../common/ers.hpp"
  11. #include "../common/malloc.hpp"
  12. #include "../common/nullpo.hpp"
  13. #include "../common/showmsg.hpp"
  14. #include "../common/strlib.hpp"
  15. #include "../common/timer.hpp"
  16. #include "../common/utils.hpp"
  17. #include "battle.hpp"
  18. #include "chat.hpp"
  19. #include "clif.hpp"
  20. #include "date.hpp" // days of week enum
  21. #include "guild.hpp"
  22. #include "instance.hpp"
  23. #include "intif.hpp"
  24. #include "log.hpp"
  25. #include "log.hpp"
  26. #include "map.hpp"
  27. #include "mob.hpp"
  28. #include "pc.hpp"
  29. #include "pet.hpp"
  30. #include "script.hpp" // script_config
  31. struct npc_data* fake_nd;
  32. // linked list of npc source files
  33. struct npc_src_list {
  34. struct npc_src_list* next;
  35. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  36. };
  37. static struct npc_src_list* npc_src_files = NULL;
  38. static int npc_id=START_NPC_NUM;
  39. static int npc_warp=0;
  40. static int npc_shop=0;
  41. static int npc_script=0;
  42. static int npc_mob=0;
  43. static int npc_delay_mob=0;
  44. static int npc_cache_mob=0;
  45. struct eri *npc_sc_display_ers;
  46. // Market Shop
  47. #if PACKETVER >= 20131223
  48. struct s_npc_market {
  49. struct npc_item_list *list;
  50. char exname[NPC_NAME_LENGTH+1];
  51. uint16 count;
  52. };
  53. static DBMap *NPCMarketDB; /// Stock persistency! Temporary market stocks from `market` table. struct s_npc_market, key: NPC exname
  54. static void npc_market_checkall(void);
  55. static void npc_market_fromsql(void);
  56. #define npc_market_delfromsql(exname,nameid) (npc_market_delfromsql_((exname), (nameid), false))
  57. #define npc_market_clearfromsql(exname) (npc_market_delfromsql_((exname), 0, true))
  58. #endif
  59. /// Returns a new npc id that isn't being used in id_db.
  60. /// Fatal error if nothing is available.
  61. int npc_get_new_npc_id(void) {
  62. if( npc_id >= START_NPC_NUM && !map_blid_exists(npc_id) )
  63. return npc_id++;// available
  64. else {// find next id
  65. int base_id = npc_id;
  66. while( base_id != ++npc_id ) {
  67. if( npc_id < START_NPC_NUM )
  68. npc_id = START_NPC_NUM;
  69. if( !map_blid_exists(npc_id) )
  70. return npc_id++;// available
  71. }
  72. // full loop, nothing available
  73. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  74. exit(1);
  75. }
  76. }
  77. static DBMap* ev_db; // const char* event_name -> struct event_data*
  78. static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  79. struct event_data {
  80. struct npc_data *nd;
  81. int pos;
  82. };
  83. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  84. /* hello */
  85. static char *npc_last_path;
  86. static char *npc_last_ref;
  87. struct npc_path_data {
  88. char* path;
  89. unsigned short references;
  90. };
  91. struct npc_path_data *npc_last_npd;
  92. static DBMap *npc_path_db;
  93. //For holding the view data of npc classes. [Skotlex]
  94. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  95. static struct view_data npc_viewdb2[MAX_NPC_CLASS2_END-MAX_NPC_CLASS2_START];
  96. struct script_event_s{
  97. struct event_data *event;
  98. const char *event_name;
  99. };
  100. // Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  101. std::map<enum npce_event, std::vector<struct script_event_s>> script_event;
  102. /**
  103. * Returns the viewdata for normal NPC classes.
  104. * @param class_: NPC class ID
  105. * @return viewdata or nullptr if the ID is invalid
  106. */
  107. struct view_data* npc_get_viewdata(int class_) {
  108. if( class_ == JT_INVISIBLE )
  109. return &npc_viewdb[0];
  110. if (npcdb_checkid(class_)){
  111. if( class_ > MAX_NPC_CLASS2_START ){
  112. return &npc_viewdb2[class_-MAX_NPC_CLASS2_START];
  113. }else{
  114. return &npc_viewdb[class_];
  115. }
  116. }
  117. return nullptr;
  118. }
  119. int npc_isnear_sub(struct block_list* bl, va_list args) {
  120. struct npc_data *nd = (struct npc_data*)bl;
  121. if (nd->sc.option & (OPTION_HIDE|OPTION_INVISIBLE))
  122. return 0;
  123. int skill_id = va_arg(args, int);
  124. if (skill_id > 0) { //If skill_id > 0 that means is used for INF2_DISABLENEARNPC [Cydh]
  125. std::shared_ptr<s_skill_db> skill = skill_db.find(skill_id);
  126. if (skill && skill->unit_nonearnpc_type) {
  127. if (skill->unit_nonearnpc_type&SKILL_NONEAR_WARPPORTAL && nd->subtype == NPCTYPE_WARP)
  128. return 1;
  129. if (skill->unit_nonearnpc_type&SKILL_NONEAR_SHOP && nd->subtype == NPCTYPE_SHOP)
  130. return 1;
  131. if (skill->unit_nonearnpc_type&SKILL_NONEAR_NPC && nd->subtype == NPCTYPE_SCRIPT)
  132. return 1;
  133. if (skill->unit_nonearnpc_type&SKILL_NONEAR_TOMB && nd->subtype == NPCTYPE_TOMB)
  134. return 1;
  135. }
  136. }
  137. return 0;
  138. }
  139. bool npc_isnear(struct block_list * bl) {
  140. if( battle_config.min_npc_vendchat_distance > 0 &&
  141. map_foreachinallrange(npc_isnear_sub,bl, battle_config.min_npc_vendchat_distance, BL_NPC, 0) )
  142. return true;
  143. return false;
  144. }
  145. int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
  146. {
  147. char name[EVENT_NAME_LENGTH];
  148. if (pc_isdead(sd)) // Dead player don't trigger 'OnTouch_'
  149. return 0;
  150. if( nd->touching_id )
  151. return 0; // Attached a player already. Can't trigger on anyone else.
  152. // pc_ishiding moved in npc_event for now.
  153. // If OnTouch_ event exists hiding player doesn't click the npc.
  154. // if( pc_ishiding(sd) )
  155. // return 1; // Can't trigger 'OnTouch_'.
  156. auto it = std::find(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), nd->bl.id);
  157. if (it != sd->npc_ontouch_.end())
  158. return 0;
  159. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  160. return npc_event(sd,name,1);
  161. }
  162. int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
  163. {
  164. char name[EVENT_NAME_LENGTH];
  165. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), nd->bl.id);
  166. if (it != sd->areanpc.end())
  167. return 0;
  168. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_event_name);
  169. return npc_event(sd,name,2);
  170. }
  171. /*==========================================
  172. * Sub-function of npc_enable, runs OnTouch event when enabled
  173. *------------------------------------------*/
  174. int npc_enable_sub(struct block_list *bl, va_list ap)
  175. {
  176. struct npc_data *nd;
  177. nullpo_ret(bl);
  178. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  179. if(bl->type == BL_PC)
  180. {
  181. TBL_PC *sd = (TBL_PC*)bl;
  182. if (nd->sc.option&OPTION_INVISIBLE)
  183. return 1;
  184. // note : disablenpc doesn't reset the previous trigger status on official
  185. if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
  186. { // failed to run OnTouch event, so just click the npc
  187. if (sd->npc_id != 0)
  188. return 0;
  189. pc_stop_walking(sd,1);
  190. npc_click(sd,nd);
  191. }
  192. }
  193. return 0;
  194. }
  195. /*==========================================
  196. * Disable / Enable NPC
  197. *------------------------------------------*/
  198. bool npc_enable(const char* name, int flag)
  199. {
  200. struct npc_data* nd = npc_name2id(name);
  201. if (nd==NULL)
  202. {
  203. ShowError("npc_enable: Attempted to %s a non-existing NPC '%s' (flag=%d).\n", (flag&3) ? "show" : "hide", name, flag);
  204. return false;
  205. }
  206. if (flag&1) {
  207. nd->sc.option&=~OPTION_INVISIBLE;
  208. clif_spawn(&nd->bl);
  209. } else if (flag&2)
  210. nd->sc.option&=~OPTION_HIDE;
  211. else if (flag&4)
  212. nd->sc.option|= OPTION_HIDE;
  213. else { //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  214. nd->sc.option|= OPTION_INVISIBLE;
  215. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
  216. }
  217. if (nd->class_ == JT_WARPNPC || nd->class_ == JT_GUILD_FLAG)
  218. { //Client won't display option changes for these classes [Toms]
  219. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE))
  220. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);
  221. else
  222. clif_spawn(&nd->bl);
  223. } else
  224. clif_changeoption(&nd->bl);
  225. if( flag&3 && (nd->u.scr.xs >= 0 || nd->u.scr.ys >= 0) )// check if player standing on a OnTouchArea
  226. map_foreachinallarea( npc_enable_sub, nd->bl.m, nd->bl.x-nd->u.scr.xs, nd->bl.y-nd->u.scr.ys, nd->bl.x+nd->u.scr.xs, nd->bl.y+nd->u.scr.ys, BL_PC, nd );
  227. return true;
  228. }
  229. /*==========================================
  230. * NPC lookup (get npc_data through npcname)
  231. *------------------------------------------*/
  232. struct npc_data* npc_name2id(const char* name)
  233. {
  234. return (struct npc_data *) strdb_get(npcname_db, name);
  235. }
  236. /**
  237. * For the Secure NPC Timeout option (check src/config/secure.hpp)
  238. * @author RR
  239. **/
  240. #ifdef SECURE_NPCTIMEOUT
  241. /**
  242. * Timer to check for idle time and timeout the dialog if necessary
  243. **/
  244. TIMER_FUNC(npc_secure_timeout_timer){
  245. struct map_session_data* sd = NULL;
  246. unsigned int timeout = NPC_SECURE_TIMEOUT_NEXT;
  247. t_tick cur_tick = gettick(); //ensure we are on last tick
  248. if ((sd = map_id2sd(id)) == NULL || !sd->npc_id || sd->state.ignoretimeout) {
  249. if (sd)
  250. sd->npc_idle_timer = INVALID_TIMER;
  251. return 0; // Not logged in anymore OR no longer attached to a NPC OR using 'ignoretimeout' script command
  252. }
  253. switch( sd->npc_idle_type ) {
  254. case NPCT_INPUT:
  255. timeout = NPC_SECURE_TIMEOUT_INPUT;
  256. break;
  257. case NPCT_MENU:
  258. timeout = NPC_SECURE_TIMEOUT_MENU;
  259. break;
  260. //case NPCT_WAIT: var starts with this value
  261. }
  262. if( DIFF_TICK(cur_tick,sd->npc_idle_tick) > (timeout*1000) ) {
  263. pc_close_npc(sd,1);
  264. } else if(sd->st && (sd->st->state == END || sd->st->state == CLOSE)){
  265. sd->npc_idle_timer = INVALID_TIMER; //stop timer the script is already ending
  266. } else { //Create a new instance of ourselves to continue
  267. sd->npc_idle_timer = add_timer(cur_tick + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_secure_timeout_timer,sd->bl.id,0);
  268. }
  269. return 0;
  270. }
  271. #endif
  272. /*==========================================
  273. * Dequeue event and add timer for execution (100ms)
  274. *------------------------------------------*/
  275. int npc_event_dequeue(struct map_session_data* sd,bool free_script_stack)
  276. {
  277. nullpo_ret(sd);
  278. if(sd->npc_id)
  279. { //Current script is aborted.
  280. if(sd->state.using_fake_npc){
  281. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  282. sd->state.using_fake_npc = 0;
  283. }
  284. if (free_script_stack&&sd->st) {
  285. script_free_state(sd->st);
  286. sd->st = NULL;
  287. }
  288. sd->npc_id = 0;
  289. }
  290. if (!sd->eventqueue[0][0])
  291. return 0; //Nothing to dequeue
  292. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  293. { //Failed to dequeue, couldn't set a timer.
  294. ShowWarning("npc_event_dequeue: event timer is full !\n");
  295. return 0;
  296. }
  297. //Event dequeued successfully, shift other elements.
  298. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  299. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  300. return 1;
  301. }
  302. /*==========================================
  303. * exports a npc event label
  304. * called from npc_parse_script
  305. *------------------------------------------*/
  306. static int npc_event_export(struct npc_data *nd, int i)
  307. {
  308. char* lname = nd->u.scr.label_list[i].name;
  309. int pos = nd->u.scr.label_list[i].pos;
  310. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
  311. struct event_data *ev;
  312. char buf[EVENT_NAME_LENGTH];
  313. if (nd->bl.m > -1 && map_getmapdata(nd->bl.m)->instance_id > 0) { // Block script events in instances
  314. int j;
  315. for (j = 0; j < NPCE_MAX; j++) {
  316. if (strcmpi(npc_get_script_event_name(j), lname) == 0) {
  317. ShowWarning("npc_event_export: attempting to duplicate a script event in an instance (%s::%s), ignoring\n", nd->name, lname);
  318. return 0;
  319. }
  320. }
  321. }
  322. // NPC:<name> the prefix uses 4 characters
  323. if( !strncasecmp( lname, script_config.onwhisper_event_name, NAME_LENGTH ) && strlen(nd->exname) > ( NAME_LENGTH - 4 ) ){
  324. // The client only allows that many character so that NPC could not be whispered by unmodified clients
  325. ShowWarning( "Whisper event in npc '" CL_WHITE "%s" CL_RESET "' was ignored, because it's name is too long.\n", nd->exname );
  326. return 0;
  327. }
  328. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  329. // generate the data and insert it
  330. CREATE(ev, struct event_data, 1);
  331. ev->nd = nd;
  332. ev->pos = pos;
  333. if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
  334. return 1;
  335. }
  336. return 0;
  337. }
  338. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  339. /**
  340. * Exec name (NPC events) on player or global
  341. * Do on all NPC when called with foreach
  342. * @see DBApply
  343. */
  344. int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
  345. {
  346. const char* p = key.str;
  347. struct event_data* ev;
  348. int* c;
  349. const char* name;
  350. int rid;
  351. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  352. nullpo_ret(c = va_arg(ap, int *));
  353. nullpo_ret(name = va_arg(ap, const char *));
  354. rid = va_arg(ap, int);
  355. p = strchr(p, ':'); // match only the event name
  356. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  357. {
  358. if(rid) // a player may only have 1 script running at the same time
  359. npc_event_sub(map_id2sd(rid),ev,key.str);
  360. else
  361. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  362. (*c)++;
  363. }
  364. return 0;
  365. }
  366. /**
  367. * @see DBApply
  368. */
  369. static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
  370. {
  371. const char* p = key.str;
  372. struct event_data* ev;
  373. int* c, rid;
  374. const char* name;
  375. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  376. nullpo_ret(c = va_arg(ap, int *));
  377. nullpo_ret(name = va_arg(ap, const char *));
  378. rid = va_arg(ap, int);
  379. if( p && strcmpi(name, p) == 0 )
  380. {
  381. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  382. (*c)++;
  383. }
  384. return 0;
  385. }
  386. int npc_event_do_id(const char* name, int rid) {
  387. int c = 0;
  388. if( name[0] == ':' && name[1] == ':' )
  389. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0,rid);
  390. else
  391. ev_db->foreach(ev_db,npc_event_do_sub,&c,name,rid);
  392. return c;
  393. }
  394. // runs the specified event (supports both single-npc and global events)
  395. int npc_event_do(const char* name) {
  396. return npc_event_do_id(name, 0);
  397. }
  398. // runs the specified event (global only)
  399. int npc_event_doall(const char* name)
  400. {
  401. return npc_event_doall_id(name, 0);
  402. }
  403. // runs the specified event(global only) and reports call count
  404. void npc_event_runall( const char* eventname ){
  405. ShowStatus( "Event '" CL_WHITE "%s" CL_RESET "' executed with '" CL_WHITE "%d" CL_RESET "' NPCs.\n", eventname, npc_event_doall( eventname ) );
  406. }
  407. // runs the specified event, with a RID attached (global only)
  408. int npc_event_doall_id(const char* name, int rid)
  409. {
  410. int c = 0;
  411. char buf[EVENT_NAME_LENGTH];
  412. safesnprintf(buf, sizeof(buf), "::%s", name);
  413. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  414. return c;
  415. }
  416. /*==========================================
  417. * Clock event execution
  418. * OnMinute/OnClock/OnHour/OnDay/OnDDHHMM
  419. *------------------------------------------*/
  420. TIMER_FUNC(npc_event_do_clock){
  421. static struct tm ev_tm_b; // tracks previous execution time
  422. time_t timer;
  423. struct tm* t;
  424. char buf[EVENT_NAME_LENGTH];
  425. int c = 0;
  426. timer = time(NULL);
  427. t = localtime(&timer);
  428. if (t->tm_min != ev_tm_b.tm_min ) {
  429. const char* day = NULL;
  430. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_minute_event_name,t->tm_min);
  431. c += npc_event_doall(buf);
  432. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_clock_event_name,t->tm_hour,t->tm_min);
  433. c += npc_event_doall(buf);
  434. switch (t->tm_wday) {
  435. case SUNDAY: day = script_config.timer_sunday_event_name; break;
  436. case MONDAY: day = script_config.timer_monday_event_name; break;
  437. case TUESDAY: day = script_config.timer_tuesday_event_name; break;
  438. case WEDNESDAY: day = script_config.timer_wednesday_event_name; break;
  439. case THURSDAY: day = script_config.timer_thursday_event_name; break;
  440. case FRIDAY: day = script_config.timer_friday_event_name; break;
  441. case SATURDAY: day = script_config.timer_saturday_event_name; break;
  442. }
  443. if( day != NULL ){
  444. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",day,t->tm_hour,t->tm_min);
  445. c += npc_event_doall(buf);
  446. }
  447. }
  448. if (t->tm_hour != ev_tm_b.tm_hour) {
  449. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_hour_event_name,t->tm_hour);
  450. c += npc_event_doall(buf);
  451. }
  452. if (t->tm_mday != ev_tm_b.tm_mday) {
  453. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_day_event_name,t->tm_mon+1,t->tm_mday);
  454. c += npc_event_doall(buf);
  455. }
  456. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  457. return c;
  458. }
  459. /*==========================================
  460. * OnInit Event execution (the start of the event and watch)
  461. *------------------------------------------*/
  462. void npc_event_do_oninit(void)
  463. {
  464. npc_event_runall(script_config.init_event_name);
  465. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  466. }
  467. /*==========================================
  468. * Incorporation of the label for the timer event
  469. * called from npc_parse_script
  470. *------------------------------------------*/
  471. int npc_timerevent_export(struct npc_data *nd, int i)
  472. {
  473. int t = 0, k = 0;
  474. char *lname = nd->u.scr.label_list[i].name;
  475. int pos = nd->u.scr.label_list[i].pos;
  476. size_t len = strlen(script_config.timer_event_name);
  477. // Check if the label name starts with OnTimer(default) and then parse the seconds right after it
  478. if ( !strncmp(lname,script_config.timer_event_name,len) && sscanf( (lname += len), "%11d%n", &t, &k) == 1 && lname[k] == '\0') {
  479. // Timer event
  480. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  481. int j, k2 = nd->u.scr.timeramount;
  482. if (te == NULL)
  483. te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
  484. else
  485. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k2+1) );
  486. for (j = 0; j < k2; j++) {
  487. if (te[j].timer > t) {
  488. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k2-j));
  489. break;
  490. }
  491. }
  492. te[j].timer = t;
  493. te[j].pos = pos;
  494. nd->u.scr.timer_event = te;
  495. nd->u.scr.timeramount++;
  496. }
  497. return 0;
  498. }
  499. struct timer_event_data {
  500. int rid; //Attached player for this timer.
  501. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  502. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  503. };
  504. /*==========================================
  505. * triger 'OnTimerXXXX' events
  506. *------------------------------------------*/
  507. TIMER_FUNC(npc_timerevent){
  508. int old_rid;
  509. t_tick old_timer;
  510. t_tick old_tick;
  511. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  512. struct npc_timerevent_list *te;
  513. struct timer_event_data *ted = (struct timer_event_data*)data;
  514. struct map_session_data *sd=NULL;
  515. if( nd == NULL )
  516. {
  517. ShowError("npc_timerevent: NPC not found??\n");
  518. return 0;
  519. }
  520. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  521. {
  522. ShowError("npc_timerevent: Attached player not found.\n");
  523. ers_free(timer_event_ers, ted);
  524. return 0;
  525. }
  526. // These stuffs might need to be restored.
  527. old_rid = nd->u.scr.rid;
  528. old_tick = nd->u.scr.timertick;
  529. old_timer = nd->u.scr.timer;
  530. // Set the values of the timer
  531. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  532. nd->u.scr.timertick = tick; //current time tick
  533. nd->u.scr.timer = ted->time; //total time from beginning to now
  534. // Locate the event
  535. te = nd->u.scr.timer_event + ted->next;
  536. // Arrange for the next event
  537. ted->next++;
  538. if( nd->u.scr.timeramount > ted->next )
  539. {
  540. int next;
  541. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  542. ted->time += next;
  543. if( sd )
  544. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  545. else
  546. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  547. }
  548. else
  549. {
  550. if( sd )
  551. sd->npc_timer_id = INVALID_TIMER;
  552. else
  553. nd->u.scr.timerid = INVALID_TIMER;
  554. ers_free(timer_event_ers, ted);
  555. }
  556. // Run the script
  557. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  558. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  559. if( sd )
  560. { // Restore previous data, only if this timer is a player-attached one.
  561. nd->u.scr.timer = old_timer;
  562. nd->u.scr.timertick = old_tick;
  563. }
  564. return 0;
  565. }
  566. /*==========================================
  567. * Start/Resume NPC timer
  568. *------------------------------------------*/
  569. int npc_timerevent_start(struct npc_data* nd, int rid)
  570. {
  571. int j;
  572. t_tick tick = gettick();
  573. struct map_session_data *sd = NULL; //Player to whom script is attached.
  574. nullpo_ret(nd);
  575. // Check if there is an OnTimer Event
  576. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  577. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  578. { // Failed to attach timer to this player.
  579. ShowError("npc_timerevent_start: Attached player not found!\n");
  580. return 1;
  581. }
  582. // Check if timer is already started.
  583. if( sd )
  584. {
  585. if( sd->npc_timer_id != INVALID_TIMER )
  586. return 0;
  587. }
  588. else if( nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick )
  589. return 0;
  590. if (j < nd->u.scr.timeramount)
  591. {
  592. t_tick next;
  593. struct timer_event_data *ted;
  594. // Arrange for the next event
  595. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  596. ted->next = j; // Set event index
  597. ted->time = nd->u.scr.timer_event[j].timer;
  598. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  599. if( sd )
  600. {
  601. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  602. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  603. }
  604. else
  605. {
  606. ted->rid = 0;
  607. nd->u.scr.timertick = tick; // Set when timer is started
  608. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  609. }
  610. }
  611. else if (!sd)
  612. {
  613. nd->u.scr.timertick = tick;
  614. }
  615. return 0;
  616. }
  617. /*==========================================
  618. * Stop NPC timer
  619. *------------------------------------------*/
  620. int npc_timerevent_stop(struct npc_data* nd)
  621. {
  622. struct map_session_data *sd = NULL;
  623. int *tid;
  624. nullpo_ret(nd);
  625. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  626. {
  627. ShowError("npc_timerevent_stop: Attached player not found!\n");
  628. return 1;
  629. }
  630. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  631. if( *tid == INVALID_TIMER && (sd || !nd->u.scr.timertick) ) // Nothing to stop
  632. return 0;
  633. // Delete timer
  634. if ( *tid != INVALID_TIMER )
  635. {
  636. const struct TimerData *td = NULL;
  637. td = get_timer(*tid);
  638. if( td && td->data )
  639. ers_free(timer_event_ers, (void*)td->data);
  640. delete_timer(*tid,npc_timerevent);
  641. *tid = INVALID_TIMER;
  642. }
  643. if( !sd && nd->u.scr.timertick )
  644. {
  645. nd->u.scr.timer += DIFF_TICK(gettick(),nd->u.scr.timertick); // Set 'timer' to the time that has passed since the beginning of the timers
  646. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  647. }
  648. return 0;
  649. }
  650. /*==========================================
  651. * Aborts a running NPC timer that is attached to a player.
  652. *------------------------------------------*/
  653. void npc_timerevent_quit(struct map_session_data* sd)
  654. {
  655. const struct TimerData *td;
  656. struct npc_data* nd;
  657. struct timer_event_data *ted;
  658. // Check timer existance
  659. if( sd->npc_timer_id == INVALID_TIMER )
  660. return;
  661. if( !(td = get_timer(sd->npc_timer_id)) )
  662. {
  663. sd->npc_timer_id = INVALID_TIMER;
  664. return;
  665. }
  666. // Delete timer
  667. nd = (struct npc_data *)map_id2bl(td->id);
  668. ted = (struct timer_event_data*)td->data;
  669. delete_timer(sd->npc_timer_id, npc_timerevent);
  670. sd->npc_timer_id = INVALID_TIMER;
  671. // Execute OnTimerQuit
  672. if( nd && nd->bl.type == BL_NPC )
  673. {
  674. char buf[EVENT_NAME_LENGTH];
  675. struct event_data *ev;
  676. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, script_config.timer_quit_event_name);
  677. ev = (struct event_data*)strdb_get(ev_db, buf);
  678. if( ev && ev->nd != nd )
  679. {
  680. ShowWarning("npc_timerevent_quit: Unable to execute \"%s\", two NPCs have the same event name [%s]!\n",script_config.timer_quit_event_name,buf);
  681. ev = NULL;
  682. }
  683. if( ev )
  684. {
  685. int old_rid;
  686. t_tick old_timer;
  687. t_tick old_tick;
  688. //Set timer related info.
  689. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  690. old_tick = nd->u.scr.timertick;
  691. old_timer = nd->u.scr.timer;
  692. nd->u.scr.rid = sd->bl.id;
  693. nd->u.scr.timertick = gettick();
  694. nd->u.scr.timer = ted->time;
  695. //Execute label
  696. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  697. //Restore previous data.
  698. nd->u.scr.rid = old_rid;
  699. nd->u.scr.timer = old_timer;
  700. nd->u.scr.timertick = old_tick;
  701. }
  702. }
  703. ers_free(timer_event_ers, ted);
  704. }
  705. /*==========================================
  706. * Get the tick value of an NPC timer
  707. * If it's stopped, return stopped time
  708. *------------------------------------------*/
  709. t_tick npc_gettimerevent_tick(struct npc_data* nd)
  710. {
  711. t_tick tick;
  712. nullpo_ret(nd);
  713. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  714. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  715. if( nd->u.scr.timertick ) // It's a running timer
  716. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  717. return tick;
  718. }
  719. /*==========================================
  720. * Set tick for running and stopped timer
  721. *------------------------------------------*/
  722. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  723. {
  724. bool flag;
  725. int old_rid;
  726. //struct map_session_data *sd = NULL;
  727. nullpo_ret(nd);
  728. // TODO: Set player attached timer's tick.
  729. old_rid = nd->u.scr.rid;
  730. nd->u.scr.rid = 0;
  731. // Check if timer is started
  732. flag = (nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick);
  733. if( flag ) npc_timerevent_stop(nd);
  734. nd->u.scr.timer = newtimer;
  735. if( flag ) npc_timerevent_start(nd, -1);
  736. nd->u.scr.rid = old_rid;
  737. return 0;
  738. }
  739. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
  740. {
  741. if ( sd->npc_id != 0 )
  742. {
  743. //Enqueue the event trigger.
  744. int i;
  745. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  746. if( i < MAX_EVENTQUEUE )
  747. {
  748. safestrncpy(sd->eventqueue[i],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  749. return 0;
  750. }
  751. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  752. return 1;
  753. }
  754. if( ev->nd->sc.option&OPTION_INVISIBLE )
  755. {
  756. //Disabled npc, shouldn't trigger event.
  757. npc_event_dequeue(sd);
  758. return 2;
  759. }
  760. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  761. return 0;
  762. }
  763. /*==========================================
  764. * NPC processing event type
  765. *------------------------------------------*/
  766. int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
  767. {
  768. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  769. struct npc_data *nd;
  770. nullpo_ret(sd);
  771. if( ev == NULL || (nd = ev->nd) == NULL )
  772. {
  773. if( !ontouch )
  774. ShowError("npc_event: event not found [%s]\n", eventname);
  775. return ontouch;
  776. }
  777. if (ontouch == 1) { // OnTouch_
  778. if (pc_ishiding(sd))
  779. return 0;
  780. nd->touching_id = sd->bl.id;
  781. auto it = std::find(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), nd->bl.id);
  782. if (it == sd->npc_ontouch_.end())
  783. sd->npc_ontouch_.push_back(nd->bl.id);
  784. } else if (ontouch == 2) { // OnTouch
  785. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), nd->bl.id);
  786. if (it == sd->areanpc.end())
  787. sd->areanpc.push_back(nd->bl.id);
  788. }
  789. npc_event_sub(sd,ev,eventname); // Don't return this value so npc_enable_sub doesn't attempt to "click" the NPC if OnTouch fails.
  790. return 0;
  791. }
  792. /*==========================================
  793. * Sub chk then execute area event type
  794. *------------------------------------------*/
  795. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  796. {
  797. struct map_session_data *sd;
  798. int pc_id;
  799. char *name;
  800. nullpo_ret(bl);
  801. nullpo_ret((sd = map_id2sd(bl->id)));
  802. pc_id = va_arg(ap,int);
  803. name = va_arg(ap,char*);
  804. if( sd->state.warping )
  805. return 0;
  806. if( pc_ishiding(sd) )
  807. return 0;
  808. if( pc_isdead(sd) )
  809. return 0;
  810. if( pc_id == sd->bl.id )
  811. return 0;
  812. npc_event(sd,name,1);
  813. return 1;
  814. }
  815. /*==========================================
  816. * Chk if sd is still touching his assigned npc.
  817. * If not, it unsets it and searches for another player in range.
  818. *------------------------------------------*/
  819. int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
  820. {
  821. if (sd->npc_ontouch_.empty())
  822. return 0;
  823. bool found = false;
  824. sd->npc_ontouch_.erase(std::remove_if(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), [&] (const int &current_npc_id) {
  825. struct npc_data *nd = map_id2nd(current_npc_id);
  826. if (!nd) {
  827. return true;
  828. } else {
  829. int16 xs = nd->u.scr.xs;
  830. int16 ys = nd->u.scr.ys;
  831. // note : hiding doesn't reset the previous trigger status
  832. // player must leave the area to reset nd->touching_id on official
  833. if (sd->bl.m != nd->bl.m || sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs || sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys || leavemap) {
  834. char name[EVENT_NAME_LENGTH];
  835. if (nd->touching_id && nd->touching_id == sd->bl.id) {// empty when reload script
  836. found = true;
  837. nd->touching_id = 0;
  838. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  839. map_forcountinarea(npc_touch_areanpc_sub,nd->bl.m,nd->bl.x - xs,nd->bl.y - ys,nd->bl.x + xs,nd->bl.y + ys,1,BL_PC,sd->bl.id,name);
  840. }
  841. return true;
  842. }
  843. }
  844. return false;
  845. }), sd->npc_ontouch_.end());
  846. return found;
  847. }
  848. /*==========================================
  849. * Exec OnTouch for player if in range of area event
  850. *------------------------------------------*/
  851. int npc_touch_areanpc(struct map_session_data* sd, int16 m, int16 x, int16 y)
  852. {
  853. int xs, ys, i, f = 1;
  854. nullpo_retr(1, sd);
  855. // Remove NPCs that are no longer within the OnTouch area
  856. for (i = 0; i < sd->areanpc.size(); i++) {
  857. struct npc_data *nd = map_id2nd(sd->areanpc[i]);
  858. if (!nd || nd->subtype != NPCTYPE_SCRIPT ||
  859. !(nd->bl.m == m && x >= nd->bl.x - nd->u.scr.xs && x <= nd->bl.x + nd->u.scr.xs && y >= nd->bl.y - nd->u.scr.ys && y <= nd->bl.y + nd->u.scr.ys))
  860. sd->areanpc.erase(sd->areanpc.begin() + i);
  861. }
  862. if (sd->state.block_action & PCBLOCK_NPCCLICK)
  863. return 0;
  864. struct map_data *mapdata = map_getmapdata(m);
  865. for (i = 0; i < mapdata->npc_num_area; i++) {
  866. if (mapdata->npc[i]->sc.option&OPTION_INVISIBLE) {
  867. f = 0; // a npc was found, but it is disabled; don't print warning
  868. continue;
  869. }
  870. switch(mapdata->npc[i]->subtype) {
  871. case NPCTYPE_WARP:
  872. xs = mapdata->npc[i]->u.warp.xs;
  873. ys = mapdata->npc[i]->u.warp.ys;
  874. break;
  875. case NPCTYPE_SCRIPT:
  876. xs = mapdata->npc[i]->u.scr.xs;
  877. ys = mapdata->npc[i]->u.scr.ys;
  878. break;
  879. default:
  880. continue;
  881. }
  882. if (x >= mapdata->npc[i]->bl.x - xs && x <= mapdata->npc[i]->bl.x + xs && y >= mapdata->npc[i]->bl.y - ys && y <= mapdata->npc[i]->bl.y + ys) {
  883. f = 0;
  884. switch (mapdata->npc[i]->subtype) {
  885. case NPCTYPE_WARP:
  886. if ((!mapdata->npc[i]->trigger_on_hidden && (pc_ishiding(sd) || (sd->sc.count && sd->sc.data[SC_CAMOUFLAGE]))) || pc_isdead(sd))
  887. break; // hidden or dead chars cannot use warps
  888. if (!pc_job_can_entermap((enum e_job)sd->status.class_, map_mapindex2mapid(mapdata->npc[i]->u.warp.mapindex), sd->group_level))
  889. break;
  890. if (sd->count_rewarp > 10) {
  891. ShowWarning("Prevented infinite warp loop for player (%d:%d). Please fix NPC: '%s', path: '%s'\n", sd->status.account_id, sd->status.char_id, mapdata->npc[i]->exname, mapdata->npc[i]->path);
  892. sd->count_rewarp = 0;
  893. break;
  894. }
  895. pc_setpos(sd, mapdata->npc[i]->u.warp.mapindex, mapdata->npc[i]->u.warp.x, mapdata->npc[i]->u.warp.y, CLR_OUTSIGHT);
  896. return 0;
  897. case NPCTYPE_SCRIPT:
  898. // warp type sorted first, no need to check if they override any other OnTouch areas.
  899. if (npc_ontouch_event(sd, mapdata->npc[i]) > 0 && npc_ontouch2_event(sd, mapdata->npc[i]) > 0) { // failed to run OnTouch event, so just click the npc
  900. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), mapdata->npc[i]->bl.id);
  901. if (it == sd->areanpc.end())
  902. sd->areanpc.push_back(mapdata->npc[i]->bl.id);
  903. npc_click(sd, mapdata->npc[i]);
  904. }
  905. break;
  906. }
  907. }
  908. }
  909. if (f == 1) {
  910. ShowError("npc_touch_areanpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", mapdata->name, x, y);
  911. return 1;
  912. }
  913. return 0;
  914. }
  915. // OnTouch NPC or Warp for Mobs
  916. // Return 1 if Warped
  917. int npc_touch_areanpc2(struct mob_data *md)
  918. {
  919. int i, x = md->bl.x, y = md->bl.y, id;
  920. char eventname[EVENT_NAME_LENGTH];
  921. struct event_data* ev;
  922. int xs, ys;
  923. struct map_data *mapdata = map_getmapdata(md->bl.m);
  924. for( i = 0; i < mapdata->npc_num_area; i++ )
  925. {
  926. if( mapdata->npc[i]->sc.option&OPTION_INVISIBLE )
  927. continue;
  928. switch( mapdata->npc[i]->subtype )
  929. {
  930. case NPCTYPE_WARP:
  931. if( !( battle_config.mob_warp&1 ) )
  932. continue;
  933. xs = mapdata->npc[i]->u.warp.xs;
  934. ys = mapdata->npc[i]->u.warp.ys;
  935. break;
  936. case NPCTYPE_SCRIPT:
  937. xs = mapdata->npc[i]->u.scr.xs;
  938. ys = mapdata->npc[i]->u.scr.ys;
  939. break;
  940. default:
  941. continue; // Keep Searching
  942. }
  943. if( x >= mapdata->npc[i]->bl.x-xs && x <= mapdata->npc[i]->bl.x+xs && y >= mapdata->npc[i]->bl.y-ys && y <= mapdata->npc[i]->bl.y+ys )
  944. { // In the npc touch area
  945. switch( mapdata->npc[i]->subtype )
  946. {
  947. case NPCTYPE_WARP: {
  948. int16 warp_m = map_mapindex2mapid(mapdata->npc[i]->u.warp.mapindex);
  949. if( warp_m < 0 )
  950. break; // Cannot Warp between map servers
  951. if( unit_warp(&md->bl, warp_m, mapdata->npc[i]->u.warp.x, mapdata->npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  952. return 1; // Warped
  953. }
  954. break;
  955. case NPCTYPE_SCRIPT:
  956. if( mapdata->npc[i]->bl.id == md->areanpc_id )
  957. break; // Already touch this NPC
  958. safesnprintf(eventname, ARRAYLENGTH(eventname), "%s::%s", mapdata->npc[i]->exname, script_config.ontouchnpc_event_name);
  959. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  960. break; // No OnTouchNPC Event
  961. md->areanpc_id = mapdata->npc[i]->bl.id;
  962. id = md->bl.id; // Stores Unique ID
  963. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  964. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  965. break;
  966. }
  967. return 0;
  968. }
  969. }
  970. return 0;
  971. }
  972. /**
  973. * Checks if there are any NPC on-touch objects on the given range.
  974. * @param flag : Flag determines the type of object to check for
  975. * &1: NPC Warps
  976. * &2: NPCs with on-touch events.
  977. * @param m : mapindex
  978. * @param x : x coord
  979. * @param y : y coord
  980. * @param range : range to check
  981. * @return 0: no npc on target cells, x: npc_id
  982. */
  983. int npc_check_areanpc(int flag, int16 m, int16 x, int16 y, int16 range)
  984. {
  985. int i;
  986. int x0,y0,x1,y1;
  987. int xs,ys;
  988. if (range < 0) return 0;
  989. struct map_data *mapdata = map_getmapdata(m);
  990. x0 = i16max(x-range, 0);
  991. y0 = i16max(y-range, 0);
  992. x1 = i16min(x+range, mapdata->xs-1);
  993. y1 = i16min(y+range, mapdata->ys-1);
  994. //First check for npc_cells on the range given
  995. i = 0;
  996. for (ys = y0; ys <= y1 && !i; ys++) {
  997. for(xs = x0; xs <= x1 && !i; xs++){
  998. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  999. i = 1;
  1000. }
  1001. }
  1002. if (!i) return 0; //No NPC_CELLs.
  1003. //Now check for the actual NPC on said range.
  1004. for (i = 0; i < mapdata->npc_num_area; i++)
  1005. {
  1006. if (mapdata->npc[i]->sc.option&OPTION_INVISIBLE)
  1007. continue;
  1008. switch(mapdata->npc[i]->subtype)
  1009. {
  1010. case NPCTYPE_WARP:
  1011. if (!(flag&1))
  1012. continue;
  1013. xs=mapdata->npc[i]->u.warp.xs;
  1014. ys=mapdata->npc[i]->u.warp.ys;
  1015. break;
  1016. case NPCTYPE_SCRIPT:
  1017. if (!(flag&2))
  1018. continue;
  1019. xs=mapdata->npc[i]->u.scr.xs;
  1020. ys=mapdata->npc[i]->u.scr.ys;
  1021. break;
  1022. default:
  1023. continue;
  1024. }
  1025. if( x1 >= mapdata->npc[i]->bl.x-xs && x0 <= mapdata->npc[i]->bl.x+xs
  1026. && y1 >= mapdata->npc[i]->bl.y-ys && y0 <= mapdata->npc[i]->bl.y+ys )
  1027. break; // found a npc
  1028. }
  1029. if (i == mapdata->npc_num_area)
  1030. return 0;
  1031. return (mapdata->npc[i]->bl.id);
  1032. }
  1033. /*==========================================
  1034. * Chk if player not too far to access the npc.
  1035. * Returns npc_data (success) or NULL (fail).
  1036. *------------------------------------------*/
  1037. struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
  1038. {
  1039. struct npc_data *nd;
  1040. nullpo_retr(NULL, sd);
  1041. if(bl == NULL) return NULL;
  1042. if(bl->type != BL_NPC) return NULL;
  1043. nd = (TBL_NPC*)bl;
  1044. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  1045. return nd;
  1046. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  1047. return nd;
  1048. if (bl->m!=sd->bl.m ||
  1049. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  1050. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  1051. return NULL;
  1052. return nd;
  1053. }
  1054. /*==========================================
  1055. * Make NPC talk in global chat (like npctalk)
  1056. *------------------------------------------*/
  1057. int npc_globalmessage(const char* name, const char* mes)
  1058. {
  1059. struct npc_data* nd = npc_name2id(name);
  1060. char temp[100];
  1061. if (!nd)
  1062. return 0;
  1063. snprintf(temp, sizeof(temp), "%s", mes);
  1064. clif_GlobalMessage(&nd->bl,temp,ALL_CLIENT);
  1065. return 0;
  1066. }
  1067. // MvP tomb [GreenBox]
  1068. void run_tomb(struct map_session_data* sd, struct npc_data* nd)
  1069. {
  1070. char buffer[200];
  1071. char time[10];
  1072. strftime(time, sizeof(time), "%H:%M", localtime(&nd->u.tomb.kill_time));
  1073. // TODO: Find exact color?
  1074. snprintf(buffer, sizeof(buffer), msg_txt(sd,657), nd->u.tomb.md->db->name);
  1075. clif_scriptmes(sd, nd->bl.id, buffer);
  1076. clif_scriptmes(sd, nd->bl.id, msg_txt(sd,658));
  1077. snprintf(buffer, sizeof(buffer), msg_txt(sd,659), time);
  1078. clif_scriptmes(sd, nd->bl.id, buffer);
  1079. clif_scriptmes(sd, nd->bl.id, msg_txt(sd,660));
  1080. snprintf(buffer, sizeof(buffer), msg_txt(sd,661), nd->u.tomb.killer_name[0] ? nd->u.tomb.killer_name : "Unknown");
  1081. clif_scriptmes(sd, nd->bl.id, buffer);
  1082. clif_scriptclose(sd, nd->bl.id);
  1083. }
  1084. /*==========================================
  1085. * NPC 1st call when clicking on npc
  1086. * Do specific action for NPC type (openshop, run scripts...)
  1087. *------------------------------------------*/
  1088. int npc_click(struct map_session_data* sd, struct npc_data* nd)
  1089. {
  1090. nullpo_retr(1, sd);
  1091. if (sd->npc_id != 0) {
  1092. ShowError("npc_click: npc_id != 0\n");
  1093. return 1;
  1094. }
  1095. if(!nd) return 1;
  1096. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  1097. return 1;
  1098. //Hidden/Disabled npc.
  1099. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  1100. return 1;
  1101. if (sd->state.block_action & PCBLOCK_NPCCLICK) {
  1102. clif_msg(sd, WORK_IN_PROGRESS);
  1103. return 1;
  1104. }
  1105. switch(nd->subtype) {
  1106. case NPCTYPE_SHOP:
  1107. clif_npcbuysell(sd,nd->bl.id);
  1108. break;
  1109. case NPCTYPE_CASHSHOP:
  1110. case NPCTYPE_ITEMSHOP:
  1111. case NPCTYPE_POINTSHOP:
  1112. clif_cashshop_show(sd,nd);
  1113. break;
  1114. case NPCTYPE_MARKETSHOP:
  1115. #if PACKETVER >= 20131223
  1116. {
  1117. unsigned short i;
  1118. for (i = 0; i < nd->u.shop.count; i++) {
  1119. if (nd->u.shop.shop_item[i].qty)
  1120. break;
  1121. }
  1122. if (i == nd->u.shop.count) {
  1123. clif_messagecolor(&sd->bl, color_table[COLOR_RED], msg_txt(sd, 534), false, SELF);
  1124. return false;
  1125. }
  1126. sd->npc_shopid = nd->bl.id;
  1127. clif_npc_market_open(sd, nd);
  1128. }
  1129. #endif
  1130. break;
  1131. case NPCTYPE_SCRIPT:
  1132. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  1133. break;
  1134. case NPCTYPE_TOMB:
  1135. run_tomb(sd,nd);
  1136. break;
  1137. }
  1138. return 0;
  1139. }
  1140. /*==========================================
  1141. *
  1142. *------------------------------------------*/
  1143. bool npc_scriptcont(struct map_session_data* sd, int id, bool closing){
  1144. struct block_list *target = map_id2bl(id);
  1145. nullpo_retr(true, sd);
  1146. if( id != sd->npc_id ){
  1147. TBL_NPC* nd_sd = (TBL_NPC*)map_id2bl(sd->npc_id);
  1148. TBL_NPC* nd = BL_CAST(BL_NPC, target);
  1149. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  1150. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  1151. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  1152. return true;
  1153. }
  1154. if(id != fake_nd->bl.id) { // Not item script
  1155. if ((npc_checknear(sd, target)) == NULL) {
  1156. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  1157. return true;
  1158. }
  1159. }
  1160. #ifdef SECURE_NPCTIMEOUT
  1161. sd->npc_idle_tick = gettick(); //Update the last NPC iteration
  1162. #endif
  1163. /**
  1164. * WPE can get to this point with a progressbar; we deny it.
  1165. **/
  1166. if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
  1167. return true;
  1168. if( sd->st == nullptr ){
  1169. return true;
  1170. }
  1171. if( closing ){
  1172. switch( sd->st->state ){
  1173. // close
  1174. case CLOSE:
  1175. sd->st->state = END;
  1176. break;
  1177. // close2
  1178. case STOP:
  1179. sd->st->state = RUN;
  1180. break;
  1181. default:
  1182. sd->st->state = END;
  1183. ShowError( "npc_scriptcont: unexpected state '%d' for closing call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1184. break;
  1185. }
  1186. }else{
  1187. switch( sd->st->state ){
  1188. // next
  1189. // progressbar
  1190. case STOP:
  1191. sd->st->state = RUN;
  1192. break;
  1193. // input
  1194. // menu
  1195. // select
  1196. case RERUNLINE:
  1197. // keep state as it is
  1198. break;
  1199. default:
  1200. sd->st->state = END;
  1201. ShowError( "npc_scriptcont: unexpected state '%d' for continue call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1202. break;
  1203. }
  1204. }
  1205. // Call this even, if it was set to end, because it will free the script state
  1206. run_script_main(sd->st);
  1207. return false;
  1208. }
  1209. /**
  1210. * Open the shop Buy or Sell list
  1211. * @param sd: Player data
  1212. * @param id: NPC ID
  1213. * @param type: 0 - Buy, 1 - Sell
  1214. * @return 0 on success or 1 on failure
  1215. */
  1216. int npc_buysellsel(struct map_session_data* sd, int id, int type)
  1217. {
  1218. struct npc_data *nd;
  1219. nullpo_retr(1, sd);
  1220. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  1221. return 1;
  1222. if (nd->subtype != NPCTYPE_SHOP) {
  1223. ShowError("no such shop npc : %d\n",id);
  1224. if (sd->npc_id == id)
  1225. sd->npc_id=0;
  1226. return 1;
  1227. }
  1228. if (nd->sc.option & OPTION_INVISIBLE) // can't buy if npc is not visible (hack?)
  1229. return 1;
  1230. sd->npc_shopid = id;
  1231. if (type == 0) {
  1232. clif_buylist(sd,nd);
  1233. } else {
  1234. clif_selllist(sd);
  1235. }
  1236. return 0;
  1237. }
  1238. /** Payment Process for NPCTYPE_CASHSHOP, NPCTYPE_ITEMSHOP, and NPCTYPE_POINTSHOP
  1239. * @param nd NPC Shop data
  1240. * @param price Price must be paid
  1241. * @param points Amount of secondary points that player requested
  1242. * @param sd Player data
  1243. * @return e_CASHSHOP_ACK
  1244. **/
  1245. static enum e_CASHSHOP_ACK npc_cashshop_process_payment(struct npc_data *nd, int price, int points, struct map_session_data *sd) {
  1246. int cost[2] = { 0, 0 };
  1247. npc_shop_currency_type(sd, nd, cost, false);
  1248. switch(nd->subtype) {
  1249. case NPCTYPE_CASHSHOP:
  1250. if (cost[1] < points || cost[0] < (price - points))
  1251. return ERROR_TYPE_MONEY;
  1252. if (pc_paycash(sd, price, points, LOG_TYPE_NPC) <= 0) {
  1253. return ERROR_TYPE_MONEY;
  1254. }
  1255. break;
  1256. case NPCTYPE_ITEMSHOP:
  1257. {
  1258. struct item_data *id = itemdb_exists(nd->u.shop.itemshop_nameid);
  1259. int delete_amount = price, i;
  1260. if (!id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  1261. ShowWarning("Failed to find sellitem %hu for itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1262. return ERROR_TYPE_PURCHASE_FAIL;
  1263. }
  1264. if (cost[1] < points || cost[0] < (price - points)) {
  1265. char output[CHAT_SIZE_MAX];
  1266. memset(output, '\0', sizeof(output));
  1267. sprintf(output, msg_txt(sd, 712), id->jname, id->nameid); // You do not have enough %s (%hu).
  1268. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  1269. return ERROR_TYPE_PURCHASE_FAIL;
  1270. }
  1271. for (i = 0; i < MAX_INVENTORY && delete_amount > 0; i++) {
  1272. struct item *it;
  1273. int amount = 0;
  1274. if (sd->inventory.u.items_inventory[i].nameid == 0 || sd->inventory_data[i] == NULL || !(it = &sd->inventory.u.items_inventory[i]) || it->nameid != nd->u.shop.itemshop_nameid)
  1275. continue;
  1276. if (!pc_can_sell_item(sd, it, nd->subtype))
  1277. continue;
  1278. amount = it->amount;
  1279. if (amount > delete_amount)
  1280. amount = delete_amount;
  1281. if (pc_delitem(sd, i, amount, 0, 0, LOG_TYPE_NPC)) {
  1282. ShowWarning("Failed to delete item %hu from '%s' at itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, sd->status.name, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1283. return ERROR_TYPE_PURCHASE_FAIL;
  1284. }
  1285. delete_amount -= amount;
  1286. }
  1287. if (delete_amount > 0) {
  1288. ShowError("Item %hu is not enough as payment at itemshop NPC '%s' (%s, %d, %d, AID=%d, CID=%d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.account_id, sd->status.char_id);
  1289. return ERROR_TYPE_PURCHASE_FAIL;
  1290. }
  1291. }
  1292. break;
  1293. case NPCTYPE_POINTSHOP:
  1294. {
  1295. char output[CHAT_SIZE_MAX];
  1296. memset(output, '\0', sizeof(output));
  1297. if (cost[1] < points || cost[0] < (price - points)) {
  1298. sprintf(output, msg_txt(sd, 713), nd->u.shop.pointshop_str); // You do not have enough '%s'.
  1299. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  1300. return ERROR_TYPE_PURCHASE_FAIL;
  1301. }
  1302. pc_setreg2(sd, nd->u.shop.pointshop_str, cost[0] - (price - points));
  1303. sprintf(output, msg_txt(sd, 716), nd->u.shop.pointshop_str, cost[0] - (price - points)); // Your '%s' is now: %d
  1304. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  1305. }
  1306. break;
  1307. }
  1308. return ERROR_TYPE_NONE;
  1309. }
  1310. /**
  1311. * Cash Shop Buy List for clients 2010-11-16 and newer
  1312. * @param sd: Player data
  1313. * @param points: Secondary point
  1314. * @param count: Amount of items to purchase
  1315. * @param item_list: List of items to purchase
  1316. * @return clif_cashshop_ack value to display
  1317. */
  1318. int npc_cashshop_buylist(struct map_session_data *sd, int points, int count, unsigned short* item_list)
  1319. {
  1320. int i, j, amount, new_, w, vt;
  1321. unsigned short nameid;
  1322. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1323. enum e_CASHSHOP_ACK res;
  1324. item_data *id;
  1325. if( !nd || ( nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP ) )
  1326. return ERROR_TYPE_NPC;
  1327. if( sd->state.trading )
  1328. return ERROR_TYPE_EXCHANGE;
  1329. new_ = 0;
  1330. w = 0;
  1331. vt = 0; // Global Value
  1332. // Validating Process ----------------------------------------------------
  1333. for( i = 0; i < count; i++ )
  1334. {
  1335. nameid = item_list[i*2+1];
  1336. amount = item_list[i*2+0];
  1337. id = itemdb_exists(nameid);
  1338. if( !id || amount <= 0 )
  1339. return ERROR_TYPE_ITEM_ID;
  1340. ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[j].nameid) == nameid);
  1341. if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
  1342. return ERROR_TYPE_ITEM_ID;
  1343. nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  1344. if( !itemdb_isstackable2(id) && amount > 1 )
  1345. {
  1346. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1347. amount = item_list[i*2+0] = 1;
  1348. }
  1349. switch( pc_checkadditem(sd,nameid,amount) )
  1350. {
  1351. case CHKADDITEM_NEW:
  1352. new_ += id->inventorySlotNeeded(amount);
  1353. break;
  1354. case CHKADDITEM_OVERAMOUNT:
  1355. return ERROR_TYPE_INVENTORY_WEIGHT;
  1356. }
  1357. vt += nd->u.shop.shop_item[j].value * amount;
  1358. w += itemdb_weight(nameid) * amount;
  1359. }
  1360. if( w + sd->weight > sd->max_weight )
  1361. return ERROR_TYPE_INVENTORY_WEIGHT;
  1362. if( pc_inventoryblank(sd) < new_ )
  1363. return ERROR_TYPE_INVENTORY_WEIGHT;
  1364. if( points > vt ) points = vt;
  1365. if ((res = npc_cashshop_process_payment(nd, vt, points, sd)) != ERROR_TYPE_NONE)
  1366. return res;
  1367. // Delivery Process ----------------------------------------------------
  1368. for( i = 0; i < count; i++ ) {
  1369. nameid = item_list[i*2+1];
  1370. amount = item_list[i*2+0];
  1371. if( !pet_create_egg(sd,nameid) ) {
  1372. struct item item_tmp;
  1373. unsigned short get_amt = amount;
  1374. memset(&item_tmp, 0, sizeof(item_tmp));
  1375. item_tmp.nameid = nameid;
  1376. item_tmp.identify = 1;
  1377. if ((itemdb_search(nameid))->flag.guid)
  1378. get_amt = 1;
  1379. for (j = 0; j < amount; j += get_amt)
  1380. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  1381. }
  1382. }
  1383. return ERROR_TYPE_NONE;
  1384. }
  1385. /**
  1386. * Returns the shop currency type
  1387. * @param sd: Player data
  1388. * @param nd: NPC data
  1389. * @param cost: Reference to cost variable
  1390. * @param display: Display cost type to player?
  1391. */
  1392. void npc_shop_currency_type(struct map_session_data *sd, struct npc_data *nd, int cost[2], bool display)
  1393. {
  1394. nullpo_retv(sd);
  1395. if (!nd) { // Assume it's Cash Shop through the button
  1396. cost[0] = sd->cashPoints;
  1397. cost[1] = sd->kafraPoints;
  1398. return;
  1399. }
  1400. switch(nd->subtype) {
  1401. case NPCTYPE_CASHSHOP:
  1402. cost[0] = sd->cashPoints;
  1403. cost[1] = sd->kafraPoints;
  1404. break;
  1405. case NPCTYPE_ITEMSHOP:
  1406. {
  1407. int total = 0, i;
  1408. struct item_data *id = itemdb_exists(nd->u.shop.itemshop_nameid);
  1409. if (id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  1410. if (display) {
  1411. char output[CHAT_SIZE_MAX];
  1412. memset(output, '\0', sizeof(output));
  1413. sprintf(output, msg_txt(sd, 714), id->jname, id->nameid); // Item Shop List: %s (%hu)
  1414. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  1415. }
  1416. for (i = 0; i < MAX_INVENTORY; i++) {
  1417. if (sd->inventory.u.items_inventory[i].amount > 0 && sd->inventory.u.items_inventory[i].nameid == id->nameid && pc_can_sell_item(sd, &sd->inventory.u.items_inventory[i], nd->subtype))
  1418. total += sd->inventory.u.items_inventory[i].amount;
  1419. }
  1420. }
  1421. cost[0] = total;
  1422. }
  1423. break;
  1424. case NPCTYPE_POINTSHOP:
  1425. if (display) {
  1426. char output[CHAT_SIZE_MAX];
  1427. memset(output, '\0', sizeof(output));
  1428. sprintf(output, msg_txt(sd, 715), nd->u.shop.pointshop_str); // Point Shop List: '%s'
  1429. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  1430. }
  1431. cost[0] = static_cast<int>(pc_readreg2(sd, nd->u.shop.pointshop_str));
  1432. break;
  1433. }
  1434. }
  1435. /**
  1436. * Cash Shop Buy List for clients 2010-11-15 and older
  1437. * @param sd: Player data
  1438. * @param nameid: Item to purchase
  1439. * @param amount: Amount of items to purchase
  1440. * @param points: Cost of total items
  1441. * @return clif_cashshop_ack value to display
  1442. */
  1443. int npc_cashshop_buy(struct map_session_data *sd, unsigned short nameid, int amount, int points)
  1444. {
  1445. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1446. struct item_data *item;
  1447. int i, price, w;
  1448. enum e_CASHSHOP_ACK res;
  1449. if( amount <= 0 )
  1450. return ERROR_TYPE_ITEM_ID;
  1451. if( points < 0 )
  1452. return ERROR_TYPE_MONEY;
  1453. if( !nd || (nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP) )
  1454. return ERROR_TYPE_NPC;
  1455. if( sd->state.trading )
  1456. return ERROR_TYPE_EXCHANGE;
  1457. if( (item = itemdb_exists(nameid)) == NULL )
  1458. return ERROR_TYPE_ITEM_ID; // Invalid Item
  1459. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[i].nameid) == nameid);
  1460. if( i == nd->u.shop.count )
  1461. return ERROR_TYPE_ITEM_ID;
  1462. if( nd->u.shop.shop_item[i].value <= 0 )
  1463. return ERROR_TYPE_ITEM_ID;
  1464. nameid = nd->u.shop.shop_item[i].nameid; //item_avail replacement
  1465. if(!itemdb_isstackable2(item) && amount > 1)
  1466. {
  1467. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
  1468. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1469. amount = 1;
  1470. }
  1471. switch( pc_checkadditem(sd, nameid, amount) )
  1472. {
  1473. case CHKADDITEM_NEW:
  1474. if( pc_inventoryblank(sd) < item->inventorySlotNeeded(amount) )
  1475. return ERROR_TYPE_INVENTORY_WEIGHT;
  1476. break;
  1477. case CHKADDITEM_OVERAMOUNT:
  1478. return ERROR_TYPE_INVENTORY_WEIGHT;
  1479. }
  1480. w = item->weight * amount;
  1481. if( w + sd->weight > sd->max_weight )
  1482. return ERROR_TYPE_INVENTORY_WEIGHT;
  1483. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  1484. {
  1485. ShowWarning("npc_cashshop_buy: Item '%s' (%hu) price overflow attempt!\n", item->name, nameid);
  1486. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n",
  1487. nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.name, sd->status.account_id, sd->status.char_id, nd->u.shop.shop_item[i].value, amount);
  1488. return ERROR_TYPE_ITEM_ID;
  1489. }
  1490. price = nd->u.shop.shop_item[i].value * amount;
  1491. if( points > price )
  1492. points = price;
  1493. if ((res = npc_cashshop_process_payment(nd, price, points, sd)) != ERROR_TYPE_NONE)
  1494. return res;
  1495. if( !pet_create_egg(sd, nameid) ) {
  1496. struct item item_tmp;
  1497. unsigned short get_amt = amount, j;
  1498. memset(&item_tmp, 0, sizeof(item_tmp));
  1499. item_tmp.nameid = nameid;
  1500. item_tmp.identify = 1;
  1501. if (item->flag.guid)
  1502. get_amt = 1;
  1503. for (j = 0; j < amount; j += get_amt)
  1504. pc_additem(sd,&item_tmp, get_amt, LOG_TYPE_NPC);
  1505. }
  1506. return ERROR_TYPE_NONE;
  1507. }
  1508. /**
  1509. * NPC buylist for script-controlled shops
  1510. * @param sd: Player who bought
  1511. * @param n: Number of items
  1512. * @param item_list: List of items
  1513. * @param nd: Attached NPC
  1514. */
  1515. static int npc_buylist_sub(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list, struct npc_data* nd) {
  1516. char npc_ev[EVENT_NAME_LENGTH];
  1517. int i, key_nameid = 0, key_amount = 0;
  1518. // discard old contents
  1519. script_cleararray_pc( sd, "@bought_nameid" );
  1520. script_cleararray_pc( sd, "@bought_quantity" );
  1521. // save list of bought items
  1522. for (i = 0; i < n; i++) {
  1523. script_setarray_pc( sd, "@bought_nameid", i, item_list[i].nameid, &key_nameid );
  1524. script_setarray_pc( sd, "@bought_quantity", i, item_list[i].qty, &key_amount );
  1525. }
  1526. // invoke event
  1527. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onbuy_event_name);
  1528. npc_event(sd, npc_ev, 0);
  1529. return 0;
  1530. }
  1531. /**
  1532. * Shop buylist that the player is attempting to purchase
  1533. * @param sd: Player who attempt to buy
  1534. * @param n: Number of items
  1535. * @param item_list: List of items
  1536. * @return result code for clif_parse_NpcBuyListSend/clif_npc_market_purchase_ack
  1537. */
  1538. uint8 npc_buylist(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list) {
  1539. struct npc_data* nd;
  1540. struct npc_item_list *shop = NULL;
  1541. double z;
  1542. int i,j,k,w,skill,new_;
  1543. uint8 market_index[MAX_INVENTORY];
  1544. nullpo_retr(3, sd);
  1545. nullpo_retr(3, item_list);
  1546. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  1547. if( nd == NULL )
  1548. return 3;
  1549. if( nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_MARKETSHOP )
  1550. return 3;
  1551. if (!item_list || !n)
  1552. return 3;
  1553. z = 0;
  1554. w = 0;
  1555. new_ = 0;
  1556. shop = nd->u.shop.shop_item;
  1557. memset(market_index, 0, sizeof(market_index));
  1558. // process entries in buy list, one by one
  1559. for( i = 0; i < n; ++i ) {
  1560. unsigned short nameid, amount;
  1561. int value;
  1562. item_data *id;
  1563. // find this entry in the shop's sell list
  1564. ARR_FIND( 0, nd->u.shop.count, j,
  1565. item_list[i].nameid == shop[j].nameid || //Normal items
  1566. item_list[i].nameid == itemdb_viewid(shop[j].nameid) //item_avail replacement
  1567. );
  1568. if( j == nd->u.shop.count )
  1569. return 3; // no such item in shop
  1570. #if PACKETVER >= 20131223
  1571. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  1572. if (item_list[i].qty > shop[j].qty)
  1573. return 3;
  1574. market_index[i] = j;
  1575. }
  1576. #endif
  1577. amount = item_list[i].qty;
  1578. nameid = item_list[i].nameid = shop[j].nameid; //item_avail replacement
  1579. value = shop[j].value;
  1580. id = itemdb_exists(nameid);
  1581. if( !id )
  1582. return 3; // item no longer in itemdb
  1583. if( !itemdb_isstackable2(id) && amount > 1 ) { //Exploit? You can't buy more than 1 of equipment types o.O
  1584. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
  1585. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1586. amount = item_list[i].qty = 1;
  1587. }
  1588. if( nd->master_nd ) { // Script-controlled shops decide by themselves, what can be bought and for what price.
  1589. continue;
  1590. }
  1591. switch( pc_checkadditem(sd,nameid,amount) ) {
  1592. case CHKADDITEM_EXIST:
  1593. break;
  1594. case CHKADDITEM_NEW:
  1595. new_ += id->inventorySlotNeeded(amount);
  1596. break;
  1597. case CHKADDITEM_OVERAMOUNT:
  1598. return 2;
  1599. }
  1600. if (npc_shop_discount(nd))
  1601. value = pc_modifybuyvalue(sd,value);
  1602. z += (double)value * amount;
  1603. w += itemdb_weight(nameid) * amount;
  1604. }
  1605. if (nd->master_nd) //Script-based shops.
  1606. return npc_buylist_sub(sd,n,item_list,nd->master_nd);
  1607. if (z > (double)sd->status.zeny)
  1608. return 1; // Not enough Zeny
  1609. if( w + sd->weight > sd->max_weight )
  1610. return 2; // Too heavy
  1611. if( pc_inventoryblank(sd) < new_ )
  1612. return 3; // Not enough space to store items
  1613. pc_payzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  1614. for( i = 0; i < n; ++i ) {
  1615. unsigned short nameid = item_list[i].nameid;
  1616. unsigned short amount = item_list[i].qty;
  1617. #if PACKETVER >= 20131223
  1618. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  1619. j = market_index[i];
  1620. if (amount > shop[j].qty)
  1621. return 1;
  1622. shop[j].qty -= amount;
  1623. npc_market_tosql(nd->exname, &shop[j]);
  1624. }
  1625. #endif
  1626. if (itemdb_type(nameid) == IT_PETEGG)
  1627. pet_create_egg(sd, nameid);
  1628. else {
  1629. unsigned short get_amt = amount;
  1630. if ((itemdb_search(nameid))->flag.guid)
  1631. get_amt = 1;
  1632. for (k = 0; k < amount; k += get_amt) {
  1633. struct item item_tmp;
  1634. memset(&item_tmp, 0, sizeof(item_tmp));
  1635. item_tmp.nameid = nameid;
  1636. item_tmp.identify = 1;
  1637. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  1638. }
  1639. }
  1640. }
  1641. // custom merchant shop exp bonus
  1642. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 ) {
  1643. uint16 sk_idx = skill_get_index(MC_DISCOUNT);
  1644. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1645. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  1646. if( skill > 0 ) {
  1647. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1648. if( z < 1 )
  1649. z = 1;
  1650. pc_gainexp(sd,NULL,0,(int)z, 0);
  1651. }
  1652. }
  1653. return 0;
  1654. }
  1655. /// npc_selllist for script-controlled shops
  1656. static int npc_selllist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1657. {
  1658. char npc_ev[EVENT_NAME_LENGTH];
  1659. char card_slot[NAME_LENGTH];
  1660. char option_id[NAME_LENGTH], option_val[NAME_LENGTH], option_param[NAME_LENGTH];
  1661. int i, j;
  1662. int key_nameid = 0;
  1663. int key_amount = 0;
  1664. int key_refine = 0;
  1665. int key_attribute = 0;
  1666. int key_identify = 0;
  1667. int key_card[MAX_SLOTS];
  1668. int key_option_id[MAX_ITEM_RDM_OPT], key_option_val[MAX_ITEM_RDM_OPT], key_option_param[MAX_ITEM_RDM_OPT];
  1669. // discard old contents
  1670. script_cleararray_pc( sd, "@sold_nameid" );
  1671. script_cleararray_pc( sd, "@sold_quantity" );
  1672. script_cleararray_pc( sd, "@sold_refine" );
  1673. script_cleararray_pc( sd, "@sold_attribute" );
  1674. script_cleararray_pc( sd, "@sold_identify" );
  1675. for( j = 0; j < MAX_SLOTS; j++ )
  1676. {// clear each of the card slot entries
  1677. key_card[j] = 0;
  1678. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1679. script_cleararray_pc( sd, card_slot );
  1680. }
  1681. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Clear each of the item option entries
  1682. key_option_id[j] = key_option_val[j] = key_option_param[j] = 0;
  1683. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  1684. script_cleararray_pc( sd, option_id );
  1685. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  1686. script_cleararray_pc( sd, option_val );
  1687. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  1688. script_cleararray_pc( sd, option_param );
  1689. }
  1690. // save list of to be sold items
  1691. for( i = 0; i < n; i++ )
  1692. {
  1693. int idx = item_list[i * 2] - 2;
  1694. script_setarray_pc( sd, "@sold_nameid", i, sd->inventory.u.items_inventory[idx].nameid, &key_nameid );
  1695. script_setarray_pc( sd, "@sold_quantity", i, item_list[i*2+1], &key_amount );
  1696. if( itemdb_isequip(sd->inventory.u.items_inventory[idx].nameid) )
  1697. {// process equipment based information into the arrays
  1698. script_setarray_pc( sd, "@sold_refine", i, sd->inventory.u.items_inventory[idx].refine, &key_refine );
  1699. script_setarray_pc( sd, "@sold_attribute", i, sd->inventory.u.items_inventory[idx].attribute, &key_attribute );
  1700. script_setarray_pc( sd, "@sold_identify", i, sd->inventory.u.items_inventory[idx].identify, &key_identify );
  1701. for( j = 0; j < MAX_SLOTS; j++ )
  1702. {// store each of the cards from the equipment in the array
  1703. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1704. script_setarray_pc( sd, card_slot, i, sd->inventory.u.items_inventory[idx].card[j], &key_card[j] );
  1705. }
  1706. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Store each of the item options in the array
  1707. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  1708. script_setarray_pc( sd, option_id, i, sd->inventory.u.items_inventory[idx].option[j].id, &key_option_id[j] );
  1709. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  1710. script_setarray_pc( sd, option_val, i, sd->inventory.u.items_inventory[idx].option[j].value, &key_option_val[j] );
  1711. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  1712. script_setarray_pc( sd, option_param, i, sd->inventory.u.items_inventory[idx].option[j].param, &key_option_param[j] );
  1713. }
  1714. }
  1715. }
  1716. // invoke event
  1717. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onsell_event_name);
  1718. npc_event(sd, npc_ev, 0);
  1719. return 0;
  1720. }
  1721. /// Player item selling to npc shop.
  1722. ///
  1723. /// @param item_list 'n' pairs <index,amount>
  1724. /// @return result code for clif_parse_NpcSellListSend
  1725. uint8 npc_selllist(struct map_session_data* sd, int n, unsigned short *item_list)
  1726. {
  1727. double z;
  1728. int i,skill;
  1729. struct npc_data *nd;
  1730. nullpo_retr(1, sd);
  1731. nullpo_retr(1, item_list);
  1732. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL || nd->subtype != NPCTYPE_SHOP )
  1733. {
  1734. return 1;
  1735. }
  1736. z = 0;
  1737. // verify the sell list
  1738. for( i = 0; i < n; i++ )
  1739. {
  1740. unsigned short nameid;
  1741. int amount, idx, value;
  1742. idx = item_list[i*2]-2;
  1743. amount = item_list[i*2+1];
  1744. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  1745. {
  1746. return 1;
  1747. }
  1748. nameid = sd->inventory.u.items_inventory[idx].nameid;
  1749. if( !nameid || !sd->inventory_data[idx] || sd->inventory.u.items_inventory[idx].amount < amount )
  1750. {
  1751. return 1;
  1752. }
  1753. if( nd->master_nd )
  1754. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  1755. continue;
  1756. }
  1757. if (!pc_can_sell_item(sd, &sd->inventory.u.items_inventory[idx], nd->subtype)) {
  1758. return 1; // In official server, this illegal attempt the player will be disconnected
  1759. }
  1760. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  1761. z+= (double)value*amount;
  1762. }
  1763. if( nd->master_nd )
  1764. {// Script-controlled shops
  1765. return npc_selllist_sub(sd, n, item_list, nd->master_nd);
  1766. }
  1767. // delete items
  1768. for( i = 0; i < n; i++ )
  1769. {
  1770. int amount, idx;
  1771. idx = item_list[i*2]-2;
  1772. amount = item_list[i*2+1];
  1773. // Forged packet, we do not care if he loses items
  1774. if( sd->inventory_data[idx] == nullptr ){
  1775. return 1;
  1776. }
  1777. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->inventory.u.items_inventory[idx].card[0] == CARD0_PET )
  1778. {
  1779. if( pet_db_search(sd->inventory.u.items_inventory[idx].nameid, PET_EGG) )
  1780. {
  1781. intif_delete_petdata(MakeDWord(sd->inventory.u.items_inventory[idx].card[1], sd->inventory.u.items_inventory[idx].card[2]));
  1782. }
  1783. }
  1784. pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC);
  1785. }
  1786. if( z > MAX_ZENY )
  1787. z = MAX_ZENY;
  1788. pc_getzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  1789. // custom merchant shop exp bonus
  1790. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  1791. {
  1792. uint16 sk_idx = skill_get_index(MC_OVERCHARGE);
  1793. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1794. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  1795. if( skill > 0 )
  1796. {
  1797. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1798. if( z < 1 )
  1799. z = 1;
  1800. pc_gainexp(sd, NULL, 0, (int)z, 0);
  1801. }
  1802. }
  1803. return 0;
  1804. }
  1805. //Atempt to remove an npc from a map
  1806. //This doesn't remove it from map_db
  1807. int npc_remove_map(struct npc_data* nd)
  1808. {
  1809. int16 i;
  1810. nullpo_retr(1, nd);
  1811. if(nd->bl.prev == NULL || nd->bl.m < 0)
  1812. return 1; //Not assigned to a map.
  1813. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  1814. if (nd->subtype == NPCTYPE_SCRIPT)
  1815. skill_clear_unitgroup(&nd->bl);
  1816. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  1817. npc_unsetcells(nd);
  1818. map_delblock(&nd->bl);
  1819. //Remove npc from map[].npc list. [Skotlex]
  1820. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  1821. if( i == mapdata->npc_num ) return 2; //failed to find it?
  1822. mapdata->npc_num--;
  1823. if (i >= mapdata->npc_num_area)
  1824. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num ];
  1825. else if (i >= mapdata->npc_num_warp) {
  1826. mapdata->npc_num_area--;
  1827. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_area ];
  1828. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  1829. }
  1830. else {
  1831. mapdata->npc_num_warp--;
  1832. mapdata->npc_num_area--;
  1833. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_warp ];
  1834. mapdata->npc[ mapdata->npc_num_warp ] = mapdata->npc[ mapdata->npc_num_area ];
  1835. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  1836. }
  1837. mapdata->npc[ mapdata->npc_num ] = NULL;
  1838. return 0;
  1839. }
  1840. /**
  1841. * @see DBApply
  1842. */
  1843. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  1844. {
  1845. struct event_data* ev = (struct event_data*)db_data2ptr(data);
  1846. char* npcname = va_arg(ap, char *);
  1847. if(strcmp(ev->nd->exname,npcname)==0){
  1848. db_remove(ev_db, key);
  1849. return 1;
  1850. }
  1851. return 0;
  1852. }
  1853. //Chk if npc matches src_id, then unload.
  1854. //Sub-function used to find duplicates.
  1855. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  1856. {
  1857. int src_id;
  1858. src_id = va_arg(args, int);
  1859. if (nd->src_id == src_id)
  1860. npc_unload(nd, true);
  1861. return 0;
  1862. }
  1863. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  1864. void npc_unload_duplicates(struct npc_data* nd)
  1865. {
  1866. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  1867. }
  1868. //Removes an npc from map and db.
  1869. //Single is to free name (for duplicates).
  1870. int npc_unload(struct npc_data* nd, bool single) {
  1871. nullpo_ret(nd);
  1872. status_change_clear(&nd->bl, 1);
  1873. npc_remove_map(nd);
  1874. map_deliddb(&nd->bl);
  1875. if( single )
  1876. strdb_remove(npcname_db, nd->exname);
  1877. if (nd->chat_id) // remove npc chatroom object and kick users
  1878. chat_deletenpcchat(nd);
  1879. #ifdef PCRE_SUPPORT
  1880. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  1881. #endif
  1882. if( single && nd->path ) {
  1883. struct npc_path_data* npd = NULL;
  1884. if( nd->path ) {
  1885. npd = (struct npc_path_data*)strdb_get(npc_path_db, nd->path);
  1886. }
  1887. if( npd && --npd->references == 0 ) {
  1888. strdb_remove(npc_path_db, nd->path);/* remove from db */
  1889. aFree(nd->path);/* remove now that no other instances exist */
  1890. if (npd == npc_last_npd) {
  1891. npc_last_npd = NULL;
  1892. npc_last_ref = NULL;
  1893. npc_last_path = NULL;
  1894. }
  1895. }
  1896. }
  1897. if( single && nd->bl.m != -1 )
  1898. map_remove_questinfo(nd->bl.m, nd);
  1899. if( (nd->subtype == NPCTYPE_SHOP || nd->subtype == NPCTYPE_CASHSHOP || nd->subtype == NPCTYPE_ITEMSHOP || nd->subtype == NPCTYPE_POINTSHOP || nd->subtype == NPCTYPE_MARKETSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  1900. aFree(nd->u.shop.shop_item);
  1901. else if( nd->subtype == NPCTYPE_SCRIPT ) {
  1902. struct s_mapiterator* iter;
  1903. struct block_list* bl;
  1904. if( single )
  1905. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  1906. iter = mapit_geteachpc();
  1907. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  1908. struct map_session_data *sd = ((TBL_PC*)bl);
  1909. if( sd && sd->npc_timer_id != INVALID_TIMER ) {
  1910. const struct TimerData *td = get_timer(sd->npc_timer_id);
  1911. if( td && td->id != nd->bl.id )
  1912. continue;
  1913. if( td && td->data )
  1914. ers_free(timer_event_ers, (void*)td->data);
  1915. delete_timer(sd->npc_timer_id, npc_timerevent);
  1916. sd->npc_timer_id = INVALID_TIMER;
  1917. }
  1918. }
  1919. mapit_free(iter);
  1920. if (nd->u.scr.timerid != INVALID_TIMER) {
  1921. const struct TimerData *td;
  1922. td = get_timer(nd->u.scr.timerid);
  1923. if (td && td->data)
  1924. ers_free(timer_event_ers, (void*)td->data);
  1925. delete_timer(nd->u.scr.timerid, npc_timerevent);
  1926. }
  1927. if (nd->u.scr.timer_event)
  1928. aFree(nd->u.scr.timer_event);
  1929. if (nd->src_id == 0) {
  1930. if(nd->u.scr.script) {
  1931. script_free_code(nd->u.scr.script);
  1932. nd->u.scr.script = NULL;
  1933. }
  1934. if (nd->u.scr.label_list) {
  1935. aFree(nd->u.scr.label_list);
  1936. nd->u.scr.label_list = NULL;
  1937. nd->u.scr.label_list_num = 0;
  1938. }
  1939. }
  1940. if( nd->u.scr.guild_id )
  1941. guild_flag_remove(nd);
  1942. if( nd->sc_display_count ){
  1943. unsigned char i;
  1944. for( i = 0; i < nd->sc_display_count; i++ )
  1945. ers_free(npc_sc_display_ers, nd->sc_display[i]);
  1946. nd->sc_display_count = 0;
  1947. aFree(nd->sc_display);
  1948. nd->sc_display = NULL;
  1949. }
  1950. }
  1951. script_stop_sleeptimers(nd->bl.id);
  1952. aFree(nd);
  1953. return 0;
  1954. }
  1955. //
  1956. // NPC Source Files
  1957. //
  1958. /// Clears the npc source file list
  1959. static void npc_clearsrcfile(void)
  1960. {
  1961. struct npc_src_list* file = npc_src_files;
  1962. while( file != NULL ) {
  1963. struct npc_src_list* file_tofree = file;
  1964. file = file->next;
  1965. aFree(file_tofree);
  1966. }
  1967. npc_src_files = NULL;
  1968. }
  1969. /**
  1970. * Adds a npc source file (or removes all)
  1971. * @param name : file to add
  1972. * @param loadscript : flag to parse the script immediately after adding the src file
  1973. * @return 0=error, 1=sucess
  1974. */
  1975. int npc_addsrcfile(const char* name, bool loadscript)
  1976. {
  1977. struct npc_src_list* file;
  1978. struct npc_src_list* file_prev = NULL;
  1979. if( strcmpi(name, "clear") == 0 )
  1980. {
  1981. npc_clearsrcfile();
  1982. return 1;
  1983. }
  1984. //Check if this is not a file
  1985. if(check_filepath(name)!=2){
  1986. ShowError("npc_addsrcfile: Can't find source file \"%s\"\n", name );
  1987. return 0;
  1988. }
  1989. // prevent multiple insert of source files
  1990. file = npc_src_files;
  1991. while( file != NULL )
  1992. {
  1993. if( strcmp(name, file->name) == 0 )
  1994. return 0;// found the file, no need to insert it again
  1995. file_prev = file;
  1996. file = file->next;
  1997. }
  1998. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  1999. file->next = NULL;
  2000. safestrncpy(file->name, name, strlen(name) + 1);
  2001. if( file_prev == NULL )
  2002. npc_src_files = file;
  2003. else
  2004. file_prev->next = file;
  2005. if (loadscript)
  2006. return npc_parsesrcfile(file->name, true);
  2007. return 1;
  2008. }
  2009. /// Removes a npc source file (or all)
  2010. void npc_delsrcfile(const char* name)
  2011. {
  2012. struct npc_src_list* file = npc_src_files;
  2013. struct npc_src_list* file_prev = NULL;
  2014. if( strcmpi(name, "all") == 0 )
  2015. {
  2016. npc_clearsrcfile();
  2017. return;
  2018. }
  2019. while( file != NULL )
  2020. {
  2021. if( strcmp(file->name, name) == 0 )
  2022. {
  2023. if( npc_src_files == file )
  2024. npc_src_files = file->next;
  2025. else
  2026. file_prev->next = file->next;
  2027. aFree(file);
  2028. break;
  2029. }
  2030. file_prev = file;
  2031. file = file->next;
  2032. }
  2033. }
  2034. /// Parses and sets the name and exname of a npc.
  2035. /// Assumes that m, x and y are already set in nd.
  2036. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  2037. {
  2038. const char* p;
  2039. struct npc_data* dnd;// duplicate npc
  2040. char newname[NPC_NAME_LENGTH+1];
  2041. // parse name
  2042. p = strstr(name,"::");
  2043. if( p ) { // <Display name>::<Unique name>
  2044. size_t len = p-name;
  2045. if( len > NPC_NAME_LENGTH ) {
  2046. ShowWarning("npc_parsename: Display name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2047. safestrncpy(nd->name, name, sizeof(nd->name));
  2048. } else {
  2049. memcpy(nd->name, name, len);
  2050. memset(nd->name+len, 0, sizeof(nd->name)-len);
  2051. }
  2052. len = strlen(p+2);
  2053. if( len > NPC_NAME_LENGTH )
  2054. ShowWarning("npc_parsename: Unique name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2055. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  2056. } else {// <Display name>
  2057. size_t len = strlen(name);
  2058. if( len > NPC_NAME_LENGTH )
  2059. ShowWarning("npc_parsename: Name '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2060. safestrncpy(nd->name, name, sizeof(nd->name));
  2061. safestrncpy(nd->exname, name, sizeof(nd->exname));
  2062. }
  2063. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL ) {// invalid
  2064. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  2065. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  2066. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  2067. }
  2068. if( (dnd=npc_name2id(nd->exname)) != NULL ) {// duplicate unique name, generate new one
  2069. char this_mapname[MAP_NAME_LENGTH_EXT];
  2070. char other_mapname[MAP_NAME_LENGTH_EXT];
  2071. int i = 0;
  2072. do {
  2073. ++i;
  2074. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  2075. } while( npc_name2id(newname) != NULL );
  2076. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(nd->bl.m)->index)));
  2077. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(dnd->bl.m)->index)));
  2078. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  2079. ShowDebug("this npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", nd->name, nd->exname, this_mapname, nd->bl.x, nd->bl.y);
  2080. ShowDebug("other npc in '%s' :\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n",dnd->path, dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  2081. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  2082. }
  2083. if( npc_last_path != filepath ) {
  2084. struct npc_path_data * npd = NULL;
  2085. if( !(npd = (struct npc_path_data *)strdb_get(npc_path_db,filepath) ) ) {
  2086. CREATE(npd, struct npc_path_data, 1);
  2087. strdb_put(npc_path_db, filepath, npd);
  2088. CREATE(npd->path, char, strlen(filepath)+1);
  2089. safestrncpy(npd->path, filepath, strlen(filepath)+1);
  2090. npd->references = 0;
  2091. }
  2092. nd->path = npd->path;
  2093. npd->references++;
  2094. npc_last_npd = npd;
  2095. npc_last_ref = npd->path;
  2096. npc_last_path = (char*) filepath;
  2097. } else {
  2098. nd->path = npc_last_ref;
  2099. if( npc_last_npd )
  2100. npc_last_npd->references++;
  2101. }
  2102. }
  2103. /**
  2104. * Parses NPC view.
  2105. * Support for using Constants in place of NPC View IDs.
  2106. */
  2107. int npc_parseview(const char* w4, const char* start, const char* buffer, const char* filepath) {
  2108. int i = 0;
  2109. char viewid[1024]; // Max size of name from const.txt, see read_constdb.
  2110. // Extract view ID / constant
  2111. while (w4[i] != '\0') {
  2112. if (ISSPACE(w4[i]) || w4[i] == '/' || w4[i] == ',')
  2113. break;
  2114. i++;
  2115. }
  2116. safestrncpy(viewid, w4, i+=1);
  2117. char *pid;
  2118. int val = strtol(viewid, &pid, 0);
  2119. // Check if view id is not an ID (only numbers).
  2120. if (pid != nullptr && *pid != '\0') {
  2121. int64 val_tmp;
  2122. // Check if constant exists and get its value.
  2123. if(!script_get_constant(viewid, &val_tmp)) {
  2124. ShowWarning("npc_parseview: Invalid NPC constant '%s' specified in file '%s', line'%d'. Defaulting to INVISIBLE. \n", viewid, filepath, strline(buffer,start-buffer));
  2125. val = JT_INVISIBLE;
  2126. } else
  2127. val = static_cast<int>(val_tmp);
  2128. }
  2129. return val;
  2130. }
  2131. /**
  2132. * Create a bare NPC object.
  2133. * @param m: Map ID
  2134. * @param x: X location
  2135. * @param y: Y location
  2136. * @return npc_data
  2137. */
  2138. struct npc_data *npc_create_npc(int16 m, int16 x, int16 y){
  2139. struct npc_data *nd = nullptr;
  2140. CREATE(nd, struct npc_data, 1);
  2141. nd->bl.id = npc_get_new_npc_id();
  2142. nd->bl.prev = nd->bl.next = nullptr;
  2143. nd->bl.m = m;
  2144. nd->bl.x = x;
  2145. nd->bl.y = y;
  2146. nd->sc_display = nullptr;
  2147. nd->sc_display_count = 0;
  2148. nd->progressbar.timeout = 0;
  2149. nd->vd = npc_viewdb[0]; // Default to JT_INVISIBLE
  2150. return nd;
  2151. }
  2152. /**
  2153. * Add then display an npc warp on map
  2154. * @param name : warp unique name
  2155. * @param from_mapid : mapid to warp from
  2156. * @param from_x : x coordinate of warp
  2157. * @param from_y : y coordinate of warp
  2158. * @param xs : x lenght of warp (for trigger activation)
  2159. * @param ys : y lenght of warp (for trigger activation)
  2160. * @param to_mapindex : mapid to warp to
  2161. * @param to_x : x coordinate to warp to
  2162. * @param to_y : y coordinate to warp to
  2163. * @return NULL:failed creation, npc_data* new warp
  2164. */
  2165. struct npc_data* npc_add_warp(char* name, short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  2166. {
  2167. int i, flag = 0;
  2168. struct npc_data *nd;
  2169. nd = npc_create_npc(from_mapid, from_x, from_y);
  2170. safestrncpy(nd->exname, name, ARRAYLENGTH(nd->exname));
  2171. if (npc_name2id(nd->exname) != NULL)
  2172. flag = 1;
  2173. if (flag == 1)
  2174. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  2175. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  2176. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  2177. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  2178. if( battle_config.warp_point_debug )
  2179. nd->class_ = JT_GUILD_FLAG;
  2180. else
  2181. nd->class_ = JT_WARPNPC;
  2182. nd->speed = 200;
  2183. nd->u.warp.mapindex = to_mapindex;
  2184. nd->u.warp.x = to_x;
  2185. nd->u.warp.y = to_y;
  2186. nd->u.warp.xs = xs;
  2187. nd->u.warp.ys = ys;
  2188. nd->bl.type = BL_NPC;
  2189. nd->subtype = NPCTYPE_WARP;
  2190. nd->trigger_on_hidden = false;
  2191. map_addnpc(from_mapid, nd);
  2192. npc_setcells(nd);
  2193. if(map_addblock(&nd->bl))
  2194. return NULL;
  2195. status_set_viewdata(&nd->bl, nd->class_);
  2196. status_change_init(&nd->bl);
  2197. unit_dataset(&nd->bl);
  2198. if( map_getmapdata(nd->bl.m)->users )
  2199. clif_spawn(&nd->bl);
  2200. strdb_put(npcname_db, nd->exname, nd);
  2201. return nd;
  2202. }
  2203. /**
  2204. * Parses a warp npc.
  2205. * Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
  2206. * @param w1 : word 1 before tab (<from map name>,<fromX>,<fromY>,<facing>)
  2207. * @param w2 : word 2 before tab (warp), keyword that sent us in this parsing
  2208. * @param w3 : word 3 before tab (<warp name>)
  2209. * @param w4 : word 4 before tab (<spanx>,<spany>,<to mapname>,<toX>,<toY>)
  2210. * @param start : index to start parsing
  2211. * @param buffer : lines to parses
  2212. * @param filepath : filename with path wich we are parsing
  2213. * @return new index for next parsing
  2214. */
  2215. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2216. {
  2217. int m;
  2218. short x, y, xs, ys, to_x, to_y;
  2219. unsigned short i;
  2220. char mapname[MAP_NAME_LENGTH_EXT], to_mapname[MAP_NAME_LENGTH_EXT];
  2221. struct npc_data *nd;
  2222. // w1=<from map name>,<fromX>,<fromY>,<facing>
  2223. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  2224. if( sscanf(w1, "%15[^,],%6hd,%6hd", mapname, &x, &y) != 3
  2225. || sscanf(w4, "%6hd,%6hd,%15[^,],%6hd,%6hd", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  2226. {
  2227. ShowError("npc_parse_warp: Invalid warp definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2228. return strchr(start,'\n');// skip and continue
  2229. }
  2230. m = map_mapname2mapid(mapname);
  2231. i = mapindex_name2id(to_mapname);
  2232. if( i == 0 )
  2233. {
  2234. ShowError("npc_parse_warp: Unknown destination map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), to_mapname, w1, w2, w3, w4);
  2235. return strchr(start,'\n');// skip and continue
  2236. }
  2237. struct map_data *mapdata = map_getmapdata(m);
  2238. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2239. ShowWarning("npc_parse_warp: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2240. }
  2241. nd = npc_create_npc(m, x, y);
  2242. npc_parsename(nd, w3, start, buffer, filepath);
  2243. if (!battle_config.warp_point_debug)
  2244. nd->class_ = JT_WARPNPC;
  2245. else
  2246. nd->class_ = JT_GUILD_FLAG;
  2247. nd->speed = 200;
  2248. nd->u.warp.mapindex = i;
  2249. nd->u.warp.x = to_x;
  2250. nd->u.warp.y = to_y;
  2251. nd->u.warp.xs = xs;
  2252. nd->u.warp.ys = ys;
  2253. npc_warp++;
  2254. nd->bl.type = BL_NPC;
  2255. nd->subtype = NPCTYPE_WARP;
  2256. if (strcasecmp("warp2", w2) == 0)
  2257. nd->trigger_on_hidden = true;
  2258. else
  2259. nd->trigger_on_hidden = false;
  2260. map_addnpc(m, nd);
  2261. npc_setcells(nd);
  2262. if(map_addblock(&nd->bl)) //couldn't add on map
  2263. return strchr(start,'\n');
  2264. status_set_viewdata(&nd->bl, nd->class_);
  2265. status_change_init(&nd->bl);
  2266. unit_dataset(&nd->bl);
  2267. if( map_getmapdata(nd->bl.m)->users )
  2268. clif_spawn(&nd->bl);
  2269. strdb_put(npcname_db, nd->exname, nd);
  2270. return strchr(start,'\n');// continue
  2271. }
  2272. /**
  2273. * Parses a shop/cashshop npc.
  2274. * Line definition :
  2275. * <map name>,<x>,<y>,<facing>%TAB%shop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  2276. * <map name>,<x>,<y>,<facing>%TAB%cashshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  2277. * <map name>,<x>,<y>,<facing>%TAB%itemshop%TAB%<NPC Name>%TAB%<sprite id>,<costitemid>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  2278. * <map name>,<x>,<y>,<facing>%TAB%pointshop%TAB%<NPC Name>%TAB%<sprite id>,<costvariable>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  2279. * <map name>,<x>,<y>,<facing>%TAB%marketshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>:<quantity>{,<itemid>:<price>:<quantity>...}
  2280. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  2281. * @param w2 : word 2 before tab (shop|cashshop|itemshop|pointshop|marketshop), keyword that sent us in this parsing
  2282. * @param w3 : word 3 before tab (<NPC Name>)
  2283. * @param w4 : word 4 before tab (<sprited id>,<shop definition...>)
  2284. * @param start : index to start parsing
  2285. * @param buffer : lines to parses
  2286. * @param filepath : filename with path wich we are parsing
  2287. * @return new index for next parsing
  2288. */
  2289. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2290. {
  2291. char *p, point_str[32];
  2292. int m, is_discount = 0;
  2293. uint16 dir;
  2294. short x, y;
  2295. unsigned short nameid = 0;
  2296. struct npc_data *nd;
  2297. enum npc_subtype type;
  2298. if( strcmp(w1,"-") == 0 )
  2299. {// 'floating' shop?
  2300. x = y = dir = 0;
  2301. m = -1;
  2302. }
  2303. else
  2304. {// w1=<map name>,<x>,<y>,<facing>
  2305. char mapname[MAP_NAME_LENGTH_EXT];
  2306. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4
  2307. || strchr(w4, ',') == NULL )
  2308. {
  2309. ShowError("npc_parse_shop: Invalid shop definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2310. return strchr(start,'\n');// skip and continue
  2311. }
  2312. m = map_mapname2mapid(mapname);
  2313. }
  2314. struct map_data *mapdata = map_getmapdata(m);
  2315. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2316. ShowWarning("npc_parse_shop: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2317. }
  2318. if( !strcasecmp(w2,"cashshop") )
  2319. type = NPCTYPE_CASHSHOP;
  2320. else if( !strcasecmp(w2,"itemshop") )
  2321. type = NPCTYPE_ITEMSHOP;
  2322. else if( !strcasecmp(w2,"pointshop") )
  2323. type = NPCTYPE_POINTSHOP;
  2324. else if( !strcasecmp(w2, "marketshop") )
  2325. type = NPCTYPE_MARKETSHOP;
  2326. else
  2327. type = NPCTYPE_SHOP;
  2328. p = strchr(w4,',');
  2329. memset(point_str,'\0',sizeof(point_str));
  2330. switch(type) {
  2331. case NPCTYPE_ITEMSHOP: {
  2332. if (sscanf(p,",%5hu:%11d,",&nameid,&is_discount) < 1) {
  2333. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2334. return strchr(start,'\n'); // skip and continue
  2335. }
  2336. if (itemdb_exists(nameid) == NULL) {
  2337. ShowWarning("npc_parse_shop: Invalid item ID cost in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid);
  2338. return strchr(start,'\n'); // skip and continue
  2339. }
  2340. p = strchr(p+1,',');
  2341. break;
  2342. }
  2343. case NPCTYPE_POINTSHOP: {
  2344. if (sscanf(p, ",%32[^,:]:%11d,",point_str,&is_discount) < 1) {
  2345. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2346. return strchr(start,'\n'); // skip and continue
  2347. }
  2348. switch(point_str[0]) {
  2349. case '$':
  2350. case '.':
  2351. case '\'':
  2352. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be permanent character or account based) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2353. return strchr(start,'\n'); // skip and continue
  2354. break;
  2355. }
  2356. if (point_str[strlen(point_str) - 1] == '$') {
  2357. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be integer) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2358. return strchr(start,'\n'); // skip and continue
  2359. }
  2360. p = strchr(p+1,',');
  2361. break;
  2362. }
  2363. case NPCTYPE_MARKETSHOP:
  2364. #if PACKETVER < 20131223
  2365. ShowError("npc_parse_shop: (MARKETSHOP) Feature is disabled, need client 20131223 or newer. Ignoring file '%s', line '%d\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2366. return strchr(start, '\n'); // skip and continue
  2367. #else
  2368. is_discount = 0;
  2369. break;
  2370. #endif
  2371. default:
  2372. if( sscanf( p, ",%32[^,:]:%11d,", point_str, &is_discount ) == 2 ){
  2373. is_discount = 1;
  2374. }else{
  2375. if( !strcasecmp( point_str, "yes" ) ){
  2376. is_discount = 1;
  2377. }else if( !strcasecmp( point_str, "no" ) ){
  2378. is_discount = 0;
  2379. }else{
  2380. ShowError( "npc_parse_shop: unknown discount setting %s\n", point_str );
  2381. return strchr( start, '\n' ); // skip and continue
  2382. }
  2383. p = strchr( p + 1, ',' );
  2384. }
  2385. break;
  2386. }
  2387. nd = npc_create_npc(m, x, y);
  2388. nd->u.shop.count = 0;
  2389. while ( p ) {
  2390. unsigned short nameid2, qty = 0;
  2391. int value;
  2392. struct item_data* id;
  2393. bool skip = false;
  2394. if( p == NULL )
  2395. break;
  2396. switch(type) {
  2397. case NPCTYPE_MARKETSHOP:
  2398. #if PACKETVER >= 20131223
  2399. if (sscanf(p, ",%6hu:%11d:%6hu", &nameid2, &value, &qty) != 3) {
  2400. ShowError("npc_parse_shop: (MARKETSHOP) Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2401. skip = true;
  2402. }
  2403. #endif
  2404. break;
  2405. default:
  2406. if (sscanf(p, ",%6hu:%11d", &nameid2, &value) != 2) {
  2407. ShowError("npc_parse_shop: Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2408. skip = true;
  2409. }
  2410. break;
  2411. }
  2412. if (skip)
  2413. break;
  2414. if( (id = itemdb_exists(nameid2)) == NULL ) {
  2415. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid2);
  2416. p = strchr(p+1,',');
  2417. continue;
  2418. }
  2419. if( value < 0 ) {
  2420. if (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP) value = id->value_buy;
  2421. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  2422. }
  2423. if (value == 0 && (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP)) { // NPC selling items for free!
  2424. ShowWarning("npc_parse_shop: Item %s [%hu] is being sold for FREE in file '%s', line '%d'.\n",
  2425. id->name, nameid2, filepath, strline(buffer,start-buffer));
  2426. }
  2427. if( type == NPCTYPE_SHOP && value*0.75 < id->value_sell*1.24 ) { // Exploit possible: you can buy and sell back with profit
  2428. ShowWarning("npc_parse_shop: Item %s [%hu] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  2429. id->name, nameid2, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  2430. }
  2431. if (type == NPCTYPE_MARKETSHOP && (!qty || qty > UINT16_MAX)) {
  2432. ShowWarning("npc_parse_shop: Item %s [%hu] is stocked with invalid value %d, changed to 1. File '%s', line '%d'.\n",
  2433. id->name, nameid2, qty, filepath, strline(buffer,start-buffer));
  2434. qty = 1;
  2435. }
  2436. //for logs filters, atcommands and iteminfo script command
  2437. if( id->maxchance == 0 )
  2438. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  2439. #if PACKETVER >= 20131223
  2440. if (nd->u.shop.count && type == NPCTYPE_MARKETSHOP) {
  2441. uint16 i;
  2442. // Duplicate entry? Replace the value
  2443. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  2444. if (i != nd->u.shop.count) {
  2445. nd->u.shop.shop_item[i].qty = qty;
  2446. nd->u.shop.shop_item[i].value = value;
  2447. p = strchr(p+1,',');
  2448. continue;
  2449. }
  2450. }
  2451. #endif
  2452. RECREATE(nd->u.shop.shop_item, struct npc_item_list,nd->u.shop.count+1);
  2453. nd->u.shop.shop_item[nd->u.shop.count].nameid = nameid2;
  2454. nd->u.shop.shop_item[nd->u.shop.count].value = value;
  2455. #if PACKETVER >= 20131223
  2456. nd->u.shop.shop_item[nd->u.shop.count].flag = 0;
  2457. if (type == NPCTYPE_MARKETSHOP)
  2458. nd->u.shop.shop_item[nd->u.shop.count].qty = qty;
  2459. #endif
  2460. nd->u.shop.count++;
  2461. p = strchr(p+1,',');
  2462. }
  2463. if( nd->u.shop.count == 0 ) {
  2464. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  2465. aFree(nd);
  2466. return strchr(start,'\n');// continue
  2467. }
  2468. if( type == NPCTYPE_ITEMSHOP ){
  2469. // Item shop currency
  2470. nd->u.shop.itemshop_nameid = nameid;
  2471. }else if( type == NPCTYPE_POINTSHOP ){
  2472. // Point shop currency
  2473. safestrncpy( nd->u.shop.pointshop_str, point_str, strlen( point_str ) + 1 );
  2474. }
  2475. nd->u.shop.discount = is_discount > 0;
  2476. npc_parsename(nd, w3, start, buffer, filepath);
  2477. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2478. nd->speed = 200;
  2479. ++npc_shop;
  2480. nd->bl.type = BL_NPC;
  2481. nd->subtype = type;
  2482. #if PACKETVER >= 20131223
  2483. // Insert market data to table
  2484. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  2485. uint16 i;
  2486. for (i = 0; i < nd->u.shop.count; i++)
  2487. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[i]);
  2488. }
  2489. #endif
  2490. if( m >= 0 )
  2491. {// normal shop npc
  2492. map_addnpc(m,nd);
  2493. if(map_addblock(&nd->bl))
  2494. return strchr(start,'\n');
  2495. status_change_init(&nd->bl);
  2496. unit_dataset(&nd->bl);
  2497. nd->ud.dir = (uint8)dir;
  2498. if( nd->class_ != JT_FAKENPC ){
  2499. status_set_viewdata(&nd->bl, nd->class_);
  2500. if( map_getmapdata(nd->bl.m)->users )
  2501. clif_spawn(&nd->bl);
  2502. }
  2503. } else
  2504. {// 'floating' shop?
  2505. map_addiddb(&nd->bl);
  2506. }
  2507. strdb_put(npcname_db, nd->exname, nd);
  2508. return strchr(start,'\n');// continue
  2509. }
  2510. /** [Cydh]
  2511. * Check if the shop is affected by discount or not
  2512. * @param type Type of NPC shop (enum npc_subtype)
  2513. * @param discount Discount flag of NPC shop
  2514. * @return bool 'true' is discountable, 'false' otherwise
  2515. */
  2516. bool npc_shop_discount( struct npc_data* nd ){
  2517. switch( nd->subtype ){
  2518. case NPCTYPE_ITEMSHOP:
  2519. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&1 );
  2520. case NPCTYPE_POINTSHOP:
  2521. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&2 );
  2522. default:
  2523. return nd->u.shop.discount;
  2524. }
  2525. }
  2526. /**
  2527. * NPC other label
  2528. * Not sure, seem to add label in a chainlink
  2529. * @see DBApply
  2530. */
  2531. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  2532. {
  2533. const char* lname = (const char*)key.str;
  2534. int lpos = db_data2i(data);
  2535. struct npc_label_list** label_list;
  2536. int* label_list_num;
  2537. const char* filepath;
  2538. struct npc_label_list* label;
  2539. const char *p;
  2540. int len;
  2541. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  2542. nullpo_ret(label_list_num = va_arg(ap,int*));
  2543. nullpo_ret(filepath = va_arg(ap,const char*));
  2544. // In case of labels not terminated with ':', for user defined function support
  2545. p = lname;
  2546. while( ISALNUM(*p) || *p == '_' )
  2547. ++p;
  2548. len = p-lname;
  2549. // here we check if the label fit into the buffer
  2550. if( len > NAME_LENGTH )
  2551. {
  2552. ShowError("npc_parse_script: label name longer than %d chars! '%s'\n (%s)", NAME_LENGTH, lname, filepath);
  2553. return 0;
  2554. }
  2555. if( *label_list == NULL )
  2556. {
  2557. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  2558. *label_list_num = 0;
  2559. } else
  2560. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  2561. label = *label_list+*label_list_num;
  2562. safestrncpy(label->name, lname, sizeof(label->name));
  2563. label->pos = lpos;
  2564. ++(*label_list_num);
  2565. return 0;
  2566. }
  2567. // Skip the contents of a script.
  2568. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  2569. {
  2570. const char* p;
  2571. int curly_count;
  2572. if( start == NULL )
  2573. return NULL;// nothing to skip
  2574. // initial bracket (assumes the previous part is ok)
  2575. p = strchr(start,'{');
  2576. if( p == NULL )
  2577. {
  2578. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  2579. return NULL;// can't continue
  2580. }
  2581. // skip everything
  2582. for( curly_count = 1; curly_count > 0 ; )
  2583. {
  2584. p = skip_space(p+1) ;
  2585. if( *p == '}' )
  2586. {// right curly
  2587. --curly_count;
  2588. }
  2589. else if( *p == '{' )
  2590. {// left curly
  2591. ++curly_count;
  2592. }
  2593. else if( *p == '"' )
  2594. {// string
  2595. for( ++p; *p != '"' ; ++p )
  2596. {
  2597. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  2598. ++p;// escape sequence (not part of a multibyte character)
  2599. else if( *p == '\0' )
  2600. {
  2601. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  2602. return NULL;// can't continue
  2603. }
  2604. else if( *p == '\n' )
  2605. {
  2606. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  2607. return NULL;// can't continue
  2608. }
  2609. }
  2610. }
  2611. else if( *p == '\0' )
  2612. {// end of buffer
  2613. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  2614. return NULL;// can't continue
  2615. }
  2616. }
  2617. return p+1;// return after the last '}'
  2618. }
  2619. /**
  2620. * Parses a npc script.
  2621. * Line definition :
  2622. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  2623. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>} * @TODO missing cashshop line definition
  2624. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  2625. * @param w2 : word 2 before tab (script), keyword that sent us in this parsing
  2626. * @param w3 : word 3 before tab (<NPC Name>)
  2627. * @param w4 : word 4 before tab (<sprited id>,<code>)
  2628. * @param start : index to start parsing
  2629. * @param buffer : lines to parses
  2630. * @param filepath : filename with path wich we are parsing
  2631. * @return new index for next parsing
  2632. */
  2633. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath, bool runOnInit) {
  2634. int16 dir = 0;
  2635. short m, x, y, xs = 0, ys = 0; // [Valaris] thanks to fov
  2636. struct script_code *script;
  2637. int i;
  2638. const char* end;
  2639. const char* script_start;
  2640. struct npc_label_list* label_list;
  2641. int label_list_num;
  2642. struct npc_data* nd;
  2643. if( strcmp(w1, "-") == 0 )
  2644. {// floating npc
  2645. x = 0;
  2646. y = 0;
  2647. m = -1;
  2648. }
  2649. else
  2650. {// npc in a map
  2651. char mapname[MAP_NAME_LENGTH_EXT];
  2652. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 )
  2653. {
  2654. ShowError("npc_parse_script: Invalid placement format for a script in file '%s', line '%d'. Skipping the rest of file...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2655. return NULL;// unknown format, don't continue
  2656. }
  2657. m = map_mapname2mapid(mapname);
  2658. }
  2659. script_start = strstr(start,",{");
  2660. end = strchr(start,'\n');
  2661. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  2662. {
  2663. ShowError("npc_parse_script: Missing left curly ',{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2664. return NULL;// can't continue
  2665. }
  2666. ++script_start;
  2667. end = npc_skip_script(script_start, buffer, filepath);
  2668. if( end == NULL )
  2669. return NULL;// (simple) parse error, don't continue
  2670. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  2671. label_list = NULL;
  2672. label_list_num = 0;
  2673. if( script )
  2674. {
  2675. DBMap* label_db = script_get_label_db();
  2676. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  2677. db_clear(label_db); // not needed anymore, so clear the db
  2678. }
  2679. nd = npc_create_npc(m, x, y);
  2680. if( sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2 )
  2681. {// OnTouch area defined
  2682. nd->u.scr.xs = xs;
  2683. nd->u.scr.ys = ys;
  2684. }
  2685. else
  2686. {// no OnTouch area
  2687. nd->u.scr.xs = -1;
  2688. nd->u.scr.ys = -1;
  2689. }
  2690. npc_parsename(nd, w3, start, buffer, filepath);
  2691. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2692. nd->speed = 200;
  2693. nd->u.scr.script = script;
  2694. nd->u.scr.label_list = label_list;
  2695. nd->u.scr.label_list_num = label_list_num;
  2696. ++npc_script;
  2697. nd->bl.type = BL_NPC;
  2698. nd->subtype = NPCTYPE_SCRIPT;
  2699. if( m >= 0 )
  2700. {
  2701. map_addnpc(m, nd);
  2702. status_change_init(&nd->bl);
  2703. unit_dataset(&nd->bl);
  2704. nd->ud.dir = (uint8)dir;
  2705. npc_setcells(nd);
  2706. if(map_addblock(&nd->bl))
  2707. return NULL;
  2708. if( nd->class_ != JT_FAKENPC )
  2709. {
  2710. status_set_viewdata(&nd->bl, nd->class_);
  2711. if( map_getmapdata(nd->bl.m)->users )
  2712. clif_spawn(&nd->bl);
  2713. }
  2714. }
  2715. else
  2716. {
  2717. // we skip map_addnpc, but still add it to the list of ID's
  2718. map_addiddb(&nd->bl);
  2719. }
  2720. strdb_put(npcname_db, nd->exname, nd);
  2721. //-----------------------------------------
  2722. // Loop through labels to export them as necessary
  2723. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2724. if (npc_event_export(nd, i)) {
  2725. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  2726. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2727. }
  2728. npc_timerevent_export(nd, i);
  2729. }
  2730. nd->u.scr.timerid = INVALID_TIMER;
  2731. if( runOnInit ) {
  2732. char evname[EVENT_NAME_LENGTH];
  2733. struct event_data *ev;
  2734. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.init_event_name);
  2735. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) ) {
  2736. //Execute OnInit
  2737. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  2738. }
  2739. }
  2740. return end;
  2741. }
  2742. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  2743. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  2744. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2745. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2746. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2747. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2748. const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2749. {
  2750. short x, y, m, xs = -1, ys = -1;
  2751. int16 dir;
  2752. char srcname[128];
  2753. int i;
  2754. const char* end;
  2755. size_t length;
  2756. int src_id;
  2757. int type;
  2758. struct npc_data* nd;
  2759. struct npc_data* dnd;
  2760. end = strchr(start,'\n');
  2761. length = strlen(w2);
  2762. // get the npc being duplicated
  2763. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  2764. {// does not match 'duplicate(%127s)', name is empty or too long
  2765. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  2766. return end;// next line, try to continue
  2767. }
  2768. safestrncpy(srcname, w2+10, length-10);
  2769. dnd = npc_name2id(srcname);
  2770. if( dnd == NULL) {
  2771. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  2772. return end;// next line, try to continue
  2773. }
  2774. src_id = dnd->src_id ? dnd->src_id : dnd->bl.id;
  2775. type = dnd->subtype;
  2776. // get placement
  2777. if ((type == NPCTYPE_SHOP || type == NPCTYPE_CASHSHOP || type == NPCTYPE_ITEMSHOP || type == NPCTYPE_POINTSHOP || type == NPCTYPE_SCRIPT || type == NPCTYPE_MARKETSHOP) && strcmp(w1, "-") == 0) {// floating shop/chashshop/itemshop/pointshop/script
  2778. x = y = dir = 0;
  2779. m = -1;
  2780. } else {
  2781. char mapname[MAP_NAME_LENGTH_EXT];
  2782. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 ) { // <map name>,<x>,<y>,<facing>
  2783. ShowError("npc_parse_duplicate: Invalid placement format for duplicate in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2784. return end;// next line, try to continue
  2785. }
  2786. m = map_mapname2mapid(mapname);
  2787. }
  2788. struct map_data *mapdata = map_getmapdata(m);
  2789. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2790. ShowError("npc_parse_duplicate: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2791. }
  2792. if( type == NPCTYPE_WARP && sscanf(w4, "%6hd,%6hd", &xs, &ys) == 2 );// <spanx>,<spany>
  2793. else if( type == NPCTYPE_SCRIPT && sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2);// <sprite id>,<triggerX>,<triggerY>
  2794. else if( type == NPCTYPE_WARP ) {
  2795. ShowError("npc_parse_duplicate: Invalid span format for duplicate warp in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2796. return end;// next line, try to continue
  2797. }
  2798. nd = npc_create_npc(m, x, y);
  2799. npc_parsename(nd, w3, start, buffer, filepath);
  2800. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2801. nd->speed = 200;
  2802. nd->src_id = src_id;
  2803. nd->bl.type = BL_NPC;
  2804. nd->subtype = (enum npc_subtype)type;
  2805. switch( type ) {
  2806. case NPCTYPE_SCRIPT:
  2807. ++npc_script;
  2808. nd->u.scr.xs = xs;
  2809. nd->u.scr.ys = ys;
  2810. nd->u.scr.script = dnd->u.scr.script;
  2811. nd->u.scr.label_list = dnd->u.scr.label_list;
  2812. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  2813. break;
  2814. case NPCTYPE_SHOP:
  2815. case NPCTYPE_CASHSHOP:
  2816. case NPCTYPE_ITEMSHOP:
  2817. case NPCTYPE_POINTSHOP:
  2818. case NPCTYPE_MARKETSHOP:
  2819. ++npc_shop;
  2820. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  2821. nd->u.shop.count = dnd->u.shop.count;
  2822. break;
  2823. case NPCTYPE_WARP:
  2824. ++npc_warp;
  2825. if( !battle_config.warp_point_debug )
  2826. nd->class_ = JT_WARPNPC;
  2827. else
  2828. nd->class_ = JT_GUILD_FLAG;
  2829. nd->u.warp.xs = xs;
  2830. nd->u.warp.ys = ys;
  2831. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  2832. nd->u.warp.x = dnd->u.warp.x;
  2833. nd->u.warp.y = dnd->u.warp.y;
  2834. nd->trigger_on_hidden = dnd->trigger_on_hidden;
  2835. break;
  2836. }
  2837. //Add the npc to its location
  2838. if( m >= 0 ) {
  2839. map_addnpc(m, nd);
  2840. status_change_init(&nd->bl);
  2841. unit_dataset(&nd->bl);
  2842. nd->ud.dir = (uint8)dir;
  2843. npc_setcells(nd);
  2844. if(map_addblock(&nd->bl))
  2845. return end;
  2846. if( nd->class_ != JT_FAKENPC ) {
  2847. status_set_viewdata(&nd->bl, nd->class_);
  2848. if( map_getmapdata(nd->bl.m)->users )
  2849. clif_spawn(&nd->bl);
  2850. }
  2851. } else {
  2852. // we skip map_addnpc, but still add it to the list of ID's
  2853. map_addiddb(&nd->bl);
  2854. }
  2855. strdb_put(npcname_db, nd->exname, nd);
  2856. if( type != NPCTYPE_SCRIPT )
  2857. return end;
  2858. //-----------------------------------------
  2859. // Loop through labels to export them as necessary
  2860. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2861. if (npc_event_export(nd, i)) {
  2862. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  2863. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2864. }
  2865. npc_timerevent_export(nd, i);
  2866. }
  2867. if(!strcmp(filepath,"INSTANCING")) //Instance NPCs will use this for commands
  2868. nd->instance_id = mapdata->instance_id;
  2869. nd->u.scr.timerid = INVALID_TIMER;
  2870. return end;
  2871. }
  2872. int npc_duplicate4instance(struct npc_data *snd, int16 m) {
  2873. char newname[NPC_NAME_LENGTH+1];
  2874. struct map_data *mapdata = map_getmapdata(m);
  2875. if( mapdata->instance_id == 0 )
  2876. return 1;
  2877. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", mapdata->instance_id, snd->bl.id);
  2878. if( npc_name2id(newname) != NULL ) { // Name already in use
  2879. ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, mapdata->instance_id);
  2880. return 1;
  2881. }
  2882. if( snd->subtype == NPCTYPE_WARP ) { // Adjust destination, if instanced
  2883. struct npc_data *wnd = NULL; // New NPC
  2884. struct instance_data *im = &instance_data[mapdata->instance_id];
  2885. int dm = map_mapindex2mapid(snd->u.warp.mapindex), imap = 0, i;
  2886. if( dm < 0 ) return 1;
  2887. for(i = 0; i < im->cnt_map; i++)
  2888. if(im->map[i]->m && map_mapname2mapid(map_getmapdata(im->map[i]->src_m)->name) == dm) {
  2889. imap = map_mapname2mapid(map_getmapdata(im->map[i]->m)->name);
  2890. break; // Instance map matches destination, update to instance map
  2891. }
  2892. if(!imap)
  2893. imap = map_mapname2mapid(map_getmapdata(dm)->name);
  2894. if( imap == -1 ) {
  2895. ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map_mapid2mapname(dm), snd->exname);
  2896. return 1;
  2897. }
  2898. wnd = npc_create_npc(m, snd->bl.x, snd->bl.y);
  2899. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  2900. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  2901. wnd->class_ = JT_WARPNPC;
  2902. wnd->speed = 200;
  2903. wnd->u.warp.mapindex = map_id2index(imap);
  2904. wnd->u.warp.x = snd->u.warp.x;
  2905. wnd->u.warp.y = snd->u.warp.y;
  2906. wnd->u.warp.xs = snd->u.warp.xs;
  2907. wnd->u.warp.ys = snd->u.warp.ys;
  2908. wnd->bl.type = BL_NPC;
  2909. wnd->subtype = NPCTYPE_WARP;
  2910. wnd->trigger_on_hidden = snd->trigger_on_hidden;
  2911. wnd->src_id = snd->src_id ? snd->src_id : snd->bl.id;
  2912. map_addnpc(m, wnd);
  2913. npc_setcells(wnd);
  2914. if(map_addblock(&wnd->bl))
  2915. return 1;
  2916. status_set_viewdata(&wnd->bl, wnd->class_);
  2917. status_change_init(&wnd->bl);
  2918. unit_dataset(&wnd->bl);
  2919. if( map_getmapdata(wnd->bl.m)->users )
  2920. clif_spawn(&wnd->bl);
  2921. strdb_put(npcname_db, wnd->exname, wnd);
  2922. } else {
  2923. static char w1[128], w2[128], w3[128], w4[128];
  2924. const char* stat_buf = "- call from instancing subsystem -\n";
  2925. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", mapdata->name, snd->bl.x, snd->bl.y, snd->ud.dir);
  2926. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  2927. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  2928. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  2929. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  2930. else
  2931. snprintf(w4, sizeof(w4), "%d", snd->class_);
  2932. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  2933. }
  2934. return 0;
  2935. }
  2936. int npc_instanceinit(struct npc_data* nd)
  2937. {
  2938. struct event_data *ev;
  2939. char evname[EVENT_NAME_LENGTH];
  2940. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_init_event_name);
  2941. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  2942. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  2943. return 0;
  2944. }
  2945. int npc_instancedestroy(struct npc_data* nd)
  2946. {
  2947. struct event_data *ev;
  2948. char evname[EVENT_NAME_LENGTH];
  2949. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_destroy_event_name);
  2950. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  2951. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  2952. return 0;
  2953. }
  2954. #if PACKETVER >= 20131223
  2955. /**
  2956. * Saves persistent NPC Market Data into SQL
  2957. * @param exname NPC exname
  2958. * @param nameid Item ID
  2959. * @param qty Stock
  2960. **/
  2961. void npc_market_tosql(const char *exname, struct npc_item_list *list) {
  2962. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  2963. if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`name`,`nameid`,`price`,`amount`,`flag`) VALUES ('%s','%hu','%d','%hu','%" PRIu8 "')",
  2964. market_table, exname, list->nameid, list->value, list->qty, list->flag) ||
  2965. SQL_ERROR == SqlStmt_Execute(stmt))
  2966. SqlStmt_ShowDebug(stmt);
  2967. SqlStmt_Free(stmt);
  2968. }
  2969. /**
  2970. * Removes persistent NPC Market Data from SQL
  2971. * @param exname NPC exname
  2972. * @param nameid Item ID
  2973. * @param clear True: will removes all records related with the NPC
  2974. **/
  2975. void npc_market_delfromsql_(const char *exname, unsigned short nameid, bool clear) {
  2976. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  2977. if (clear) {
  2978. if( SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s'", market_table, exname) ||
  2979. SQL_ERROR == SqlStmt_Execute(stmt))
  2980. SqlStmt_ShowDebug(stmt);
  2981. } else {
  2982. if (SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s' AND `nameid`='%d' LIMIT 1", market_table, exname, nameid) ||
  2983. SQL_ERROR == SqlStmt_Execute(stmt))
  2984. SqlStmt_ShowDebug(stmt);
  2985. }
  2986. SqlStmt_Free(stmt);
  2987. }
  2988. /**
  2989. * Check NPC Market Shop for each entry
  2990. **/
  2991. static int npc_market_checkall_sub(DBKey key, DBData *data, va_list ap) {
  2992. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  2993. struct npc_data *nd = NULL;
  2994. uint16 i;
  2995. if (!market)
  2996. return 1;
  2997. nd = npc_name2id(market->exname);
  2998. if (!nd) {
  2999. ShowInfo("npc_market_checkall_sub: NPC '%s' not found, removing...\n", market->exname);
  3000. npc_market_clearfromsql(market->exname);
  3001. return 1;
  3002. }
  3003. else if (nd->subtype != NPCTYPE_MARKETSHOP || !nd->u.shop.shop_item || !nd->u.shop.count ) {
  3004. ShowError("npc_market_checkall_sub: NPC '%s' is not proper for market, removing...\n", nd->exname);
  3005. npc_market_clearfromsql(nd->exname);
  3006. return 1;
  3007. }
  3008. if (!market->count || !market->list)
  3009. return 1;
  3010. for (i = 0; i < market->count; i++) {
  3011. struct npc_item_list *list = &market->list[i];
  3012. uint16 j;
  3013. if (!list->nameid || !itemdb_exists(list->nameid)) {
  3014. ShowError("npc_market_checkall_sub: NPC '%s' sells invalid item '%hu', deleting...\n", nd->exname, list->nameid);
  3015. npc_market_delfromsql(nd->exname, list->nameid);
  3016. continue;
  3017. }
  3018. // Reloading stock from `market` table
  3019. ARR_FIND(0, nd->u.shop.count, j, nd->u.shop.shop_item[j].nameid == list->nameid);
  3020. if (j != nd->u.shop.count) {
  3021. nd->u.shop.shop_item[j].value = list->value;
  3022. nd->u.shop.shop_item[j].qty = list->qty;
  3023. nd->u.shop.shop_item[j].flag = list->flag;
  3024. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  3025. continue;
  3026. }
  3027. if (list->flag&1) { // Item added by npcshopitem/npcshopadditem, add new entry
  3028. RECREATE(nd->u.shop.shop_item, struct npc_item_list, nd->u.shop.count+1);
  3029. nd->u.shop.shop_item[j].nameid = list->nameid;
  3030. nd->u.shop.shop_item[j].value = list->value;
  3031. nd->u.shop.shop_item[j].qty = list->qty;
  3032. nd->u.shop.shop_item[j].flag = list->flag;
  3033. nd->u.shop.count++;
  3034. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  3035. }
  3036. else { // Removing "out-of-date" entry
  3037. ShowError("npc_market_checkall_sub: NPC '%s' does not sell item %hu (qty %hu), deleting...\n", nd->exname, list->nameid, list->qty);
  3038. npc_market_delfromsql(nd->exname, list->nameid);
  3039. }
  3040. }
  3041. return 0;
  3042. }
  3043. /**
  3044. * Clear NPC market single entry
  3045. **/
  3046. static int npc_market_free(DBKey key, DBData *data, va_list ap) {
  3047. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  3048. if (!market)
  3049. return 0;
  3050. if (market->list) {
  3051. aFree(market->list);
  3052. market->list = NULL;
  3053. }
  3054. aFree(market);
  3055. return 1;
  3056. }
  3057. /**
  3058. * Check all existing NPC Market Shop after first loading map-server or after reloading scripts.
  3059. * Overwrite stocks from NPC by using stock entries from `market` table.
  3060. **/
  3061. static void npc_market_checkall(void) {
  3062. if (!db_size(NPCMarketDB))
  3063. return;
  3064. else {
  3065. ShowInfo("Checking '" CL_WHITE "%d" CL_RESET "' NPC Markets...\n", db_size(NPCMarketDB));
  3066. NPCMarketDB->foreach(NPCMarketDB, npc_market_checkall_sub);
  3067. ShowStatus("Done checking '" CL_WHITE "%d" CL_RESET "' NPC Markets.\n", db_size(NPCMarketDB));
  3068. NPCMarketDB->clear(NPCMarketDB, npc_market_free);
  3069. }
  3070. }
  3071. /**
  3072. * Loads persistent NPC Market Data from SQL, use the records after NPCs init'd to reuse the stock values.
  3073. **/
  3074. static void npc_market_fromsql(void) {
  3075. uint32 count = 0;
  3076. if (SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `name`,`nameid`,`price`,`amount`,`flag` FROM `%s` ORDER BY `name`", market_table)) {
  3077. Sql_ShowDebug(mmysql_handle);
  3078. return;
  3079. }
  3080. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  3081. char *data;
  3082. struct s_npc_market *market;
  3083. struct npc_item_list list;
  3084. Sql_GetData(mmysql_handle, 0, &data, NULL);
  3085. if (!(market = (struct s_npc_market *)strdb_get(NPCMarketDB,data))) {
  3086. CREATE(market, struct s_npc_market, 1);
  3087. market->count = 0;
  3088. safestrncpy(market->exname, data, NPC_NAME_LENGTH);
  3089. strdb_put(NPCMarketDB, market->exname, market);
  3090. }
  3091. Sql_GetData(mmysql_handle, 1, &data, NULL); list.nameid = atoi(data);
  3092. Sql_GetData(mmysql_handle, 2, &data, NULL); list.value = atoi(data);
  3093. Sql_GetData(mmysql_handle, 3, &data, NULL); list.qty = atoi(data);
  3094. Sql_GetData(mmysql_handle, 4, &data, NULL); list.flag = atoi(data);
  3095. RECREATE(market->list, struct npc_item_list, market->count+1);
  3096. market->list[market->count++] = list;
  3097. count++;
  3098. }
  3099. Sql_FreeResult(mmysql_handle);
  3100. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' entries for '" CL_WHITE "%d" CL_RESET "' NPC Markets from '" CL_WHITE "%s" CL_RESET "' table.\n", count, db_size(NPCMarketDB), market_table);
  3101. }
  3102. #endif
  3103. //Set mapcell CELL_NPC to trigger event later
  3104. void npc_setcells(struct npc_data* nd)
  3105. {
  3106. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  3107. int i,j;
  3108. switch(nd->subtype)
  3109. {
  3110. case NPCTYPE_WARP:
  3111. xs = nd->u.warp.xs;
  3112. ys = nd->u.warp.ys;
  3113. break;
  3114. case NPCTYPE_SCRIPT:
  3115. xs = nd->u.scr.xs;
  3116. ys = nd->u.scr.ys;
  3117. break;
  3118. default:
  3119. return; // Other types doesn't have touch area
  3120. }
  3121. if (m < 0 || xs < 0 || ys < 0) //invalid range or map
  3122. return;
  3123. for (i = y-ys; i <= y+ys; i++) {
  3124. for (j = x-xs; j <= x+xs; j++) {
  3125. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  3126. continue;
  3127. map_setcell(m, j, i, CELL_NPC, true);
  3128. }
  3129. }
  3130. }
  3131. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  3132. {
  3133. struct npc_data *nd = (struct npc_data*)bl;
  3134. int id = va_arg(ap,int);
  3135. if (nd->bl.id == id) return 0;
  3136. npc_setcells(nd);
  3137. return 1;
  3138. }
  3139. void npc_unsetcells(struct npc_data* nd)
  3140. {
  3141. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  3142. int i,j, x0, x1, y0, y1;
  3143. if (nd->subtype == NPCTYPE_WARP) {
  3144. xs = nd->u.warp.xs;
  3145. ys = nd->u.warp.ys;
  3146. } else {
  3147. xs = nd->u.scr.xs;
  3148. ys = nd->u.scr.ys;
  3149. }
  3150. if (m < 0 || xs < 0 || ys < 0)
  3151. return;
  3152. struct map_data *mapdata = map_getmapdata(m);
  3153. //Locate max range on which we can locate npc cells
  3154. //FIXME: does this really do what it's supposed to do? [ultramage]
  3155. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  3156. for(x1 = x+xs; x1 < mapdata->xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  3157. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  3158. for(y1 = y+ys; y1 < mapdata->ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  3159. //Erase this npc's cells
  3160. for (i = y-ys; i <= y+ys; i++)
  3161. for (j = x-xs; j <= x+xs; j++)
  3162. map_setcell(m, j, i, CELL_NPC, false);
  3163. //Re-deploy NPC cells for other nearby npcs.
  3164. map_foreachinallarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  3165. }
  3166. bool npc_movenpc(struct npc_data* nd, int16 x, int16 y)
  3167. {
  3168. if (nd->bl.m < 0 || nd->bl.prev == NULL)
  3169. return false; //Not on a map.
  3170. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  3171. x = cap_value(x, 0, mapdata->xs-1);
  3172. y = cap_value(y, 0, mapdata->ys-1);
  3173. map_foreachinallrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  3174. map_moveblock(&nd->bl, x, y, gettick());
  3175. map_foreachinallrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  3176. return true;
  3177. }
  3178. /// Changes the display name of the npc.
  3179. ///
  3180. /// @param nd Target npc
  3181. /// @param newname New display name
  3182. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  3183. {
  3184. nullpo_retv(nd);
  3185. safestrncpy(nd->name, newname, sizeof(nd->name));
  3186. if( map_getmapdata(nd->bl.m)->users )
  3187. clif_name_area(&nd->bl);
  3188. }
  3189. /// Changes the display class of the npc.
  3190. ///
  3191. /// @param nd Target npc
  3192. /// @param class_ New display class
  3193. void npc_setclass(struct npc_data* nd, short class_)
  3194. {
  3195. nullpo_retv(nd);
  3196. if( nd->class_ == class_ )
  3197. return;
  3198. nd->class_ = class_;
  3199. status_set_viewdata(&nd->bl, class_);
  3200. unit_refresh(&nd->bl);
  3201. }
  3202. // @commands (script based)
  3203. int npc_do_atcmd_event(struct map_session_data* sd, const char* command, const char* message, const char* eventname)
  3204. {
  3205. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  3206. struct npc_data *nd;
  3207. struct script_state *st;
  3208. int i = 0, j = 0, k = 0;
  3209. char *temp;
  3210. nullpo_ret(sd);
  3211. if( ev == NULL || (nd = ev->nd) == NULL ) {
  3212. ShowError("npc_event: event not found [%s]\n", eventname);
  3213. return 0;
  3214. }
  3215. if( sd->npc_id != 0 ) { // Enqueue the event trigger.
  3216. int l;
  3217. ARR_FIND( 0, MAX_EVENTQUEUE, l, sd->eventqueue[l][0] == '\0' );
  3218. if( l < MAX_EVENTQUEUE ) {
  3219. safestrncpy(sd->eventqueue[l],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  3220. return 0;
  3221. }
  3222. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  3223. return 1;
  3224. }
  3225. if( ev->nd->sc.option&OPTION_INVISIBLE ) { // Disabled npc, shouldn't trigger event.
  3226. npc_event_dequeue(sd);
  3227. return 2;
  3228. }
  3229. st = script_alloc_state(ev->nd->u.scr.script, ev->pos, sd->bl.id, ev->nd->bl.id);
  3230. setd_sub_str( st, NULL, ".@atcmd_command$", 0, command, NULL );
  3231. // split atcmd parameters based on spaces
  3232. temp = (char*)aMalloc(strlen(message) + 1);
  3233. for( i = 0; i < ( strlen( message ) + 1 ) && k < 127; i ++ ) {
  3234. if( message[i] == ' ' || message[i] == '\0' ) {
  3235. if( message[ ( i - 1 ) ] == ' ' ) {
  3236. continue; // To prevent "@atcmd [space][space]" and .@atcmd_numparameters return 1 without any parameter.
  3237. }
  3238. temp[k] = '\0';
  3239. k = 0;
  3240. if( temp[0] != '\0' ) {
  3241. setd_sub_str( st, NULL, ".@atcmd_parameters$", j++, temp, NULL );
  3242. }
  3243. } else {
  3244. temp[k] = message[i];
  3245. k++;
  3246. }
  3247. }
  3248. setd_sub_num( st, NULL, ".@atcmd_numparameters", 0, j, NULL );
  3249. aFree(temp);
  3250. run_script_main(st);
  3251. return 0;
  3252. }
  3253. /// Parses a function.
  3254. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  3255. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3256. {
  3257. DBMap* func_db;
  3258. DBData old_data;
  3259. struct script_code *script;
  3260. const char* end;
  3261. const char* script_start;
  3262. script_start = strstr(start,"\t{");
  3263. end = strchr(start,'\n');
  3264. if (*w4 != '{' || script_start == NULL || (end != NULL && script_start > end)) {
  3265. ShowError("npc_parse_function: Missing left curly '%%TAB%%{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3266. return NULL;// can't continue
  3267. }
  3268. ++script_start;
  3269. end = npc_skip_script(script_start,buffer,filepath);
  3270. if( end == NULL )
  3271. return NULL;// (simple) parse error, don't continue
  3272. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  3273. if( script == NULL )// parse error, continue
  3274. return end;
  3275. func_db = script_get_userfunc_db();
  3276. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data)) {
  3277. struct script_code *oldscript = (struct script_code*)db_data2ptr(&old_data);
  3278. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  3279. script_stop_scriptinstances(oldscript);
  3280. script_free_vars(oldscript->local.vars);
  3281. aFree(oldscript->script_buf);
  3282. aFree(oldscript);
  3283. }
  3284. return end;
  3285. }
  3286. /*==========================================
  3287. * Parse Mob 1 - Parse mob list into each map
  3288. * Parse Mob 2 - Actually Spawns Mob
  3289. * [Wizputer]
  3290. *------------------------------------------*/
  3291. void npc_parse_mob2(struct spawn_data* mob)
  3292. {
  3293. int i;
  3294. for( i = mob->active; i < mob->num; ++i )
  3295. {
  3296. struct mob_data* md = mob_spawn_dataset(mob);
  3297. md->spawn = mob;
  3298. md->spawn->active++;
  3299. mob_spawn(md);
  3300. }
  3301. }
  3302. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3303. {
  3304. int num, mob_id, mob_lv = -1, size = -1, w1count;
  3305. short m, x = 0, y = 0, xs = -1, ys = -1;
  3306. char mapname[MAP_NAME_LENGTH_EXT], mobname[NAME_LENGTH];
  3307. struct spawn_data mob, *data;
  3308. int ai = AI_NONE; // mob_ai
  3309. memset(&mob, 0, sizeof(struct spawn_data));
  3310. mob.state.boss = !strcmpi(w2,"boss_monster");
  3311. // w1=<map name>{,<x>,<y>,<xs>{,<ys>}}
  3312. // w3=<mob name>{,<mob level>}
  3313. // w4=<mob id>,<amount>{,<delay1>{,<delay2>{,<event>{,<mob size>{,<mob ai>}}}}}
  3314. if( ( w1count = sscanf(w1, "%15[^,],%6hd,%6hd,%6hd,%6hd", mapname, &x, &y, &xs, &ys) ) < 1
  3315. || sscanf(w3, "%23[^,],%11d", mobname, &mob_lv) < 1
  3316. || sscanf(w4, "%11d,%11d,%11u,%11u,%77[^,],%11d,%11d[^\t\r\n]", &mob_id, &num, &mob.delay1, &mob.delay2, mob.eventname, &size, &ai) < 2 )
  3317. {
  3318. ShowError("npc_parse_mob: Invalid mob definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3319. return strchr(start,'\n');// skip and continue
  3320. }
  3321. if( mapindex_name2id(mapname) == 0 )
  3322. {
  3323. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  3324. return strchr(start,'\n');// skip and continue
  3325. }
  3326. m = map_mapname2mapid(mapname);
  3327. if( m < 0 )//Not loaded on this map-server instance.
  3328. return strchr(start,'\n');// skip and continue
  3329. mob.m = (unsigned short)m;
  3330. struct map_data *mapdata = map_getmapdata(m);
  3331. if( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys )
  3332. {
  3333. ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", mapdata->name, x, y, (mapdata->xs-1), (mapdata->ys-1), w1, w3, filepath, strline(buffer,start-buffer));
  3334. return strchr(start,'\n');// skip and continue
  3335. }
  3336. // check monster ID if exists!
  3337. if( mobdb_checkid(mob_id) == 0 )
  3338. {
  3339. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  3340. return strchr(start,'\n');// skip and continue
  3341. }
  3342. if( num < 1 || num > 1000 )
  3343. {
  3344. ShowError("npc_parse_mob: Invalid number of monsters %d, must be inside the range [1,1000] (file '%s', line '%d').\n", num, filepath, strline(buffer,start-buffer));
  3345. return strchr(start,'\n');// skip and continue
  3346. }
  3347. if( mob.state.size > SZ_BIG && size != -1 )
  3348. {
  3349. ShowError("npc_parse_mob: Invalid size number %d for mob ID %d (file '%s', line '%d').\n", mob.state.size, mob_id, filepath, strline(buffer, start - buffer));
  3350. return strchr(start, '\n');
  3351. }
  3352. if( (mob.state.ai < AI_NONE || mob.state.ai >= AI_MAX) && ai != -1 )
  3353. {
  3354. ShowError("npc_parse_mob: Invalid ai %d for mob ID %d (file '%s', line '%d').\n", mob.state.ai, mob_id, filepath, strline(buffer, start - buffer));
  3355. return strchr(start, '\n');
  3356. }
  3357. if( (mob_lv == 0 || mob_lv > MAX_LEVEL) && mob_lv != -1 )
  3358. {
  3359. ShowError("npc_parse_mob: Invalid level %d for mob ID %d (file '%s', line '%d').\n", mob_lv, mob_id, filepath, strline(buffer, start - buffer));
  3360. return strchr(start, '\n');
  3361. }
  3362. mob.num = (unsigned short)num;
  3363. mob.active = 0;
  3364. mob.id = (short) mob_id;
  3365. mob.x = (unsigned short)x;
  3366. mob.y = (unsigned short)y;
  3367. mob.xs = (signed short)xs;
  3368. mob.ys = (signed short)ys;
  3369. if (mob_lv > 0 && mob_lv <= MAX_LEVEL)
  3370. mob.level = mob_lv;
  3371. if (size > SZ_SMALL && size <= SZ_BIG)
  3372. mob.state.size = size;
  3373. if (ai > AI_NONE && ai <= AI_MAX)
  3374. mob.state.ai = static_cast<enum mob_ai>(ai);
  3375. if (mob.xs < 0) {
  3376. if (w1count > 3) {
  3377. ShowWarning("npc_parse_mob: Negative x-span %hd for mob ID %d (file '%s', line '%d').\n", mob.xs, mob_id, filepath, strline(buffer, start - buffer));
  3378. }
  3379. mob.xs = 0;
  3380. }
  3381. if (mob.ys < 0) {
  3382. if (w1count > 4) {
  3383. ShowWarning("npc_parse_mob: Negative y-span %hd for mob ID %d (file '%s', line '%d').\n", mob.ys, mob_id, filepath, strline(buffer, start - buffer));
  3384. }
  3385. mob.ys = 0;
  3386. }
  3387. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  3388. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  3389. mob.num = 1;
  3390. }
  3391. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  3392. { //Force a random spawn anywhere on the map.
  3393. mob.x = mob.y = 0;
  3394. mob.xs = mob.ys = -1;
  3395. }
  3396. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  3397. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  3398. return strchr(start,'\n');// skip and continue
  3399. }
  3400. //Use db names instead of the spawn file ones.
  3401. if(battle_config.override_mob_names==1)
  3402. strcpy(mob.name,"--en--");
  3403. else if (battle_config.override_mob_names==2)
  3404. strcpy(mob.name,"--ja--");
  3405. else
  3406. safestrncpy(mob.name, mobname, sizeof(mob.name));
  3407. //Verify dataset.
  3408. if( !mob_parse_dataset(&mob) )
  3409. {
  3410. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  3411. return strchr(start,'\n');// skip and continue
  3412. }
  3413. //Update mob spawn lookup database
  3414. struct spawn_info spawn = { mapdata->index, mob.num };
  3415. mob_add_spawn(mob_id, spawn);
  3416. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  3417. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  3418. memcpy(data, &mob, sizeof(struct spawn_data));
  3419. // spawn / cache the new mobs
  3420. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  3421. {
  3422. data->state.dynamic = true;
  3423. npc_cache_mob += data->num;
  3424. // check if target map has players
  3425. // (usually shouldn't occur when map server is just starting,
  3426. // but not the case when we do @reloadscript
  3427. if( map_getmapdata(data->m)->users > 0 )
  3428. npc_parse_mob2(data);
  3429. }
  3430. else
  3431. {
  3432. data->state.dynamic = false;
  3433. npc_parse_mob2(data);
  3434. npc_delay_mob += data->num;
  3435. }
  3436. npc_mob++;
  3437. return strchr(start,'\n');// continue
  3438. }
  3439. /*==========================================
  3440. * Set or disable mapflag on map
  3441. * eg : bat_c01 mapflag battleground 2
  3442. * also chking if mapflag conflict with another
  3443. *------------------------------------------*/
  3444. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3445. {
  3446. int16 m;
  3447. char mapname[MAP_NAME_LENGTH_EXT];
  3448. bool state = true;
  3449. enum e_mapflag mapflag;
  3450. // w1=<mapname>
  3451. if (sscanf(w1, "%15[^,]", mapname) != 1) {
  3452. ShowError("npc_parse_mapflag: Invalid mapflag definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3453. return strchr(start,'\n');// skip and continue
  3454. }
  3455. m = map_mapname2mapid(mapname);
  3456. if (m < 0) {
  3457. ShowWarning("npc_parse_mapflag: Unknown map '%s' in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3458. return strchr(start,'\n');// skip and continue
  3459. }
  3460. if (w4 && !strcmpi(w4, "off"))
  3461. state = false; //Disable mapflag rather than enable it. [Skotlex]
  3462. mapflag = map_getmapflag_by_name(w3);
  3463. switch( mapflag ){
  3464. case MF_INVALID:
  3465. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  3466. break;
  3467. case MF_NOSAVE: {
  3468. char savemap[MAP_NAME_LENGTH_EXT];
  3469. union u_mapflag_args args = {};
  3470. if (state && !strcmpi(w4, "SavePoint")) {
  3471. args.nosave.map = 0;
  3472. args.nosave.x = -1;
  3473. args.nosave.y = -1;
  3474. } else if (state && sscanf(w4, "%15[^,],%6hd,%6hd", savemap, &args.nosave.x, &args.nosave.y) == 3) {
  3475. args.nosave.map = mapindex_name2id(savemap);
  3476. if (!args.nosave.map) {
  3477. ShowWarning("npc_parse_mapflag: Specified save point map '%s' for mapflag 'nosave' not found (file '%s', line '%d'), using 'SavePoint'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", savemap, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3478. args.nosave.x = -1;
  3479. args.nosave.y = -1;
  3480. }
  3481. }
  3482. map_setmapflag_sub(m, MF_NOSAVE, state, &args);
  3483. break;
  3484. }
  3485. case MF_PVP_NIGHTMAREDROP: {
  3486. char drop_arg1[16], drop_arg2[16];
  3487. union u_mapflag_args args = {};
  3488. if (sscanf(w4, "%15[^,],%15[^,],%11d", drop_arg1, drop_arg2, &args.nightmaredrop.drop_per) == 3) {
  3489. if (!strcmpi(drop_arg1, "random"))
  3490. args.nightmaredrop.drop_id = -1;
  3491. else if (itemdb_exists((args.nightmaredrop.drop_id = atoi(drop_arg1))) == NULL) {
  3492. args.nightmaredrop.drop_id = 0;
  3493. ShowWarning("npc_parse_mapflag: Invalid item ID '%d' supplied for mapflag 'pvp_nightmaredrop' (file '%s', line '%d'), removing.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", args.nightmaredrop.drop_id, filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  3494. break;
  3495. }
  3496. if (!strcmpi(drop_arg2, "inventory"))
  3497. args.nightmaredrop.drop_type = NMDT_INVENTORY;
  3498. else if (!strcmpi(drop_arg2, "equip"))
  3499. args.nightmaredrop.drop_type = NMDT_EQUIP;
  3500. else if (!strcmpi(drop_arg2, "all"))
  3501. args.nightmaredrop.drop_type = NMDT_ALL;
  3502. if (args.nightmaredrop.drop_id != 0)
  3503. map_setmapflag_sub(m, MF_PVP_NIGHTMAREDROP, true, &args);
  3504. } else if (!state)
  3505. map_setmapflag(m, MF_PVP_NIGHTMAREDROP, false);
  3506. break;
  3507. }
  3508. case MF_BATTLEGROUND:
  3509. if (state) {
  3510. union u_mapflag_args args = {};
  3511. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3512. args.flag_val = 1; // Default value
  3513. map_setmapflag_sub(m, MF_BATTLEGROUND, true, &args);
  3514. } else
  3515. map_setmapflag(m, MF_BATTLEGROUND, false);
  3516. break;
  3517. case MF_NOCOMMAND:
  3518. if (state) {
  3519. union u_mapflag_args args = {};
  3520. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3521. args.flag_val = 100; // No level specified, block everyone.
  3522. map_setmapflag_sub(m, MF_NOCOMMAND, true, &args);
  3523. } else
  3524. map_setmapflag(m, MF_NOCOMMAND, false);
  3525. break;
  3526. case MF_RESTRICTED:
  3527. if (state) {
  3528. union u_mapflag_args args = {};
  3529. if (sscanf(w4, "%11d", &args.flag_val) == 1)
  3530. map_setmapflag_sub(m, MF_RESTRICTED, true, &args);
  3531. else // Could not be read, no value defined; don't remove as other restrictions may be set on the map
  3532. ShowWarning("npc_parse_mapflag: Zone value not set for the restricted mapflag! Skipped flag from %s (file '%s', line '%d').\n", map_mapid2mapname(m), filepath, strline(buffer,start-buffer));
  3533. } else
  3534. map_setmapflag(m, MF_RESTRICTED, false);
  3535. break;
  3536. case MF_JEXP:
  3537. case MF_BEXP: {
  3538. union u_mapflag_args args = {};
  3539. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3540. args.flag_val = 0;
  3541. map_setmapflag_sub(m, mapflag, state, &args);
  3542. }
  3543. break;
  3544. case MF_SKILL_DAMAGE: {
  3545. char skill_name[SKILL_NAME_LENGTH];
  3546. char caster_constant[NAME_LENGTH];
  3547. union u_mapflag_args args = {};
  3548. memset(skill_name, 0, sizeof(skill_name));
  3549. if (!state)
  3550. map_setmapflag_sub(m, MF_SKILL_DAMAGE, false, &args);
  3551. else {
  3552. if (sscanf(w4, "%30[^,],%23[^,],%11d,%11d,%11d,%11d[^\n]", skill_name, caster_constant, &args.skill_damage.rate[SKILLDMG_PC], &args.skill_damage.rate[SKILLDMG_MOB], &args.skill_damage.rate[SKILLDMG_BOSS], &args.skill_damage.rate[SKILLDMG_OTHER]) >= 3) {
  3553. if (ISDIGIT(caster_constant[0]))
  3554. args.skill_damage.caster = atoi(caster_constant);
  3555. else {
  3556. int64 val_tmp;
  3557. int val;
  3558. if (!script_get_constant(caster_constant, &val_tmp)) {
  3559. ShowError( "npc_parse_mapflag: Unknown constant '%s'. Skipping (file '%s', line '%d').\n", caster_constant, filepath, strline(buffer, start - buffer) );
  3560. break;
  3561. }
  3562. val = static_cast<int>(val_tmp);
  3563. args.skill_damage.caster = val;
  3564. }
  3565. if (!args.skill_damage.caster)
  3566. args.skill_damage.caster = BL_ALL;
  3567. for (int i = 0; i < SKILLDMG_MAX; i++)
  3568. args.skill_damage.rate[i] = cap_value(args.skill_damage.rate[i], -100, 100000);
  3569. if (strcmp(skill_name, "all") == 0) // Adjust damage for all skills
  3570. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  3571. else if (skill_name2id(skill_name) <= 0)
  3572. ShowWarning("npc_parse_mapflag: Invalid skill name '%s' for Skill Damage mapflag. Skipping (file '%s', line '%d').\n", skill_name, filepath, strline(buffer, start - buffer));
  3573. else { // Adjusted damage for specified skill
  3574. args.flag_val = 1;
  3575. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  3576. map_skill_damage_add(map_getmapdata(m), skill_name2id(skill_name), args.skill_damage.rate, args.skill_damage.caster);
  3577. }
  3578. }
  3579. }
  3580. break;
  3581. }
  3582. case MF_SKILL_DURATION: {
  3583. union u_mapflag_args args = {};
  3584. if (!state)
  3585. map_setmapflag_sub(m, MF_SKILL_DURATION, false, &args);
  3586. else {
  3587. char skill_name[SKILL_NAME_LENGTH];
  3588. if (sscanf(w4, "%30[^,],%5hu[^\n]", skill_name, &args.skill_duration.per) == 2) {
  3589. args.skill_duration.skill_id = skill_name2id(skill_name);
  3590. if (!args.skill_duration.skill_id)
  3591. ShowError("npc_parse_mapflag: skill_duration: Invalid skill name '%s' for Skill Duration mapflag. Skipping (file '%s', line '%d')\n", skill_name, filepath, strline(buffer, start - buffer));
  3592. else {
  3593. args.skill_duration.per = cap_value(args.skill_duration.per, 0, UINT16_MAX);
  3594. map_setmapflag_sub(m, MF_SKILL_DURATION, true, &args);
  3595. }
  3596. }
  3597. }
  3598. break;
  3599. }
  3600. // All others do not need special treatment
  3601. default:
  3602. map_setmapflag(m, mapflag, state);
  3603. break;
  3604. }
  3605. return strchr(start,'\n');// continue
  3606. }
  3607. /**
  3608. * Read file and create npc/func/mapflag/monster... accordingly.
  3609. * @param filepath : Relative path of file from map-serv bin
  3610. * @param runOnInit : should we exec OnInit when it's done ?
  3611. * @return 0:error, 1:success
  3612. */
  3613. int npc_parsesrcfile(const char* filepath, bool runOnInit)
  3614. {
  3615. int16 m, x, y;
  3616. int lines = 0;
  3617. FILE* fp;
  3618. size_t len;
  3619. char* buffer;
  3620. const char* p;
  3621. if(check_filepath(filepath)!=2) { //this is not a file
  3622. ShowDebug("npc_parsesrcfile: Path doesn't seem to be a file skipping it : '%s'.\n", filepath);
  3623. return 0;
  3624. }
  3625. // read whole file to buffer
  3626. fp = fopen(filepath, "rb");
  3627. if( fp == NULL )
  3628. {
  3629. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  3630. return 0;
  3631. }
  3632. fseek(fp, 0, SEEK_END);
  3633. len = ftell(fp);
  3634. buffer = (char*)aMalloc(len+1);
  3635. fseek(fp, 0, SEEK_SET);
  3636. len = fread(buffer, 1, len, fp);
  3637. buffer[len] = '\0';
  3638. if( ferror(fp) )
  3639. {
  3640. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  3641. aFree(buffer);
  3642. fclose(fp);
  3643. return 0;
  3644. }
  3645. fclose(fp);
  3646. if ((unsigned char)buffer[0] == 0xEF && (unsigned char)buffer[1] == 0xBB && (unsigned char)buffer[2] == 0xBF) {
  3647. // UTF-8 BOM. This is most likely an error on the user's part, because:
  3648. // - BOM is discouraged in UTF-8, and the only place where you see it is Notepad and such.
  3649. // - It's unlikely that the user wants to use UTF-8 data here, since we don't really support it, nor does the client by default.
  3650. // - If the user really wants to use UTF-8 (instead of latin1, EUC-KR, SJIS, etc), then they can still do it <without BOM>.
  3651. // More info at http://unicode.org/faq/utf_bom.html#bom5 and http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  3652. ShowError("npc_parsesrcfile: Detected unsupported UTF-8 BOM in file '%s'. Stopping (please consider using another character set).\n", filepath);
  3653. aFree(buffer);
  3654. return 0;
  3655. }
  3656. // parse buffer
  3657. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  3658. {
  3659. int pos[9];
  3660. char w1[2048], w2[2048], w3[2048], w4[2048];
  3661. int i, count;
  3662. lines++;
  3663. // w1<TAB>w2<TAB>w3<TAB>w4
  3664. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  3665. if( count < 0 )
  3666. {
  3667. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  3668. break;
  3669. }
  3670. // fill w1
  3671. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  3672. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  3673. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  3674. memcpy(w1, p+pos[2], i*sizeof(char));
  3675. w1[i] = '\0';
  3676. // fill w2
  3677. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  3678. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  3679. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  3680. memcpy(w2, p+pos[4], i*sizeof(char));
  3681. w2[i] = '\0';
  3682. // fill w3
  3683. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  3684. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  3685. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  3686. memcpy(w3, p+pos[6], i*sizeof(char));
  3687. w3[i] = '\0';
  3688. // fill w4 (to end of line)
  3689. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  3690. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  3691. if( pos[8] != -1 )
  3692. {
  3693. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  3694. memcpy(w4, p+pos[8], i*sizeof(char));
  3695. w4[i] = '\0';
  3696. }
  3697. else
  3698. w4[0] = '\0';
  3699. if( count < 3 )
  3700. {// Unknown syntax
  3701. ShowError("npc_parsesrcfile: Unknown syntax in file '%s', line '%d'. Stopping...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3702. break;
  3703. }
  3704. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  3705. {// w1 = <map name>,<x>,<y>,<facing>
  3706. char mapname[MAP_NAME_LENGTH_EXT];
  3707. int count2;
  3708. count2 = sscanf(w1,"%15[^,],%6hd,%6hd[^,]",mapname,&x,&y);
  3709. if ( count2 < 1 ) {
  3710. ShowError("npc_parsesrcfile: Invalid script definition in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3711. if (strcasecmp(w2,"script") == 0 && count > 3) {
  3712. if ((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3713. break;
  3714. }
  3715. p = strchr(p,'\n');// next line
  3716. continue;
  3717. }else if( count2 < 3 ){
  3718. // If we were not able to parse any x and y coordinates(usually used by mapflags)
  3719. x = y = 0;
  3720. }
  3721. if( !mapindex_name2id(mapname) )
  3722. {// Incorrect map, we must skip the script info...
  3723. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  3724. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3725. {
  3726. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3727. {
  3728. break;
  3729. }
  3730. }
  3731. p = strchr(p,'\n');// next line
  3732. continue;
  3733. }
  3734. m = map_mapname2mapid(mapname);
  3735. if( m < 0 )
  3736. {// "mapname" is not assigned to this server, we must skip the script info...
  3737. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3738. {
  3739. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3740. {
  3741. break;
  3742. }
  3743. }
  3744. p = strchr(p,'\n');// next line
  3745. continue;
  3746. }
  3747. struct map_data *mapdata = map_getmapdata(m);
  3748. if (x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys) {
  3749. ShowError("npc_parsesrcfile: Unknown coordinates ('%d', '%d') for map '%s' in file '%s', line '%d'. Skipping line...\n", x, y, mapname, filepath, strline(buffer,p-buffer));
  3750. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3751. {
  3752. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3753. {
  3754. break;
  3755. }
  3756. }
  3757. p = strchr(p,'\n');// next line
  3758. continue;
  3759. }
  3760. }
  3761. if((strcasecmp(w2,"warp") == 0 || strcasecmp(w2,"warp2") == 0) && count > 3)
  3762. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  3763. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop") || !strcasecmp(w2,"itemshop") || !strcasecmp(w2,"pointshop") || !strcasecmp(w2,"marketshop") ) && count > 3 )
  3764. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  3765. else if( strcasecmp(w2,"script") == 0 && count > 3 ) {
  3766. if( strcasecmp(w1,"function") == 0 )
  3767. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  3768. else
  3769. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath,runOnInit);
  3770. }
  3771. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  3772. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  3773. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  3774. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  3775. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  3776. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  3777. else {
  3778. ShowError("npc_parsesrcfile: Unable to parse, probably a missing or extra TAB in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3779. p = strchr(p,'\n');// skip and continue
  3780. }
  3781. }
  3782. aFree(buffer);
  3783. return 1;
  3784. }
  3785. int npc_script_event(struct map_session_data* sd, enum npce_event type){
  3786. if (type == NPCE_MAX)
  3787. return 0;
  3788. if (!sd) {
  3789. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  3790. return 0;
  3791. }
  3792. std::vector<struct script_event_s>& vector = script_event[type];
  3793. for( struct script_event_s& evt : vector ){
  3794. npc_event_sub( sd, evt.event, evt.event_name );
  3795. }
  3796. return vector.size();
  3797. }
  3798. const char *npc_get_script_event_name(int npce_index)
  3799. {
  3800. switch (npce_index) {
  3801. case NPCE_LOGIN:
  3802. return script_config.login_event_name;
  3803. case NPCE_LOGOUT:
  3804. return script_config.logout_event_name;
  3805. case NPCE_LOADMAP:
  3806. return script_config.loadmap_event_name;
  3807. case NPCE_BASELVUP:
  3808. return script_config.baselvup_event_name;
  3809. case NPCE_JOBLVUP:
  3810. return script_config.joblvup_event_name;
  3811. case NPCE_DIE:
  3812. return script_config.die_event_name;
  3813. case NPCE_KILLPC:
  3814. return script_config.kill_pc_event_name;
  3815. case NPCE_KILLNPC:
  3816. return script_config.kill_mob_event_name;
  3817. case NPCE_STATCALC:
  3818. return script_config.stat_calc_event_name;
  3819. default:
  3820. ShowError("npc_get_script_event_name: npce_index is outside the array limits: %d (max: %d).\n", npce_index, NPCE_MAX);
  3821. return NULL;
  3822. }
  3823. }
  3824. void npc_read_event_script(void)
  3825. {
  3826. int i;
  3827. script_event.clear();
  3828. for (i = 0; i < NPCE_MAX; i++)
  3829. {
  3830. DBIterator* iter;
  3831. DBKey key;
  3832. DBData *data;
  3833. char name[EVENT_NAME_LENGTH];
  3834. safesnprintf(name,EVENT_NAME_LENGTH,"::%s", npc_get_script_event_name(i));
  3835. iter = db_iterator(ev_db);
  3836. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  3837. {
  3838. const char* p = key.str;
  3839. struct event_data* ed = (struct event_data*)db_data2ptr(data);
  3840. if( (p=strchr(p,':')) && strcmpi(name,p)==0 ){
  3841. struct script_event_s evt;
  3842. evt.event = ed;
  3843. evt.event_name = key.str;
  3844. script_event[static_cast<enum npce_event>(i)].push_back(evt);
  3845. }
  3846. }
  3847. dbi_destroy(iter);
  3848. }
  3849. if (battle_config.etc_log) {
  3850. //Print summary.
  3851. for (i = 0; i < NPCE_MAX; i++)
  3852. ShowInfo("%" PRIuPTR " '%s' events.\n", script_event[static_cast<enum npce_event>(i)].size(), npc_get_script_event_name(i));
  3853. }
  3854. }
  3855. void npc_clear_pathlist(void) {
  3856. struct npc_path_data *npd = NULL;
  3857. DBIterator *path_list = db_iterator(npc_path_db);
  3858. /* free all npc_path_data filepaths */
  3859. for( npd = (struct npc_path_data *)dbi_first(path_list); dbi_exists(path_list); npd = (struct npc_path_data *)dbi_next(path_list) ) {
  3860. if( npd->path )
  3861. aFree(npd->path);
  3862. }
  3863. dbi_destroy(path_list);
  3864. }
  3865. //Clear then reload npcs files
  3866. int npc_reload(void) {
  3867. struct npc_src_list *nsl;
  3868. int npc_new_min = npc_id;
  3869. struct s_mapiterator* iter;
  3870. struct block_list* bl;
  3871. /* clear guild flag cache */
  3872. guild_flags_clear();
  3873. npc_clear_pathlist();
  3874. db_clear(npc_path_db);
  3875. db_clear(npcname_db);
  3876. db_clear(ev_db);
  3877. //Remove all npcs/mobs. [Skotlex]
  3878. #if PACKETVER >= 20131223
  3879. npc_market_fromsql();
  3880. #endif
  3881. iter = mapit_geteachiddb();
  3882. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  3883. switch(bl->type) {
  3884. case BL_NPC:
  3885. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  3886. npc_unload((struct npc_data *)bl, false);
  3887. break;
  3888. case BL_MOB:
  3889. unit_free(bl,CLR_OUTSIGHT);
  3890. break;
  3891. }
  3892. }
  3893. mapit_free(iter);
  3894. // dynamic check by [random]
  3895. if( battle_config.dynamic_mobs ){
  3896. for (int i = 0; i < map_num; i++) {
  3897. for( int16 j = 0; j < MAX_MOB_LIST_PER_MAP; j++ ){
  3898. struct map_data *mapdata = map_getmapdata(i);
  3899. if (mapdata->moblist[j] != NULL) {
  3900. aFree(mapdata->moblist[j]);
  3901. mapdata->moblist[j] = NULL;
  3902. }
  3903. if( mapdata->mob_delete_timer != INVALID_TIMER )
  3904. { // Mobs were removed anyway,so delete the timer [Inkfish]
  3905. delete_timer(mapdata->mob_delete_timer, map_removemobs_timer);
  3906. mapdata->mob_delete_timer = INVALID_TIMER;
  3907. }
  3908. if( mapdata->npc_num > 0 ){
  3909. ShowWarning( "npc_reload: %d npcs weren't removed at map %s!\n", mapdata->npc_num, mapdata->name );
  3910. }
  3911. }
  3912. }
  3913. }
  3914. // clear mob spawn lookup index
  3915. mob_clear_spawninfo();
  3916. npc_warp = npc_shop = npc_script = 0;
  3917. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  3918. // reset mapflags
  3919. map_flags_init();
  3920. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  3921. // Reloading npcs now
  3922. for (nsl = npc_src_files; nsl; nsl = nsl->next) {
  3923. ShowStatus("Loading NPC file: %s" CL_CLL "\r", nsl->name);
  3924. npc_parsesrcfile(nsl->name,false);
  3925. }
  3926. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  3927. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  3928. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  3929. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  3930. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  3931. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  3932. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  3933. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3934. //Re-read the NPC Script Events cache.
  3935. npc_read_event_script();
  3936. /* refresh guild castle flags on both woe setups */
  3937. npc_event_doall( script_config.agit_init_event_name );
  3938. npc_event_doall( script_config.agit_init2_event_name );
  3939. npc_event_doall( script_config.agit_init3_event_name );
  3940. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  3941. npc_event_runall(script_config.init_event_name);
  3942. map_data_copyall();
  3943. do_reload_instance();
  3944. // Execute rest of the startup events if connected to char-server. [Lance]
  3945. if(!CheckForCharServer()){
  3946. npc_event_runall(script_config.inter_init_event_name);
  3947. }
  3948. #if PACKETVER >= 20131223
  3949. npc_market_checkall();
  3950. #endif
  3951. return 0;
  3952. }
  3953. //Unload all npc in the given file
  3954. bool npc_unloadfile( const char* path ) {
  3955. DBIterator * iter = db_iterator(npcname_db);
  3956. struct npc_data* nd = NULL;
  3957. bool found = false;
  3958. for( nd = (struct npc_data*)dbi_first(iter); dbi_exists(iter); nd = (struct npc_data*)dbi_next(iter) ) {
  3959. if( nd->path && strcasecmp(nd->path,path) == 0 ) {
  3960. found = true;
  3961. npc_unload_duplicates(nd);/* unload any npcs which could duplicate this but be in a different file */
  3962. npc_unload(nd, true);
  3963. }
  3964. }
  3965. dbi_destroy(iter);
  3966. if( found ) /* refresh event cache */
  3967. npc_read_event_script();
  3968. npc_delsrcfile(path);
  3969. return found;
  3970. }
  3971. void do_clear_npc(void) {
  3972. db_clear(npcname_db);
  3973. db_clear(ev_db);
  3974. }
  3975. /*==========================================
  3976. * Destructor
  3977. *------------------------------------------*/
  3978. void do_final_npc(void) {
  3979. npc_clear_pathlist();
  3980. script_event.clear();
  3981. ev_db->destroy(ev_db, NULL);
  3982. npcname_db->destroy(npcname_db, NULL);
  3983. npc_path_db->destroy(npc_path_db, NULL);
  3984. #if PACKETVER >= 20131223
  3985. NPCMarketDB->destroy(NPCMarketDB, npc_market_free);
  3986. #endif
  3987. ers_destroy(timer_event_ers);
  3988. ers_destroy(npc_sc_display_ers);
  3989. npc_clearsrcfile();
  3990. }
  3991. static void npc_debug_warps_sub(struct npc_data* nd)
  3992. {
  3993. int16 m;
  3994. if (nd->bl.type != BL_NPC || nd->subtype != NPCTYPE_WARP || nd->bl.m < 0)
  3995. return;
  3996. m = map_mapindex2mapid(nd->u.warp.mapindex);
  3997. if (m < 0) return; //Warps to another map, nothing to do about it.
  3998. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  3999. struct map_data *mapdata = map_getmapdata(m);
  4000. struct map_data *mapdata_nd = map_getmapdata(nd->bl.m);
  4001. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  4002. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  4003. nd->name,
  4004. mapdata_nd->name, nd->bl.x, nd->bl.y,
  4005. mapdata->name, nd->u.warp.x, nd->u.warp.y
  4006. );
  4007. }
  4008. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  4009. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  4010. nd->name,
  4011. mapdata_nd->name, nd->bl.x, nd->bl.y,
  4012. mapdata->name, nd->u.warp.x, nd->u.warp.y
  4013. );
  4014. }
  4015. }
  4016. static void npc_debug_warps(void){
  4017. for (int i = 0; i < map_num; i++) {
  4018. struct map_data *mapdata = map_getmapdata(i);
  4019. for( int i = 0; i < mapdata->npc_num; i++ ){
  4020. npc_debug_warps_sub(mapdata->npc[i]);
  4021. }
  4022. }
  4023. }
  4024. /*==========================================
  4025. * npc initialization
  4026. *------------------------------------------*/
  4027. void do_init_npc(void){
  4028. struct npc_src_list *file;
  4029. int i;
  4030. //Stock view data for normal npcs.
  4031. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  4032. npc_viewdb[0].class_ = JT_INVISIBLE; //Invisible class is stored here.
  4033. for( i = 1; i < MAX_NPC_CLASS; i++ )
  4034. npc_viewdb[i].class_ = i;
  4035. for( i = MAX_NPC_CLASS2_START; i < MAX_NPC_CLASS2_END; i++ )
  4036. npc_viewdb2[i - MAX_NPC_CLASS2_START].class_ = i;
  4037. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA), EVENT_NAME_LENGTH);
  4038. npcname_db = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  4039. npc_path_db = strdb_alloc((DBOptions)(DB_OPT_BASE|DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),80);
  4040. #if PACKETVER >= 20131223
  4041. NPCMarketDB = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  4042. npc_market_fromsql();
  4043. #endif
  4044. timer_event_ers = ers_new(sizeof(struct timer_event_data),"npc.cpp::timer_event_ers",ERS_OPT_NONE);
  4045. npc_sc_display_ers = ers_new(sizeof(struct sc_display_entry), "npc.cpp:npc_sc_display_ers", ERS_OPT_NONE);
  4046. // process all npc files
  4047. ShowStatus("Loading NPCs...\r");
  4048. for( file = npc_src_files; file != NULL; file = file->next ) {
  4049. ShowStatus("Loading NPC file: %s" CL_CLL "\r", file->name);
  4050. npc_parsesrcfile(file->name,false);
  4051. }
  4052. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  4053. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  4054. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  4055. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  4056. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  4057. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  4058. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  4059. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  4060. // set up the events cache
  4061. npc_read_event_script();
  4062. #if PACKETVER >= 20131223
  4063. npc_market_checkall();
  4064. #endif
  4065. //Debug function to locate all endless loop warps.
  4066. if (battle_config.warp_point_debug)
  4067. npc_debug_warps();
  4068. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  4069. add_timer_func_list(npc_timerevent,"npc_timerevent");
  4070. // Init dummy NPC
  4071. fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
  4072. fake_nd->bl.m = -1;
  4073. fake_nd->bl.id = npc_get_new_npc_id();
  4074. fake_nd->class_ = JT_FAKENPC;
  4075. fake_nd->speed = 200;
  4076. strcpy(fake_nd->name,"FAKE_NPC");
  4077. memcpy(fake_nd->exname, fake_nd->name, 9);
  4078. npc_script++;
  4079. fake_nd->bl.type = BL_NPC;
  4080. fake_nd->subtype = NPCTYPE_SCRIPT;
  4081. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  4082. fake_nd->u.scr.timerid = INVALID_TIMER;
  4083. map_addiddb(&fake_nd->bl);
  4084. // End of initialization
  4085. }