npc.cpp 150 KB

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