npc.cpp 157 KB

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