npc.cpp 150 KB

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