npc.cpp 149 KB

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