npc.c 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/cbasetypes.h"
  4. #include "../common/timer.h"
  5. #include "../common/nullpo.h"
  6. #include "../common/malloc.h"
  7. #include "../common/showmsg.h"
  8. #include "../common/strlib.h"
  9. #include "../common/utils.h"
  10. #include "../common/ers.h"
  11. #include "../common/db.h"
  12. #include "../common/socket.h"
  13. #include "map.h"
  14. #include "log.h"
  15. #include "clif.h"
  16. #include "intif.h"
  17. #include "pc.h"
  18. #include "status.h"
  19. #include "itemdb.h"
  20. #include "script.h"
  21. #include "mob.h"
  22. #include "pet.h"
  23. #include "instance.h"
  24. #include "battle.h"
  25. #include "skill.h"
  26. #include "unit.h"
  27. #include "npc.h"
  28. #include "chat.h"
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <time.h>
  34. #include <errno.h>
  35. struct npc_data* fake_nd;
  36. // linked list of npc source files
  37. struct npc_src_list {
  38. struct npc_src_list* next;
  39. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  40. };
  41. static struct npc_src_list* npc_src_files = NULL;
  42. static int npc_id=START_NPC_NUM;
  43. static int npc_warp=0;
  44. static int npc_shop=0;
  45. static int npc_script=0;
  46. static int npc_mob=0;
  47. static int npc_delay_mob=0;
  48. static int npc_cache_mob=0;
  49. /// Returns a new npc id that isn't being used in id_db.
  50. /// Fatal error if nothing is available.
  51. int npc_get_new_npc_id(void)
  52. {
  53. if( npc_id >= START_NPC_NUM && map_id2bl(npc_id) == NULL )
  54. return npc_id++;// available
  55. {// find next id
  56. int base_id = npc_id;
  57. while( base_id != ++npc_id )
  58. {
  59. if( npc_id < START_NPC_NUM )
  60. npc_id = START_NPC_NUM;
  61. if( map_id2bl(npc_id) == NULL )
  62. return npc_id++;// available
  63. }
  64. // full loop, nothing available
  65. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  66. exit(1);
  67. }
  68. }
  69. static DBMap* ev_db; // const char* event_name -> struct event_data*
  70. static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  71. struct event_data {
  72. struct npc_data *nd;
  73. int pos;
  74. };
  75. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  76. //For holding the view data of npc classes. [Skotlex]
  77. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  78. static struct script_event_s
  79. { //Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  80. struct event_data *event[UCHAR_MAX];
  81. const char *event_name[UCHAR_MAX];
  82. uint8 event_count;
  83. } script_event[NPCE_MAX];
  84. struct view_data* npc_get_viewdata(int class_)
  85. { //Returns the viewdata for normal npc classes.
  86. if( class_ == INVISIBLE_CLASS )
  87. return &npc_viewdb[0];
  88. if (npcdb_checkid(class_) || class_ == WARP_CLASS)
  89. return &npc_viewdb[class_];
  90. return NULL;
  91. }
  92. int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
  93. {
  94. char name[EVENT_NAME_LENGTH];
  95. if( nd->touching_id )
  96. return 0; // Attached a player already. Can't trigger on anyone else.
  97. if( pc_ishiding(sd) )
  98. return 1; // Can't trigger 'OnTouch_'. try 'OnTouch' later.
  99. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  100. return npc_event(sd,name,1);
  101. }
  102. int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
  103. {
  104. char name[EVENT_NAME_LENGTH];
  105. if( sd->areanpc_id == nd->bl.id )
  106. return 0;
  107. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_name);
  108. return npc_event(sd,name,2);
  109. }
  110. /*==========================================
  111. * NPCの無効化/有効化
  112. * npc_enable
  113. * npc_enable_sub 有効時にOnTouchイベントを実行
  114. *------------------------------------------*/
  115. int npc_enable_sub(struct block_list *bl, va_list ap)
  116. {
  117. struct npc_data *nd;
  118. nullpo_ret(bl);
  119. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  120. if(bl->type == BL_PC)
  121. {
  122. TBL_PC *sd = (TBL_PC*)bl;
  123. if (nd->sc.option&OPTION_INVISIBLE)
  124. return 1;
  125. if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
  126. { // failed to run OnTouch event, so just click the npc
  127. if (sd->npc_id != 0)
  128. return 0;
  129. pc_stop_walking(sd,1);
  130. npc_click(sd,nd);
  131. }
  132. }
  133. return 0;
  134. }
  135. int npc_enable(const char* name, int flag)
  136. {
  137. struct npc_data* nd = npc_name2id(name);
  138. if (nd==NULL)
  139. {
  140. ShowError("npc_enable: Attempted to %s a non-existing NPC '%s' (flag=%d).\n", (flag&3) ? "show" : "hide", name, flag);
  141. return 0;
  142. }
  143. if (flag&1)
  144. {
  145. nd->sc.option&=~OPTION_INVISIBLE;
  146. clif_spawn(&nd->bl);
  147. }
  148. else if (flag&2)
  149. nd->sc.option&=~OPTION_HIDE;
  150. else if (flag&4)
  151. nd->sc.option|= OPTION_HIDE;
  152. else //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  153. {
  154. nd->sc.option|= OPTION_INVISIBLE;
  155. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
  156. }
  157. if (nd->class_ == WARP_CLASS || nd->class_ == FLAG_CLASS)
  158. { //Client won't display option changes for these classes [Toms]
  159. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE))
  160. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);
  161. else
  162. clif_spawn(&nd->bl);
  163. } else
  164. clif_changeoption(&nd->bl);
  165. if( flag&3 && (nd->u.scr.xs >= 0 || nd->u.scr.ys >= 0) )
  166. map_foreachinarea( npc_enable_sub, nd->bl.m, nd->bl.x-nd->u.scr.xs, nd->bl.y-nd->u.scr.ys, nd->bl.x+nd->u.scr.xs, nd->bl.y+nd->u.scr.ys, BL_PC, nd );
  167. return 0;
  168. }
  169. /*==========================================
  170. * NPCを名前で探す
  171. *------------------------------------------*/
  172. struct npc_data* npc_name2id(const char* name)
  173. {
  174. return (struct npc_data *) strdb_get(npcname_db, name);
  175. }
  176. /**
  177. * For the Secure NPC Timeout option (check config/Secure.h) [RR]
  178. **/
  179. #if SECURE_NPCTIMEOUT
  180. /**
  181. * Timer to check for idle time and timeout the dialog if necessary
  182. **/
  183. int npc_rr_secure_timeout_timer(int tid, unsigned int tick, int id, intptr_t data) {
  184. struct map_session_data* sd = NULL;
  185. if( (sd = map_id2sd(id)) == NULL || !sd->npc_id ) {
  186. if( sd ) sd->npc_idle_timer = INVALID_TIMER;
  187. return 0;//Not logged in anymore OR no longer attached to a npc
  188. }
  189. if( DIFF_TICK(tick,sd->npc_idle_tick) > (SECURE_NPCTIMEOUT*1000) ) {
  190. /**
  191. * If we still have the NPC script attached, tell it to stop.
  192. **/
  193. if( sd->st )
  194. sd->st->state = END;
  195. /**
  196. * This guy's been idle for longer than allowed, close him.
  197. **/
  198. clif_scriptclose(sd,sd->npc_id);
  199. sd->npc_idle_timer = INVALID_TIMER;
  200. } else //Create a new instance of ourselves to continue
  201. sd->npc_idle_timer = add_timer(gettick() + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_rr_secure_timeout_timer,sd->bl.id,0);
  202. return 0;
  203. }
  204. #endif
  205. /*==========================================
  206. * イベントキューのイベント処理
  207. *------------------------------------------*/
  208. int npc_event_dequeue(struct map_session_data* sd)
  209. {
  210. nullpo_ret(sd);
  211. if(sd->npc_id)
  212. { //Current script is aborted.
  213. if(sd->state.using_fake_npc){
  214. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  215. sd->state.using_fake_npc = 0;
  216. }
  217. if (sd->st) {
  218. script_free_state(sd->st);
  219. sd->st = NULL;
  220. }
  221. sd->npc_id = 0;
  222. }
  223. if (!sd->eventqueue[0][0])
  224. return 0; //Nothing to dequeue
  225. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  226. { //Failed to dequeue, couldn't set a timer.
  227. ShowWarning("npc_event_dequeue: event timer is full !\n");
  228. return 0;
  229. }
  230. //Event dequeued successfully, shift other elements.
  231. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  232. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  233. return 1;
  234. }
  235. /*==========================================
  236. * exports a npc event label
  237. * called from npc_parse_script
  238. *------------------------------------------*/
  239. static int npc_event_export(struct npc_data *nd, int i)
  240. {
  241. char* lname = nd->u.scr.label_list[i].name;
  242. int pos = nd->u.scr.label_list[i].pos;
  243. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
  244. struct event_data *ev;
  245. char buf[EVENT_NAME_LENGTH];
  246. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  247. // generate the data and insert it
  248. CREATE(ev, struct event_data, 1);
  249. ev->nd = nd;
  250. ev->pos = pos;
  251. if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
  252. return 1;
  253. }
  254. return 0;
  255. }
  256. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  257. /**
  258. * 全てのNPCのOn*イベント実行
  259. * @see DBApply
  260. */
  261. int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
  262. {
  263. const char* p = key.str;
  264. struct event_data* ev;
  265. int* c;
  266. const char* name;
  267. int rid;
  268. nullpo_ret(ev = db_data2ptr(data));
  269. nullpo_ret(c = va_arg(ap, int *));
  270. nullpo_ret(name = va_arg(ap, const char *));
  271. rid = va_arg(ap, int);
  272. p = strchr(p, ':'); // match only the event name
  273. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  274. {
  275. if(rid) // a player may only have 1 script running at the same time
  276. npc_event_sub(map_id2sd(rid),ev,key.str);
  277. else
  278. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  279. (*c)++;
  280. }
  281. return 0;
  282. }
  283. /**
  284. * @see DBApply
  285. */
  286. static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
  287. {
  288. const char* p = key.str;
  289. struct event_data* ev;
  290. int* c;
  291. const char* name;
  292. nullpo_ret(ev = db_data2ptr(data));
  293. nullpo_ret(c = va_arg(ap, int *));
  294. nullpo_ret(name = va_arg(ap, const char *));
  295. if( p && strcmpi(name, p) == 0 )
  296. {
  297. run_script(ev->nd->u.scr.script,ev->pos,0,ev->nd->bl.id);
  298. (*c)++;
  299. }
  300. return 0;
  301. }
  302. // runs the specified event (supports both single-npc and global events)
  303. int npc_event_do(const char* name)
  304. {
  305. int c = 0;
  306. if( name[0] == ':' && name[1] == ':' )
  307. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0);
  308. else
  309. ev_db->foreach(ev_db,npc_event_do_sub,&c,name);
  310. return c;
  311. }
  312. // runs the specified event (global only)
  313. int npc_event_doall(const char* name)
  314. {
  315. return npc_event_doall_id(name, 0);
  316. }
  317. // runs the specified event, with a RID attached (global only)
  318. int npc_event_doall_id(const char* name, int rid)
  319. {
  320. int c = 0;
  321. char buf[64];
  322. safesnprintf(buf, sizeof(buf), "::%s", name);
  323. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  324. return c;
  325. }
  326. /// Checks whether or not the event name is used as transport for
  327. /// special flags.
  328. bool npc_event_isspecial(const char* eventname)
  329. {
  330. return (bool)( eventname && ISDIGIT(eventname[0]) && !strstr(eventname, "::") );
  331. }
  332. /*==========================================
  333. * 時計イベント実行
  334. *------------------------------------------*/
  335. int npc_event_do_clock(int tid, unsigned int tick, int id, intptr_t data)
  336. {
  337. static struct tm ev_tm_b; // tracks previous execution time
  338. time_t timer;
  339. struct tm* t;
  340. char buf[64];
  341. char* day;
  342. int c = 0;
  343. timer = time(NULL);
  344. t = localtime(&timer);
  345. switch (t->tm_wday) {
  346. case 0: day = "Sun"; break;
  347. case 1: day = "Mon"; break;
  348. case 2: day = "Tue"; break;
  349. case 3: day = "Wed"; break;
  350. case 4: day = "Thu"; break;
  351. case 5: day = "Fri"; break;
  352. case 6: day = "Sat"; break;
  353. default:day = ""; break;
  354. }
  355. if (t->tm_min != ev_tm_b.tm_min ) {
  356. sprintf(buf,"OnMinute%02d",t->tm_min);
  357. c+=npc_event_doall(buf);
  358. sprintf(buf,"OnClock%02d%02d",t->tm_hour,t->tm_min);
  359. c+=npc_event_doall(buf);
  360. sprintf(buf,"On%s%02d%02d",day,t->tm_hour,t->tm_min);
  361. c+=npc_event_doall(buf);
  362. }
  363. if (t->tm_hour!= ev_tm_b.tm_hour) {
  364. sprintf(buf,"OnHour%02d",t->tm_hour);
  365. c+=npc_event_doall(buf);
  366. }
  367. if (t->tm_mday!= ev_tm_b.tm_mday) {
  368. sprintf(buf,"OnDay%02d%02d",t->tm_mon+1,t->tm_mday);
  369. c+=npc_event_doall(buf);
  370. }
  371. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  372. return c;
  373. }
  374. /*==========================================
  375. * OnInitイベント実行(&時計イベント開始)
  376. *------------------------------------------*/
  377. void npc_event_do_oninit(void)
  378. {
  379. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs."CL_CLL"\n", npc_event_doall("OnInit"));
  380. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  381. }
  382. /*==========================================
  383. * タイマーイベント用ラベルの取り込み
  384. * called from npc_parse_script
  385. *------------------------------------------*/
  386. int npc_timerevent_export(struct npc_data *nd, int i)
  387. {
  388. int t = 0, k = 0;
  389. char *lname = nd->u.scr.label_list[i].name;
  390. int pos = nd->u.scr.label_list[i].pos;
  391. if (sscanf(lname, "OnTimer%d%n", &t, &k) == 1 && lname[k] == '\0') {
  392. // タイマーイベント
  393. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  394. int j, k = nd->u.scr.timeramount;
  395. if (te == NULL)
  396. te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
  397. else
  398. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k+1) );
  399. for (j = 0; j < k; j++) {
  400. if (te[j].timer > t) {
  401. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k-j));
  402. break;
  403. }
  404. }
  405. te[j].timer = t;
  406. te[j].pos = pos;
  407. nd->u.scr.timer_event = te;
  408. nd->u.scr.timeramount++;
  409. }
  410. return 0;
  411. }
  412. struct timer_event_data {
  413. int rid; //Attached player for this timer.
  414. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  415. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  416. };
  417. /*==========================================
  418. * triger 'OnTimerXXXX' events
  419. *------------------------------------------*/
  420. int npc_timerevent(int tid, unsigned int tick, int id, intptr_t data)
  421. {
  422. int next;
  423. int old_rid, old_timer;
  424. unsigned int old_tick;
  425. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  426. struct npc_timerevent_list *te;
  427. struct timer_event_data *ted = (struct timer_event_data*)data;
  428. struct map_session_data *sd=NULL;
  429. if( nd == NULL )
  430. {
  431. ShowError("npc_timerevent: NPC not found??\n");
  432. return 0;
  433. }
  434. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  435. {
  436. ShowError("npc_timerevent: Attached player not found.\n");
  437. ers_free(timer_event_ers, ted);
  438. return 0;
  439. }
  440. // These stuffs might need to be restored.
  441. old_rid = nd->u.scr.rid;
  442. old_tick = nd->u.scr.timertick;
  443. old_timer = nd->u.scr.timer;
  444. // Set the values of the timer
  445. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  446. nd->u.scr.timertick = tick; //current time tick
  447. nd->u.scr.timer = ted->time; //total time from beginning to now
  448. // Locate the event
  449. te = nd->u.scr.timer_event + ted->next;
  450. // Arrange for the next event
  451. ted->next++;
  452. if( nd->u.scr.timeramount > ted->next )
  453. {
  454. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  455. ted->time += next;
  456. if( sd )
  457. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  458. else
  459. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  460. }
  461. else
  462. {
  463. if( sd )
  464. sd->npc_timer_id = INVALID_TIMER;
  465. else
  466. {
  467. nd->u.scr.timerid = INVALID_TIMER;
  468. nd->u.scr.timertick = 0; // NPC timer stopped
  469. }
  470. ers_free(timer_event_ers, ted);
  471. }
  472. // Run the script
  473. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  474. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  475. if( sd )
  476. { // Restore previous data, only if this timer is a player-attached one.
  477. nd->u.scr.timer = old_timer;
  478. nd->u.scr.timertick = old_tick;
  479. }
  480. return 0;
  481. }
  482. /*==========================================
  483. * Start/Resume NPC timer
  484. *------------------------------------------*/
  485. int npc_timerevent_start(struct npc_data* nd, int rid)
  486. {
  487. int j, next;
  488. unsigned int tick = gettick();
  489. struct map_session_data *sd = NULL; //Player to whom script is attached.
  490. struct timer_event_data *ted;
  491. nullpo_ret(nd);
  492. // No need to start because of no events
  493. if( nd->u.scr.timeramount == 0 )
  494. return 0;
  495. // Check if there is an OnTimer Event
  496. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  497. if( j >= nd->u.scr.timeramount ) // No need to start because of no events left to trigger
  498. return 0;
  499. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  500. { // Failed to attach timer to this player.
  501. ShowError("npc_timerevent_start: Attached player not found!\n");
  502. return 1;
  503. }
  504. // Check if timer is already started.
  505. if( sd )
  506. {
  507. if( sd->npc_timer_id != INVALID_TIMER )
  508. return 0;
  509. }
  510. else if( nd->u.scr.timerid != INVALID_TIMER )
  511. return 0;
  512. // Arrange for the next event
  513. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  514. ted->next = j; // Set event index
  515. ted->time = nd->u.scr.timer_event[j].timer;
  516. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  517. if( sd )
  518. {
  519. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  520. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  521. }
  522. else
  523. {
  524. ted->rid = 0;
  525. nd->u.scr.timertick = tick; // Set when timer is started
  526. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  527. }
  528. return 0;
  529. }
  530. /*==========================================
  531. * Stop NPC timer
  532. *------------------------------------------*/
  533. int npc_timerevent_stop(struct npc_data* nd)
  534. {
  535. struct map_session_data *sd = NULL;
  536. const struct TimerData *td = NULL;
  537. int *tid;
  538. nullpo_ret(nd);
  539. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  540. {
  541. ShowError("npc_timerevent_stop: Attached player not found!\n");
  542. return 1;
  543. }
  544. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  545. if( *tid == INVALID_TIMER ) // Nothing to stop
  546. return 0;
  547. // Delete timer
  548. td = get_timer(*tid);
  549. if( td && td->data )
  550. ers_free(timer_event_ers, (void*)td->data);
  551. delete_timer(*tid,npc_timerevent);
  552. *tid = INVALID_TIMER;
  553. if( !sd )
  554. {
  555. 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
  556. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  557. }
  558. return 0;
  559. }
  560. /*==========================================
  561. * Aborts a running NPC timer that is attached to a player.
  562. *------------------------------------------*/
  563. void npc_timerevent_quit(struct map_session_data* sd)
  564. {
  565. const struct TimerData *td;
  566. struct npc_data* nd;
  567. struct timer_event_data *ted;
  568. // Check timer existance
  569. if( sd->npc_timer_id == INVALID_TIMER )
  570. return;
  571. if( !(td = get_timer(sd->npc_timer_id)) )
  572. {
  573. sd->npc_timer_id = INVALID_TIMER;
  574. return;
  575. }
  576. // Delete timer
  577. nd = (struct npc_data *)map_id2bl(td->id);
  578. ted = (struct timer_event_data*)td->data;
  579. delete_timer(sd->npc_timer_id, npc_timerevent);
  580. sd->npc_timer_id = INVALID_TIMER;
  581. // Execute OnTimerQuit
  582. if( nd && nd->bl.type == BL_NPC )
  583. {
  584. char buf[EVENT_NAME_LENGTH];
  585. struct event_data *ev;
  586. snprintf(buf, ARRAYLENGTH(buf), "%s::OnTimerQuit", nd->exname);
  587. ev = (struct event_data*)strdb_get(ev_db, buf);
  588. if( ev && ev->nd != nd )
  589. {
  590. ShowWarning("npc_timerevent_quit: Unable to execute \"OnTimerQuit\", two NPCs have the same event name [%s]!\n",buf);
  591. ev = NULL;
  592. }
  593. if( ev )
  594. {
  595. int old_rid,old_timer;
  596. unsigned int old_tick;
  597. //Set timer related info.
  598. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  599. old_tick = nd->u.scr.timertick;
  600. old_timer = nd->u.scr.timer;
  601. nd->u.scr.rid = sd->bl.id;
  602. nd->u.scr.timertick = gettick();
  603. nd->u.scr.timer = ted->time;
  604. //Execute label
  605. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  606. //Restore previous data.
  607. nd->u.scr.rid = old_rid;
  608. nd->u.scr.timer = old_timer;
  609. nd->u.scr.timertick = old_tick;
  610. }
  611. }
  612. ers_free(timer_event_ers, ted);
  613. }
  614. /*==========================================
  615. * Get the tick value of an NPC timer
  616. * If it's stopped, return stopped time
  617. *------------------------------------------*/
  618. int npc_gettimerevent_tick(struct npc_data* nd)
  619. {
  620. int tick;
  621. nullpo_ret(nd);
  622. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  623. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  624. if( nd->u.scr.timertick ) // It's a running timer
  625. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  626. return tick;
  627. }
  628. /*==========================================
  629. * Set tick for running and stopped timer
  630. *------------------------------------------*/
  631. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  632. {
  633. bool flag;
  634. int old_rid;
  635. //struct map_session_data *sd = NULL;
  636. nullpo_ret(nd);
  637. // TODO: Set player attached timer's tick.
  638. old_rid = nd->u.scr.rid;
  639. nd->u.scr.rid = 0;
  640. // Check if timer is started
  641. flag = (nd->u.scr.timerid != INVALID_TIMER);
  642. if( flag ) npc_timerevent_stop(nd);
  643. nd->u.scr.timer = newtimer;
  644. if( flag ) npc_timerevent_start(nd, -1);
  645. nd->u.scr.rid = old_rid;
  646. return 0;
  647. }
  648. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
  649. {
  650. if ( sd->npc_id != 0 )
  651. {
  652. //Enqueue the event trigger.
  653. int i;
  654. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  655. if( i < MAX_EVENTQUEUE )
  656. {
  657. safestrncpy(sd->eventqueue[i],eventname,50); //Event enqueued.
  658. return 0;
  659. }
  660. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  661. return 1;
  662. }
  663. if( ev->nd->sc.option&OPTION_INVISIBLE )
  664. {
  665. //Disabled npc, shouldn't trigger event.
  666. npc_event_dequeue(sd);
  667. return 2;
  668. }
  669. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  670. return 0;
  671. }
  672. /*==========================================
  673. * イベント型のNPC処理
  674. *------------------------------------------*/
  675. int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
  676. {
  677. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  678. struct npc_data *nd;
  679. nullpo_ret(sd);
  680. if( ev == NULL || (nd = ev->nd) == NULL )
  681. {
  682. if( !ontouch )
  683. ShowError("npc_event: event not found [%s]\n", eventname);
  684. return ontouch;
  685. }
  686. switch(ontouch)
  687. {
  688. case 1:
  689. nd->touching_id = sd->bl.id;
  690. sd->touching_id = nd->bl.id;
  691. break;
  692. case 2:
  693. sd->areanpc_id = nd->bl.id;
  694. break;
  695. }
  696. return npc_event_sub(sd,ev,eventname);
  697. }
  698. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  699. {
  700. struct map_session_data *sd;
  701. int pc_id,npc_id;
  702. char *name;
  703. nullpo_ret(bl);
  704. nullpo_ret((sd = map_id2sd(bl->id)));
  705. pc_id = va_arg(ap,int);
  706. npc_id = va_arg(ap,int);
  707. name = va_arg(ap,char*);
  708. if( pc_ishiding(sd) )
  709. return 0;
  710. if( pc_id == sd->bl.id )
  711. return 0;
  712. npc_event(sd,name,1);
  713. return 1;
  714. }
  715. int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
  716. {
  717. struct npc_data *nd = map_id2nd(sd->touching_id);
  718. short xs, ys;
  719. if( !nd || nd->touching_id != sd->bl.id )
  720. return 1;
  721. xs = nd->u.scr.xs;
  722. ys = nd->u.scr.ys;
  723. if( sd->bl.m != nd->bl.m ||
  724. sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs ||
  725. sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys ||
  726. pc_ishiding(sd) || leavemap )
  727. {
  728. char name[EVENT_NAME_LENGTH];
  729. nd->touching_id = sd->touching_id = 0;
  730. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  731. 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,nd->bl.id,name);
  732. }
  733. return 0;
  734. }
  735. /*==========================================
  736. * 接触型のNPC処理
  737. *------------------------------------------*/
  738. int npc_touch_areanpc(struct map_session_data* sd, int m, int x, int y)
  739. {
  740. int xs,ys;
  741. int f = 1;
  742. int i;
  743. nullpo_retr(1, sd);
  744. // Why not enqueue it? [Inkfish]
  745. //if(sd->npc_id)
  746. // return 1;
  747. for(i=0;i<map[m].npc_num;i++)
  748. {
  749. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE) {
  750. f=0; // a npc was found, but it is disabled; don't print warning
  751. continue;
  752. }
  753. switch(map[m].npc[i]->subtype) {
  754. case WARP:
  755. xs=map[m].npc[i]->u.warp.xs;
  756. ys=map[m].npc[i]->u.warp.ys;
  757. break;
  758. case SCRIPT:
  759. xs=map[m].npc[i]->u.scr.xs;
  760. ys=map[m].npc[i]->u.scr.ys;
  761. break;
  762. default:
  763. continue;
  764. }
  765. if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs
  766. && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
  767. break;
  768. }
  769. if( i == map[m].npc_num )
  770. {
  771. if( f == 1 ) // no npc found
  772. ShowError("npc_touch_areanpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", map[m].name, x, y);
  773. return 1;
  774. }
  775. switch(map[m].npc[i]->subtype) {
  776. case WARP:
  777. if( pc_ishiding(sd) )
  778. break; // hidden chars cannot use warps
  779. pc_setpos(sd,map[m].npc[i]->u.warp.mapindex,map[m].npc[i]->u.warp.x,map[m].npc[i]->u.warp.y,CLR_OUTSIGHT);
  780. break;
  781. case SCRIPT:
  782. if( npc_ontouch_event(sd,map[m].npc[i]) > 0 && npc_ontouch2_event(sd,map[m].npc[i]) > 0 )
  783. { // failed to run OnTouch event, so just click the npc
  784. struct unit_data *ud = unit_bl2ud(&sd->bl);
  785. if( ud && ud->walkpath.path_pos < ud->walkpath.path_len )
  786. { // Since walktimer always == INVALID_TIMER at this time, we stop walking manually. [Inkfish]
  787. clif_fixpos(&sd->bl);
  788. ud->walkpath.path_pos = ud->walkpath.path_len;
  789. }
  790. sd->areanpc_id = map[m].npc[i]->bl.id;
  791. npc_click(sd,map[m].npc[i]);
  792. }
  793. break;
  794. }
  795. return 0;
  796. }
  797. // OnTouch NPC or Warp for Mobs
  798. // Return 1 if Warped
  799. int npc_touch_areanpc2(struct mob_data *md)
  800. {
  801. int i, m = md->bl.m, x = md->bl.x, y = md->bl.y, id;
  802. char eventname[EVENT_NAME_LENGTH];
  803. struct event_data* ev;
  804. int xs, ys;
  805. for( i = 0; i < map[m].npc_num; i++ )
  806. {
  807. if( map[m].npc[i]->sc.option&OPTION_INVISIBLE )
  808. continue;
  809. switch( map[m].npc[i]->subtype )
  810. {
  811. case WARP:
  812. if( !( battle_config.mob_warp&1 ) )
  813. continue;
  814. xs = map[m].npc[i]->u.warp.xs;
  815. ys = map[m].npc[i]->u.warp.ys;
  816. break;
  817. case SCRIPT:
  818. xs = map[m].npc[i]->u.scr.xs;
  819. ys = map[m].npc[i]->u.scr.ys;
  820. break;
  821. default:
  822. continue; // Keep Searching
  823. }
  824. if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
  825. { // In the npc touch area
  826. switch( map[m].npc[i]->subtype )
  827. {
  828. case WARP:
  829. xs = map_mapindex2mapid(map[m].npc[i]->u.warp.mapindex);
  830. if( m < 0 )
  831. break; // Cannot Warp between map servers
  832. if( unit_warp(&md->bl, xs, map[m].npc[i]->u.warp.x, map[m].npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  833. return 1; // Warped
  834. break;
  835. case SCRIPT:
  836. if( map[m].npc[i]->bl.id == md->areanpc_id )
  837. break; // Already touch this NPC
  838. snprintf(eventname, ARRAYLENGTH(eventname), "%s::OnTouchNPC", map[m].npc[i]->exname);
  839. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  840. break; // No OnTouchNPC Event
  841. md->areanpc_id = map[m].npc[i]->bl.id;
  842. id = md->bl.id; // Stores Unique ID
  843. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  844. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  845. break;
  846. }
  847. return 0;
  848. }
  849. }
  850. return 0;
  851. }
  852. //Checks if there are any NPC on-touch objects on the given range.
  853. //Flag determines the type of object to check for:
  854. //&1: NPC Warps
  855. //&2: NPCs with on-touch events.
  856. int npc_check_areanpc(int flag, int m, int x, int y, int range)
  857. {
  858. int i;
  859. int x0,y0,x1,y1;
  860. int xs,ys;
  861. if (range < 0) return 0;
  862. x0 = max(x-range, 0);
  863. y0 = max(y-range, 0);
  864. x1 = min(x+range, map[m].xs-1);
  865. y1 = min(y+range, map[m].ys-1);
  866. //First check for npc_cells on the range given
  867. i = 0;
  868. for (ys = y0; ys <= y1 && !i; ys++) {
  869. for(xs = x0; xs <= x1 && !i; xs++){
  870. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  871. i = 1;
  872. }
  873. }
  874. if (!i) return 0; //No NPC_CELLs.
  875. //Now check for the actual NPC on said range.
  876. for(i=0;i<map[m].npc_num;i++)
  877. {
  878. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE)
  879. continue;
  880. switch(map[m].npc[i]->subtype)
  881. {
  882. case WARP:
  883. if (!(flag&1))
  884. continue;
  885. xs=map[m].npc[i]->u.warp.xs;
  886. ys=map[m].npc[i]->u.warp.ys;
  887. break;
  888. case SCRIPT:
  889. if (!(flag&2))
  890. continue;
  891. xs=map[m].npc[i]->u.scr.xs;
  892. ys=map[m].npc[i]->u.scr.ys;
  893. break;
  894. default:
  895. continue;
  896. }
  897. if( x1 >= map[m].npc[i]->bl.x-xs && x0 <= map[m].npc[i]->bl.x+xs
  898. && y1 >= map[m].npc[i]->bl.y-ys && y0 <= map[m].npc[i]->bl.y+ys )
  899. break; // found a npc
  900. }
  901. if (i==map[m].npc_num)
  902. return 0;
  903. return (map[m].npc[i]->bl.id);
  904. }
  905. struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
  906. {
  907. struct npc_data *nd;
  908. nullpo_retr(NULL, sd);
  909. if(bl == NULL) return NULL;
  910. if(bl->type != BL_NPC) return NULL;
  911. nd = (TBL_NPC*)bl;
  912. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  913. return nd;
  914. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  915. return nd;
  916. if (bl->m!=sd->bl.m ||
  917. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  918. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  919. return NULL;
  920. return nd;
  921. }
  922. /*==========================================
  923. * NPCのオープンチャット発言
  924. *------------------------------------------*/
  925. int npc_globalmessage(const char* name, const char* mes)
  926. {
  927. struct npc_data* nd = npc_name2id(name);
  928. char temp[100];
  929. if (!nd)
  930. return 0;
  931. snprintf(temp, sizeof(temp), "%s : %s", name, mes);
  932. clif_GlobalMessage(&nd->bl,temp);
  933. return 0;
  934. }
  935. /*==========================================
  936. * クリック時のNPC処理
  937. *------------------------------------------*/
  938. int npc_click(struct map_session_data* sd, struct npc_data* nd)
  939. {
  940. nullpo_retr(1, sd);
  941. if (sd->npc_id != 0) {
  942. ShowError("npc_click: npc_id != 0\n");
  943. return 1;
  944. }
  945. if(!nd) return 1;
  946. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  947. return 1;
  948. //Hidden/Disabled npc.
  949. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  950. return 1;
  951. switch(nd->subtype) {
  952. case SHOP:
  953. clif_npcbuysell(sd,nd->bl.id);
  954. break;
  955. case CASHSHOP:
  956. clif_cashshop_show(sd,nd);
  957. break;
  958. case SCRIPT:
  959. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  960. break;
  961. }
  962. return 0;
  963. }
  964. /*==========================================
  965. *
  966. *------------------------------------------*/
  967. int npc_scriptcont(struct map_session_data* sd, int id)
  968. {
  969. nullpo_retr(1, sd);
  970. if( id != sd->npc_id ){
  971. TBL_NPC* nd_sd=(TBL_NPC*)map_id2bl(sd->npc_id);
  972. TBL_NPC* nd=(TBL_NPC*)map_id2bl(id);
  973. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  974. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  975. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  976. return 1;
  977. }
  978. if(id != fake_nd->bl.id) { // Not item script
  979. if ((npc_checknear(sd,map_id2bl(id))) == NULL){
  980. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  981. return 1;
  982. }
  983. }
  984. /**
  985. * For the Secure NPC Timeout option (check config/Secure.h) [RR]
  986. **/
  987. #if SECURE_NPCTIMEOUT
  988. /**
  989. * Update the last NPC iteration
  990. **/
  991. sd->npc_idle_tick = gettick();
  992. #endif
  993. /**
  994. * WPE can get to this point with a progressbar; we deny it.
  995. **/
  996. if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
  997. return 1;
  998. run_script_main(sd->st);
  999. return 0;
  1000. }
  1001. /*==========================================
  1002. *
  1003. *------------------------------------------*/
  1004. int npc_buysellsel(struct map_session_data* sd, int id, int type)
  1005. {
  1006. struct npc_data *nd;
  1007. nullpo_retr(1, sd);
  1008. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  1009. return 1;
  1010. if (nd->subtype!=SHOP) {
  1011. ShowError("no such shop npc : %d\n",id);
  1012. if (sd->npc_id == id)
  1013. sd->npc_id=0;
  1014. return 1;
  1015. }
  1016. if (nd->sc.option&OPTION_INVISIBLE) // 無効化されている
  1017. return 1;
  1018. if( nd->class_ < 0 && !sd->state.callshop )
  1019. {// not called through a script and is not a visible NPC so an invalid call
  1020. return 1;
  1021. }
  1022. // reset the callshop state for future calls
  1023. sd->state.callshop = 0;
  1024. sd->npc_shopid = id;
  1025. if (type==0) {
  1026. clif_buylist(sd,nd);
  1027. } else {
  1028. clif_selllist(sd);
  1029. }
  1030. return 0;
  1031. }
  1032. /*==========================================
  1033. * Cash Shop Buy List
  1034. *------------------------------------------*/
  1035. int npc_cashshop_buylist(struct map_session_data *sd, int points, int count, unsigned short* item_list)
  1036. {
  1037. int i, j, nameid, amount, new_, w, vt;
  1038. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1039. if( !nd || nd->subtype != CASHSHOP )
  1040. return 1;
  1041. if( sd->state.trading )
  1042. return 4;
  1043. new_ = 0;
  1044. w = 0;
  1045. vt = 0; // Global Value
  1046. // Validating Process ----------------------------------------------------
  1047. for( i = 0; i < count; i++ )
  1048. {
  1049. nameid = item_list[i*2+1];
  1050. amount = item_list[i*2+0];
  1051. if( !itemdb_exists(nameid) || amount <= 0 )
  1052. return 5;
  1053. ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid);
  1054. if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
  1055. return 5;
  1056. if( !itemdb_isstackable(nameid) && amount > 1 )
  1057. {
  1058. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1059. amount = item_list[i*2+0] = 1;
  1060. }
  1061. switch( pc_checkadditem(sd,nameid,amount) )
  1062. {
  1063. case ADDITEM_NEW:
  1064. new_++;
  1065. break;
  1066. case ADDITEM_OVERAMOUNT:
  1067. return 3;
  1068. }
  1069. vt += nd->u.shop.shop_item[j].value * amount;
  1070. w += itemdb_weight(nameid) * amount;
  1071. }
  1072. if( w + sd->weight > sd->max_weight )
  1073. return 3;
  1074. if( pc_inventoryblank(sd) < new_ )
  1075. return 3;
  1076. if( points > vt ) points = vt;
  1077. // Payment Process ----------------------------------------------------
  1078. if( sd->kafraPoints < points || sd->cashPoints < (vt - points) )
  1079. return 6;
  1080. pc_paycash(sd,vt,points);
  1081. // Delivery Process ----------------------------------------------------
  1082. for( i = 0; i < count; i++ )
  1083. {
  1084. struct item item_tmp;
  1085. nameid = item_list[i*2+1];
  1086. amount = item_list[i*2+0];
  1087. memset(&item_tmp,0,sizeof(item_tmp));
  1088. if( !pet_create_egg(sd,nameid) )
  1089. {
  1090. item_tmp.nameid = nameid;
  1091. item_tmp.identify = 1;
  1092. pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
  1093. }
  1094. }
  1095. return 0;
  1096. }
  1097. //npc_buylist for script-controlled shops.
  1098. static int npc_buylist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1099. {
  1100. char npc_ev[EVENT_NAME_LENGTH];
  1101. int i;
  1102. int key_nameid = 0;
  1103. int key_amount = 0;
  1104. // discard old contents
  1105. script_cleararray_pc(sd, "@bought_nameid", (void*)0);
  1106. script_cleararray_pc(sd, "@bought_quantity", (void*)0);
  1107. // save list of bought items
  1108. for( i = 0; i < n; i++ )
  1109. {
  1110. script_setarray_pc(sd, "@bought_nameid", i, (void*)(intptr_t)item_list[i*2+1], &key_nameid);
  1111. script_setarray_pc(sd, "@bought_quantity", i, (void*)(intptr_t)item_list[i*2], &key_amount);
  1112. }
  1113. // invoke event
  1114. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnBuyItem", nd->exname);
  1115. npc_event(sd, npc_ev, 0);
  1116. return 0;
  1117. }
  1118. /*==========================================
  1119. * Cash Shop Buy
  1120. *------------------------------------------*/
  1121. int npc_cashshop_buy(struct map_session_data *sd, int nameid, int amount, int points)
  1122. {
  1123. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1124. struct item_data *item;
  1125. int i, price, w;
  1126. if( amount <= 0 )
  1127. return 5;
  1128. if( points < 0 )
  1129. return 6;
  1130. if( !nd || nd->subtype != CASHSHOP )
  1131. return 1;
  1132. if( sd->state.trading )
  1133. return 4;
  1134. if( (item = itemdb_exists(nameid)) == NULL )
  1135. return 5; // Invalid Item
  1136. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  1137. if( i == nd->u.shop.count )
  1138. return 5;
  1139. if( nd->u.shop.shop_item[i].value <= 0 )
  1140. return 5;
  1141. if(!itemdb_isstackable(nameid) && amount > 1)
  1142. {
  1143. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1144. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1145. amount = 1;
  1146. }
  1147. switch( pc_checkadditem(sd, nameid, amount) )
  1148. {
  1149. case ADDITEM_NEW:
  1150. if( pc_inventoryblank(sd) == 0 )
  1151. return 3;
  1152. break;
  1153. case ADDITEM_OVERAMOUNT:
  1154. return 3;
  1155. }
  1156. w = item->weight * amount;
  1157. if( w + sd->weight > sd->max_weight )
  1158. return 3;
  1159. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  1160. {
  1161. ShowWarning("npc_cashshop_buy: Item '%s' (%d) price overflow attempt!\n", item->name, nameid);
  1162. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n", nd->exname, map[nd->bl.m].name, 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);
  1163. return 5;
  1164. }
  1165. price = nd->u.shop.shop_item[i].value * amount;
  1166. if( points > price )
  1167. points = price;
  1168. if( (sd->kafraPoints < points) || (sd->cashPoints < price - points) )
  1169. return 6;
  1170. pc_paycash(sd, price, points);
  1171. if( !pet_create_egg(sd, nameid) )
  1172. {
  1173. struct item item_tmp;
  1174. memset(&item_tmp, 0, sizeof(struct item));
  1175. item_tmp.nameid = nameid;
  1176. item_tmp.identify = 1;
  1177. pc_additem(sd,&item_tmp, amount, LOG_TYPE_NPC);
  1178. }
  1179. return 0;
  1180. }
  1181. /// Player item purchase from npc shop.
  1182. ///
  1183. /// @param item_list 'n' pairs <amount,itemid>
  1184. /// @return result code for clif_parse_NpcBuyListSend
  1185. int npc_buylist(struct map_session_data* sd, int n, unsigned short* item_list)
  1186. {
  1187. struct npc_data* nd;
  1188. double z;
  1189. int i,j,w,skill,new_;
  1190. nullpo_retr(3, sd);
  1191. nullpo_retr(3, item_list);
  1192. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  1193. if( nd == NULL )
  1194. return 3;
  1195. if( nd->subtype != SHOP )
  1196. return 3;
  1197. z = 0;
  1198. w = 0;
  1199. new_ = 0;
  1200. // process entries in buy list, one by one
  1201. for( i = 0; i < n; ++i )
  1202. {
  1203. int nameid, amount, value;
  1204. // find this entry in the shop's sell list
  1205. ARR_FIND( 0, nd->u.shop.count, j,
  1206. item_list[i*2+1] == nd->u.shop.shop_item[j].nameid || //Normal items
  1207. item_list[i*2+1] == itemdb_viewid(nd->u.shop.shop_item[j].nameid) //item_avail replacement
  1208. );
  1209. if( j == nd->u.shop.count )
  1210. return 3; // no such item in shop
  1211. amount = item_list[i*2+0];
  1212. nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  1213. value = nd->u.shop.shop_item[j].value;
  1214. if( !itemdb_exists(nameid) )
  1215. return 3; // item no longer in itemdb
  1216. if( !itemdb_isstackable(nameid) && amount > 1 )
  1217. { //Exploit? You can't buy more than 1 of equipment types o.O
  1218. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1219. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1220. amount = item_list[i*2+0] = 1;
  1221. }
  1222. if( nd->master_nd )
  1223. {// Script-controlled shops decide by themselves, what can be bought and for what price.
  1224. continue;
  1225. }
  1226. switch( pc_checkadditem(sd,nameid,amount) )
  1227. {
  1228. case ADDITEM_EXIST:
  1229. break;
  1230. case ADDITEM_NEW:
  1231. new_++;
  1232. break;
  1233. case ADDITEM_OVERAMOUNT:
  1234. return 2;
  1235. }
  1236. value = pc_modifybuyvalue(sd,value);
  1237. z += (double)value * amount;
  1238. w += itemdb_weight(nameid) * amount;
  1239. }
  1240. if( nd->master_nd != NULL ) //Script-based shops.
  1241. return npc_buylist_sub(sd,n,item_list,nd->master_nd);
  1242. if( z > (double)sd->status.zeny )
  1243. return 1; // Not enough Zeny
  1244. if( w + sd->weight > sd->max_weight )
  1245. return 2; // Too heavy
  1246. if( pc_inventoryblank(sd) < new_ )
  1247. return 3; // Not enough space to store items
  1248. //Logs (S)hopping Zeny [Lupus]
  1249. log_zeny(sd, LOG_TYPE_NPC, sd, -(int)z);
  1250. //Logs
  1251. pc_payzeny(sd,(int)z);
  1252. for( i = 0; i < n; ++i )
  1253. {
  1254. int nameid = item_list[i*2+1];
  1255. int amount = item_list[i*2+0];
  1256. struct item item_tmp;
  1257. memset(&item_tmp,0,sizeof(item_tmp));
  1258. item_tmp.nameid = nameid;
  1259. item_tmp.identify = 1;
  1260. pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
  1261. }
  1262. // custom merchant shop exp bonus
  1263. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 )
  1264. {
  1265. if( sd->status.skill[MC_DISCOUNT].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1266. skill = sd->status.skill[MC_DISCOUNT].flag - SKILL_FLAG_REPLACED_LV_0;
  1267. if( skill > 0 )
  1268. {
  1269. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1270. if( z < 1 )
  1271. z = 1;
  1272. pc_gainexp(sd,NULL,0,(int)z, false);
  1273. }
  1274. }
  1275. return 0;
  1276. }
  1277. /// npc_selllist for script-controlled shops
  1278. static int npc_selllist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1279. {
  1280. char npc_ev[EVENT_NAME_LENGTH];
  1281. char card_slot[NAME_LENGTH];
  1282. int i, j, idx;
  1283. int key_nameid = 0;
  1284. int key_amount = 0;
  1285. int key_refine = 0;
  1286. int key_attribute = 0;
  1287. int key_identify = 0;
  1288. int key_card = 0;
  1289. // discard old contents
  1290. script_cleararray_pc(sd, "@sold_nameid", (void*)0);
  1291. script_cleararray_pc(sd, "@sold_quantity", (void*)0);
  1292. script_cleararray_pc(sd, "@sold_refine", (void*)0);
  1293. script_cleararray_pc(sd, "@sold_attribute", (void*)0);
  1294. script_cleararray_pc(sd, "@sold_identify", (void*)0);
  1295. for( j = 0; MAX_SLOTS > j; j++ )
  1296. {// clear each of the card slot entries
  1297. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1298. script_cleararray_pc(sd, card_slot, (void*)0);
  1299. }
  1300. // save list of to be sold items
  1301. for( i = 0; i < n; i++ )
  1302. {
  1303. idx = item_list[i*2]-2;
  1304. script_setarray_pc(sd, "@sold_nameid", i, (void*)(intptr_t)sd->status.inventory[idx].nameid, &key_nameid);
  1305. script_setarray_pc(sd, "@sold_quantity", i, (void*)(intptr_t)item_list[i*2+1], &key_amount);
  1306. if( itemdb_isequip(sd->status.inventory[idx].nameid) )
  1307. {// process equipment based information into the arrays
  1308. script_setarray_pc(sd, "@sold_refine", i, (void*)(intptr_t)sd->status.inventory[idx].refine, &key_refine);
  1309. script_setarray_pc(sd, "@sold_attribute", i, (void*)(intptr_t)sd->status.inventory[idx].attribute, &key_attribute);
  1310. script_setarray_pc(sd, "@sold_identify", i, (void*)(intptr_t)sd->status.inventory[idx].identify, &key_identify);
  1311. for( j = 0; MAX_SLOTS > j; j++ )
  1312. {// store each of the cards from the equipment in the array
  1313. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1314. script_setarray_pc(sd, card_slot, i, (void*)(intptr_t)sd->status.inventory[idx].card[j], &key_card);
  1315. }
  1316. }
  1317. }
  1318. // invoke event
  1319. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnSellItem", nd->exname);
  1320. npc_event(sd, npc_ev, 0);
  1321. return 0;
  1322. }
  1323. /// Player item selling to npc shop.
  1324. ///
  1325. /// @param item_list 'n' pairs <index,amount>
  1326. /// @return result code for clif_parse_NpcSellListSend
  1327. int npc_selllist(struct map_session_data* sd, int n, unsigned short* item_list)
  1328. {
  1329. double z;
  1330. int i,skill;
  1331. struct npc_data *nd;
  1332. nullpo_retr(1, sd);
  1333. nullpo_retr(1, item_list);
  1334. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL || nd->subtype != SHOP )
  1335. {
  1336. return 1;
  1337. }
  1338. z = 0;
  1339. // verify the sell list
  1340. for( i = 0; i < n; i++ )
  1341. {
  1342. int nameid, amount, idx, value;
  1343. idx = item_list[i*2]-2;
  1344. amount = item_list[i*2+1];
  1345. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  1346. {
  1347. return 1;
  1348. }
  1349. nameid = sd->status.inventory[idx].nameid;
  1350. if( !nameid || !sd->inventory_data[idx] || sd->status.inventory[idx].amount < amount )
  1351. {
  1352. return 1;
  1353. }
  1354. if( nd->master_nd )
  1355. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  1356. continue;
  1357. }
  1358. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  1359. z+= (double)value*amount;
  1360. }
  1361. if( nd->master_nd )
  1362. {// Script-controlled shops
  1363. return npc_selllist_sub(sd, n, item_list, nd->master_nd);
  1364. }
  1365. // delete items
  1366. for( i = 0; i < n; i++ )
  1367. {
  1368. int nameid, amount, idx;
  1369. idx = item_list[i*2]-2;
  1370. amount = item_list[i*2+1];
  1371. nameid = sd->status.inventory[idx].nameid;
  1372. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->status.inventory[idx].card[0] == CARD0_PET )
  1373. {
  1374. if( search_petDB_index(sd->status.inventory[idx].nameid, PET_EGG) >= 0 )
  1375. {
  1376. intif_delete_petdata(MakeDWord(sd->status.inventory[idx].card[1], sd->status.inventory[idx].card[2]));
  1377. }
  1378. }
  1379. pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC);
  1380. }
  1381. if( z > MAX_ZENY )
  1382. z = MAX_ZENY;
  1383. //Logs (S)hopping Zeny [Lupus]
  1384. log_zeny(sd, LOG_TYPE_NPC, sd, (int)z);
  1385. //Logs
  1386. pc_getzeny(sd, (int)z);
  1387. // custom merchant shop exp bonus
  1388. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  1389. {
  1390. if( sd->status.skill[MC_OVERCHARGE].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1391. skill = sd->status.skill[MC_OVERCHARGE].flag - SKILL_FLAG_REPLACED_LV_0;
  1392. if( skill > 0 )
  1393. {
  1394. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1395. if( z < 1 )
  1396. z = 1;
  1397. pc_gainexp(sd, NULL, 0, (int)z, false);
  1398. }
  1399. }
  1400. return 0;
  1401. }
  1402. int npc_remove_map(struct npc_data* nd)
  1403. {
  1404. int m,i;
  1405. nullpo_retr(1, nd);
  1406. if(nd->bl.prev == NULL || nd->bl.m < 0)
  1407. return 1; //Not assigned to a map.
  1408. m = nd->bl.m;
  1409. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  1410. npc_unsetcells(nd);
  1411. map_delblock(&nd->bl);
  1412. //Remove npc from map[].npc list. [Skotlex]
  1413. ARR_FIND( 0, map[m].npc_num, i, map[m].npc[i] == nd );
  1414. if( i == map[m].npc_num ) return 2; //failed to find it?
  1415. map[m].npc_num--;
  1416. map[m].npc[i] = map[m].npc[map[m].npc_num];
  1417. map[m].npc[map[m].npc_num] = NULL;
  1418. return 0;
  1419. }
  1420. /**
  1421. * @see DBApply
  1422. */
  1423. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  1424. {
  1425. struct event_data* ev = db_data2ptr(data);
  1426. char* npcname = va_arg(ap, char *);
  1427. if(strcmp(ev->nd->exname,npcname)==0){
  1428. db_remove(ev_db, key);
  1429. return 1;
  1430. }
  1431. return 0;
  1432. }
  1433. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  1434. {
  1435. int src_id;
  1436. src_id = va_arg(args, int);
  1437. if (nd->src_id == src_id)
  1438. npc_unload(nd);
  1439. return 0;
  1440. }
  1441. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  1442. void npc_unload_duplicates(struct npc_data* nd)
  1443. {
  1444. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  1445. }
  1446. int npc_unload(struct npc_data* nd)
  1447. {
  1448. nullpo_ret(nd);
  1449. npc_remove_map(nd);
  1450. map_deliddb(&nd->bl);
  1451. strdb_remove(npcname_db, nd->exname);
  1452. if (nd->chat_id) // remove npc chatroom object and kick users
  1453. chat_deletenpcchat(nd);
  1454. #ifdef PCRE_SUPPORT
  1455. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  1456. #endif
  1457. if( (nd->subtype == SHOP || nd->subtype == CASHSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  1458. aFree(nd->u.shop.shop_item);
  1459. else
  1460. if( nd->subtype == SCRIPT )
  1461. {
  1462. struct s_mapiterator* iter;
  1463. struct block_list* bl;
  1464. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  1465. iter = mapit_geteachpc();
  1466. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  1467. {
  1468. struct map_session_data *sd = map_id2sd(bl->id);
  1469. if( sd && sd->npc_timer_id != INVALID_TIMER )
  1470. {
  1471. const struct TimerData *td = get_timer(sd->npc_timer_id);
  1472. if( td && td->id != nd->bl.id )
  1473. continue;
  1474. if( td && td->data )
  1475. ers_free(timer_event_ers, (void*)td->data);
  1476. delete_timer(sd->npc_timer_id, npc_timerevent);
  1477. sd->npc_timer_id = INVALID_TIMER;
  1478. }
  1479. }
  1480. mapit_free(iter);
  1481. if (nd->u.scr.timerid != INVALID_TIMER) {
  1482. const struct TimerData *td = NULL;
  1483. td = get_timer(nd->u.scr.timerid);
  1484. if (td && td->data)
  1485. ers_free(timer_event_ers, (void*)td->data);
  1486. delete_timer(nd->u.scr.timerid, npc_timerevent);
  1487. }
  1488. if (nd->u.scr.timer_event)
  1489. aFree(nd->u.scr.timer_event);
  1490. if (nd->src_id == 0) {
  1491. if(nd->u.scr.script) {
  1492. script_free_code(nd->u.scr.script);
  1493. nd->u.scr.script = NULL;
  1494. }
  1495. if (nd->u.scr.label_list) {
  1496. aFree(nd->u.scr.label_list);
  1497. nd->u.scr.label_list = NULL;
  1498. nd->u.scr.label_list_num = 0;
  1499. }
  1500. }
  1501. }
  1502. script_stop_sleeptimers(nd->bl.id);
  1503. aFree(nd);
  1504. return 0;
  1505. }
  1506. //
  1507. // NPC Source Files
  1508. //
  1509. /// Clears the npc source file list
  1510. static void npc_clearsrcfile(void)
  1511. {
  1512. struct npc_src_list* file = npc_src_files;
  1513. struct npc_src_list* file_tofree;
  1514. while( file != NULL )
  1515. {
  1516. file_tofree = file;
  1517. file = file->next;
  1518. aFree(file_tofree);
  1519. }
  1520. npc_src_files = NULL;
  1521. }
  1522. /// Adds a npc source file (or removes all)
  1523. void npc_addsrcfile(const char* name)
  1524. {
  1525. struct npc_src_list* file;
  1526. struct npc_src_list* file_prev = NULL;
  1527. if( strcmpi(name, "clear") == 0 )
  1528. {
  1529. npc_clearsrcfile();
  1530. return;
  1531. }
  1532. // prevent multiple insert of source files
  1533. file = npc_src_files;
  1534. while( file != NULL )
  1535. {
  1536. if( strcmp(name, file->name) == 0 )
  1537. return;// found the file, no need to insert it again
  1538. file_prev = file;
  1539. file = file->next;
  1540. }
  1541. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  1542. file->next = NULL;
  1543. strncpy(file->name, name, strlen(name) + 1);
  1544. if( file_prev == NULL )
  1545. npc_src_files = file;
  1546. else
  1547. file_prev->next = file;
  1548. }
  1549. /// Removes a npc source file (or all)
  1550. void npc_delsrcfile(const char* name)
  1551. {
  1552. struct npc_src_list* file = npc_src_files;
  1553. struct npc_src_list* file_prev = NULL;
  1554. if( strcmpi(name, "all") == 0 )
  1555. {
  1556. npc_clearsrcfile();
  1557. return;
  1558. }
  1559. while( file != NULL )
  1560. {
  1561. if( strcmp(file->name, name) == 0 )
  1562. {
  1563. if( npc_src_files == file )
  1564. npc_src_files = file->next;
  1565. else
  1566. file_prev->next = file->next;
  1567. aFree(file);
  1568. break;
  1569. }
  1570. file_prev = file;
  1571. file = file->next;
  1572. }
  1573. }
  1574. /// Parses and sets the name and exname of a npc.
  1575. /// Assumes that m, x and y are already set in nd.
  1576. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  1577. {
  1578. const char* p;
  1579. struct npc_data* dnd;// duplicate npc
  1580. char newname[NAME_LENGTH];
  1581. // parse name
  1582. p = strstr(name,"::");
  1583. if( p )
  1584. {// <Display name>::<Unique name>
  1585. size_t len = p-name;
  1586. if( len > NAME_LENGTH )
  1587. {
  1588. 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), NAME_LENGTH);
  1589. safestrncpy(nd->name, name, sizeof(nd->name));
  1590. }
  1591. else
  1592. {
  1593. memcpy(nd->name, name, len);
  1594. memset(nd->name+len, 0, sizeof(nd->name)-len);
  1595. }
  1596. len = strlen(p+2);
  1597. if( len > NAME_LENGTH )
  1598. 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), NAME_LENGTH);
  1599. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  1600. }
  1601. else
  1602. {// <Display name>
  1603. size_t len = strlen(name);
  1604. if( len > NAME_LENGTH )
  1605. 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), NAME_LENGTH);
  1606. safestrncpy(nd->name, name, sizeof(nd->name));
  1607. safestrncpy(nd->exname, name, sizeof(nd->exname));
  1608. }
  1609. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL )
  1610. {// invalid
  1611. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  1612. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1613. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1614. }
  1615. if( (dnd=npc_name2id(nd->exname)) != NULL )
  1616. {// duplicate unique name, generate new one
  1617. char this_mapname[32];
  1618. char other_mapname[32];
  1619. int i = 0;
  1620. do
  1621. {
  1622. ++i;
  1623. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  1624. }
  1625. while( npc_name2id(newname) != NULL );
  1626. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map[nd->bl.m].index)));
  1627. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map[dnd->bl.m].index)));
  1628. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1629. 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);
  1630. ShowDebug("other npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  1631. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1632. }
  1633. }
  1634. struct npc_data* npc_add_warp(short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  1635. {
  1636. int i;
  1637. struct npc_data *nd;
  1638. CREATE(nd, struct npc_data, 1);
  1639. nd->bl.id = npc_get_new_npc_id();
  1640. map_addnpc(from_mapid, nd);
  1641. nd->bl.prev = nd->bl.next = NULL;
  1642. nd->bl.m = from_mapid;
  1643. nd->bl.x = from_x;
  1644. nd->bl.y = from_y;
  1645. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  1646. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  1647. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  1648. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  1649. if( battle_config.warp_point_debug )
  1650. nd->class_ = WARP_DEBUG_CLASS;
  1651. else
  1652. nd->class_ = WARP_CLASS;
  1653. nd->speed = 200;
  1654. nd->u.warp.mapindex = to_mapindex;
  1655. nd->u.warp.x = to_x;
  1656. nd->u.warp.y = to_y;
  1657. nd->u.warp.xs = xs;
  1658. nd->u.warp.ys = xs;
  1659. nd->bl.type = BL_NPC;
  1660. nd->subtype = WARP;
  1661. npc_setcells(nd);
  1662. map_addblock(&nd->bl);
  1663. status_set_viewdata(&nd->bl, nd->class_);
  1664. status_change_init(&nd->bl);
  1665. unit_dataset(&nd->bl);
  1666. clif_spawn(&nd->bl);
  1667. strdb_put(npcname_db, nd->exname, nd);
  1668. return nd;
  1669. }
  1670. /// Parses a warp npc.
  1671. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1672. {
  1673. int x, y, xs, ys, to_x, to_y, m;
  1674. unsigned short i;
  1675. char mapname[32], to_mapname[32];
  1676. struct npc_data *nd;
  1677. // w1=<from map name>,<fromX>,<fromY>,<facing>
  1678. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  1679. if( sscanf(w1, "%31[^,],%d,%d", mapname, &x, &y) != 3
  1680. || sscanf(w4, "%d,%d,%31[^,],%d,%d", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  1681. {
  1682. 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);
  1683. return strchr(start,'\n');// skip and continue
  1684. }
  1685. m = map_mapname2mapid(mapname);
  1686. i = mapindex_name2id(to_mapname);
  1687. if( i == 0 )
  1688. {
  1689. 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);
  1690. return strchr(start,'\n');// skip and continue
  1691. }
  1692. CREATE(nd, struct npc_data, 1);
  1693. nd->bl.id = npc_get_new_npc_id();
  1694. map_addnpc(m, nd);
  1695. nd->bl.prev = nd->bl.next = NULL;
  1696. nd->bl.m = m;
  1697. nd->bl.x = x;
  1698. nd->bl.y = y;
  1699. npc_parsename(nd, w3, start, buffer, filepath);
  1700. if (!battle_config.warp_point_debug)
  1701. nd->class_ = WARP_CLASS;
  1702. else
  1703. nd->class_ = WARP_DEBUG_CLASS;
  1704. nd->speed = 200;
  1705. nd->u.warp.mapindex = i;
  1706. nd->u.warp.x = to_x;
  1707. nd->u.warp.y = to_y;
  1708. nd->u.warp.xs = xs;
  1709. nd->u.warp.ys = ys;
  1710. npc_warp++;
  1711. nd->bl.type = BL_NPC;
  1712. nd->subtype = WARP;
  1713. npc_setcells(nd);
  1714. map_addblock(&nd->bl);
  1715. status_set_viewdata(&nd->bl, nd->class_);
  1716. status_change_init(&nd->bl);
  1717. unit_dataset(&nd->bl);
  1718. clif_spawn(&nd->bl);
  1719. strdb_put(npcname_db, nd->exname, nd);
  1720. return strchr(start,'\n');// continue
  1721. }
  1722. /// Parses a shop/cashshop npc.
  1723. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1724. {
  1725. //TODO: could be rewritten to NOT need this temp array [ultramage]
  1726. #define MAX_SHOPITEM 100
  1727. struct npc_item_list items[MAX_SHOPITEM];
  1728. char *p;
  1729. int x, y, dir, m, i;
  1730. struct npc_data *nd;
  1731. enum npc_subtype type;
  1732. if( strcmp(w1,"-") == 0 )
  1733. {// 'floating' shop?
  1734. x = y = dir = 0;
  1735. m = -1;
  1736. }
  1737. else
  1738. {// w1=<map name>,<x>,<y>,<facing>
  1739. char mapname[32];
  1740. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4
  1741. || strchr(w4, ',') == NULL )
  1742. {
  1743. 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);
  1744. return strchr(start,'\n');// skip and continue
  1745. }
  1746. m = map_mapname2mapid(mapname);
  1747. }
  1748. if( !strcasecmp(w2,"cashshop") )
  1749. type = CASHSHOP;
  1750. else
  1751. type = SHOP;
  1752. p = strchr(w4,',');
  1753. for( i = 0; i < ARRAYLENGTH(items) && p; ++i )
  1754. {
  1755. int nameid, value;
  1756. struct item_data* id;
  1757. if( sscanf(p, ",%d:%d", &nameid, &value) != 2 )
  1758. {
  1759. 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);
  1760. break;
  1761. }
  1762. if( (id = itemdb_exists(nameid)) == NULL )
  1763. {
  1764. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%d').\n", filepath, strline(buffer,start-buffer), nameid);
  1765. p = strchr(p+1,',');
  1766. continue;
  1767. }
  1768. if( value < 0 )
  1769. {
  1770. if( type == SHOP ) value = id->value_buy;
  1771. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  1772. }
  1773. if( type == SHOP && value*0.75 < id->value_sell*1.24 )
  1774. {// Exploit possible: you can buy and sell back with profit
  1775. ShowWarning("npc_parse_shop: Item %s [%d] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  1776. id->name, nameid, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  1777. }
  1778. //for logs filters, atcommands and iteminfo script command
  1779. if( id->maxchance == 0 )
  1780. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  1781. items[i].nameid = nameid;
  1782. items[i].value = value;
  1783. p = strchr(p+1,',');
  1784. }
  1785. if( i == 0 )
  1786. {
  1787. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  1788. return strchr(start,'\n');// continue
  1789. }
  1790. CREATE(nd, struct npc_data, 1);
  1791. CREATE(nd->u.shop.shop_item, struct npc_item_list, i);
  1792. memcpy(nd->u.shop.shop_item, items, sizeof(struct npc_item_list)*i);
  1793. nd->u.shop.count = i;
  1794. nd->bl.prev = nd->bl.next = NULL;
  1795. nd->bl.m = m;
  1796. nd->bl.x = x;
  1797. nd->bl.y = y;
  1798. nd->bl.id = npc_get_new_npc_id();
  1799. npc_parsename(nd, w3, start, buffer, filepath);
  1800. nd->class_ = m==-1?-1:atoi(w4);
  1801. nd->speed = 200;
  1802. ++npc_shop;
  1803. nd->bl.type = BL_NPC;
  1804. nd->subtype = type;
  1805. if( m >= 0 )
  1806. {// normal shop npc
  1807. map_addnpc(m,nd);
  1808. map_addblock(&nd->bl);
  1809. status_set_viewdata(&nd->bl, nd->class_);
  1810. status_change_init(&nd->bl);
  1811. unit_dataset(&nd->bl);
  1812. nd->ud.dir = dir;
  1813. clif_spawn(&nd->bl);
  1814. } else
  1815. {// 'floating' shop?
  1816. map_addiddb(&nd->bl);
  1817. }
  1818. strdb_put(npcname_db, nd->exname, nd);
  1819. return strchr(start,'\n');// continue
  1820. }
  1821. /**
  1822. * NPCのラベルデータコンバート
  1823. * @see DBApply
  1824. */
  1825. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  1826. {
  1827. const char* lname = (const char*)key.str;
  1828. int lpos = db_data2i(data);
  1829. struct npc_label_list** label_list;
  1830. int* label_list_num;
  1831. const char* filepath;
  1832. struct npc_label_list* label;
  1833. const char *p;
  1834. int len;
  1835. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  1836. nullpo_ret(label_list_num = va_arg(ap,int*));
  1837. nullpo_ret(filepath = va_arg(ap,const char*));
  1838. // In case of labels not terminated with ':', for user defined function support
  1839. p = lname;
  1840. while( ISALNUM(*p) || *p == '_' )
  1841. ++p;
  1842. len = p-lname;
  1843. // here we check if the label fit into the buffer
  1844. if( len > 23 )
  1845. {
  1846. ShowError("npc_parse_script: label name longer than 23 chars! '%s'\n (%s)", lname, filepath);
  1847. return 0;
  1848. }
  1849. if( *label_list == NULL )
  1850. {
  1851. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  1852. *label_list_num = 0;
  1853. } else
  1854. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  1855. label = *label_list+*label_list_num;
  1856. safestrncpy(label->name, lname, sizeof(label->name));
  1857. label->pos = lpos;
  1858. ++(*label_list_num);
  1859. return 0;
  1860. }
  1861. // Skip the contents of a script.
  1862. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  1863. {
  1864. const char* p;
  1865. int curly_count;
  1866. if( start == NULL )
  1867. return NULL;// nothing to skip
  1868. // initial bracket (assumes the previous part is ok)
  1869. p = strchr(start,'{');
  1870. if( p == NULL )
  1871. {
  1872. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  1873. return NULL;// can't continue
  1874. }
  1875. // skip everything
  1876. for( curly_count = 1; curly_count > 0 ; )
  1877. {
  1878. p = skip_space(p+1) ;
  1879. if( *p == '}' )
  1880. {// right curly
  1881. --curly_count;
  1882. }
  1883. else if( *p == '{' )
  1884. {// left curly
  1885. ++curly_count;
  1886. }
  1887. else if( *p == '"' )
  1888. {// string
  1889. for( ++p; *p != '"' ; ++p )
  1890. {
  1891. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  1892. ++p;// escape sequence (not part of a multibyte character)
  1893. else if( *p == '\0' )
  1894. {
  1895. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  1896. return NULL;// can't continue
  1897. }
  1898. else if( *p == '\n' )
  1899. {
  1900. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  1901. return NULL;// can't continue
  1902. }
  1903. }
  1904. }
  1905. else if( *p == '\0' )
  1906. {// end of buffer
  1907. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  1908. return NULL;// can't continue
  1909. }
  1910. }
  1911. return p+1;// return after the last '}'
  1912. }
  1913. /// Parses a npc script.
  1914. ///
  1915. /// -%TAB%script%TAB%<NPC Name>%TAB%-1,{<code>}
  1916. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  1917. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>}
  1918. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1919. {
  1920. int x, y, dir = 0, m, xs = 0, ys = 0, class_ = 0; // [Valaris] thanks to fov
  1921. char mapname[32];
  1922. struct script_code *script;
  1923. int i;
  1924. const char* end;
  1925. const char* script_start;
  1926. struct npc_label_list* label_list;
  1927. int label_list_num;
  1928. struct npc_data* nd;
  1929. if( strcmp(w1, "-") == 0 )
  1930. {// floating npc
  1931. x = 0;
  1932. y = 0;
  1933. m = -1;
  1934. }
  1935. else
  1936. {// npc in a map
  1937. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )
  1938. {
  1939. 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);
  1940. return NULL;// unknown format, don't continue
  1941. }
  1942. m = map_mapname2mapid(mapname);
  1943. }
  1944. script_start = strstr(start,",{");
  1945. end = strchr(start,'\n');
  1946. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  1947. {
  1948. 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);
  1949. return NULL;// can't continue
  1950. }
  1951. ++script_start;
  1952. end = npc_skip_script(script_start, buffer, filepath);
  1953. if( end == NULL )
  1954. return NULL;// (simple) parse error, don't continue
  1955. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  1956. label_list = NULL;
  1957. label_list_num = 0;
  1958. if( script )
  1959. {
  1960. DBMap* label_db = script_get_label_db();
  1961. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  1962. db_clear(label_db); // not needed anymore, so clear the db
  1963. }
  1964. CREATE(nd, struct npc_data, 1);
  1965. if( sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3 )
  1966. {// OnTouch area defined
  1967. nd->u.scr.xs = xs;
  1968. nd->u.scr.ys = ys;
  1969. }
  1970. else
  1971. {// no OnTouch area
  1972. class_ = atoi(w4);
  1973. nd->u.scr.xs = -1;
  1974. nd->u.scr.ys = -1;
  1975. }
  1976. nd->bl.prev = nd->bl.next = NULL;
  1977. nd->bl.m = m;
  1978. nd->bl.x = x;
  1979. nd->bl.y = y;
  1980. npc_parsename(nd, w3, start, buffer, filepath);
  1981. nd->bl.id = npc_get_new_npc_id();
  1982. nd->class_ = class_;
  1983. nd->speed = 200;
  1984. nd->u.scr.script = script;
  1985. nd->u.scr.label_list = label_list;
  1986. nd->u.scr.label_list_num = label_list_num;
  1987. ++npc_script;
  1988. nd->bl.type = BL_NPC;
  1989. nd->subtype = SCRIPT;
  1990. if( m >= 0 )
  1991. {
  1992. map_addnpc(m, nd);
  1993. status_change_init(&nd->bl);
  1994. unit_dataset(&nd->bl);
  1995. nd->ud.dir = dir;
  1996. npc_setcells(nd);
  1997. map_addblock(&nd->bl);
  1998. if( class_ >= 0 )
  1999. {
  2000. status_set_viewdata(&nd->bl, nd->class_);
  2001. clif_spawn(&nd->bl);
  2002. }
  2003. }
  2004. else
  2005. {
  2006. // we skip map_addnpc, but still add it to the list of ID's
  2007. map_addiddb(&nd->bl);
  2008. }
  2009. strdb_put(npcname_db, nd->exname, nd);
  2010. //-----------------------------------------
  2011. // Loop through labels to export them as necessary
  2012. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2013. if (npc_event_export(nd, i)) {
  2014. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  2015. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2016. }
  2017. npc_timerevent_export(nd, i);
  2018. }
  2019. nd->u.scr.timerid = INVALID_TIMER;
  2020. return end;
  2021. }
  2022. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  2023. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  2024. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2025. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2026. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2027. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2028. const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2029. {
  2030. int x, y, dir, m, xs = -1, ys = -1, class_ = 0;
  2031. char mapname[32];
  2032. char srcname[128];
  2033. int i;
  2034. const char* end;
  2035. size_t length;
  2036. int src_id;
  2037. int type;
  2038. struct npc_data* nd;
  2039. struct npc_data* dnd;
  2040. end = strchr(start,'\n');
  2041. length = strlen(w2);
  2042. // get the npc being duplicated
  2043. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  2044. {// does not match 'duplicate(%127s)', name is empty or too long
  2045. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  2046. return end;// next line, try to continue
  2047. }
  2048. safestrncpy(srcname, w2+10, length-10);
  2049. dnd = npc_name2id(srcname);
  2050. if( dnd == NULL) {
  2051. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  2052. return end;// next line, try to continue
  2053. }
  2054. src_id = dnd->bl.id;
  2055. type = dnd->subtype;
  2056. // get placement
  2057. if( (type==SHOP || type==CASHSHOP || type==SCRIPT) && strcmp(w1, "-") == 0 )
  2058. {// floating shop/chashshop/script
  2059. x = y = dir = 0;
  2060. m = -1;
  2061. }
  2062. else
  2063. {
  2064. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )// <map name>,<x>,<y>,<facing>
  2065. {
  2066. 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);
  2067. return end;// next line, try to continue
  2068. }
  2069. m = map_mapname2mapid(mapname);
  2070. }
  2071. if( type == WARP && sscanf(w4, "%d,%d", &xs, &ys) == 2 );// <spanx>,<spany>
  2072. else if( type == SCRIPT && sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3);// <sprite id>,<triggerX>,<triggerY>
  2073. else if( type != WARP ) class_ = atoi(w4);// <sprite id>
  2074. else
  2075. {
  2076. 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);
  2077. return end;// next line, try to continue
  2078. }
  2079. CREATE(nd, struct npc_data, 1);
  2080. nd->bl.prev = nd->bl.next = NULL;
  2081. nd->bl.m = m;
  2082. nd->bl.x = x;
  2083. nd->bl.y = y;
  2084. npc_parsename(nd, w3, start, buffer, filepath);
  2085. nd->bl.id = npc_get_new_npc_id();
  2086. nd->class_ = class_;
  2087. nd->speed = 200;
  2088. nd->src_id = src_id;
  2089. nd->bl.type = BL_NPC;
  2090. nd->subtype = (enum npc_subtype)type;
  2091. switch( type )
  2092. {
  2093. case SCRIPT:
  2094. ++npc_script;
  2095. nd->u.scr.xs = xs;
  2096. nd->u.scr.ys = ys;
  2097. nd->u.scr.script = dnd->u.scr.script;
  2098. nd->u.scr.label_list = dnd->u.scr.label_list;
  2099. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  2100. break;
  2101. case SHOP:
  2102. case CASHSHOP:
  2103. ++npc_shop;
  2104. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  2105. nd->u.shop.count = dnd->u.shop.count;
  2106. break;
  2107. case WARP:
  2108. ++npc_warp;
  2109. if( !battle_config.warp_point_debug )
  2110. nd->class_ = WARP_CLASS;
  2111. else
  2112. nd->class_ = WARP_DEBUG_CLASS;
  2113. nd->u.warp.xs = xs;
  2114. nd->u.warp.ys = ys;
  2115. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  2116. nd->u.warp.x = dnd->u.warp.x;
  2117. nd->u.warp.y = dnd->u.warp.y;
  2118. break;
  2119. }
  2120. //Add the npc to its location
  2121. if( m >= 0 )
  2122. {
  2123. map_addnpc(m, nd);
  2124. status_change_init(&nd->bl);
  2125. unit_dataset(&nd->bl);
  2126. nd->ud.dir = dir;
  2127. npc_setcells(nd);
  2128. map_addblock(&nd->bl);
  2129. if( class_ >= 0 )
  2130. {
  2131. status_set_viewdata(&nd->bl, nd->class_);
  2132. clif_spawn(&nd->bl);
  2133. }
  2134. }
  2135. else
  2136. {
  2137. // we skip map_addnpc, but still add it to the list of ID's
  2138. map_addiddb(&nd->bl);
  2139. }
  2140. strdb_put(npcname_db, nd->exname, nd);
  2141. if( type != SCRIPT )
  2142. return end;
  2143. //-----------------------------------------
  2144. // Loop through labels to export them as necessary
  2145. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2146. if (npc_event_export(nd, i)) {
  2147. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  2148. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2149. }
  2150. npc_timerevent_export(nd, i);
  2151. }
  2152. nd->u.scr.timerid = INVALID_TIMER;
  2153. return end;
  2154. }
  2155. int npc_duplicate4instance(struct npc_data *snd, int m)
  2156. {
  2157. char newname[NAME_LENGTH];
  2158. if( map[m].instance_id == 0 )
  2159. return 1;
  2160. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", map[m].instance_id, snd->bl.id);
  2161. if( npc_name2id(newname) != NULL )
  2162. { // Name already in use
  2163. ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, map[m].instance_id);
  2164. return 1;
  2165. }
  2166. if( snd->subtype == WARP )
  2167. { // Adjust destination, if instanced
  2168. struct npc_data *wnd = NULL; // New NPC
  2169. int dm = map_mapindex2mapid(snd->u.warp.mapindex), im;
  2170. if( dm < 0 ) return 1;
  2171. im = instance_mapid2imapid(dm, map[m].instance_id);
  2172. if( im == -1 )
  2173. {
  2174. ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map[dm].name, snd->exname);
  2175. return 1;
  2176. }
  2177. CREATE(wnd, struct npc_data, 1);
  2178. wnd->bl.id = npc_get_new_npc_id();
  2179. map_addnpc(m, wnd);
  2180. wnd->bl.prev = wnd->bl.next = NULL;
  2181. wnd->bl.m = m;
  2182. wnd->bl.x = snd->bl.x;
  2183. wnd->bl.y = snd->bl.y;
  2184. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  2185. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  2186. wnd->class_ = WARP_CLASS;
  2187. wnd->speed = 200;
  2188. wnd->u.warp.mapindex = map_id2index(im);
  2189. wnd->u.warp.x = snd->u.warp.x;
  2190. wnd->u.warp.y = snd->u.warp.y;
  2191. wnd->u.warp.xs = snd->u.warp.xs;
  2192. wnd->u.warp.ys = snd->u.warp.ys;
  2193. wnd->bl.type = BL_NPC;
  2194. wnd->subtype = WARP;
  2195. npc_setcells(wnd);
  2196. map_addblock(&wnd->bl);
  2197. status_set_viewdata(&wnd->bl, wnd->class_);
  2198. status_change_init(&wnd->bl);
  2199. unit_dataset(&wnd->bl);
  2200. clif_spawn(&wnd->bl);
  2201. strdb_put(npcname_db, wnd->exname, wnd);
  2202. }
  2203. else
  2204. {
  2205. static char w1[50], w2[50], w3[50], w4[50];
  2206. const char* stat_buf = "- call from instancing subsystem -\n";
  2207. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map[m].name, snd->bl.x, snd->bl.y, snd->ud.dir);
  2208. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  2209. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  2210. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  2211. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  2212. else
  2213. snprintf(w4, sizeof(w4), "%d", snd->class_);
  2214. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  2215. }
  2216. return 0;
  2217. }
  2218. void npc_setcells(struct npc_data* nd)
  2219. {
  2220. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2221. int i,j;
  2222. switch(nd->subtype)
  2223. {
  2224. case WARP:
  2225. xs = nd->u.warp.xs;
  2226. ys = nd->u.warp.ys;
  2227. break;
  2228. case SCRIPT:
  2229. xs = nd->u.scr.xs;
  2230. ys = nd->u.scr.ys;
  2231. break;
  2232. default:
  2233. return; // Other types doesn't have touch area
  2234. }
  2235. if (m < 0 || xs < 0 || ys < 0)
  2236. return;
  2237. for (i = y-ys; i <= y+ys; i++) {
  2238. for (j = x-xs; j <= x+xs; j++) {
  2239. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  2240. continue;
  2241. map_setcell(m, j, i, CELL_NPC, true);
  2242. }
  2243. }
  2244. }
  2245. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  2246. {
  2247. struct npc_data *nd = (struct npc_data*)bl;
  2248. int id = va_arg(ap,int);
  2249. if (nd->bl.id == id) return 0;
  2250. npc_setcells(nd);
  2251. return 1;
  2252. }
  2253. void npc_unsetcells(struct npc_data* nd)
  2254. {
  2255. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2256. int i,j, x0, x1, y0, y1;
  2257. if (nd->subtype == WARP) {
  2258. xs = nd->u.warp.xs;
  2259. ys = nd->u.warp.ys;
  2260. } else {
  2261. xs = nd->u.scr.xs;
  2262. ys = nd->u.scr.ys;
  2263. }
  2264. if (m < 0 || xs < 0 || ys < 0)
  2265. return;
  2266. //Locate max range on which we can locate npc cells
  2267. //FIXME: does this really do what it's supposed to do? [ultramage]
  2268. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  2269. for(x1 = x+xs; x1 < map[m].xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  2270. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  2271. for(y1 = y+ys; y1 < map[m].ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  2272. //Erase this npc's cells
  2273. for (i = y-ys; i <= y+ys; i++)
  2274. for (j = x-xs; j <= x+xs; j++)
  2275. map_setcell(m, j, i, CELL_NPC, false);
  2276. //Re-deploy NPC cells for other nearby npcs.
  2277. map_foreachinarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  2278. }
  2279. void npc_movenpc(struct npc_data* nd, int x, int y)
  2280. {
  2281. const int m = nd->bl.m;
  2282. if (m < 0 || nd->bl.prev == NULL) return; //Not on a map.
  2283. x = cap_value(x, 0, map[m].xs-1);
  2284. y = cap_value(y, 0, map[m].ys-1);
  2285. map_foreachinrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2286. map_moveblock(&nd->bl, x, y, gettick());
  2287. map_foreachinrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2288. }
  2289. /// Changes the display name of the npc.
  2290. ///
  2291. /// @param nd Target npc
  2292. /// @param newname New display name
  2293. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  2294. {
  2295. nullpo_retv(nd);
  2296. safestrncpy(nd->name, newname, sizeof(nd->name));
  2297. clif_charnameack(0, &nd->bl);
  2298. }
  2299. /// Changes the display class of the npc.
  2300. ///
  2301. /// @param nd Target npc
  2302. /// @param class_ New display class
  2303. void npc_setclass(struct npc_data* nd, short class_)
  2304. {
  2305. nullpo_retv(nd);
  2306. if( nd->class_ == class_ )
  2307. return;
  2308. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);// fade out
  2309. nd->class_ = class_;
  2310. status_set_viewdata(&nd->bl, class_);
  2311. clif_spawn(&nd->bl);// fade in
  2312. }
  2313. /// Parses a function.
  2314. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  2315. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2316. {
  2317. DBMap* func_db;
  2318. DBData old_data;
  2319. struct script_code *script;
  2320. const char* end;
  2321. const char* script_start;
  2322. script_start = strstr(start,"\t{");
  2323. end = strchr(start,'\n');
  2324. if( *w4 != '{' || script_start == NULL || (end != NULL && script_start > end) )
  2325. {
  2326. 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);
  2327. return NULL;// can't continue
  2328. }
  2329. ++script_start;
  2330. end = npc_skip_script(script_start,buffer,filepath);
  2331. if( end == NULL )
  2332. return NULL;// (simple) parse error, don't continue
  2333. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  2334. if( script == NULL )// parse error, continue
  2335. return end;
  2336. func_db = script_get_userfunc_db();
  2337. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data))
  2338. {
  2339. struct script_code *oldscript = db_data2ptr(&old_data);
  2340. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  2341. script_free_vars(&oldscript->script_vars);
  2342. aFree(oldscript->script_buf);
  2343. aFree(oldscript);
  2344. }
  2345. return end;
  2346. }
  2347. /*==========================================
  2348. * Parse Mob 1 - Parse mob list into each map
  2349. * Parse Mob 2 - Actually Spawns Mob
  2350. * [Wizputer]
  2351. *------------------------------------------*/
  2352. void npc_parse_mob2(struct spawn_data* mob)
  2353. {
  2354. int i;
  2355. for( i = mob->active; i < mob->num; ++i )
  2356. {
  2357. struct mob_data* md = mob_spawn_dataset(mob);
  2358. md->spawn = mob;
  2359. md->spawn->active++;
  2360. mob_spawn(md);
  2361. }
  2362. }
  2363. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2364. {
  2365. int num, class_, m,x,y,xs,ys, i,j;
  2366. char mapname[32];
  2367. struct spawn_data mob, *data;
  2368. struct mob_db* db;
  2369. memset(&mob, 0, sizeof(struct spawn_data));
  2370. mob.state.boss = !strcmpi(w2,"boss_monster");
  2371. // w1=<map name>,<x>,<y>,<xs>,<ys>
  2372. // w4=<mob id>,<amount>,<delay1>,<delay2>,<event>
  2373. if( sscanf(w1, "%31[^,],%d,%d,%d,%d", mapname, &x, &y, &xs, &ys) < 3
  2374. || sscanf(w4, "%d,%d,%u,%u,%127[^\t\r\n]", &class_, &num, &mob.delay1, &mob.delay2, mob.eventname) < 2 )
  2375. {
  2376. 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);
  2377. return strchr(start,'\n');// skip and continue
  2378. }
  2379. if( mapindex_name2id(mapname) == 0 )
  2380. {
  2381. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  2382. return strchr(start,'\n');// skip and continue
  2383. }
  2384. m = map_mapname2mapid(mapname);
  2385. if( m < 0 )//Not loaded on this map-server instance.
  2386. return strchr(start,'\n');// skip and continue
  2387. mob.m = (unsigned short)m;
  2388. if( x < 0 || x >= map[mob.m].xs || y < 0 || y >= map[mob.m].ys )
  2389. {
  2390. ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", map[mob.m].name, x, y, (map[mob.m].xs-1), (map[mob.m].ys-1), w1, w3, filepath, strline(buffer,start-buffer));
  2391. return strchr(start,'\n');// skip and continue
  2392. }
  2393. // check monster ID if exists!
  2394. if( mobdb_checkid(class_) == 0 )
  2395. {
  2396. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
  2397. return strchr(start,'\n');// skip and continue
  2398. }
  2399. if( num < 1 || num > 1000 )
  2400. {
  2401. 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));
  2402. return strchr(start,'\n');// skip and continue
  2403. }
  2404. mob.num = (unsigned short)num;
  2405. mob.active = 0;
  2406. mob.class_ = (short) class_;
  2407. mob.x = (unsigned short)x;
  2408. mob.y = (unsigned short)y;
  2409. mob.xs = (signed short)xs;
  2410. mob.ys = (signed short)ys;
  2411. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  2412. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  2413. mob.num = 1;
  2414. }
  2415. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  2416. { //Force a random spawn anywhere on the map.
  2417. mob.x = mob.y = 0;
  2418. mob.xs = mob.ys = -1;
  2419. }
  2420. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  2421. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  2422. return strchr(start,'\n');// skip and continue
  2423. }
  2424. //Use db names instead of the spawn file ones.
  2425. if(battle_config.override_mob_names==1)
  2426. strcpy(mob.name,"--en--");
  2427. else if (battle_config.override_mob_names==2)
  2428. strcpy(mob.name,"--ja--");
  2429. else
  2430. safestrncpy(mob.name, w3, sizeof(mob.name));
  2431. //Verify dataset.
  2432. if( !mob_parse_dataset(&mob) )
  2433. {
  2434. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
  2435. return strchr(start,'\n');// skip and continue
  2436. }
  2437. //Update mob spawn lookup database
  2438. db = mob_db(class_);
  2439. for( i = 0; i < ARRAYLENGTH(db->spawn); ++i )
  2440. {
  2441. if (map[mob.m].index == db->spawn[i].mapindex)
  2442. { //Update total
  2443. db->spawn[i].qty += mob.num;
  2444. //Re-sort list
  2445. for( j = i; j > 0 && db->spawn[j-1].qty < db->spawn[i].qty; --j );
  2446. if( j != i )
  2447. {
  2448. xs = db->spawn[i].mapindex;
  2449. ys = db->spawn[i].qty;
  2450. memmove(&db->spawn[j+1], &db->spawn[j], (i-j)*sizeof(db->spawn[0]));
  2451. db->spawn[j].mapindex = xs;
  2452. db->spawn[j].qty = ys;
  2453. }
  2454. break;
  2455. }
  2456. if (mob.num > db->spawn[i].qty)
  2457. { //Insert into list
  2458. memmove(&db->spawn[i+1], &db->spawn[i], sizeof(db->spawn) -(i+1)*sizeof(db->spawn[0]));
  2459. db->spawn[i].mapindex = map[mob.m].index;
  2460. db->spawn[i].qty = mob.num;
  2461. break;
  2462. }
  2463. }
  2464. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  2465. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  2466. memcpy(data, &mob, sizeof(struct spawn_data));
  2467. // spawn / cache the new mobs
  2468. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  2469. {
  2470. data->state.dynamic = true;
  2471. npc_cache_mob += data->num;
  2472. // check if target map has players
  2473. // (usually shouldn't occur when map server is just starting,
  2474. // but not the case when we do @reloadscript
  2475. if( map[data->m].users > 0 )
  2476. npc_parse_mob2(data);
  2477. }
  2478. else
  2479. {
  2480. data->state.dynamic = false;
  2481. npc_parse_mob2(data);
  2482. npc_delay_mob += data->num;
  2483. }
  2484. npc_mob++;
  2485. return strchr(start,'\n');// continue
  2486. }
  2487. /*==========================================
  2488. * マップフラグ行の解析
  2489. *------------------------------------------*/
  2490. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2491. {
  2492. int m;
  2493. char mapname[32];
  2494. int state = 1;
  2495. // w1=<mapname>
  2496. if( sscanf(w1, "%31[^,]", mapname) != 1 )
  2497. {
  2498. 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);
  2499. return strchr(start,'\n');// skip and continue
  2500. }
  2501. m = map_mapname2mapid(mapname);
  2502. if( m < 0 )
  2503. {
  2504. ShowWarning("npc_parse_mapflag: Unknown map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2505. return strchr(start,'\n');// skip and continue
  2506. }
  2507. if (w4 && !strcmpi(w4, "off"))
  2508. state = 0; //Disable mapflag rather than enable it. [Skotlex]
  2509. if (!strcmpi(w3, "nosave")) {
  2510. char savemap[32];
  2511. int savex, savey;
  2512. if (state == 0)
  2513. ; //Map flag disabled.
  2514. else if (!strcmpi(w4, "SavePoint")) {
  2515. map[m].save.map = 0;
  2516. map[m].save.x = -1;
  2517. map[m].save.y = -1;
  2518. } else if (sscanf(w4, "%31[^,],%d,%d", savemap, &savex, &savey) == 3) {
  2519. map[m].save.map = mapindex_name2id(savemap);
  2520. map[m].save.x = savex;
  2521. map[m].save.y = savey;
  2522. if (!map[m].save.map) {
  2523. 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);
  2524. map[m].save.x = -1;
  2525. map[m].save.y = -1;
  2526. }
  2527. }
  2528. map[m].flag.nosave = state;
  2529. }
  2530. else if (!strcmpi(w3,"autotrade"))
  2531. map[m].flag.autotrade=state;
  2532. else if (!strcmpi(w3,"allowks"))
  2533. map[m].flag.allowks=state; // [Kill Steal Protection]
  2534. else if (!strcmpi(w3,"town"))
  2535. map[m].flag.town=state;
  2536. else if (!strcmpi(w3,"nomemo"))
  2537. map[m].flag.nomemo=state;
  2538. else if (!strcmpi(w3,"noteleport"))
  2539. map[m].flag.noteleport=state;
  2540. else if (!strcmpi(w3,"nowarp"))
  2541. map[m].flag.nowarp=state;
  2542. else if (!strcmpi(w3,"nowarpto"))
  2543. map[m].flag.nowarpto=state;
  2544. else if (!strcmpi(w3,"noreturn"))
  2545. map[m].flag.noreturn=state;
  2546. else if (!strcmpi(w3,"monster_noteleport"))
  2547. map[m].flag.monster_noteleport=state;
  2548. else if (!strcmpi(w3,"nobranch"))
  2549. map[m].flag.nobranch=state;
  2550. else if (!strcmpi(w3,"nopenalty")) {
  2551. map[m].flag.noexppenalty=state;
  2552. map[m].flag.nozenypenalty=state;
  2553. }
  2554. else if (!strcmpi(w3,"pvp")) {
  2555. map[m].flag.pvp = state;
  2556. if( state && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2557. {
  2558. map[m].flag.gvg = 0;
  2559. map[m].flag.gvg_dungeon = 0;
  2560. map[m].flag.gvg_castle = 0;
  2561. ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing GvG flags from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2562. }
  2563. if( state && map[m].flag.battleground )
  2564. {
  2565. map[m].flag.battleground = 0;
  2566. ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2567. }
  2568. }
  2569. else if (!strcmpi(w3,"pvp_noparty"))
  2570. map[m].flag.pvp_noparty=state;
  2571. else if (!strcmpi(w3,"pvp_noguild"))
  2572. map[m].flag.pvp_noguild=state;
  2573. else if (!strcmpi(w3, "pvp_nightmaredrop")) {
  2574. char drop_arg1[16], drop_arg2[16];
  2575. int drop_id = 0, drop_type = 0, drop_per = 0;
  2576. if (sscanf(w4, "%[^,],%[^,],%d", drop_arg1, drop_arg2, &drop_per) == 3) {
  2577. int i;
  2578. if (!strcmpi(drop_arg1, "random"))
  2579. drop_id = -1;
  2580. else if (itemdb_exists((drop_id = atoi(drop_arg1))) == NULL)
  2581. drop_id = 0;
  2582. if (!strcmpi(drop_arg2, "inventory"))
  2583. drop_type = 1;
  2584. else if (!strcmpi(drop_arg2,"equip"))
  2585. drop_type = 2;
  2586. else if (!strcmpi(drop_arg2,"all"))
  2587. drop_type = 3;
  2588. if (drop_id != 0){
  2589. for (i = 0; i < MAX_DROP_PER_MAP; i++) {
  2590. if (map[m].drop_list[i].drop_id == 0){
  2591. map[m].drop_list[i].drop_id = drop_id;
  2592. map[m].drop_list[i].drop_type = drop_type;
  2593. map[m].drop_list[i].drop_per = drop_per;
  2594. break;
  2595. }
  2596. }
  2597. map[m].flag.pvp_nightmaredrop = 1;
  2598. }
  2599. } else if (!state) //Disable
  2600. map[m].flag.pvp_nightmaredrop = 0;
  2601. }
  2602. else if (!strcmpi(w3,"pvp_nocalcrank"))
  2603. map[m].flag.pvp_nocalcrank=state;
  2604. else if (!strcmpi(w3,"gvg")) {
  2605. map[m].flag.gvg = state;
  2606. if( state && map[m].flag.pvp )
  2607. {
  2608. map[m].flag.pvp = 0;
  2609. ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2610. }
  2611. if( state && map[m].flag.battleground )
  2612. {
  2613. map[m].flag.battleground = 0;
  2614. ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2615. }
  2616. }
  2617. else if (!strcmpi(w3,"gvg_noparty"))
  2618. map[m].flag.gvg_noparty=state;
  2619. else if (!strcmpi(w3,"gvg_dungeon")) {
  2620. map[m].flag.gvg_dungeon=state;
  2621. if (state) map[m].flag.pvp=0;
  2622. }
  2623. else if (!strcmpi(w3,"gvg_castle")) {
  2624. map[m].flag.gvg_castle=state;
  2625. if (state) map[m].flag.pvp=0;
  2626. }
  2627. else if (!strcmpi(w3,"battleground")) {
  2628. if( state )
  2629. {
  2630. if( sscanf(w4, "%d", &state) == 1 )
  2631. map[m].flag.battleground = state;
  2632. else
  2633. map[m].flag.battleground = 1; // Default value
  2634. }
  2635. else
  2636. map[m].flag.battleground = 0;
  2637. if( map[m].flag.battleground && map[m].flag.pvp )
  2638. {
  2639. map[m].flag.pvp = 0;
  2640. ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2641. }
  2642. if( map[m].flag.battleground && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2643. {
  2644. map[m].flag.gvg = 0;
  2645. map[m].flag.gvg_dungeon = 0;
  2646. map[m].flag.gvg_castle = 0;
  2647. ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing GvG flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2648. }
  2649. }
  2650. else if (!strcmpi(w3,"noexppenalty"))
  2651. map[m].flag.noexppenalty=state;
  2652. else if (!strcmpi(w3,"nozenypenalty"))
  2653. map[m].flag.nozenypenalty=state;
  2654. else if (!strcmpi(w3,"notrade"))
  2655. map[m].flag.notrade=state;
  2656. else if (!strcmpi(w3,"novending"))
  2657. map[m].flag.novending=state;
  2658. else if (!strcmpi(w3,"nodrop"))
  2659. map[m].flag.nodrop=state;
  2660. else if (!strcmpi(w3,"noskill"))
  2661. map[m].flag.noskill=state;
  2662. else if (!strcmpi(w3,"noicewall"))
  2663. map[m].flag.noicewall=state;
  2664. else if (!strcmpi(w3,"snow"))
  2665. map[m].flag.snow=state;
  2666. else if (!strcmpi(w3,"clouds"))
  2667. map[m].flag.clouds=state;
  2668. else if (!strcmpi(w3,"clouds2"))
  2669. map[m].flag.clouds2=state;
  2670. else if (!strcmpi(w3,"fog"))
  2671. map[m].flag.fog=state;
  2672. else if (!strcmpi(w3,"fireworks"))
  2673. map[m].flag.fireworks=state;
  2674. else if (!strcmpi(w3,"sakura"))
  2675. map[m].flag.sakura=state;
  2676. else if (!strcmpi(w3,"leaves"))
  2677. map[m].flag.leaves=state;
  2678. /**
  2679. * No longer available, keeping here just in case it's back someday. [Ind]
  2680. **/
  2681. //else if (!strcmpi(w3,"rain"))
  2682. // map[m].flag.rain=state;
  2683. else if (!strcmpi(w3,"nightenabled"))
  2684. map[m].flag.nightenabled=state;
  2685. else if (!strcmpi(w3,"nogo"))
  2686. map[m].flag.nogo=state;
  2687. else if (!strcmpi(w3,"noexp")) {
  2688. map[m].flag.nobaseexp=state;
  2689. map[m].flag.nojobexp=state;
  2690. }
  2691. else if (!strcmpi(w3,"nobaseexp"))
  2692. map[m].flag.nobaseexp=state;
  2693. else if (!strcmpi(w3,"nojobexp"))
  2694. map[m].flag.nojobexp=state;
  2695. else if (!strcmpi(w3,"noloot")) {
  2696. map[m].flag.nomobloot=state;
  2697. map[m].flag.nomvploot=state;
  2698. }
  2699. else if (!strcmpi(w3,"nomobloot"))
  2700. map[m].flag.nomobloot=state;
  2701. else if (!strcmpi(w3,"nomvploot"))
  2702. map[m].flag.nomvploot=state;
  2703. else if (!strcmpi(w3,"nocommand")) {
  2704. if (state) {
  2705. if (sscanf(w4, "%d", &state) == 1)
  2706. map[m].nocommand =state;
  2707. else //No level specified, block everyone.
  2708. map[m].nocommand =100;
  2709. } else
  2710. map[m].nocommand=0;
  2711. }
  2712. else if (!strcmpi(w3,"restricted")) {
  2713. if (state) {
  2714. map[m].flag.restricted=1;
  2715. sscanf(w4, "%d", &state);
  2716. map[m].zone |= 1<<(state+1);
  2717. } else {
  2718. map[m].flag.restricted=0;
  2719. map[m].zone = 0;
  2720. }
  2721. }
  2722. else if (!strcmpi(w3,"jexp")) {
  2723. map[m].jexp = (state) ? atoi(w4) : 100;
  2724. if( map[m].jexp < 0 ) map[m].jexp = 100;
  2725. map[m].flag.nojobexp = (map[m].jexp==0)?1:0;
  2726. }
  2727. else if (!strcmpi(w3,"bexp")) {
  2728. map[m].bexp = (state) ? atoi(w4) : 100;
  2729. if( map[m].bexp < 0 ) map[m].bexp = 100;
  2730. map[m].flag.nobaseexp = (map[m].bexp==0)?1:0;
  2731. }
  2732. else if (!strcmpi(w3,"loadevent"))
  2733. map[m].flag.loadevent=state;
  2734. else if (!strcmpi(w3,"nochat"))
  2735. map[m].flag.nochat=state;
  2736. else if (!strcmpi(w3,"partylock"))
  2737. map[m].flag.partylock=state;
  2738. else if (!strcmpi(w3,"guildlock"))
  2739. map[m].flag.guildlock=state;
  2740. else if (!strcmpi(w3,"reset"))
  2741. map[m].flag.reset=state;
  2742. else
  2743. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  2744. return strchr(start,'\n');// continue
  2745. }
  2746. void npc_parsesrcfile(const char* filepath)
  2747. {
  2748. int m, lines = 0;
  2749. FILE* fp;
  2750. size_t len;
  2751. char* buffer;
  2752. const char* p;
  2753. // read whole file to buffer
  2754. fp = fopen(filepath, "rb");
  2755. if( fp == NULL )
  2756. {
  2757. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  2758. return;
  2759. }
  2760. fseek(fp, 0, SEEK_END);
  2761. len = ftell(fp);
  2762. buffer = (char*)aMalloc(len+1);
  2763. fseek(fp, 0, SEEK_SET);
  2764. len = fread(buffer, sizeof(char), len, fp);
  2765. buffer[len] = '\0';
  2766. if( ferror(fp) )
  2767. {
  2768. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  2769. aFree(buffer);
  2770. fclose(fp);
  2771. return;
  2772. }
  2773. fclose(fp);
  2774. // parse buffer
  2775. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  2776. {
  2777. int pos[9];
  2778. char w1[2048], w2[2048], w3[2048], w4[2048];
  2779. int i, count;
  2780. lines++;
  2781. // w1<TAB>w2<TAB>w3<TAB>w4
  2782. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  2783. if( count < 0 )
  2784. {
  2785. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  2786. break;
  2787. }
  2788. // fill w1
  2789. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  2790. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  2791. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  2792. memcpy(w1, p+pos[2], i*sizeof(char));
  2793. w1[i] = '\0';
  2794. // fill w2
  2795. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  2796. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  2797. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  2798. memcpy(w2, p+pos[4], i*sizeof(char));
  2799. w2[i] = '\0';
  2800. // fill w3
  2801. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  2802. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  2803. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  2804. memcpy(w3, p+pos[6], i*sizeof(char));
  2805. w3[i] = '\0';
  2806. // fill w4 (to end of line)
  2807. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  2808. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  2809. if( pos[8] != -1 )
  2810. {
  2811. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  2812. memcpy(w4, p+pos[8], i*sizeof(char));
  2813. w4[i] = '\0';
  2814. }
  2815. else
  2816. w4[0] = '\0';
  2817. if( count < 3 )
  2818. {// Unknown syntax
  2819. 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);
  2820. break;
  2821. }
  2822. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  2823. {// w1 = <map name>,<x>,<y>,<facing>
  2824. char mapname[2048];
  2825. sscanf(w1,"%[^,]",mapname);
  2826. if( !mapindex_name2id(mapname) )
  2827. {// Incorrect map, we must skip the script info...
  2828. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  2829. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2830. {
  2831. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2832. {
  2833. break;
  2834. }
  2835. }
  2836. p = strchr(p,'\n');// next line
  2837. continue;
  2838. }
  2839. m = map_mapname2mapid(mapname);
  2840. if( m < 0 )
  2841. {// "mapname" is not assigned to this server, we must skip the script info...
  2842. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2843. {
  2844. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2845. {
  2846. break;
  2847. }
  2848. }
  2849. p = strchr(p,'\n');// next line
  2850. continue;
  2851. }
  2852. }
  2853. if( strcasecmp(w2,"warp") == 0 && count > 3 )
  2854. {
  2855. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  2856. }
  2857. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop")) && count > 3 )
  2858. {
  2859. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  2860. }
  2861. else if( strcasecmp(w2,"script") == 0 && count > 3 )
  2862. {
  2863. if( strcasecmp(w1,"function") == 0 )
  2864. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  2865. else
  2866. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath);
  2867. }
  2868. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  2869. {
  2870. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  2871. }
  2872. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  2873. {
  2874. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  2875. }
  2876. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  2877. {
  2878. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  2879. }
  2880. else
  2881. {
  2882. 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);
  2883. p = strchr(p,'\n');// skip and continue
  2884. }
  2885. }
  2886. aFree(buffer);
  2887. return;
  2888. }
  2889. int npc_script_event(struct map_session_data* sd, enum npce_event type)
  2890. {
  2891. int i;
  2892. if (type == NPCE_MAX)
  2893. return 0;
  2894. if (!sd) {
  2895. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  2896. return 0;
  2897. }
  2898. for (i = 0; i<script_event[type].event_count; i++)
  2899. npc_event_sub(sd,script_event[type].event[i],script_event[type].event_name[i]);
  2900. return i;
  2901. }
  2902. void npc_read_event_script(void)
  2903. {
  2904. int i;
  2905. struct {
  2906. char *name;
  2907. const char *event_name;
  2908. } config[] = {
  2909. {"Login Event",script_config.login_event_name},
  2910. {"Logout Event",script_config.logout_event_name},
  2911. {"Load Map Event",script_config.loadmap_event_name},
  2912. {"Base LV Up Event",script_config.baselvup_event_name},
  2913. {"Job LV Up Event",script_config.joblvup_event_name},
  2914. {"Die Event",script_config.die_event_name},
  2915. {"Kill PC Event",script_config.kill_pc_event_name},
  2916. {"Kill NPC Event",script_config.kill_mob_event_name},
  2917. };
  2918. for (i = 0; i < NPCE_MAX; i++)
  2919. {
  2920. DBIterator* iter;
  2921. DBKey key;
  2922. DBData *data;
  2923. char name[64]="::";
  2924. strncpy(name+2,config[i].event_name,62);
  2925. script_event[i].event_count = 0;
  2926. iter = db_iterator(ev_db);
  2927. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  2928. {
  2929. const char* p = key.str;
  2930. struct event_data* ed = db_data2ptr(data);
  2931. unsigned char count = script_event[i].event_count;
  2932. if( count >= ARRAYLENGTH(script_event[i].event) )
  2933. {
  2934. ShowWarning("npc_read_event_script: too many occurences of event '%s'!\n", config[i].event_name);
  2935. break;
  2936. }
  2937. if( (p=strchr(p,':')) && p && strcmpi(name,p)==0 )
  2938. {
  2939. script_event[i].event[count] = ed;
  2940. script_event[i].event_name[count] = key.str;
  2941. script_event[i].event_count++;
  2942. }
  2943. }
  2944. dbi_destroy(iter);
  2945. }
  2946. if (battle_config.etc_log) {
  2947. //Print summary.
  2948. for (i = 0; i < NPCE_MAX; i++)
  2949. ShowInfo("%s: %d '%s' events.\n", config[i].name, script_event[i].event_count, config[i].event_name);
  2950. }
  2951. }
  2952. int npc_reload(void)
  2953. {
  2954. struct npc_src_list *nsl;
  2955. int m, i;
  2956. int npc_new_min = npc_id;
  2957. struct s_mapiterator* iter;
  2958. struct block_list* bl;
  2959. //Remove all npcs/mobs. [Skotlex]
  2960. iter = mapit_geteachiddb();
  2961. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  2962. {
  2963. switch(bl->type) {
  2964. case BL_NPC:
  2965. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  2966. npc_unload((struct npc_data *)bl);
  2967. break;
  2968. case BL_MOB:
  2969. unit_free(bl,CLR_OUTSIGHT);
  2970. break;
  2971. }
  2972. }
  2973. mapit_free(iter);
  2974. if(battle_config.dynamic_mobs)
  2975. {// dynamic check by [random]
  2976. for (m = 0; m < map_num; m++) {
  2977. for (i = 0; i < MAX_MOB_LIST_PER_MAP; i++) {
  2978. if (map[m].moblist[i] != NULL) {
  2979. aFree(map[m].moblist[i]);
  2980. map[m].moblist[i] = NULL;
  2981. }
  2982. if( map[m].mob_delete_timer != INVALID_TIMER )
  2983. { // Mobs were removed anyway,so delete the timer [Inkfish]
  2984. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2985. map[m].mob_delete_timer = INVALID_TIMER;
  2986. }
  2987. }
  2988. }
  2989. if (map[m].npc_num > 0)
  2990. ShowWarning("npc_reload: %d npcs weren't removed at map %s!\n", map[m].npc_num, map[m].name);
  2991. }
  2992. // clear mob spawn lookup index
  2993. mob_clear_spawninfo();
  2994. // clear npc-related data structures
  2995. ev_db->clear(ev_db,NULL);
  2996. npcname_db->clear(npcname_db,NULL);
  2997. npc_warp = npc_shop = npc_script = 0;
  2998. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  2999. // reset mapflags
  3000. map_flags_init();
  3001. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  3002. // Reloading npcs now
  3003. for (nsl = npc_src_files; nsl; nsl = nsl->next)
  3004. {
  3005. ShowStatus("Loading NPC file: %s"CL_CLL"\r", nsl->name);
  3006. npc_parsesrcfile(nsl->name);
  3007. }
  3008. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  3009. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  3010. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  3011. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  3012. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  3013. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  3014. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  3015. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3016. for( i = 0; i < ARRAYLENGTH(instance); ++i )
  3017. instance_init(instance[i].instance_id);
  3018. //Re-read the NPC Script Events cache.
  3019. npc_read_event_script();
  3020. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  3021. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n",npc_event_doall("OnInit"));
  3022. // Execute rest of the startup events if connected to char-server. [Lance]
  3023. if(!CheckForCharServer()){
  3024. ShowStatus("Event '"CL_WHITE"OnInterIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInit"));
  3025. ShowStatus("Event '"CL_WHITE"OnInterIfInitOnce"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInitOnce"));
  3026. }
  3027. return 0;
  3028. }
  3029. /*==========================================
  3030. * 終了
  3031. *------------------------------------------*/
  3032. int do_final_npc(void)
  3033. {
  3034. int i;
  3035. struct block_list *bl;
  3036. for (i = START_NPC_NUM; i < npc_id; i++){
  3037. if ((bl = map_id2bl(i))){
  3038. if (bl->type == BL_NPC)
  3039. npc_unload((struct npc_data *)bl);
  3040. else if (bl->type&(BL_MOB|BL_PET|BL_HOM|BL_MER))
  3041. unit_free(bl, CLR_OUTSIGHT);
  3042. }
  3043. }
  3044. ev_db->destroy(ev_db, NULL);
  3045. //There is no free function for npcname_db because at this point there shouldn't be any npcs left!
  3046. //So if there is anything remaining, let the memory manager catch it and report it.
  3047. npcname_db->destroy(npcname_db, NULL);
  3048. ers_destroy(timer_event_ers);
  3049. npc_clearsrcfile();
  3050. return 0;
  3051. }
  3052. static void npc_debug_warps_sub(struct npc_data* nd)
  3053. {
  3054. int m;
  3055. if (nd->bl.type != BL_NPC || nd->subtype != WARP || nd->bl.m < 0)
  3056. return;
  3057. m = map_mapindex2mapid(nd->u.warp.mapindex);
  3058. if (m < 0) return; //Warps to another map, nothing to do about it.
  3059. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  3060. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  3061. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  3062. nd->name,
  3063. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  3064. map[m].name, nd->u.warp.x, nd->u.warp.y
  3065. );
  3066. }
  3067. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  3068. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  3069. nd->name,
  3070. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  3071. map[m].name, nd->u.warp.x, nd->u.warp.y
  3072. );
  3073. }
  3074. }
  3075. static void npc_debug_warps(void)
  3076. {
  3077. int m, i;
  3078. for (m = 0; m < map_num; m++)
  3079. for (i = 0; i < map[m].npc_num; i++)
  3080. npc_debug_warps_sub(map[m].npc[i]);
  3081. }
  3082. /*==========================================
  3083. * npc initialization
  3084. *------------------------------------------*/
  3085. int do_init_npc(void)
  3086. {
  3087. struct npc_src_list *file;
  3088. int i;
  3089. //Stock view data for normal npcs.
  3090. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  3091. npc_viewdb[0].class_ = INVISIBLE_CLASS; //Invisible class is stored here.
  3092. for( i = 1; i < MAX_NPC_CLASS; i++ )
  3093. npc_viewdb[i].class_ = i;
  3094. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),2*NAME_LENGTH+2+1);
  3095. npcname_db = strdb_alloc(DB_OPT_BASE,NAME_LENGTH);
  3096. timer_event_ers = ers_new(sizeof(struct timer_event_data));
  3097. // process all npc files
  3098. ShowStatus("Loading NPCs...\r");
  3099. for( file = npc_src_files; file != NULL; file = file->next )
  3100. {
  3101. ShowStatus("Loading NPC file: %s"CL_CLL"\r", file->name);
  3102. npc_parsesrcfile(file->name);
  3103. }
  3104. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  3105. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  3106. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  3107. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  3108. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  3109. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  3110. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  3111. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3112. // set up the events cache
  3113. memset(script_event, 0, sizeof(script_event));
  3114. npc_read_event_script();
  3115. //Debug function to locate all endless loop warps.
  3116. if (battle_config.warp_point_debug)
  3117. npc_debug_warps();
  3118. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  3119. add_timer_func_list(npc_timerevent,"npc_timerevent");
  3120. // Init dummy NPC
  3121. fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
  3122. fake_nd->bl.m = -1;
  3123. fake_nd->bl.id = npc_get_new_npc_id();
  3124. fake_nd->class_ = -1;
  3125. fake_nd->speed = 200;
  3126. strcpy(fake_nd->name,"FAKE_NPC");
  3127. memcpy(fake_nd->exname, fake_nd->name, 9);
  3128. npc_script++;
  3129. fake_nd->bl.type = BL_NPC;
  3130. fake_nd->subtype = SCRIPT;
  3131. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  3132. fake_nd->u.scr.timerid = INVALID_TIMER;
  3133. map_addiddb(&fake_nd->bl);
  3134. // End of initialization
  3135. return 0;
  3136. }