npc.cpp 146 KB

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