npc.cpp 143 KB

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