npc.cpp 146 KB

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