npc.cpp 187 KB

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