npc.cpp 147 KB

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