npc.cpp 180 KB

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