npc.cpp 143 KB

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