mob.cpp 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "mob.hpp"
  4. #include <algorithm>
  5. #include <map>
  6. #include <math.h>
  7. #include <stdlib.h>
  8. #include <unordered_map>
  9. #include <vector>
  10. #include "../common/cbasetypes.hpp"
  11. #include "../common/db.hpp"
  12. #include "../common/ers.hpp"
  13. #include "../common/malloc.hpp"
  14. #include "../common/nullpo.hpp"
  15. #include "../common/random.hpp"
  16. #include "../common/showmsg.hpp"
  17. #include "../common/socket.hpp"
  18. #include "../common/strlib.hpp"
  19. #include "../common/timer.hpp"
  20. #include "../common/utilities.hpp"
  21. #include "../common/utils.hpp"
  22. #include "achievement.hpp"
  23. #include "battle.hpp"
  24. #include "clif.hpp"
  25. #include "elemental.hpp"
  26. #include "guild.hpp"
  27. #include "homunculus.hpp"
  28. #include "intif.hpp"
  29. #include "log.hpp"
  30. #include "map.hpp"
  31. #include "mercenary.hpp"
  32. #include "npc.hpp"
  33. #include "party.hpp"
  34. #include "path.hpp"
  35. #include "pc.hpp"
  36. #include "pet.hpp"
  37. #include "quest.hpp"
  38. using namespace rathena;
  39. #define ACTIVE_AI_RANGE 2 //Distance added on top of 'AREA_SIZE' at which mobs enter active AI mode.
  40. #define IDLE_SKILL_INTERVAL 10 //Active idle skills should be triggered every 1 second (1000/MIN_MOBTHINKTIME)
  41. const t_tick MOB_MAX_DELAY = 24 * 3600 * 1000;
  42. #define MAX_MINCHASE 30 //Max minimum chase value to use for mobs.
  43. #define RUDE_ATTACKED_COUNT 1 //After how many rude-attacks should the skill be used?
  44. // On official servers, monsters will only seek targets that are closer to walk to than their
  45. // search range. The search range is affected depending on if the monster is walking or not.
  46. // On some maps there can be a quite long path for just walking two cells in a direction and
  47. // the client does not support displaying walk paths that are longer than 14 cells, so this
  48. // option reduces position lag in such situation. But doing a complex search for every possible
  49. // target, might be CPU intensive.
  50. // Disable this to make monsters not do any path search when looking for a target (old behavior).
  51. #define ACTIVEPATHSEARCH
  52. // Limits for the monster database
  53. #define MIN_MOB_DB 1000
  54. #define MAX_MOB_DB 3999
  55. #define MIN_MOB_DB2 20020
  56. #define MAX_MOB_DB2 31999
  57. // These define the range of available IDs for clones. [Valaris]
  58. #define MOB_CLONE_START MAX_MOB_DB
  59. #define MOB_CLONE_END MIN_MOB_DB2
  60. //Dynamic mob database
  61. std::map<uint16, struct mob_db> mob_db_data;
  62. struct mob_db *mob_db( int mob_id ){
  63. return util::map_find( mob_db_data, (uint16)mob_id );
  64. }
  65. // holds Monster Spawn informations
  66. std::unordered_map<uint16, std::vector<spawn_info>> mob_spawn_data;
  67. //Dynamic mob chat database
  68. std::map<short,struct mob_chat> mob_chat_db;
  69. struct mob_chat *mob_chat(short id) {
  70. return util::map_find( mob_chat_db, id );
  71. }
  72. //Dynamic item drop ratio database for per-item drop ratio modifiers overriding global drop ratios.
  73. #define MAX_ITEMRATIO_MOBS 10
  74. struct s_mob_item_drop_ratio {
  75. unsigned short nameid;
  76. int drop_ratio;
  77. unsigned short mob_id[MAX_ITEMRATIO_MOBS];
  78. };
  79. static DBMap *mob_item_drop_ratio;
  80. /// Mob skill struct for temporary storage
  81. struct s_mob_skill {
  82. int16 mob_id; ///< Monster ID. -1 boss types, -2 normal types, -3 all monsters
  83. struct mob_skill skill[MAX_MOBSKILL]; ///< Skills
  84. uint8 count; ///< Number of skills
  85. };
  86. static DBMap *mob_skill_db; /// Monster skill temporary db. s_mob_skill -> mobid
  87. static struct eri *item_drop_ers; //For loot drops delay structures.
  88. static struct eri *item_drop_list_ers;
  89. struct s_randomsummon_entry {
  90. uint16 mob_id;
  91. uint32 rate;
  92. };
  93. struct s_randomsummon_group {
  94. uint8 random_id;
  95. struct s_randomsummon_entry *list;
  96. uint16 count;
  97. };
  98. static DBMap *mob_summon_db; /// Random Summon DB. struct s_randomsummon_group -> group_id
  99. /*==========================================
  100. * Local prototype declaration (only required thing)
  101. *------------------------------------------*/
  102. static TIMER_FUNC(mob_spawn_guardian_sub);
  103. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id);
  104. /*========================================== [Playtester]
  105. * Removes all characters that spotted the monster but are no longer online
  106. * @param md: Monster whose spotted log should be cleaned
  107. *------------------------------------------*/
  108. void mob_clean_spotted(struct mob_data *md) {
  109. int i;
  110. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  111. if (md->spotted_log[i] && !map_charid2sd(md->spotted_log[i]))
  112. md->spotted_log[i] = 0;
  113. }
  114. }
  115. /*========================================== [Playtester]
  116. * Adds a char_id to the spotted log of a monster
  117. * @param md: Monster to whose spotted log char_id should be added
  118. * @param char_id: Char_id to add to the spotted log
  119. *------------------------------------------*/
  120. void mob_add_spotted(struct mob_data *md, uint32 char_id) {
  121. int i;
  122. //Check if char_id is already logged
  123. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  124. if (md->spotted_log[i] == char_id)
  125. return;
  126. }
  127. //Not logged, add char_id to first empty slot
  128. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  129. if (md->spotted_log[i] == 0) {
  130. md->spotted_log[i] = char_id;
  131. return;
  132. }
  133. }
  134. }
  135. /*========================================== [Playtester]
  136. * Checks if a monster was spotted
  137. * @param md: Monster to check
  138. * @return Returns true if the monster is spotted, otherwise 0
  139. *------------------------------------------*/
  140. bool mob_is_spotted(struct mob_data *md) {
  141. int i;
  142. //Check if monster is spotted
  143. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  144. if (md->spotted_log[i] != 0)
  145. return true; //Spotted
  146. }
  147. return false; //Not spotted
  148. }
  149. /**
  150. * Tomb spawn time calculations
  151. * @param nd: NPC data
  152. */
  153. int mvptomb_setdelayspawn(struct npc_data *nd) {
  154. if (nd->u.tomb.spawn_timer != INVALID_TIMER)
  155. delete_timer(nd->u.tomb.spawn_timer, mvptomb_delayspawn);
  156. nd->u.tomb.spawn_timer = add_timer(gettick() + battle_config.mvp_tomb_delay, mvptomb_delayspawn, nd->bl.id, 0);
  157. return 0;
  158. }
  159. /**
  160. * Tomb spawn with delay (timer function)
  161. * @param tid: Timer ID
  162. * @param tick: Time
  163. * @param id: Block list ID
  164. * @param data: Used for add_timer_func_list
  165. */
  166. TIMER_FUNC(mvptomb_delayspawn){
  167. struct npc_data *nd = BL_CAST(BL_NPC, map_id2bl(id));
  168. if (nd) {
  169. if (nd->u.tomb.spawn_timer != tid) {
  170. ShowError("mvptomb_delayspawn: Timer mismatch: %d != %d\n", tid, nd->u.tomb.spawn_timer);
  171. return 0;
  172. }
  173. nd->u.tomb.spawn_timer = INVALID_TIMER;
  174. clif_spawn(&nd->bl);
  175. }
  176. return 0;
  177. }
  178. /**
  179. * Create and display a tombstone on the map
  180. * @param md: the mob to create a tombstone for
  181. * @param killer: name of player who killed the mob
  182. * @param time: time of mob's death
  183. * @author [GreenBox]
  184. */
  185. void mvptomb_create(struct mob_data *md, char *killer, time_t time)
  186. {
  187. struct npc_data *nd;
  188. if ( md->tomb_nid )
  189. mvptomb_destroy(md);
  190. CREATE(nd, struct npc_data, 1);
  191. nd->bl.id = md->tomb_nid = npc_get_new_npc_id();
  192. nd->ud.dir = md->ud.dir;
  193. nd->bl.m = md->bl.m;
  194. nd->bl.x = md->bl.x;
  195. nd->bl.y = md->bl.y;
  196. nd->bl.type = BL_NPC;
  197. safestrncpy(nd->name, msg_txt(NULL,656), sizeof(nd->name));
  198. nd->class_ = 565;
  199. nd->speed = 200;
  200. nd->subtype = NPCTYPE_TOMB;
  201. nd->u.tomb.md = md;
  202. nd->u.tomb.kill_time = time;
  203. nd->u.tomb.spawn_timer = INVALID_TIMER;
  204. if (killer)
  205. safestrncpy(nd->u.tomb.killer_name, killer, NAME_LENGTH);
  206. else
  207. nd->u.tomb.killer_name[0] = '\0';
  208. map_addnpc(nd->bl.m, nd);
  209. if(map_addblock(&nd->bl))
  210. return;
  211. status_set_viewdata(&nd->bl, nd->class_);
  212. status_change_init(&nd->bl);
  213. unit_dataset(&nd->bl);
  214. mvptomb_setdelayspawn(nd);
  215. }
  216. /**
  217. * Destroys MVP Tomb
  218. * @param md: Mob data
  219. */
  220. void mvptomb_destroy(struct mob_data *md) {
  221. struct npc_data *nd;
  222. if ( (nd = map_id2nd(md->tomb_nid)) ) {
  223. int16 i;
  224. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  225. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT);
  226. map_delblock(&nd->bl);
  227. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  228. if( !(i == mapdata->npc_num) ) {
  229. mapdata->npc_num--;
  230. mapdata->npc[i] = mapdata->npc[mapdata->npc_num];
  231. mapdata->npc[mapdata->npc_num] = NULL;
  232. }
  233. map_deliddb(&nd->bl);
  234. aFree(nd);
  235. }
  236. md->tomb_nid = 0;
  237. }
  238. /**
  239. * Sub function for mob namesearch. Here is defined which are accepted.
  240. */
  241. static bool mobdb_searchname_sub(uint16 mob_id, const char * const str, bool full_cmp)
  242. {
  243. const struct mob_db * const mob = mob_db(mob_id);
  244. if( mobdb_checkid(mob_id) <= 0 )
  245. return false; // invalid mob_id (includes clone check)
  246. if(!mob->base_exp && !mob->job_exp && !mob_has_spawn(mob_id))
  247. return false; // Monsters with no base/job exp and no spawn point are, by this criteria, considered "slave mobs" and excluded from search results
  248. if( full_cmp ) {
  249. // str must equal the db value
  250. if( strcmpi(mob->name, str) == 0 ||
  251. strcmpi(mob->jname, str) == 0 ||
  252. strcmpi(mob->sprite, str) == 0 )
  253. return true;
  254. } else {
  255. // str must be in the db value
  256. if( stristr(mob->name, str) != NULL ||
  257. stristr(mob->jname, str) != NULL ||
  258. stristr(mob->sprite, str) != NULL )
  259. return true;
  260. }
  261. return false;
  262. }
  263. /**
  264. * Searches for the Mobname
  265. */
  266. uint16 mobdb_searchname_(const char * const str, bool full_cmp)
  267. {
  268. for( auto const &mobdb_pair : mob_db_data ) {
  269. const uint16 mob_id = mobdb_pair.first;
  270. if( mobdb_searchname_sub(mob_id, str, full_cmp) )
  271. return mob_id;
  272. }
  273. return 0;
  274. }
  275. uint16 mobdb_searchname(const char * const str)
  276. {
  277. return mobdb_searchname_(str, true);
  278. }
  279. struct mob_db* mobdb_search_aegisname( const char* str ){
  280. for( auto &mobdb_pair : mob_db_data ){
  281. if( strcmpi( str, mobdb_pair.second.sprite ) == 0 ){
  282. return &mobdb_pair.second;
  283. }
  284. }
  285. return nullptr;
  286. }
  287. /*==========================================
  288. * Founds up to N matches. Returns number of matches [Skotlex]
  289. *------------------------------------------*/
  290. int mobdb_searchname_array_(const char *str, uint16 * out, int size, bool full_cmp)
  291. {
  292. unsigned short count = 0;
  293. for( auto const &mobdb_pair : mob_db_data ) {
  294. const uint16 mob_id = mobdb_pair.first;
  295. if( mobdb_searchname_sub(mob_id, str, full_cmp) ) {
  296. if( count < size )
  297. out[count] = mob_id;
  298. count++;
  299. }
  300. }
  301. return count;
  302. }
  303. int mobdb_searchname_array(const char *str, uint16 * out, int size)
  304. {
  305. return mobdb_searchname_array_(str, out, size, false);
  306. }
  307. /*==========================================
  308. * Id Mob is checked.
  309. *------------------------------------------*/
  310. int mobdb_checkid(const int id)
  311. {
  312. if (mob_db(id) == NULL)
  313. return 0;
  314. if (mob_is_clone(id)) //checkid is used mostly for random ID based code, therefore clone mobs are out of the question.
  315. return 0;
  316. return id;
  317. }
  318. /*==========================================
  319. * Returns the view data associated to this mob class.
  320. *------------------------------------------*/
  321. struct view_data * mob_get_viewdata(int mob_id)
  322. {
  323. struct mob_db* db = mob_db(mob_id);
  324. if( !db ) return nullptr;
  325. return &db->vd;
  326. }
  327. /**
  328. * Create unique view data associated to a spawned monster.
  329. * @param md: Mob to adjust
  330. */
  331. void mob_set_dynamic_viewdata( struct mob_data* md ){
  332. // If it is a valid monster and it has not already been created
  333. if( md && !md->vd_changed ){
  334. // Allocate a dynamic entry
  335. struct view_data* vd = (struct view_data*)aMalloc( sizeof( struct view_data ) );
  336. // Copy the current values
  337. memcpy( vd, md->vd, sizeof( struct view_data ) );
  338. // Update the pointer to the new entry
  339. md->vd = vd;
  340. // Flag it as changed so it is freed later on
  341. md->vd_changed = true;
  342. }
  343. }
  344. /**
  345. * Free any view data associated to a spawned monster.
  346. * @param md: Mob to free
  347. */
  348. void mob_free_dynamic_viewdata( struct mob_data* md ){
  349. // If it is a valid monster and it has already been allocated
  350. if( md && md->vd_changed ){
  351. // Free it
  352. aFree( md->vd );
  353. // Remove the reference
  354. md->vd = NULL;
  355. // Unflag it as changed
  356. md->vd_changed = false;
  357. }
  358. }
  359. /*==========================================
  360. * Cleans up mob-spawn data to make it "valid"
  361. *------------------------------------------*/
  362. int mob_parse_dataset(struct spawn_data *data)
  363. {
  364. size_t len;
  365. if ((!mobdb_checkid(data->id) && !mob_is_clone(data->id)) || !data->num)
  366. return 0;
  367. if( ( len = strlen(data->eventname) ) > 0 )
  368. {
  369. if( data->eventname[len-1] == '"' )
  370. data->eventname[len-1] = '\0'; //Remove trailing quote.
  371. if( data->eventname[0] == '"' ) //Strip leading quotes
  372. memmove(data->eventname, data->eventname+1, len-1);
  373. }
  374. if(strcmp(data->name,"--en--")==0)
  375. safestrncpy(data->name, mob_db(data->id)->name, sizeof(data->name));
  376. else if(strcmp(data->name,"--ja--")==0)
  377. safestrncpy(data->name, mob_db(data->id)->jname, sizeof(data->name));
  378. return 1;
  379. }
  380. /*==========================================
  381. * Generates the basic mob data using the spawn_data provided.
  382. *------------------------------------------*/
  383. struct mob_data* mob_spawn_dataset(struct spawn_data *data)
  384. {
  385. struct mob_data *md = (struct mob_data*)aCalloc(1, sizeof(struct mob_data));
  386. md->bl.id= npc_get_new_npc_id();
  387. md->bl.type = BL_MOB;
  388. md->bl.m = data->m;
  389. md->bl.x = data->x;
  390. md->bl.y = data->y;
  391. md->mob_id = data->id;
  392. md->state.boss = data->state.boss;
  393. md->db = mob_db(md->mob_id);
  394. if (data->level > 0 && data->level <= MAX_LEVEL)
  395. md->level = data->level;
  396. memcpy(md->name, data->name, NAME_LENGTH);
  397. if (data->state.ai)
  398. md->special_state.ai = data->state.ai;
  399. if (data->state.size)
  400. md->special_state.size = data->state.size;
  401. if (data->eventname[0] && strlen(data->eventname) >= 4)
  402. safestrncpy(md->npc_event, data->eventname, EVENT_NAME_LENGTH);
  403. if(status_has_mode(&md->db->status,MD_LOOTER))
  404. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  405. md->spawn_timer = INVALID_TIMER;
  406. md->deletetimer = INVALID_TIMER;
  407. md->skill_idx = -1;
  408. status_set_viewdata(&md->bl, md->mob_id);
  409. status_change_init(&md->bl);
  410. unit_dataset(&md->bl);
  411. map_addiddb(&md->bl);
  412. return md;
  413. }
  414. /*==========================================
  415. * Fetches a random mob_id [Skotlex]
  416. * type: Where to fetch from (see enum e_random_monster)
  417. * flag: Type of checks to apply (see enum e_random_monster_flags)
  418. * lv: Mob level to check against
  419. *------------------------------------------*/
  420. int mob_get_random_id(int type, enum e_random_monster_flags flag, int lv)
  421. {
  422. struct mob_db *mob;
  423. int i = 0, mob_id = 0, rand = 0;
  424. struct s_randomsummon_group *msummon = (struct s_randomsummon_group *)idb_get(mob_summon_db, type);
  425. struct s_randomsummon_entry *entry = nullptr;
  426. if (type == MOBG_Bloody_Dead_Branch && flag&RMF_MOB_NOT_BOSS)
  427. flag = static_cast<e_random_monster_flags>(flag&~RMF_MOB_NOT_BOSS);
  428. if (!msummon) {
  429. ShowError("mob_get_random_id: Invalid type (%d) of random monster.\n", type);
  430. return 0;
  431. }
  432. if (!msummon->count) {
  433. ShowError("mob_get_random_id: Random monster type %d is not defined.\n", type);
  434. return 0;
  435. }
  436. do {
  437. rand = rnd()%msummon->count;
  438. entry = &msummon->list[rand];
  439. mob_id = entry->mob_id;
  440. mob = mob_db(mob_id);
  441. } while ((rand == 0 || // Skip default first
  442. mob == nullptr ||
  443. mob_is_clone(mob_id) ||
  444. (flag&RMF_DB_RATE && (entry->rate < 1000000 && entry->rate <= rnd() % 1000000)) ||
  445. (flag&RMF_CHECK_MOB_LV && lv < mob->lv) ||
  446. (flag&RMF_MOB_NOT_BOSS && status_has_mode(&mob->status,MD_STATUS_IMMUNE) ) ||
  447. (flag&RMF_MOB_NOT_SPAWN && !mob_has_spawn(mob_id)) ||
  448. (flag&RMF_MOB_NOT_PLANT && status_has_mode(&mob->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC) )
  449. ) && (i++) < MAX_MOB_DB && msummon->count > 1);
  450. if (i >= MAX_MOB_DB && &msummon->list[0]) {
  451. ShowError("mob_get_random_id: no suitable monster found, use fallback for given list. Last_MobID: %d\n", mob_id);
  452. mob_id = msummon->list[0].mob_id;
  453. }
  454. return mob_id;
  455. }
  456. /*==========================================
  457. * Kill Steal Protection [Zephyrus]
  458. *------------------------------------------*/
  459. bool mob_ksprotected (struct block_list *src, struct block_list *target)
  460. {
  461. struct block_list *s_bl, *t_bl;
  462. struct map_session_data
  463. *sd, // Source
  464. *t_sd; // Mob Target
  465. struct mob_data *md;
  466. t_tick tick = gettick();
  467. if( !battle_config.ksprotection )
  468. return false; // KS Protection Disabled
  469. if( !(md = BL_CAST(BL_MOB,target)) )
  470. return false; // Tarjet is not MOB
  471. if( (s_bl = battle_get_master(src)) == nullptr )
  472. s_bl = src;
  473. if( !(sd = BL_CAST(BL_PC,s_bl)) )
  474. return false; // Master is not PC
  475. t_bl = map_id2bl(md->target_id);
  476. if( !t_bl || (s_bl = battle_get_master(t_bl)) == nullptr )
  477. s_bl = t_bl;
  478. t_sd = BL_CAST(BL_PC,s_bl);
  479. do {
  480. struct status_change_entry *sce;
  481. struct map_session_data *pl_sd; // Owner
  482. struct map_data *mapdata = map_getmapdata(md->bl.m);
  483. char output[128];
  484. if( mapdata->flag[MF_ALLOWKS] || mapdata_flag_ks(mapdata) )
  485. return false; // Ignores GVG, PVP and AllowKS map flags
  486. if( md->db->mexp || md->master_id )
  487. return false; // MVP, Slaves mobs ignores KS
  488. if( (sce = md->sc.data[SC_KSPROTECTED]) == nullptr )
  489. break; // No KS Protected
  490. if( sd->bl.id == sce->val1 || // Same Owner
  491. (sce->val2 == 2 && sd->status.party_id && sd->status.party_id == sce->val3) || // Party KS allowed
  492. (sce->val2 == 3 && sd->status.guild_id && sd->status.guild_id == sce->val4) ) // Guild KS allowed
  493. break;
  494. if( t_sd && (
  495. (sce->val2 == 1 && sce->val1 != t_sd->bl.id) ||
  496. (sce->val2 == 2 && sce->val3 && sce->val3 != t_sd->status.party_id) ||
  497. (sce->val2 == 3 && sce->val4 && sce->val4 != t_sd->status.guild_id)) )
  498. break;
  499. if( (pl_sd = map_id2sd(sce->val1)) == NULL || pl_sd->bl.m != md->bl.m )
  500. break;
  501. if( !pl_sd->state.noks )
  502. return false; // No KS Protected, but normal players should be protected too
  503. // Message to KS
  504. if( DIFF_TICK(sd->ks_floodprotect_tick, tick) <= 0 )
  505. {
  506. sprintf(output, "[KS Warning!! - Owner : %s]", pl_sd->status.name);
  507. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  508. sd->ks_floodprotect_tick = tick + 2000;
  509. }
  510. // Message to Owner
  511. if( DIFF_TICK(pl_sd->ks_floodprotect_tick, tick) <= 0 )
  512. {
  513. sprintf(output, "[Watch out! %s is trying to KS you!]", sd->status.name);
  514. clif_messagecolor(&pl_sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  515. pl_sd->ks_floodprotect_tick = tick + 2000;
  516. }
  517. return true;
  518. } while(0);
  519. status_change_start(src, target, SC_KSPROTECTED, 10000, sd->bl.id, sd->state.noks, sd->status.party_id, sd->status.guild_id, battle_config.ksprotection, SCSTART_NOAVOID);
  520. return false;
  521. }
  522. struct mob_data *mob_once_spawn_sub(struct block_list *bl, int16 m, int16 x, int16 y, const char *mobname, int mob_id, const char *event, unsigned int size, enum mob_ai ai)
  523. {
  524. struct spawn_data data;
  525. memset(&data, 0, sizeof(struct spawn_data)); //why ? this might screw attribute object and cause leak..
  526. data.m = m;
  527. data.num = 1;
  528. data.id = mob_id;
  529. data.state.size = size;
  530. data.state.ai = ai;
  531. if (mobname)
  532. safestrncpy(data.name, mobname, sizeof(data.name));
  533. else
  534. if (battle_config.override_mob_names == 1)
  535. strcpy(data.name, "--en--");
  536. else
  537. strcpy(data.name, "--ja--");
  538. if (event)
  539. safestrncpy(data.eventname, event, sizeof(data.eventname));
  540. // Locate spot next to player.
  541. if (bl && (x < 0 || y < 0))
  542. map_search_freecell(bl, m, &x, &y, 1, 1, 0);
  543. struct map_data *mapdata = map_getmapdata(m);
  544. // if none found, pick random position on map
  545. if (x <= 0 || x >= mapdata->xs || y <= 0 || y >= mapdata->ys)
  546. map_search_freecell(NULL, m, &x, &y, -1, -1, 1);
  547. data.x = x;
  548. data.y = y;
  549. if (!mob_parse_dataset(&data))
  550. return nullptr;
  551. return mob_spawn_dataset(&data);
  552. }
  553. /*==========================================
  554. * Spawn a single mob on the specified coordinates.
  555. *------------------------------------------*/
  556. int mob_once_spawn(struct map_session_data* sd, int16 m, int16 x, int16 y, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  557. {
  558. struct mob_data* md = nullptr;
  559. int count, lv;
  560. if (m < 0 || amount <= 0)
  561. return 0; // invalid input
  562. lv = (sd) ? sd->status.base_level : 255;
  563. for (count = 0; count < amount; count++)
  564. {
  565. int c = (mob_id >= 0) ? mob_id : mob_get_random_id(-mob_id - 1, (battle_config.random_monster_checklv) ? static_cast<e_random_monster_flags>(RMF_DB_RATE|RMF_CHECK_MOB_LV) : RMF_DB_RATE, lv);
  566. md = mob_once_spawn_sub((sd) ? &sd->bl : NULL, m, x, y, mobname, c, event, size, ai);
  567. if (!md)
  568. continue;
  569. if (mob_id == MOBID_EMPERIUM)
  570. {
  571. struct guild_castle* gc = guild_mapindex2gc(map_getmapdata(m)->index);
  572. struct guild* g = (gc) ? guild_search(gc->guild_id) : nullptr;
  573. if (gc)
  574. {
  575. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  576. md->guardian_data->castle = gc;
  577. md->guardian_data->number = MAX_GUARDIANS;
  578. md->guardian_data->guild_id = gc->guild_id;
  579. if (g)
  580. {
  581. md->guardian_data->emblem_id = g->emblem_id;
  582. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  583. }
  584. else if (gc->guild_id) //Guild not yet available, retry in 5.
  585. add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  586. }
  587. } // end addition [Valaris]
  588. mob_spawn(md);
  589. if (mob_id < 0 && battle_config.dead_branch_active)
  590. //Behold Aegis's masterful decisions yet again...
  591. //"I understand the "Aggressive" part, but the "Can Move" and "Can Attack" is just stupid" - Poki#3
  592. sc_start4(NULL,&md->bl, SC_MODECHANGE, 100, 1, 0, MD_AGGRESSIVE|MD_CANATTACK|MD_CANMOVE|MD_ANGRY, 0, 60000);
  593. }
  594. return (md) ? md->bl.id : 0; // id of last spawned mob
  595. }
  596. /*==========================================
  597. * Spawn mobs in the specified area.
  598. *------------------------------------------*/
  599. int mob_once_spawn_area(struct map_session_data* sd, int16 m, int16 x0, int16 y0, int16 x1, int16 y1, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  600. {
  601. int i, max, id = 0;
  602. int lx = -1, ly = -1;
  603. if (m < 0 || amount <= 0)
  604. return 0; // invalid input
  605. // normalize x/y coordinates
  606. if (x0 > x1)
  607. SWAP(x0, x1);
  608. if (y0 > y1)
  609. SWAP(y0, y1);
  610. // choose a suitable max. number of attempts
  611. max = (y1 - y0 + 1)*(x1 - x0 + 1)*3;
  612. if (max > 1000)
  613. max = 1000;
  614. // spawn mobs, one by one
  615. for (i = 0; i < amount; i++)
  616. {
  617. int x, y;
  618. int j = 0;
  619. // find a suitable map cell
  620. do {
  621. x = rnd()%(x1-x0+1)+x0;
  622. y = rnd()%(y1-y0+1)+y0;
  623. j++;
  624. } while (map_getcell(m,x,y,CELL_CHKNOPASS) && j < max);
  625. if (j == max)
  626. {// attempt to find an available cell failed
  627. if (lx == -1 && ly == -1)
  628. return 0; // total failure
  629. // fallback to last good x/y pair
  630. x = lx;
  631. y = ly;
  632. }
  633. // record last successful coordinates
  634. lx = x;
  635. ly = y;
  636. id = mob_once_spawn(sd, m, x, y, mobname, mob_id, 1, event, size, ai);
  637. }
  638. return id; // id of last spawned mob
  639. }
  640. /*==========================================
  641. * Set a Guardian's guild data [Skotlex]
  642. *------------------------------------------*/
  643. static TIMER_FUNC(mob_spawn_guardian_sub){
  644. //Needed because the guild_data may not be available at guardian spawn time.
  645. struct block_list* bl = map_id2bl(id);
  646. struct mob_data* md;
  647. struct guild* g;
  648. int guardup_lv;
  649. if (bl == nullptr) //It is possible mob was already removed from map when the castle has no owner. [Skotlex]
  650. return 0;
  651. if (bl->type != BL_MOB)
  652. {
  653. ShowError("mob_spawn_guardian_sub: Block error!\n");
  654. return 0;
  655. }
  656. md = (struct mob_data*)bl;
  657. nullpo_ret(md->guardian_data);
  658. g = guild_search((int)data);
  659. if (g == nullptr)
  660. { //Liberate castle, if the guild is not found this is an error! [Skotlex]
  661. ShowError("mob_spawn_guardian_sub: Couldn't load guild %d!\n", (int)data);
  662. if (md->mob_id == MOBID_EMPERIUM)
  663. { //Not sure this is the best way, but otherwise we'd be invoking this for ALL guardians spawned later on.
  664. md->guardian_data->guild_id = 0;
  665. if (md->guardian_data->castle->guild_id) //Free castle up.
  666. {
  667. ShowNotice("Clearing ownership of castle %d (%s)\n", md->guardian_data->castle->castle_id, md->guardian_data->castle->castle_name);
  668. guild_castledatasave(md->guardian_data->castle->castle_id, CD_GUILD_ID, 0);
  669. }
  670. } else {
  671. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  672. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  673. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  674. }
  675. return 0;
  676. }
  677. guardup_lv = guild_checkskill(g,GD_GUARDUP);
  678. md->guardian_data->emblem_id = g->emblem_id;
  679. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  680. md->guardian_data->guardup_lv = guardup_lv;
  681. if( guardup_lv )
  682. status_calc_mob(md, SCO_NONE); //Give bonuses.
  683. return 0;
  684. }
  685. /*==========================================
  686. * Summoning Guardians [Valaris]
  687. *------------------------------------------*/
  688. int mob_spawn_guardian(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, int guardian, bool has_index)
  689. {
  690. struct mob_data *md=nullptr;
  691. struct spawn_data data;
  692. struct guild *g=nullptr;
  693. struct guild_castle *gc;
  694. int16 m;
  695. memset(&data, 0, sizeof(struct spawn_data)); //fixme
  696. data.num = 1;
  697. m=map_mapname2mapid(mapname);
  698. if(m<0)
  699. {
  700. ShowWarning("mob_spawn_guardian: Map [%s] not found.\n", mapname);
  701. return 0;
  702. }
  703. data.m = m;
  704. data.num = 1;
  705. if(mob_id<=0) {
  706. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  707. if (!mob_id) return 0;
  708. }
  709. data.id = mob_id;
  710. if( !has_index )
  711. {
  712. guardian = -1;
  713. }
  714. else if( guardian < 0 || guardian >= MAX_GUARDIANS )
  715. {
  716. ShowError("mob_spawn_guardian: Invalid guardian index %d for guardian %d (castle map %s)\n", guardian, mob_id, mapname);
  717. return 0;
  718. }
  719. if((x<=0 || y<=0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1))
  720. {
  721. ShowWarning("mob_spawn_guardian: Couldn't locate a spawn cell for guardian class %d (index %d) at castle map %s\n",mob_id, guardian, mapname);
  722. return 0;
  723. }
  724. data.x = x;
  725. data.y = y;
  726. safestrncpy(data.name, mobname, sizeof(data.name));
  727. safestrncpy(data.eventname, event, sizeof(data.eventname));
  728. if (!mob_parse_dataset(&data))
  729. return 0;
  730. gc=guild_mapname2gc(mapname);
  731. if (gc == NULL)
  732. {
  733. ShowError("mob_spawn_guardian: No castle set at map %s\n", mapname);
  734. return 0;
  735. }
  736. if (!gc->guild_id)
  737. ShowWarning("mob_spawn_guardian: Spawning guardian %d on a castle with no guild (castle map %s)\n", mob_id, mapname);
  738. else
  739. g = guild_search(gc->guild_id);
  740. if( has_index && gc->guardian[guardian].id )
  741. { //Check if guardian already exists, refuse to spawn if so.
  742. struct mob_data *md2 = (TBL_MOB*)map_id2bl(gc->guardian[guardian].id);
  743. if (md2 && md2->bl.type == BL_MOB &&
  744. md2->guardian_data && md2->guardian_data->number == guardian)
  745. {
  746. ShowError("mob_spawn_guardian: Attempted to spawn guardian in position %d which already has a guardian (castle map %s)\n", guardian, mapname);
  747. return 0;
  748. }
  749. }
  750. md = mob_spawn_dataset(&data);
  751. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  752. md->guardian_data->number = guardian;
  753. md->guardian_data->guild_id = gc->guild_id;
  754. md->guardian_data->castle = gc;
  755. if( has_index )
  756. {// permanent guardian
  757. gc->guardian[guardian].id = md->bl.id;
  758. }
  759. else
  760. {// temporary guardian
  761. int i;
  762. ARR_FIND(0, gc->temp_guardians_max, i, gc->temp_guardians[i] == 0);
  763. if( i == gc->temp_guardians_max )
  764. {
  765. ++(gc->temp_guardians_max);
  766. RECREATE(gc->temp_guardians, int, gc->temp_guardians_max);
  767. }
  768. gc->temp_guardians[i] = md->bl.id;
  769. }
  770. if (g)
  771. {
  772. md->guardian_data->emblem_id = g->emblem_id;
  773. memcpy (md->guardian_data->guild_name, g->name, NAME_LENGTH);
  774. md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
  775. } else if (md->guardian_data->guild_id)
  776. add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  777. mob_spawn(md);
  778. return md->bl.id;
  779. }
  780. /*==========================================
  781. * Summoning BattleGround [Zephyrus]
  782. *------------------------------------------*/
  783. int mob_spawn_bg(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, unsigned int bg_id)
  784. {
  785. struct mob_data *md = nullptr;
  786. struct spawn_data data;
  787. int16 m;
  788. if( (m = map_mapname2mapid(mapname)) < 0 )
  789. {
  790. ShowWarning("mob_spawn_bg: Map [%s] not found.\n", mapname);
  791. return 0;
  792. }
  793. memset(&data, 0, sizeof(struct spawn_data));
  794. data.m = m;
  795. data.num = 1;
  796. if( mob_id <= 0 )
  797. {
  798. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  799. if( !mob_id ) return 0;
  800. }
  801. data.id = mob_id;
  802. if( (x <= 0 || y <= 0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1) )
  803. {
  804. ShowWarning("mob_spawn_bg: Couldn't locate a spawn cell for guardian class %d (bg_id %d) at map %s\n",mob_id, bg_id, mapname);
  805. return 0;
  806. }
  807. data.x = x;
  808. data.y = y;
  809. safestrncpy(data.name, mobname, sizeof(data.name));
  810. safestrncpy(data.eventname, event, sizeof(data.eventname));
  811. if( !mob_parse_dataset(&data) )
  812. return 0;
  813. md = mob_spawn_dataset(&data);
  814. mob_spawn(md);
  815. md->bg_id = bg_id; // BG Team ID
  816. return md->bl.id;
  817. }
  818. /*==========================================
  819. * Reachability to a Specification ID existence place
  820. * state indicates type of 'seek' mob should do:
  821. * - MSS_LOOT: Looking for item, path must be easy.
  822. * - MSS_RUSH: Chasing attacking player, path is complex
  823. * - MSS_FOLLOW: Initiative/support seek, path is complex
  824. *------------------------------------------*/
  825. int mob_can_reach(struct mob_data *md,struct block_list *bl,int range, int state)
  826. {
  827. int easy = 0;
  828. nullpo_ret(md);
  829. nullpo_ret(bl);
  830. switch (state) {
  831. case MSS_RUSH:
  832. case MSS_FOLLOW:
  833. easy = 0; //(battle_config.mob_ai&0x1?0:1);
  834. break;
  835. case MSS_LOOT:
  836. default:
  837. easy = 1;
  838. break;
  839. }
  840. return unit_can_reach_bl(&md->bl, bl, range, easy, NULL, NULL);
  841. }
  842. /*==========================================
  843. * Links nearby mobs (supportive mobs)
  844. *------------------------------------------*/
  845. int mob_linksearch(struct block_list *bl,va_list ap)
  846. {
  847. struct mob_data *md;
  848. int mob_id;
  849. struct block_list *target;
  850. t_tick tick;
  851. nullpo_ret(bl);
  852. md=(struct mob_data *)bl;
  853. mob_id = va_arg(ap, int);
  854. target = va_arg(ap, struct block_list *);
  855. tick=va_arg(ap, t_tick);
  856. if (md->mob_id == mob_id && DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME
  857. && !md->target_id)
  858. {
  859. md->last_linktime = tick;
  860. if( mob_can_reach(md,target,md->db->range2, MSS_FOLLOW) ){ // Reachability judging
  861. md->target_id = target->id;
  862. md->min_chase=md->db->range3;
  863. return 1;
  864. }
  865. }
  866. return 0;
  867. }
  868. /*==========================================
  869. * mob spawn with delay (timer function)
  870. *------------------------------------------*/
  871. TIMER_FUNC(mob_delayspawn){
  872. struct block_list* bl = map_id2bl(id);
  873. struct mob_data* md = BL_CAST(BL_MOB, bl);
  874. if( md )
  875. {
  876. if( md->spawn_timer != tid )
  877. {
  878. ShowError("mob_delayspawn: Timer mismatch: %d != %d\n", tid, md->spawn_timer);
  879. return 0;
  880. }
  881. md->spawn_timer = INVALID_TIMER;
  882. mob_spawn(md);
  883. }
  884. return 0;
  885. }
  886. /*==========================================
  887. * spawn timing calculation
  888. *------------------------------------------*/
  889. int mob_setdelayspawn(struct mob_data *md)
  890. {
  891. unsigned int spawntime;
  892. struct mob_db *db;
  893. if (!md->spawn) //Doesn't has respawn data!
  894. return unit_free(&md->bl,CLR_DEAD);
  895. spawntime = md->spawn->delay1; //Base respawn time
  896. if (md->spawn->delay2) //random variance
  897. spawntime+= rnd()%md->spawn->delay2;
  898. //Apply the spawn delay fix [Skotlex]
  899. db = mob_db(md->spawn->id);
  900. if (status_has_mode(&db->status,MD_STATUS_IMMUNE)) { // Status Immune
  901. if (battle_config.boss_spawn_delay != 100) {
  902. // Divide by 100 first to prevent overflows
  903. //(precision loss is minimal as duration is in ms already)
  904. spawntime = spawntime/100*battle_config.boss_spawn_delay;
  905. }
  906. } else if (status_has_mode(&db->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC)) { // Plant type
  907. if (battle_config.plant_spawn_delay != 100) {
  908. spawntime = spawntime/100*battle_config.plant_spawn_delay;
  909. }
  910. } else if (battle_config.mob_spawn_delay != 100) { //Normal mobs
  911. spawntime = spawntime/100*battle_config.mob_spawn_delay;
  912. }
  913. if (spawntime < 5000) //Monsters should never respawn faster than within 5 seconds
  914. spawntime = 5000;
  915. if( md->spawn_timer != INVALID_TIMER )
  916. delete_timer(md->spawn_timer, mob_delayspawn);
  917. md->spawn_timer = add_timer(gettick()+spawntime, mob_delayspawn, md->bl.id, 0);
  918. return 0;
  919. }
  920. int mob_count_sub(struct block_list *bl, va_list ap) {
  921. int mobid[10], i;
  922. ARR_FIND(0, 10, i, (mobid[i] = va_arg(ap, int)) == 0); //fetch till 0
  923. if (mobid[0]) { //if there one let's check it otherwise go backward
  924. TBL_MOB *md = BL_CAST(BL_MOB, bl);
  925. ARR_FIND(0, 10, i, md->mob_id == mobid[i]);
  926. return (i < 10) ? 1 : 0;
  927. }
  928. return 1; //backward compatibility
  929. }
  930. /**
  931. * Mob spawning. Initialization is also variously here. (Spawn a mob in a map)
  932. * @param md : mob data to spawn
  933. * @return 0:spawned, 1:delayed, 2:error
  934. */
  935. int mob_spawn (struct mob_data *md)
  936. {
  937. int i=0;
  938. t_tick tick = gettick();
  939. md->last_thinktime = tick;
  940. if (md->bl.prev != NULL)
  941. unit_remove_map(&md->bl,CLR_RESPAWN);
  942. else
  943. if (md->spawn && md->mob_id != md->spawn->id)
  944. {
  945. md->mob_id = md->spawn->id;
  946. status_set_viewdata(&md->bl, md->mob_id);
  947. md->db = mob_db(md->mob_id);
  948. memcpy(md->name,md->spawn->name,NAME_LENGTH);
  949. }
  950. if (md->spawn) { //Respawn data
  951. md->bl.m = md->spawn->m;
  952. md->bl.x = md->spawn->x;
  953. md->bl.y = md->spawn->y;
  954. if( (md->bl.x == 0 && md->bl.y == 0) || md->spawn->xs || md->spawn->ys )
  955. { //Monster can be spawned on an area.
  956. if( !map_search_freecell(&md->bl, -1, &md->bl.x, &md->bl.y, md->spawn->xs, md->spawn->ys, battle_config.no_spawn_on_player?4:0) )
  957. { // retry again later
  958. if( md->spawn_timer != INVALID_TIMER )
  959. delete_timer(md->spawn_timer, mob_delayspawn);
  960. md->spawn_timer = add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
  961. return 1;
  962. }
  963. }
  964. else if( battle_config.no_spawn_on_player > 99 && map_foreachinallrange(mob_count_sub, &md->bl, AREA_SIZE, BL_PC) )
  965. { // retry again later (players on sight)
  966. if( md->spawn_timer != INVALID_TIMER )
  967. delete_timer(md->spawn_timer, mob_delayspawn);
  968. md->spawn_timer = add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
  969. return 1;
  970. }
  971. }
  972. memset(&md->state, 0, sizeof(md->state));
  973. status_calc_mob(md, SCO_FIRST);
  974. md->attacked_id = 0;
  975. md->norm_attacked_id = 0;
  976. md->target_id = 0;
  977. md->move_fail_count = 0;
  978. md->ud.state.attack_continue = 0;
  979. md->ud.target_to = 0;
  980. md->ud.dir = 0;
  981. if( md->spawn_timer != INVALID_TIMER ) {
  982. delete_timer(md->spawn_timer, mob_delayspawn);
  983. md->spawn_timer = INVALID_TIMER;
  984. }
  985. // md->master_id = 0;
  986. md->master_dist = 0;
  987. md->state.aggressive = status_has_mode(&md->status,MD_ANGRY)?1:0;
  988. md->state.skillstate = MSS_IDLE;
  989. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  990. md->last_linktime = tick;
  991. md->dmgtick = tick - 5000;
  992. md->last_pcneartime = 0;
  993. t_tick c = tick - MOB_MAX_DELAY;
  994. for (i = 0; i < MAX_MOBSKILL; i++)
  995. md->skilldelay[i] = c;
  996. for (i = 0; i < DAMAGELOG_SIZE; i++)
  997. md->spotted_log[i] = 0;
  998. memset(md->dmglog, 0, sizeof(md->dmglog));
  999. md->tdmg = 0;
  1000. if (md->lootitems)
  1001. memset(md->lootitems, 0, sizeof(*md->lootitems));
  1002. md->lootitem_count = 0;
  1003. if(md->db->option)
  1004. // Added for carts, falcons and pecos for cloned monsters. [Valaris]
  1005. md->sc.option = md->db->option;
  1006. // MvP tomb [GreenBox]
  1007. if ( md->tomb_nid )
  1008. mvptomb_destroy(md);
  1009. if(map_addblock(&md->bl))
  1010. return 2;
  1011. if( map_getmapdata(md->bl.m)->users )
  1012. clif_spawn(&md->bl);
  1013. skill_unit_move(&md->bl,tick,1);
  1014. mobskill_use(md, tick, MSC_SPAWN);
  1015. return 0;
  1016. }
  1017. /*==========================================
  1018. * Determines if the mob can change target. [Skotlex]
  1019. *------------------------------------------*/
  1020. static int mob_can_changetarget(struct mob_data* md, struct block_list* target, enum e_mode mode)
  1021. {
  1022. // Special feature that makes monsters always attack the person that provoked them
  1023. if(battle_config.mob_ai&0x800 && md->state.provoke_flag)
  1024. {
  1025. if (md->state.provoke_flag == target->id)
  1026. return 1;
  1027. else if (!(battle_config.mob_ai&0x4))
  1028. return 0;
  1029. }
  1030. switch (md->state.skillstate) {
  1031. case MSS_BERSERK:
  1032. if (!(mode&MD_CHANGETARGET_MELEE))
  1033. return 0;
  1034. if (!(battle_config.mob_ai&0x80) && md->norm_attacked_id != target->id)
  1035. return 0;
  1036. return (battle_config.mob_ai&0x4 || check_distance_bl(&md->bl, target, md->status.rhw.range+1));
  1037. case MSS_RUSH:
  1038. return (mode&MD_CHANGETARGET_CHASE);
  1039. case MSS_FOLLOW:
  1040. case MSS_ANGRY:
  1041. case MSS_IDLE:
  1042. case MSS_WALK:
  1043. case MSS_LOOT:
  1044. return 1;
  1045. default:
  1046. return 0;
  1047. }
  1048. }
  1049. /*==========================================
  1050. * Determination for an attack of a monster
  1051. *------------------------------------------*/
  1052. int mob_target(struct mob_data *md,struct block_list *bl,int dist)
  1053. {
  1054. nullpo_ret(md);
  1055. nullpo_ret(bl);
  1056. // Nothing will be carried out if there is no mind of changing TAGE by TAGE ending.
  1057. if(md->target_id && !mob_can_changetarget(md, bl, status_get_mode(&md->bl)))
  1058. return 0;
  1059. if(!status_check_skilluse(&md->bl, bl, 0, 0))
  1060. return 0;
  1061. md->target_id = bl->id; // Since there was no disturbance, it locks on to target.
  1062. if (md->state.provoke_flag && bl->id != md->state.provoke_flag)
  1063. md->state.provoke_flag = 0;
  1064. // When an angry monster is provoked, it will switch to retaliate AI
  1065. if (md->state.provoke_flag && md->state.aggressive)
  1066. md->state.aggressive = 0;
  1067. md->min_chase=dist+md->db->range3;
  1068. if(md->min_chase>MAX_MINCHASE)
  1069. md->min_chase=MAX_MINCHASE;
  1070. return 0;
  1071. }
  1072. /*==========================================
  1073. * The ?? routine of an active monster
  1074. *------------------------------------------*/
  1075. static int mob_ai_sub_hard_activesearch(struct block_list *bl,va_list ap)
  1076. {
  1077. struct mob_data *md;
  1078. struct block_list **target;
  1079. enum e_mode mode;
  1080. int dist;
  1081. nullpo_ret(bl);
  1082. md=va_arg(ap,struct mob_data *);
  1083. target= va_arg(ap,struct block_list**);
  1084. mode= static_cast<enum e_mode>(va_arg(ap, int));
  1085. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1086. if ((*target) == bl || !status_check_skilluse(&md->bl, bl, 0, 0))
  1087. return 0;
  1088. if ((mode&MD_TARGETWEAK) && status_get_lv(bl) >= md->level-5)
  1089. return 0;
  1090. if(battle_check_target(&md->bl,bl,BCT_ENEMY)<=0)
  1091. return 0;
  1092. switch (bl->type)
  1093. {
  1094. case BL_PC:
  1095. if (((TBL_PC*)bl)->state.gangsterparadise &&
  1096. !status_has_mode(&md->status,MD_STATUS_IMMUNE))
  1097. return 0; //Gangster paradise protection.
  1098. default:
  1099. if (battle_config.hom_setting&HOMSET_FIRST_TARGET &&
  1100. (*target) && (*target)->type == BL_HOM && bl->type != BL_HOM)
  1101. return 0; //For some reason Homun targets are never overriden.
  1102. dist = distance_bl(&md->bl, bl);
  1103. if(
  1104. ((*target) == NULL || !check_distance_bl(&md->bl, *target, dist)) &&
  1105. battle_check_range(&md->bl,bl,md->db->range2)
  1106. ) { //Pick closest target?
  1107. #ifdef ACTIVEPATHSEARCH
  1108. struct walkpath_data wpd;
  1109. if (!path_search(&wpd, md->bl.m, md->bl.x, md->bl.y, bl->x, bl->y, 0, CELL_CHKWALL)) // Count walk path cells
  1110. return 0;
  1111. //Standing monsters use range2, walking monsters use range3
  1112. if ((md->ud.walktimer == INVALID_TIMER && wpd.path_len > md->db->range2)
  1113. || (md->ud.walktimer != INVALID_TIMER && wpd.path_len > md->db->range3))
  1114. return 0;
  1115. #endif
  1116. (*target) = bl;
  1117. md->target_id=bl->id;
  1118. md->min_chase= dist + md->db->range3;
  1119. if(md->min_chase>MAX_MINCHASE)
  1120. md->min_chase=MAX_MINCHASE;
  1121. return 1;
  1122. }
  1123. break;
  1124. }
  1125. return 0;
  1126. }
  1127. /*==========================================
  1128. * chase target-change routine.
  1129. *------------------------------------------*/
  1130. static int mob_ai_sub_hard_changechase(struct block_list *bl,va_list ap)
  1131. {
  1132. struct mob_data *md;
  1133. struct block_list **target;
  1134. nullpo_ret(bl);
  1135. md=va_arg(ap,struct mob_data *);
  1136. target= va_arg(ap,struct block_list**);
  1137. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1138. if ((*target) == bl ||
  1139. battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ||
  1140. !status_check_skilluse(&md->bl, bl, 0, 0))
  1141. return 0;
  1142. if(battle_check_range (&md->bl, bl, md->status.rhw.range))
  1143. {
  1144. (*target) = bl;
  1145. md->target_id=bl->id;
  1146. md->min_chase= md->db->range3;
  1147. }
  1148. return 1;
  1149. }
  1150. /*==========================================
  1151. * finds nearby bg ally for guardians looking for users to follow.
  1152. *------------------------------------------*/
  1153. static int mob_ai_sub_hard_bg_ally(struct block_list *bl,va_list ap) {
  1154. struct mob_data *md;
  1155. struct block_list **target;
  1156. nullpo_ret(bl);
  1157. md=va_arg(ap,struct mob_data *);
  1158. target= va_arg(ap,struct block_list**);
  1159. if( status_check_skilluse(&md->bl, bl, 0, 0) && battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ) {
  1160. (*target) = bl;
  1161. }
  1162. return 1;
  1163. }
  1164. /*==========================================
  1165. * loot monster item search
  1166. *------------------------------------------*/
  1167. static int mob_ai_sub_hard_lootsearch(struct block_list *bl,va_list ap)
  1168. {
  1169. struct mob_data* md;
  1170. struct block_list **target;
  1171. int dist;
  1172. md = va_arg(ap,struct mob_data *);
  1173. target = va_arg(ap,struct block_list**);
  1174. dist = distance_bl(&md->bl, bl);
  1175. if (mob_can_reach(md,bl,dist+1, MSS_LOOT) && (
  1176. (*target) == nullptr ||
  1177. (battle_config.monster_loot_search_type && md->target_id > bl->id) ||
  1178. (!battle_config.monster_loot_search_type && !check_distance_bl(&md->bl, *target, dist)) // New target closer than previous one.
  1179. ))
  1180. {
  1181. (*target) = bl;
  1182. md->target_id = bl->id;
  1183. md->min_chase = md->db->range3;
  1184. }
  1185. else if (!battle_config.monster_loot_search_type)
  1186. mob_stop_walking(md, 1); // Stop walking immediately if item is no longer on the ground.
  1187. return 0;
  1188. }
  1189. static int mob_warpchase_sub(struct block_list *bl,va_list ap) {
  1190. struct block_list *target;
  1191. struct npc_data **target_nd;
  1192. struct npc_data *nd;
  1193. int *min_distance;
  1194. int cur_distance;
  1195. target= va_arg(ap, struct block_list*);
  1196. target_nd= va_arg(ap, struct npc_data**);
  1197. min_distance= va_arg(ap, int*);
  1198. nd = (TBL_NPC*) bl;
  1199. if(nd->subtype != NPCTYPE_WARP)
  1200. return 0; //Not a warp
  1201. if(nd->u.warp.mapindex != map_getmapdata(target->m)->index)
  1202. return 0; //Does not lead to the same map.
  1203. cur_distance = distance_blxy(target, nd->u.warp.x, nd->u.warp.y);
  1204. if (cur_distance < *min_distance)
  1205. { //Pick warp that leads closest to target.
  1206. *target_nd = nd;
  1207. *min_distance = cur_distance;
  1208. return 1;
  1209. }
  1210. return 0;
  1211. }
  1212. /*==========================================
  1213. * Processing of slave monsters
  1214. *------------------------------------------*/
  1215. static int mob_ai_sub_hard_slavemob(struct mob_data *md,t_tick tick)
  1216. {
  1217. struct block_list *bl;
  1218. bl=map_id2bl(md->master_id);
  1219. if (!bl || status_isdead(bl)) {
  1220. status_kill(&md->bl);
  1221. return 1;
  1222. }
  1223. if (bl->prev == nullptr)
  1224. return 0; //Master not on a map? Could be warping, do not process.
  1225. if(status_has_mode(&md->status,MD_CANMOVE))
  1226. { //If the mob can move, follow around. [Check by Skotlex]
  1227. int old_dist;
  1228. // Distance with between slave and master is measured.
  1229. old_dist=md->master_dist;
  1230. md->master_dist=distance_bl(&md->bl, bl);
  1231. // Since the master was in near immediately before, teleport is carried out and it pursues.
  1232. if(bl->m != md->bl.m ||
  1233. (old_dist<10 && md->master_dist>18) ||
  1234. md->master_dist > MAX_MINCHASE
  1235. ){
  1236. md->master_dist = 0;
  1237. unit_warp(&md->bl,bl->m,bl->x,bl->y,CLR_TELEPORT);
  1238. return 1;
  1239. }
  1240. if(md->target_id) //Slave is busy with a target.
  1241. return 0;
  1242. // Approach master if within view range, chase back to Master's area also if standing on top of the master.
  1243. if((md->master_dist>MOB_SLAVEDISTANCE || md->master_dist == 0) &&
  1244. unit_can_move(&md->bl))
  1245. {
  1246. short x = bl->x, y = bl->y;
  1247. mob_stop_attack(md);
  1248. if(map_search_freecell(&md->bl, bl->m, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 1)
  1249. && unit_walktoxy(&md->bl, x, y, 0))
  1250. return 1;
  1251. }
  1252. } else if (bl->m != md->bl.m && map_flag_gvg2(md->bl.m)) {
  1253. //Delete the summoned mob if it's in a gvg ground and the master is elsewhere. [Skotlex]
  1254. status_kill(&md->bl);
  1255. return 1;
  1256. }
  1257. //Avoid attempting to lock the master's target too often to avoid unnecessary overload. [Skotlex]
  1258. if (DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME && !md->target_id)
  1259. {
  1260. struct unit_data *ud = unit_bl2ud(bl);
  1261. md->last_linktime = tick;
  1262. if (ud) {
  1263. struct block_list *tbl=nullptr;
  1264. if (ud->target && ud->state.attack_continue)
  1265. tbl = map_id2bl(ud->target);
  1266. else if (ud->target_to && ud->state.attack_continue)
  1267. tbl = map_id2bl(ud->target_to);
  1268. else if (ud->skilltarget) {
  1269. tbl = map_id2bl(ud->skilltarget);
  1270. //Required check as skilltarget is not always an enemy. [Skotlex]
  1271. if (tbl && battle_check_target(&md->bl, tbl, BCT_ENEMY) <= 0)
  1272. tbl = nullptr;
  1273. }
  1274. if (tbl && status_check_skilluse(&md->bl, tbl, 0, 0)) {
  1275. md->target_id=tbl->id;
  1276. md->min_chase=md->db->range3+distance_bl(&md->bl, tbl);
  1277. if(md->min_chase>MAX_MINCHASE)
  1278. md->min_chase=MAX_MINCHASE;
  1279. return 1;
  1280. }
  1281. }
  1282. }
  1283. return 0;
  1284. }
  1285. /*==========================================
  1286. * A lock of target is stopped and mob moves to a standby state.
  1287. * This also triggers idle skill/movement since the AI can get stuck
  1288. * when trying to pick new targets when the current chosen target is
  1289. * unreachable.
  1290. *------------------------------------------*/
  1291. int mob_unlocktarget(struct mob_data *md, t_tick tick)
  1292. {
  1293. nullpo_ret(md);
  1294. switch (md->state.skillstate) {
  1295. case MSS_WALK:
  1296. if (md->ud.walktimer != INVALID_TIMER)
  1297. break;
  1298. //Because it is not unset when the mob finishes walking.
  1299. md->state.skillstate = MSS_IDLE;
  1300. case MSS_IDLE:
  1301. // Idle skill.
  1302. if (!(++md->ud.walk_count%IDLE_SKILL_INTERVAL) && mobskill_use(md, tick, -1))
  1303. break;
  1304. //Random walk.
  1305. if (!md->master_id &&
  1306. DIFF_TICK(md->next_walktime, tick) <= 0 &&
  1307. !mob_randomwalk(md,tick))
  1308. //Delay next random walk when this one failed.
  1309. md->next_walktime = tick+rnd()%1000;
  1310. break;
  1311. default:
  1312. mob_stop_attack(md);
  1313. mob_stop_walking(md,1); //Stop chasing.
  1314. if (status_has_mode(&md->status,MD_ANGRY) && !md->state.aggressive)
  1315. md->state.aggressive = 1; //Restore angry state when switching to idle
  1316. md->state.skillstate = MSS_IDLE;
  1317. if(battle_config.mob_ai&0x8) //Walk instantly after dropping target
  1318. md->next_walktime = tick+rnd()%1000;
  1319. else
  1320. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  1321. break;
  1322. }
  1323. if (md->target_id) {
  1324. md->target_id=0;
  1325. md->ud.target_to = 0;
  1326. unit_set_target(&md->ud, 0);
  1327. }
  1328. if (battle_config.official_cell_stack_limit > 0
  1329. && (md->min_chase == md->db->range3 || battle_config.mob_ai & 0x8)
  1330. && map_count_oncell(md->bl.m, md->bl.x, md->bl.y, BL_CHAR | BL_NPC, 1) > battle_config.official_cell_stack_limit) {
  1331. unit_walktoxy(&md->bl, md->bl.x, md->bl.y, 8);
  1332. }
  1333. return 0;
  1334. }
  1335. /*==========================================
  1336. * Random walk
  1337. *------------------------------------------*/
  1338. int mob_randomwalk(struct mob_data *md,t_tick tick)
  1339. {
  1340. const int d=7;
  1341. int i,c,r,rdir,dx,dy,max;
  1342. int speed;
  1343. nullpo_ret(md);
  1344. if(DIFF_TICK(md->next_walktime,tick)>0 ||
  1345. status_has_mode(&md->status,MD_NORANDOM_WALK) ||
  1346. !unit_can_move(&md->bl) ||
  1347. !status_has_mode(&md->status,MD_CANMOVE))
  1348. return 0;
  1349. r=rnd();
  1350. rdir=rnd()%4; // Randomize direction in which we iterate to prevent monster cluttering up in one corner
  1351. dx=r%(d*2+1)-d;
  1352. dy=r/(d*2+1)%(d*2+1)-d;
  1353. max=(d*2+1)*(d*2+1);
  1354. for(i=0;i<max;i++){ // Search of a movable place
  1355. int x = dx + md->bl.x;
  1356. int y = dy + md->bl.y;
  1357. if(((x != md->bl.x) || (y != md->bl.y)) && map_getcell(md->bl.m,x,y,CELL_CHKPASS) && unit_walktoxy(&md->bl,x,y,0)){
  1358. break;
  1359. }
  1360. // Could not move to cell, try the 7th cell in direction randomly decided by rdir
  1361. // We don't move step-by-step because this will make monster stick to the walls
  1362. switch(rdir) {
  1363. case 0:
  1364. dx += d;
  1365. if (dx > d) {
  1366. dx -= d*2+1;
  1367. dy += d;
  1368. if (dy > d) {
  1369. dy -= d*2+1;
  1370. }
  1371. }
  1372. break;
  1373. case 1:
  1374. dx -= d;
  1375. if (dx < -d) {
  1376. dx += d*2+1;
  1377. dy -= d;
  1378. if (dy < -d) {
  1379. dy += d*2+1;
  1380. }
  1381. }
  1382. break;
  1383. case 2:
  1384. dy += d;
  1385. if (dy > d) {
  1386. dy -= d*2+1;
  1387. dx += d;
  1388. if (dx > d) {
  1389. dx -= d*2+1;
  1390. }
  1391. }
  1392. break;
  1393. case 3:
  1394. dy -= d;
  1395. if (dy < -d) {
  1396. dy += d*2+1;
  1397. dx -= d;
  1398. if (dx < -d) {
  1399. dx += d*2+1;
  1400. }
  1401. }
  1402. break;
  1403. }
  1404. }
  1405. if(i==max){
  1406. // None of the available cells worked, try again next interval
  1407. if(battle_config.mob_stuck_warning) {
  1408. md->move_fail_count++;
  1409. if(md->move_fail_count>1000){
  1410. ShowWarning("MOB can't move. random spawn %d, class = %d, at %s (%d,%d)\n",md->bl.id,md->mob_id,map_getmapdata(md->bl.m)->name, md->bl.x, md->bl.y);
  1411. md->move_fail_count=0;
  1412. mob_spawn(md);
  1413. }
  1414. }
  1415. return 0;
  1416. }
  1417. speed=status_get_speed(&md->bl);
  1418. for(i=c=0;i<md->ud.walkpath.path_len;i++){ // The next walk start time is calculated.
  1419. if( direction_diagonal( md->ud.walkpath.path[i] ) )
  1420. c+=speed*MOVE_DIAGONAL_COST/MOVE_COST;
  1421. else
  1422. c+=speed;
  1423. }
  1424. md->state.skillstate=MSS_WALK;
  1425. md->move_fail_count=0;
  1426. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME+c;
  1427. return 1;
  1428. }
  1429. int mob_warpchase(struct mob_data *md, struct block_list *target)
  1430. {
  1431. struct npc_data *warp = nullptr;
  1432. int distance = AREA_SIZE;
  1433. if (!(target && battle_config.mob_ai&0x40 && battle_config.mob_warp&1))
  1434. return 0; //Can't warp chase.
  1435. if (target->m == md->bl.m && check_distance_bl(&md->bl, target, AREA_SIZE))
  1436. return 0; //No need to do a warp chase.
  1437. if (md->ud.walktimer != INVALID_TIMER &&
  1438. map_getcell(md->bl.m,md->ud.to_x,md->ud.to_y,CELL_CHKNPC))
  1439. return 1; //Already walking to a warp.
  1440. //Search for warps within mob's viewing range.
  1441. map_foreachinallrange(mob_warpchase_sub, &md->bl,
  1442. md->db->range2, BL_NPC, target, &warp, &distance);
  1443. if (warp && unit_walktobl(&md->bl, &warp->bl, 1, 1))
  1444. return 1;
  1445. return 0;
  1446. }
  1447. /*==========================================
  1448. * AI of MOB whose is near a Player
  1449. *------------------------------------------*/
  1450. static bool mob_ai_sub_hard(struct mob_data *md, t_tick tick)
  1451. {
  1452. struct block_list *tbl = nullptr, *abl = nullptr;
  1453. enum e_mode mode;
  1454. int view_range, can_move;
  1455. if(md->bl.prev == nullptr || md->status.hp == 0)
  1456. return false;
  1457. if (DIFF_TICK(tick, md->last_thinktime) < MIN_MOBTHINKTIME)
  1458. return false;
  1459. md->last_thinktime = tick;
  1460. if (md->ud.skilltimer != INVALID_TIMER)
  1461. return false;
  1462. // Abnormalities
  1463. if(( md->sc.opt1 > 0 && md->sc.opt1 != OPT1_STONEWAIT && md->sc.opt1 != OPT1_BURNING )
  1464. || md->sc.data[SC_BLADESTOP] || md->sc.data[SC__MANHOLE] || md->sc.data[SC_CURSEDCIRCLE_TARGET]) {//Should reset targets.
  1465. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  1466. return false;
  1467. }
  1468. if (md->sc.count && md->sc.data[SC_BLIND])
  1469. view_range = 3;
  1470. else
  1471. view_range = md->db->range2;
  1472. mode = status_get_mode(&md->bl);
  1473. can_move = (mode&MD_CANMOVE) && unit_can_move(&md->bl);
  1474. if (md->target_id)
  1475. { //Check validity of current target. [Skotlex]
  1476. tbl = map_id2bl(md->target_id);
  1477. if (!tbl || tbl->m != md->bl.m ||
  1478. (md->ud.attacktimer == INVALID_TIMER && !status_check_skilluse(&md->bl, tbl, 0, 0)) ||
  1479. (md->ud.walktimer != INVALID_TIMER && !(battle_config.mob_ai&0x1) && !check_distance_bl(&md->bl, tbl, md->min_chase)) ||
  1480. (
  1481. tbl->type == BL_PC &&
  1482. ((((TBL_PC*)tbl)->state.gangsterparadise && !(mode&MD_STATUS_IMMUNE)) ||
  1483. ((TBL_PC*)tbl)->invincible_timer != INVALID_TIMER)
  1484. )) { //No valid target
  1485. if (mob_warpchase(md, tbl))
  1486. return true; //Chasing this target.
  1487. if(md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh)
  1488. && (tbl || md->ud.walkpath.path_pos == 0))
  1489. return true; //Walk at least "mob_chase_refresh" cells before dropping the target unless target is non-existent
  1490. mob_unlocktarget(md, tick); //Unlock target
  1491. tbl = NULL;
  1492. }
  1493. }
  1494. // Check for target change.
  1495. if( md->attacked_id && mode&MD_CANATTACK )
  1496. {
  1497. if( md->attacked_id == md->target_id )
  1498. { //Rude attacked check.
  1499. if( !battle_check_range(&md->bl, tbl, md->status.rhw.range)
  1500. && ( //Can't attack back and can't reach back.
  1501. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB]
  1502. || md->sc.data[SC_BITE] || md->sc.data[SC_VACUUM_EXTREME] || md->sc.data[SC_THORNSTRAP]
  1503. || md->sc.data[SC__MANHOLE] // Not yet confirmed if boss will teleport once it can't reach target.
  1504. || md->walktoxy_fail_count > 0)
  1505. )
  1506. || !mob_can_reach(md, tbl, md->min_chase, MSS_RUSH)
  1507. )
  1508. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1509. && !mobskill_use(md, tick, MSC_RUDEATTACKED) // If can't rude Attack
  1510. && can_move && unit_escape(&md->bl, tbl, rnd()%10 +1)) // Attempt escape
  1511. { //Escaped
  1512. md->attacked_id = md->norm_attacked_id = 0;
  1513. return true;
  1514. }
  1515. }
  1516. else
  1517. if( (abl = map_id2bl(md->attacked_id)) && (!tbl || mob_can_changetarget(md, abl, mode)) )
  1518. {
  1519. int dist;
  1520. if( md->bl.m != abl->m || abl->prev == NULL
  1521. || (dist = distance_bl(&md->bl, abl)) >= MAX_MINCHASE // Attacker longer than visual area
  1522. || battle_check_target(&md->bl, abl, BCT_ENEMY) <= 0 // Attacker is not enemy of mob
  1523. || (battle_config.mob_ai&0x2 && !status_check_skilluse(&md->bl, abl, 0, 0)) // Cannot normal attack back to Attacker
  1524. || (!battle_check_range(&md->bl, abl, md->status.rhw.range) // Not on Melee Range and ...
  1525. && ( // Reach check
  1526. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB]
  1527. || md->sc.data[SC_BITE] || md->sc.data[SC_VACUUM_EXTREME] || md->sc.data[SC_THORNSTRAP]
  1528. || md->sc.data[SC__MANHOLE] // Not yet confirmed if boss will teleport once it can't reach target.
  1529. || md->walktoxy_fail_count > 0)
  1530. )
  1531. || !mob_can_reach(md, abl, dist+md->db->range3, MSS_RUSH)
  1532. )
  1533. ) )
  1534. { // Rude attacked
  1535. if (abl->id != md->bl.id //Self damage does not cause rude attack
  1536. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1537. && !mobskill_use(md, tick, MSC_RUDEATTACKED) && can_move
  1538. && !tbl && unit_escape(&md->bl, abl, rnd()%10 +1))
  1539. { //Escaped.
  1540. //TODO: Maybe it shouldn't attempt to run if it has another, valid target?
  1541. md->attacked_id = md->norm_attacked_id = 0;
  1542. return true;
  1543. }
  1544. }
  1545. else
  1546. if (!(battle_config.mob_ai&0x2) && !status_check_skilluse(&md->bl, abl, 0, 0))
  1547. {
  1548. //Can't attack back, but didn't invoke a rude attacked skill...
  1549. }
  1550. else
  1551. { //Attackable
  1552. //If a monster can change the target to the attacker, it will change the target
  1553. md->target_id = md->attacked_id; // set target
  1554. if (md->state.attacked_count)
  1555. md->state.attacked_count--; //Should we reset rude attack count?
  1556. md->min_chase = dist+md->db->range3;
  1557. if(md->min_chase>MAX_MINCHASE)
  1558. md->min_chase=MAX_MINCHASE;
  1559. tbl = abl; //Set the new target
  1560. }
  1561. }
  1562. //Clear it since it's been checked for already.
  1563. md->attacked_id = md->norm_attacked_id = 0;
  1564. }
  1565. // Processing of slave monster
  1566. if (md->master_id > 0 && mob_ai_sub_hard_slavemob(md, tick))
  1567. return true;
  1568. // Scan area for targets
  1569. if (!tbl && can_move && mode&MD_LOOTER && md->lootitems && DIFF_TICK(tick, md->ud.canact_tick) > 0 &&
  1570. (md->lootitem_count < LOOTITEM_SIZE || battle_config.monster_loot_type != 1))
  1571. { // Scan area for items to loot, avoid trying to loot if the mob is full and can't consume the items.
  1572. map_foreachinshootrange (mob_ai_sub_hard_lootsearch, &md->bl, view_range, BL_ITEM, md, &tbl);
  1573. }
  1574. if ((!tbl && mode&MD_AGGRESSIVE) || md->state.skillstate == MSS_FOLLOW)
  1575. {
  1576. map_foreachinallrange (mob_ai_sub_hard_activesearch, &md->bl, view_range, DEFAULT_ENEMY_TYPE(md), md, &tbl, mode);
  1577. }
  1578. else
  1579. if (mode&MD_CHANGECHASE && (md->state.skillstate == MSS_RUSH || md->state.skillstate == MSS_FOLLOW))
  1580. {
  1581. int search_size;
  1582. search_size = view_range<md->status.rhw.range ? view_range:md->status.rhw.range;
  1583. map_foreachinallrange (mob_ai_sub_hard_changechase, &md->bl, search_size, DEFAULT_ENEMY_TYPE(md), md, &tbl);
  1584. }
  1585. if (!tbl) { //No targets available.
  1586. /* bg guardians follow allies when no targets nearby */
  1587. if( md->bg_id && mode&MD_CANATTACK ) {
  1588. if( md->ud.walktimer != INVALID_TIMER )
  1589. return true;/* we are already moving */
  1590. map_foreachinallrange (mob_ai_sub_hard_bg_ally, &md->bl, view_range, BL_PC, md, &tbl, mode);
  1591. if( tbl ) {
  1592. if( distance_blxy(&md->bl, tbl->x, tbl->y) <= 3 || unit_walktobl(&md->bl, tbl, 1, 1) )
  1593. return true;/* we're moving or close enough don't unlock the target. */
  1594. }
  1595. }
  1596. //This handles triggering idle/walk skill.
  1597. mob_unlocktarget(md, tick);
  1598. return true;
  1599. }
  1600. //Target exists, attack or loot as applicable.
  1601. if (tbl->type == BL_ITEM)
  1602. { //Loot time.
  1603. struct flooritem_data *fitem;
  1604. if (md->ud.target == tbl->id && md->ud.walktimer != INVALID_TIMER)
  1605. return true; //Already locked.
  1606. if (md->lootitems == NULL)
  1607. { //Can't loot...
  1608. mob_unlocktarget(md, tick);
  1609. return true;
  1610. }
  1611. if (!check_distance_bl(&md->bl, tbl, 0))
  1612. { //Still not within loot range.
  1613. if (!(mode&MD_CANMOVE))
  1614. { //A looter that can't move? Real smart.
  1615. mob_unlocktarget(md, tick);
  1616. return true;
  1617. }
  1618. if (!can_move) //Stuck. Wait before walking.
  1619. return true;
  1620. md->state.skillstate = MSS_LOOT;
  1621. if (!unit_walktobl(&md->bl, tbl, 0, 1))
  1622. mob_unlocktarget(md, tick); //Can't loot...
  1623. return true;
  1624. }
  1625. //Within looting range.
  1626. if (md->ud.attacktimer != INVALID_TIMER)
  1627. return true; //Busy attacking?
  1628. fitem = (struct flooritem_data *)tbl;
  1629. //Logs items, taken by (L)ooter Mobs [Lupus]
  1630. log_pick_mob(md, LOG_TYPE_LOOT, fitem->item.amount, &fitem->item);
  1631. if (md->lootitem_count < LOOTITEM_SIZE) {
  1632. memcpy (&md->lootitems[md->lootitem_count].item, &fitem->item, sizeof(md->lootitems[0].item));
  1633. md->lootitems[md->lootitem_count].mob_id = fitem->mob_id;
  1634. md->lootitem_count++;
  1635. } else { //Destroy first looted item...
  1636. if (md->lootitems[0].item.card[0] == CARD0_PET)
  1637. intif_delete_petdata(MakeDWord(md->lootitems[0].item.card[1],md->lootitems[0].item.card[2]));
  1638. memmove(&md->lootitems[0], &md->lootitems[1], (LOOTITEM_SIZE-1)*sizeof(md->lootitems[0]));
  1639. memcpy (&md->lootitems[LOOTITEM_SIZE-1].item, &fitem->item, sizeof(md->lootitems[0].item));
  1640. md->lootitems[LOOTITEM_SIZE-1].mob_id = fitem->mob_id;
  1641. }
  1642. if (pcdb_checkid(md->vd->class_))
  1643. { //Give them walk act/delay to properly mimic players. [Skotlex]
  1644. clif_takeitem(&md->bl,tbl);
  1645. md->ud.canact_tick = tick + md->status.amotion;
  1646. unit_set_walkdelay(&md->bl, tick, md->status.amotion, 1);
  1647. }
  1648. //Clear item.
  1649. map_clearflooritem(tbl);
  1650. mob_unlocktarget(md, tick);
  1651. return true;
  1652. }
  1653. //Attempt to attack.
  1654. //At this point we know the target is attackable, we just gotta check if the range matches.
  1655. if (battle_check_range(&md->bl, tbl, md->status.rhw.range) && !(md->sc.option&OPTION_HIDE))
  1656. { //Target within range and able to use normal attack, engage
  1657. if (md->ud.target != tbl->id || md->ud.attacktimer == INVALID_TIMER)
  1658. { //Only attack if no more attack delay left
  1659. if(tbl->type == BL_PC)
  1660. mob_log_damage(md, tbl, 0); //Log interaction (counts as 'attacker' for the exp bonus)
  1661. if( !(mode&MD_RANDOMTARGET) )
  1662. unit_attack(&md->bl,tbl->id,1);
  1663. else { // Attack once and find a new random target
  1664. int search_size = (view_range < md->status.rhw.range) ? view_range : md->status.rhw.range;
  1665. unit_attack(&md->bl, tbl->id, 0);
  1666. if ((tbl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md), search_size))) {
  1667. md->target_id = tbl->id;
  1668. md->min_chase = md->db->range3;
  1669. }
  1670. }
  1671. }
  1672. return true;
  1673. }
  1674. //Monsters in berserk state, unable to use normal attacks, will always attempt a skill
  1675. if(md->ud.walktimer == INVALID_TIMER && (md->state.skillstate == MSS_BERSERK || md->state.skillstate == MSS_ANGRY))
  1676. {
  1677. if (DIFF_TICK(md->ud.canmove_tick, tick) <= MIN_MOBTHINKTIME && DIFF_TICK(md->ud.canact_tick, tick) < -MIN_MOBTHINKTIME*IDLE_SKILL_INTERVAL)
  1678. { //Only use skill if able to walk on next tick and not used a skill the last second
  1679. if (mobskill_use(md, tick, -1))
  1680. return true;
  1681. }
  1682. }
  1683. //Target still in attack range, no need to chase the target
  1684. if(battle_check_range(&md->bl, tbl, md->status.rhw.range))
  1685. return true;
  1686. //Only update target cell / drop target after having moved at least "mob_chase_refresh" cells
  1687. if(md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh))
  1688. return true;
  1689. //Out of range...
  1690. if (!(mode&MD_CANMOVE) || (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0))
  1691. { //Can't chase. Immobile and trapped mobs should unlock target and use an idle skill.
  1692. if (md->ud.attacktimer == INVALID_TIMER)
  1693. { //Only unlock target if no more attack delay left
  1694. //This handles triggering idle/walk skill.
  1695. mob_unlocktarget(md,tick);
  1696. }
  1697. return true;
  1698. }
  1699. if (md->ud.walktimer != INVALID_TIMER && md->ud.target == tbl->id &&
  1700. (
  1701. !(battle_config.mob_ai&0x1) ||
  1702. check_distance_blxy(tbl, md->ud.to_x, md->ud.to_y, md->status.rhw.range)
  1703. )) //Current target tile is still within attack range.
  1704. return true;
  1705. //Follow up if possible.
  1706. //Hint: Chase skills are handled in the walktobl routine
  1707. if(!mob_can_reach(md, tbl, md->min_chase, MSS_RUSH) ||
  1708. !unit_walktobl(&md->bl, tbl, md->status.rhw.range, 2))
  1709. mob_unlocktarget(md,tick);
  1710. return true;
  1711. }
  1712. static int mob_ai_sub_hard_timer(struct block_list *bl,va_list ap)
  1713. {
  1714. struct mob_data *md = (struct mob_data*)bl;
  1715. uint32 char_id = va_arg(ap, uint32);
  1716. t_tick tick = va_arg(ap, t_tick);
  1717. if (mob_ai_sub_hard(md, tick))
  1718. { //Hard AI triggered.
  1719. mob_add_spotted(md, char_id);
  1720. md->last_pcneartime = tick;
  1721. }
  1722. return 0;
  1723. }
  1724. /*==========================================
  1725. * Serious processing for mob in PC field of view (foreachclient)
  1726. *------------------------------------------*/
  1727. static int mob_ai_sub_foreachclient(struct map_session_data *sd,va_list ap)
  1728. {
  1729. t_tick tick=va_arg(ap,t_tick);
  1730. map_foreachinallrange(mob_ai_sub_hard_timer,&sd->bl, AREA_SIZE+ACTIVE_AI_RANGE, BL_MOB, sd->status.char_id, tick);
  1731. return 0;
  1732. }
  1733. /*==========================================
  1734. * Negligent mode MOB AI (PC is not in near)
  1735. *------------------------------------------*/
  1736. static int mob_ai_sub_lazy(struct mob_data *md, va_list args)
  1737. {
  1738. nullpo_ret(md);
  1739. if(md->bl.prev == NULL)
  1740. return 0;
  1741. t_tick tick = va_arg(args,t_tick);
  1742. if (battle_config.mob_ai&0x20 && map_getmapdata(md->bl.m)->users>0)
  1743. return (int)mob_ai_sub_hard(md, tick);
  1744. if (md->bl.prev==NULL || md->status.hp == 0)
  1745. return 1;
  1746. if(battle_config.mob_active_time &&
  1747. md->last_pcneartime &&
  1748. !status_has_mode(&md->status,MD_STATUS_IMMUNE) &&
  1749. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1750. {
  1751. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.mob_active_time)
  1752. return (int)mob_ai_sub_hard(md, tick);
  1753. md->last_pcneartime = 0;
  1754. }
  1755. if(battle_config.boss_active_time &&
  1756. md->last_pcneartime &&
  1757. status_has_mode(&md->status,MD_STATUS_IMMUNE) &&
  1758. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1759. {
  1760. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.boss_active_time)
  1761. return (int)mob_ai_sub_hard(md, tick);
  1762. md->last_pcneartime = 0;
  1763. }
  1764. //Clean the spotted log
  1765. mob_clean_spotted(md);
  1766. if(DIFF_TICK(tick,md->last_thinktime)< 10*MIN_MOBTHINKTIME)
  1767. return 0;
  1768. md->last_thinktime=tick;
  1769. if (md->master_id) {
  1770. mob_ai_sub_hard_slavemob (md,tick);
  1771. return 0;
  1772. }
  1773. if( DIFF_TICK(md->next_walktime,tick) < 0 && status_has_mode(&md->status,MD_CANMOVE) && unit_can_move(&md->bl) )
  1774. {
  1775. // Move probability for mobs away from players
  1776. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1777. if( mob_is_spotted(md) && rnd()%100 < battle_config.mob_nopc_move_rate )
  1778. mob_randomwalk(md, tick);
  1779. }
  1780. else if( md->ud.walktimer == INVALID_TIMER )
  1781. {
  1782. //Because it is not unset when the mob finishes walking.
  1783. md->state.skillstate = MSS_IDLE;
  1784. // Probability for mobs far from players from doing their IDLE skill.
  1785. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1786. if( mob_is_spotted(md) && rnd()%100 < battle_config.mob_nopc_idleskill_rate )
  1787. mobskill_use(md, tick, -1);
  1788. }
  1789. return 0;
  1790. }
  1791. /*==========================================
  1792. * Negligent processing for mob outside PC field of view (interval timer function)
  1793. *------------------------------------------*/
  1794. static TIMER_FUNC(mob_ai_lazy){
  1795. map_foreachmob(mob_ai_sub_lazy,tick);
  1796. return 0;
  1797. }
  1798. /*==========================================
  1799. * Serious processing for mob in PC field of view (interval timer function)
  1800. *------------------------------------------*/
  1801. static TIMER_FUNC(mob_ai_hard){
  1802. if (battle_config.mob_ai&0x20)
  1803. map_foreachmob(mob_ai_sub_lazy,tick);
  1804. else
  1805. map_foreachpc(mob_ai_sub_foreachclient,tick);
  1806. return 0;
  1807. }
  1808. /**
  1809. * Set random option for item when dropped from monster
  1810. * @param itm Item data
  1811. * @param mobdrop Drop data
  1812. * @author [Cydh]
  1813. **/
  1814. void mob_setdropitem_option(struct item *itm, struct s_mob_drop *mobdrop) {
  1815. struct s_random_opt_group *g = NULL;
  1816. if (!itm || !mobdrop || mobdrop->randomopt_group == RDMOPTG_None)
  1817. return;
  1818. if ((g = itemdb_randomopt_group_exists(mobdrop->randomopt_group)) && g->total) {
  1819. int r = rnd()%g->total;
  1820. if (&g->entries[r]) {
  1821. memcpy(&itm->option, &g->entries[r], sizeof(itm->option));
  1822. return;
  1823. }
  1824. }
  1825. }
  1826. /*==========================================
  1827. * Initializes the delay drop structure for mob-dropped items.
  1828. *------------------------------------------*/
  1829. static struct item_drop* mob_setdropitem(struct s_mob_drop *mobdrop, int qty, unsigned short mob_id)
  1830. {
  1831. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1832. memset(&drop->item_data, 0, sizeof(struct item));
  1833. drop->item_data.nameid = mobdrop->nameid;
  1834. drop->item_data.amount = qty;
  1835. drop->item_data.identify = itemdb_isidentified(mobdrop->nameid);
  1836. mob_setdropitem_option(&drop->item_data, mobdrop);
  1837. drop->mob_id = mob_id;
  1838. drop->next = NULL;
  1839. return drop;
  1840. }
  1841. /*==========================================
  1842. * Initializes the delay drop structure for mob-looted items.
  1843. *------------------------------------------*/
  1844. static struct item_drop* mob_setlootitem(struct s_mob_lootitem *item, unsigned short mob_id)
  1845. {
  1846. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1847. memcpy(&drop->item_data, item, sizeof(struct item));
  1848. /**
  1849. * Conditions for lotted item, so it can be announced when player pick it up
  1850. * 1. Not-dropped other than monster. (This will be done later on pc_takeitem/party_share_loot)
  1851. * 2. The mob_id is become the last lootter, instead of the real monster who drop it.
  1852. **/
  1853. drop->mob_id = item->mob_id;
  1854. drop->next = NULL;
  1855. return drop;
  1856. }
  1857. /*==========================================
  1858. * item drop with delay (timer function)
  1859. *------------------------------------------*/
  1860. static TIMER_FUNC(mob_delay_item_drop){
  1861. struct item_drop_list *list;
  1862. struct item_drop *ditem;
  1863. list = (struct item_drop_list *)data;
  1864. ditem = list->item;
  1865. while (ditem) {
  1866. struct item_drop *ditem_prev;
  1867. map_addflooritem(&ditem->item_data,ditem->item_data.amount,
  1868. list->m,list->x,list->y,
  1869. list->first_charid,list->second_charid,list->third_charid,4,ditem->mob_id,true);
  1870. ditem_prev = ditem;
  1871. ditem = ditem->next;
  1872. ers_free(item_drop_ers, ditem_prev);
  1873. }
  1874. ers_free(item_drop_list_ers, list);
  1875. return 0;
  1876. }
  1877. /*==========================================
  1878. * Sets the item_drop into the item_drop_list.
  1879. * Also performs logging and autoloot if enabled.
  1880. * rate is the drop-rate of the item, required for autoloot.
  1881. * flag : Killed only by homunculus?
  1882. *------------------------------------------*/
  1883. static void mob_item_drop(struct mob_data *md, struct item_drop_list *dlist, struct item_drop *ditem, int loot, int drop_rate, unsigned short flag)
  1884. {
  1885. TBL_PC* sd;
  1886. bool test_autoloot;
  1887. //Logs items, dropped by mobs [Lupus]
  1888. log_pick_mob(md, loot?LOG_TYPE_LOOT:LOG_TYPE_PICKDROP_MONSTER, -ditem->item_data.amount, &ditem->item_data);
  1889. sd = map_charid2sd(dlist->first_charid);
  1890. if( sd == NULL ) sd = map_charid2sd(dlist->second_charid);
  1891. if( sd == NULL ) sd = map_charid2sd(dlist->third_charid);
  1892. test_autoloot = sd
  1893. && (drop_rate <= sd->state.autoloot || pc_isautolooting(sd, ditem->item_data.nameid))
  1894. && (battle_config.idle_no_autoloot == 0 || DIFF_TICK(last_tick, sd->idletime) < battle_config.idle_no_autoloot)
  1895. && (battle_config.homunculus_autoloot?1:!flag);
  1896. #ifdef AUTOLOOT_DISTANCE
  1897. test_autoloot = test_autoloot && sd->bl.m == md->bl.m
  1898. && check_distance_blxy(&sd->bl, dlist->x, dlist->y, AUTOLOOT_DISTANCE);
  1899. #endif
  1900. if( test_autoloot ) { //Autoloot.
  1901. struct party_data *p = party_search(sd->status.party_id);
  1902. if ((itemdb_search(ditem->item_data.nameid))->flag.broadcast &&
  1903. (!p || !(p->party.item & 2)) // Somehow, if party's pickup distribution is 'Even Share', no announcemet
  1904. )
  1905. intif_broadcast_obtain_special_item(sd, ditem->item_data.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  1906. if (party_share_loot(party_search(sd->status.party_id),
  1907. sd, &ditem->item_data, sd->status.char_id) == 0
  1908. ) {
  1909. ers_free(item_drop_ers, ditem);
  1910. return;
  1911. }
  1912. }
  1913. ditem->next = dlist->item;
  1914. dlist->item = ditem;
  1915. }
  1916. TIMER_FUNC(mob_timer_delete){
  1917. struct block_list* bl = map_id2bl(id);
  1918. struct mob_data* md = BL_CAST(BL_MOB, bl);
  1919. if( md )
  1920. {
  1921. if( md->deletetimer != tid )
  1922. {
  1923. ShowError("mob_timer_delete: Timer mismatch: %d != %d\n", tid, md->deletetimer);
  1924. return 0;
  1925. }
  1926. //for Alchemist CANNIBALIZE [Lupus]
  1927. md->deletetimer = INVALID_TIMER;
  1928. unit_free(bl, CLR_TELEPORT);
  1929. }
  1930. return 0;
  1931. }
  1932. /*==========================================
  1933. *
  1934. *------------------------------------------*/
  1935. int mob_deleteslave_sub(struct block_list *bl,va_list ap)
  1936. {
  1937. struct mob_data *md;
  1938. int id;
  1939. nullpo_ret(bl);
  1940. nullpo_ret(md = (struct mob_data *)bl);
  1941. id=va_arg(ap,int);
  1942. if(md->master_id > 0 && md->master_id == id )
  1943. status_kill(bl);
  1944. return 0;
  1945. }
  1946. /*==========================================
  1947. *
  1948. *------------------------------------------*/
  1949. int mob_deleteslave(struct mob_data *md)
  1950. {
  1951. nullpo_ret(md);
  1952. map_foreachinmap(mob_deleteslave_sub, md->bl.m, BL_MOB,md->bl.id);
  1953. return 0;
  1954. }
  1955. // Mob respawning through KAIZEL or NPC_REBIRTH [Skotlex]
  1956. TIMER_FUNC(mob_respawn){
  1957. struct block_list *bl = map_id2bl(id);
  1958. if(!bl) return 0;
  1959. status_revive(bl, (uint8)data, 0);
  1960. return 1;
  1961. }
  1962. void mob_log_damage(struct mob_data *md, struct block_list *src, int damage)
  1963. {
  1964. uint32 char_id = 0;
  1965. int flag = MDLF_NORMAL;
  1966. if( damage < 0 )
  1967. return; //Do nothing for absorbed damage.
  1968. if( !damage && !(src->type&DEFAULT_ENEMY_TYPE(md)) )
  1969. return; //Do not log non-damaging effects from non-enemies.
  1970. switch( src->type )
  1971. {
  1972. case BL_PC:
  1973. {
  1974. struct map_session_data *sd = (TBL_PC*)src;
  1975. char_id = sd->status.char_id;
  1976. if( damage )
  1977. md->attacked_id = src->id;
  1978. break;
  1979. }
  1980. case BL_HOM:
  1981. {
  1982. struct homun_data *hd = (TBL_HOM*)src;
  1983. flag = MDLF_HOMUN;
  1984. if( hd->master )
  1985. char_id = hd->master->status.char_id;
  1986. if( damage )
  1987. md->attacked_id = src->id;
  1988. break;
  1989. }
  1990. case BL_MER:
  1991. {
  1992. struct mercenary_data *mer = (TBL_MER*)src;
  1993. if( mer->master )
  1994. char_id = mer->master->status.char_id;
  1995. if( damage )
  1996. md->attacked_id = src->id;
  1997. break;
  1998. }
  1999. case BL_PET:
  2000. {
  2001. struct pet_data *pd = (TBL_PET*)src;
  2002. flag = MDLF_PET;
  2003. if( pd->master )
  2004. {
  2005. char_id = pd->master->status.char_id;
  2006. if( damage ) //Let mobs retaliate against the pet's master [Skotlex]
  2007. md->attacked_id = pd->master->bl.id;
  2008. }
  2009. break;
  2010. }
  2011. case BL_MOB:
  2012. {
  2013. struct mob_data* md2 = (TBL_MOB*)src;
  2014. if( md2->special_state.ai && md2->master_id )
  2015. {
  2016. struct map_session_data* msd = map_id2sd(md2->master_id);
  2017. if( msd )
  2018. char_id = msd->status.char_id;
  2019. }
  2020. if( !damage )
  2021. break;
  2022. //Let players decide whether to retaliate versus the master or the mob. [Skotlex]
  2023. if( md2->master_id && battle_config.retaliate_to_master )
  2024. md->attacked_id = md2->master_id;
  2025. else
  2026. md->attacked_id = src->id;
  2027. break;
  2028. }
  2029. case BL_ELEM:
  2030. {
  2031. struct elemental_data *ele = (TBL_ELEM*)src;
  2032. if( ele->master )
  2033. char_id = ele->master->status.char_id;
  2034. if( damage )
  2035. md->attacked_id = src->id;
  2036. break;
  2037. }
  2038. default: //For all unhandled types.
  2039. md->attacked_id = src->id;
  2040. }
  2041. //Self damage increases tap bonus
  2042. if (!char_id && src->id == md->bl.id && damage > 0) {
  2043. char_id = src->id;
  2044. flag = MDLF_SELF;
  2045. }
  2046. if( char_id )
  2047. { //Log damage...
  2048. int i,minpos;
  2049. unsigned int mindmg;
  2050. for(i=0,minpos=DAMAGELOG_SIZE-1,mindmg=UINT_MAX;i<DAMAGELOG_SIZE;i++){
  2051. if(md->dmglog[i].id==char_id &&
  2052. md->dmglog[i].flag==flag)
  2053. break;
  2054. if(md->dmglog[i].id==0) { //Store data in first empty slot.
  2055. md->dmglog[i].id = char_id;
  2056. md->dmglog[i].flag= flag;
  2057. if(md->db->mexp)
  2058. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2059. break;
  2060. }
  2061. if(md->dmglog[i].dmg<mindmg && i)
  2062. { //Never overwrite first hit slot (he gets double exp bonus)
  2063. minpos=i;
  2064. mindmg=md->dmglog[i].dmg;
  2065. }
  2066. }
  2067. if(i<DAMAGELOG_SIZE)
  2068. md->dmglog[i].dmg+=damage;
  2069. else {
  2070. md->dmglog[minpos].id = char_id;
  2071. md->dmglog[minpos].flag= flag;
  2072. md->dmglog[minpos].dmg = damage;
  2073. if(md->db->mexp)
  2074. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2075. }
  2076. }
  2077. return;
  2078. }
  2079. //Call when a mob has received damage.
  2080. void mob_damage(struct mob_data *md, struct block_list *src, int damage)
  2081. {
  2082. if (src && damage > 0) { //Store total damage...
  2083. if (UINT_MAX - (unsigned int)damage > md->tdmg)
  2084. md->tdmg += damage;
  2085. else if (md->tdmg == UINT_MAX)
  2086. damage = 0; //Stop recording damage once the cap has been reached.
  2087. else { //Cap damage log...
  2088. damage = (int)(UINT_MAX - md->tdmg);
  2089. md->tdmg = UINT_MAX;
  2090. }
  2091. if ((src != &md->bl) && md->state.aggressive) //No longer aggressive, change to retaliate AI.
  2092. md->state.aggressive = 0;
  2093. //Log damage
  2094. mob_log_damage(md, src, damage);
  2095. md->dmgtick = gettick();
  2096. }
  2097. if (battle_config.show_mob_info&3)
  2098. clif_name_area(&md->bl);
  2099. #if PACKETVER >= 20120404
  2100. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2101. int i;
  2102. for(i = 0; i < DAMAGELOG_SIZE; i++){ // must show hp bar to all char who already hit the mob.
  2103. struct map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2104. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2105. clif_monster_hp_bar(md, sd->fd);
  2106. }
  2107. }
  2108. #endif
  2109. if (!src)
  2110. return;
  2111. if( md->special_state.ai == AI_SPHERE ) {//LOne WOlf explained that ANYONE can trigger the marine countdown skill. [Skotlex]
  2112. md->state.alchemist = 1;
  2113. mobskill_use(md, gettick(), MSC_ALCHEMIST);
  2114. }
  2115. }
  2116. /*==========================================
  2117. * Signals death of mob.
  2118. * type&1 -> no drops, type&2 -> no exp
  2119. *------------------------------------------*/
  2120. int mob_dead(struct mob_data *md, struct block_list *src, int type)
  2121. {
  2122. struct status_data *status;
  2123. struct map_session_data *sd = NULL, *tmpsd[DAMAGELOG_SIZE];
  2124. struct map_session_data *mvp_sd = NULL, *second_sd = NULL, *third_sd = NULL;
  2125. struct {
  2126. struct party_data *p;
  2127. int id,zeny;
  2128. unsigned int base_exp,job_exp;
  2129. } pt[DAMAGELOG_SIZE];
  2130. int i, temp, count, m = md->bl.m;
  2131. int dmgbltypes = 0; // bitfield of all bl types, that caused damage to the mob and are elligible for exp distribution
  2132. unsigned int mvp_damage;
  2133. t_tick tick = gettick();
  2134. bool rebirth, homkillonly;
  2135. status = &md->status;
  2136. if( src && src->type == BL_PC ) {
  2137. sd = (struct map_session_data *)src;
  2138. mvp_sd = sd;
  2139. }
  2140. if( md->guardian_data && md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
  2141. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  2142. if( src ) { // Use Dead skill only if not killed by Script or Command
  2143. md->status.hp = 1;
  2144. md->state.skillstate = MSS_DEAD;
  2145. mobskill_use(md,tick,-1);
  2146. md->status.hp = 0;
  2147. }
  2148. map_freeblock_lock();
  2149. memset(pt,0,sizeof(pt));
  2150. if(src && src->type == BL_MOB)
  2151. mob_unlocktarget((struct mob_data *)src,tick);
  2152. // filter out entries not eligible for exp distribution
  2153. memset(tmpsd,0,sizeof(tmpsd));
  2154. for(i = 0, count = 0, mvp_damage = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2155. struct map_session_data* tsd = NULL;
  2156. if (md->dmglog[i].flag == MDLF_SELF) {
  2157. //Self damage counts as exp tap
  2158. count++;
  2159. continue;
  2160. }
  2161. tsd = map_charid2sd(md->dmglog[i].id);
  2162. if (tsd == NULL)
  2163. continue; // skip empty entries
  2164. if (tsd->bl.m != m)
  2165. continue; // skip players not on this map
  2166. count++; //Only logged into same map chars are counted for the total.
  2167. if (pc_isdead(tsd))
  2168. continue; // skip dead players
  2169. if (md->dmglog[i].flag == MDLF_HOMUN && !hom_is_active(tsd->hd))
  2170. continue; // skip homunc's share if inactive
  2171. if (md->dmglog[i].flag == MDLF_PET && (!tsd->status.pet_id || !tsd->pd))
  2172. continue; // skip pet's share if inactive
  2173. if(md->dmglog[i].dmg > mvp_damage) {
  2174. third_sd = second_sd;
  2175. second_sd = mvp_sd;
  2176. mvp_sd = tsd;
  2177. mvp_damage = md->dmglog[i].dmg;
  2178. }
  2179. tmpsd[i] = tsd; // record as valid damage-log entry
  2180. switch( md->dmglog[i].flag ) {
  2181. case MDLF_NORMAL: dmgbltypes|= BL_PC; break;
  2182. case MDLF_HOMUN: dmgbltypes|= BL_HOM; break;
  2183. case MDLF_PET: dmgbltypes|= BL_PET; break;
  2184. }
  2185. }
  2186. // determines, if the monster was killed by homunculus' damage only
  2187. homkillonly = (bool)( ( dmgbltypes&BL_HOM ) && !( dmgbltypes&~BL_HOM ) );
  2188. if(!battle_config.exp_calc_type && count > 1) { //Apply first-attacker 200% exp share bonus
  2189. //TODO: Determine if this should go before calculating the MVP player instead of after.
  2190. if (UINT_MAX - md->dmglog[0].dmg > md->tdmg) {
  2191. md->tdmg += md->dmglog[0].dmg;
  2192. md->dmglog[0].dmg<<=1;
  2193. } else {
  2194. md->dmglog[0].dmg+= UINT_MAX - md->tdmg;
  2195. md->tdmg = UINT_MAX;
  2196. }
  2197. }
  2198. if(!(type&2) && //No exp
  2199. (!map_getmapflag(m, MF_PVP) || battle_config.pvp_exp) && //Pvp no exp rule [MouseJstr]
  2200. (!md->master_id || !md->special_state.ai) && //Only player-summoned mobs do not give exp. [Skotlex]
  2201. (!map_getmapflag(m, MF_NOBASEEXP) || !map_getmapflag(m, MF_NOJOBEXP)) //Gives Exp
  2202. ) { //Experience calculation.
  2203. int bonus = 100; //Bonus on top of your share (common to all attackers).
  2204. int pnum = 0;
  2205. if (md->sc.data[SC_RICHMANKIM])
  2206. bonus += md->sc.data[SC_RICHMANKIM]->val2;
  2207. if(sd) {
  2208. temp = status_get_class(&md->bl);
  2209. if(sd->sc.data[SC_MIRACLE]) i = 2; //All mobs are Star Targets
  2210. else
  2211. ARR_FIND(0, MAX_PC_FEELHATE, i, temp == sd->hate_mob[i] &&
  2212. (battle_config.allow_skill_without_day || sg_info[i].day_func()));
  2213. if(i<MAX_PC_FEELHATE && (temp=pc_checkskill(sd,sg_info[i].bless_id)))
  2214. bonus += (i==2?20:10)*temp;
  2215. }
  2216. if(battle_config.mobs_level_up && md->level > md->db->lv) // [Valaris]
  2217. bonus += (md->level-md->db->lv)*battle_config.mobs_level_up_exp_rate;
  2218. for(i = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2219. int flag=1,zeny=0;
  2220. unsigned int base_exp, job_exp;
  2221. double per; //Your share of the mob's exp
  2222. if (!tmpsd[i]) continue;
  2223. if (!battle_config.exp_calc_type && md->tdmg)
  2224. //jAthena's exp formula based on total damage.
  2225. per = (double)md->dmglog[i].dmg/(double)md->tdmg;
  2226. else {
  2227. //eAthena's exp formula based on max hp.
  2228. per = (double)md->dmglog[i].dmg/(double)status->max_hp;
  2229. if (per > 2) per = 2; // prevents unlimited exp gain
  2230. }
  2231. if (count>1 && battle_config.exp_bonus_attacker) {
  2232. //Exp bonus per additional attacker.
  2233. if (count > battle_config.exp_bonus_max_attacker)
  2234. count = battle_config.exp_bonus_max_attacker;
  2235. per += per*((count-1)*battle_config.exp_bonus_attacker)/100.;
  2236. }
  2237. // change experience for different sized monsters [Valaris]
  2238. if (battle_config.mob_size_influence) {
  2239. switch( md->special_state.size ) {
  2240. case SZ_MEDIUM:
  2241. per /= 2.;
  2242. break;
  2243. case SZ_BIG:
  2244. per *= 2.;
  2245. break;
  2246. }
  2247. }
  2248. if( md->dmglog[i].flag == MDLF_PET )
  2249. per *= battle_config.pet_attack_exp_rate/100.;
  2250. if(battle_config.zeny_from_mobs && md->level) {
  2251. // zeny calculation moblv + random moblv [Valaris]
  2252. zeny=(int) ((md->level+rnd()%md->level)*per*bonus/100.);
  2253. if(md->db->mexp > 0)
  2254. zeny*=rnd()%250;
  2255. }
  2256. if (map_getmapflag(m, MF_NOBASEEXP) || !md->db->base_exp)
  2257. base_exp = 0;
  2258. else {
  2259. double exp = apply_rate2(md->db->base_exp, per, 1);
  2260. exp = apply_rate(exp, bonus);
  2261. exp = apply_rate(exp, map_getmapflag(m, MF_BEXP));
  2262. base_exp = (unsigned int)cap_value(exp, 1, UINT_MAX);
  2263. }
  2264. if (map_getmapflag(m, MF_NOJOBEXP) || !md->db->job_exp || md->dmglog[i].flag == MDLF_HOMUN) //Homun earned job-exp is always lost.
  2265. job_exp = 0;
  2266. else {
  2267. double exp = apply_rate2(md->db->job_exp, per, 1);
  2268. exp = apply_rate(exp, bonus);
  2269. exp = apply_rate(exp, map_getmapflag(m, MF_JEXP));
  2270. job_exp = (unsigned int)cap_value(exp, 1, UINT_MAX);
  2271. }
  2272. if ( ( temp = tmpsd[i]->status.party_id)>0 ) {
  2273. int j;
  2274. for( j = 0; j < pnum && pt[j].id != temp; j++ ); //Locate party.
  2275. if( j == pnum ) { //Possibly add party.
  2276. pt[pnum].p = party_search(temp);
  2277. if(pt[pnum].p && pt[pnum].p->party.exp) {
  2278. pt[pnum].id = temp;
  2279. pt[pnum].base_exp = base_exp;
  2280. pt[pnum].job_exp = job_exp;
  2281. pt[pnum].zeny = zeny; // zeny share [Valaris]
  2282. pnum++;
  2283. flag = 0;
  2284. }
  2285. } else { //Add to total
  2286. if (pt[j].base_exp > UINT_MAX - base_exp)
  2287. pt[j].base_exp = UINT_MAX;
  2288. else
  2289. pt[j].base_exp += base_exp;
  2290. if (pt[j].job_exp > UINT_MAX - job_exp)
  2291. pt[j].job_exp = UINT_MAX;
  2292. else
  2293. pt[j].job_exp += job_exp;
  2294. pt[j].zeny += zeny; // zeny share [Valaris]
  2295. flag = 0;
  2296. }
  2297. }
  2298. if(base_exp && md->dmglog[i].flag == MDLF_HOMUN) //tmpsd[i] is null if it has no homunc.
  2299. hom_gainexp(tmpsd[i]->hd, base_exp);
  2300. if(flag) {
  2301. if(base_exp || job_exp) {
  2302. if( md->dmglog[i].flag != MDLF_PET || battle_config.pet_attack_exp_to_master ) {
  2303. #ifdef RENEWAL_EXP
  2304. int rate = pc_level_penalty_mod(md->level - tmpsd[i]->status.base_level, md->status.class_, md->status.mode, 1);
  2305. if (rate != 100) {
  2306. if (base_exp)
  2307. base_exp = (unsigned int)cap_value(apply_rate(base_exp, rate), 1, UINT_MAX);
  2308. if (job_exp)
  2309. job_exp = (unsigned int)cap_value(apply_rate(job_exp, rate), 1, UINT_MAX);
  2310. }
  2311. #endif
  2312. pc_gainexp(tmpsd[i], &md->bl, base_exp, job_exp, 0);
  2313. }
  2314. }
  2315. if(zeny) // zeny from mobs [Valaris]
  2316. pc_getzeny(tmpsd[i], zeny, LOG_TYPE_PICKDROP_MONSTER, NULL);
  2317. }
  2318. if( md->db->mexp )
  2319. pc_damage_log_clear(tmpsd[i],md->bl.id);
  2320. }
  2321. for( i = 0; i < pnum; i++ ) //Party share.
  2322. party_exp_share(pt[i].p, &md->bl, pt[i].base_exp,pt[i].job_exp,pt[i].zeny);
  2323. } //End EXP giving.
  2324. if( !(type&1) && !map_getmapflag(m, MF_NOMOBLOOT) && !md->state.rebirth && (
  2325. !md->special_state.ai || //Non special mob
  2326. battle_config.alchemist_summon_reward == 2 || //All summoned give drops
  2327. (md->special_state.ai==AI_SPHERE && battle_config.alchemist_summon_reward == 1) //Marine Sphere Drops items.
  2328. ) )
  2329. { // Item Drop
  2330. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2331. struct item_drop *ditem;
  2332. struct item_data* it = NULL;
  2333. int drop_rate;
  2334. #ifdef RENEWAL_DROP
  2335. int drop_modifier = mvp_sd ? pc_level_penalty_mod(md->level - mvp_sd->status.base_level, md->status.class_, md->status.mode, 2) :
  2336. second_sd ? pc_level_penalty_mod(md->level - second_sd->status.base_level, md->status.class_, md->status.mode, 2):
  2337. third_sd ? pc_level_penalty_mod(md->level - third_sd->status.base_level, md->status.class_, md->status.mode, 2) :
  2338. 100; // No player was attached, we don't use any modifier (100 = rates are not touched)
  2339. #endif
  2340. dlist->m = md->bl.m;
  2341. dlist->x = md->bl.x;
  2342. dlist->y = md->bl.y;
  2343. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2344. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2345. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2346. dlist->item = NULL;
  2347. for (i = 0; i < MAX_MOB_DROP_TOTAL; i++) {
  2348. if (md->db->dropitem[i].nameid <= 0)
  2349. continue;
  2350. if ( !(it = itemdb_exists(md->db->dropitem[i].nameid)) )
  2351. continue;
  2352. drop_rate = md->db->dropitem[i].p;
  2353. if (drop_rate <= 0) {
  2354. if (battle_config.drop_rate0item)
  2355. continue;
  2356. drop_rate = 1;
  2357. }
  2358. // change drops depending on monsters size [Valaris]
  2359. if (battle_config.mob_size_influence) {
  2360. if (md->special_state.size == SZ_MEDIUM && drop_rate >= 2)
  2361. drop_rate /= 2;
  2362. else if( md->special_state.size == SZ_BIG)
  2363. drop_rate *= 2;
  2364. }
  2365. if (src) {
  2366. //Drops affected by luk as a fixed increase [Valaris]
  2367. if (battle_config.drops_by_luk)
  2368. drop_rate += status_get_luk(src)*battle_config.drops_by_luk/100;
  2369. //Drops affected by luk as a % increase [Skotlex]
  2370. if (battle_config.drops_by_luk2)
  2371. drop_rate += (int)(0.5+drop_rate*status_get_luk(src)*battle_config.drops_by_luk2/10000.);
  2372. }
  2373. // Player specific drop rate adjustments
  2374. if( sd ){
  2375. int drop_rate_bonus = 0;
  2376. // pk_mode increase drops if 20 level difference [Valaris]
  2377. if( battle_config.pk_mode && (int)(md->level - sd->status.base_level) >= 20 )
  2378. drop_rate = (int)(drop_rate*1.25);
  2379. // Add class and race specific bonuses
  2380. drop_rate_bonus += sd->dropaddclass[md->status.class_] + sd->dropaddclass[CLASS_ALL];
  2381. drop_rate_bonus += sd->dropaddrace[md->status.race] + sd->dropaddrace[RC_ALL];
  2382. // Increase drop rate if user has SC_ITEMBOOST
  2383. if (sd->sc.data[SC_ITEMBOOST])
  2384. drop_rate_bonus += sd->sc.data[SC_ITEMBOOST]->val1;
  2385. drop_rate_bonus = (int)(0.5 + drop_rate * drop_rate_bonus / 100.);
  2386. // Now rig the drop rate to never be over 90% unless it is originally >90%.
  2387. drop_rate = i32max(drop_rate, cap_value(drop_rate_bonus, 0, 9000));
  2388. if (pc_isvip(sd)) { // Increase item drop rate for VIP.
  2389. drop_rate += (int)(0.5 + drop_rate * battle_config.vip_drop_increase / 100.);
  2390. drop_rate = min(drop_rate,10000); //cap it to 100%
  2391. }
  2392. }
  2393. #ifdef RENEWAL_DROP
  2394. if( drop_modifier != 100 ) {
  2395. drop_rate = apply_rate(drop_rate, drop_modifier);
  2396. if( drop_rate < 1 )
  2397. drop_rate = 1;
  2398. }
  2399. #endif
  2400. // attempt to drop the item
  2401. if (rnd() % 10000 >= drop_rate)
  2402. continue;
  2403. if( mvp_sd && it->type == IT_PETEGG ) {
  2404. pet_create_egg(mvp_sd, md->db->dropitem[i].nameid);
  2405. continue;
  2406. }
  2407. ditem = mob_setdropitem(&md->db->dropitem[i], 1, md->mob_id);
  2408. //A Rare Drop Global Announce by Lupus
  2409. if( mvp_sd && drop_rate <= battle_config.rare_drop_announce ) {
  2410. char message[128];
  2411. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, it->jname, (float)drop_rate/100);
  2412. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2413. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2414. }
  2415. // Announce first, or else ditem will be freed. [Lance]
  2416. // By popular demand, use base drop rate for autoloot code. [Skotlex]
  2417. mob_item_drop(md, dlist, ditem, 0, battle_config.autoloot_adjust ? drop_rate : md->db->dropitem[i].p, homkillonly);
  2418. }
  2419. // Ore Discovery [Celest]
  2420. if (sd == mvp_sd && pc_checkskill(sd,BS_FINDINGORE)>0 && battle_config.finding_ore_rate/10 >= rnd()%10000) {
  2421. struct s_mob_drop mobdrop;
  2422. memset(&mobdrop, 0, sizeof(struct s_mob_drop));
  2423. mobdrop.nameid = itemdb_searchrandomid(IG_FINDINGORE,1);
  2424. ditem = mob_setdropitem(&mobdrop, 1, md->mob_id);
  2425. mob_item_drop(md, dlist, ditem, 0, battle_config.finding_ore_rate/10, homkillonly);
  2426. }
  2427. if(sd) {
  2428. // process script-granted extra drop bonuses
  2429. uint16 dropid = 0;
  2430. for (const auto &it : sd->add_drop) {
  2431. struct s_mob_drop mobdrop;
  2432. if (!&it || (!it.nameid && !it.group))
  2433. continue;
  2434. if ((it.race < RC_NONE_ && it.race == -md->mob_id) || //Race < RC_NONE_, use mob_id
  2435. (it.race == RC_ALL || it.race == status->race) || //Matched race
  2436. (it.class_ == CLASS_ALL || it.class_ == status->class_)) //Matched class
  2437. {
  2438. //Check if the bonus item drop rate should be multiplied with mob level/10 [Lupus]
  2439. if (it.rate < 0) {
  2440. //It's negative, then it should be multiplied. with mob_level/10
  2441. //rate = base_rate * (mob_level/10) + 1
  2442. drop_rate = (-it.rate) * md->level / 10 + 1;
  2443. drop_rate = cap_value(drop_rate, max(battle_config.item_drop_adddrop_min,1), min(battle_config.item_drop_adddrop_max,10000));
  2444. }
  2445. else
  2446. //it's positive, then it goes as it is
  2447. drop_rate = it.rate;
  2448. if (rnd()%10000 >= drop_rate)
  2449. continue;
  2450. dropid = (it.nameid > 0) ? it.nameid : itemdb_searchrandomid(it.group,1);
  2451. memset(&mobdrop, 0, sizeof(struct s_mob_drop));
  2452. mobdrop.nameid = dropid;
  2453. mob_item_drop(md, dlist, mob_setdropitem(&mobdrop,1,md->mob_id), 0, drop_rate, homkillonly);
  2454. }
  2455. }
  2456. // process script-granted zeny bonus (get_zeny_num) [Skotlex]
  2457. if( sd->bonus.get_zeny_num && rnd()%100 < sd->bonus.get_zeny_rate ) {
  2458. i = sd->bonus.get_zeny_num > 0 ? sd->bonus.get_zeny_num : -md->level * sd->bonus.get_zeny_num;
  2459. if (!i) i = 1;
  2460. pc_getzeny(sd, 1+rnd()%i, LOG_TYPE_PICKDROP_MONSTER, NULL);
  2461. }
  2462. }
  2463. // process items looted by the mob
  2464. if (md->lootitems) {
  2465. for (i = 0; i < md->lootitem_count; i++)
  2466. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly);
  2467. }
  2468. if (dlist->item) //There are drop items.
  2469. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2470. else //No drops
  2471. ers_free(item_drop_list_ers, dlist);
  2472. } else if (md->lootitems && md->lootitem_count) { //Loot MUST drop!
  2473. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2474. dlist->m = md->bl.m;
  2475. dlist->x = md->bl.x;
  2476. dlist->y = md->bl.y;
  2477. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2478. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2479. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2480. dlist->item = NULL;
  2481. for (i = 0; i < md->lootitem_count; i++)
  2482. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly);
  2483. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2484. }
  2485. if(mvp_sd && md->db->mexp > 0 && !md->special_state.ai) {
  2486. unsigned int log_mvp[2] = {0};
  2487. unsigned int mexp;
  2488. struct item item;
  2489. double exp;
  2490. //mapflag: noexp check [Lorky]
  2491. if (map_getmapflag(m, MF_NOBASEEXP) || type&2)
  2492. exp =1;
  2493. else {
  2494. exp = md->db->mexp;
  2495. if (count > 1)
  2496. exp += exp*(battle_config.exp_bonus_attacker*(count-1))/100.; //[Gengar]
  2497. }
  2498. mexp = (unsigned int)cap_value(exp, 1, UINT_MAX);
  2499. clif_mvp_effect(mvp_sd);
  2500. clif_mvp_exp(mvp_sd,mexp);
  2501. pc_gainexp(mvp_sd, &md->bl, mexp,0, 0);
  2502. log_mvp[1] = mexp;
  2503. if( !(map_getmapflag(m, MF_NOMVPLOOT) || type&1) ) {
  2504. //Order might be random depending on item_drop_mvp_mode config setting
  2505. struct s_mob_drop mdrop[MAX_MVP_DROP_TOTAL];
  2506. memset(&mdrop,0,sizeof(mdrop));
  2507. if(battle_config.item_drop_mvp_mode == 1) {
  2508. //Random order
  2509. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2510. while( 1 ) {
  2511. uint8 va = rnd()%MAX_MVP_DROP_TOTAL;
  2512. if (mdrop[va].nameid == 0) {
  2513. if (md->db->mvpitem[i].nameid > 0)
  2514. memcpy(&mdrop[va],&md->db->mvpitem[i],sizeof(mdrop[va]));
  2515. break;
  2516. }
  2517. }
  2518. }
  2519. } else {
  2520. //Normal order
  2521. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2522. if (md->db->mvpitem[i].nameid > 0)
  2523. memcpy(&mdrop[i],&md->db->mvpitem[i],sizeof(mdrop[i]));
  2524. }
  2525. }
  2526. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2527. struct item_data *i_data;
  2528. if(mdrop[i].nameid <= 0 || !(i_data = itemdb_exists(mdrop[i].nameid)))
  2529. continue;
  2530. temp = mdrop[i].p;
  2531. if (temp != 10000) {
  2532. if(temp <= 0 && !battle_config.drop_rate0item)
  2533. temp = 1;
  2534. if(rnd()%10000 >= temp) //if ==0, then it doesn't drop
  2535. continue;
  2536. }
  2537. memset(&item,0,sizeof(item));
  2538. item.nameid=mdrop[i].nameid;
  2539. item.identify= itemdb_isidentified(item.nameid);
  2540. clif_mvp_item(mvp_sd,item.nameid);
  2541. log_mvp[0] = item.nameid;
  2542. //A Rare MVP Drop Global Announce by Lupus
  2543. if(temp<=battle_config.rare_drop_announce) {
  2544. char message[128];
  2545. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, i_data->jname, temp/100.);
  2546. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2547. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2548. }
  2549. mob_setdropitem_option(&item, &mdrop[i]);
  2550. if((temp = pc_additem(mvp_sd,&item,1,LOG_TYPE_PICKDROP_PLAYER)) != 0) {
  2551. clif_additem(mvp_sd,0,0,temp);
  2552. map_addflooritem(&item,1,mvp_sd->bl.m,mvp_sd->bl.x,mvp_sd->bl.y,mvp_sd->status.char_id,(second_sd?second_sd->status.char_id:0),(third_sd?third_sd->status.char_id:0),1,0,true);
  2553. }
  2554. if (i_data->flag.broadcast)
  2555. intif_broadcast_obtain_special_item(mvp_sd, item.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  2556. //Logs items, MVP prizes [Lupus]
  2557. log_pick_mob(md, LOG_TYPE_MVP, -1, &item);
  2558. //If item_drop_mvp_mode is not 2, then only one item should be granted
  2559. if(battle_config.item_drop_mvp_mode != 2) {
  2560. break;
  2561. }
  2562. }
  2563. }
  2564. log_mvpdrop(mvp_sd, md->mob_id, log_mvp);
  2565. }
  2566. if (type&2 && !sd && md->mob_id == MOBID_EMPERIUM)
  2567. //Emperium destroyed by script. Discard mvp character. [Skotlex]
  2568. mvp_sd = NULL;
  2569. rebirth = ( md->sc.data[SC_KAIZEL] || (md->sc.data[SC_REBIRTH] && !md->state.rebirth) );
  2570. if( !rebirth ) { // Only trigger event on final kill
  2571. if( src ) {
  2572. switch( src->type ) { //allowed type
  2573. case BL_PET:
  2574. case BL_HOM:
  2575. case BL_MER:
  2576. case BL_ELEM:
  2577. case BL_MOB:
  2578. sd = BL_CAST(BL_PC,battle_get_master(src));
  2579. }
  2580. }
  2581. if (sd) {
  2582. struct mob_db *mission_mdb = mob_db(sd->mission_mobid);
  2583. if ((sd->mission_mobid == md->mob_id) || (mission_mdb != nullptr &&
  2584. ((battle_config.taekwon_mission_mobname == 1 && status_get_race2(&md->bl) == RC2_GOBLIN && mission_mdb->race2 == RC2_GOBLIN) ||
  2585. (battle_config.taekwon_mission_mobname == 2 && strcmp(mob_db(md->mob_id)->jname, mission_mdb->jname) == 0))))
  2586. { //TK_MISSION [Skotlex]
  2587. if (++(sd->mission_count) >= 100 && (temp = mob_get_random_id(MOBG_Branch_Of_Dead_Tree, static_cast<e_random_monster_flags>(RMF_CHECK_MOB_LV|RMF_MOB_NOT_BOSS|RMF_MOB_NOT_SPAWN), sd->status.base_level)))
  2588. {
  2589. pc_addfame(sd, battle_config.fame_taekwon_mission);
  2590. sd->mission_mobid = temp;
  2591. pc_setglobalreg(sd, add_str(TKMISSIONID_VAR), temp);
  2592. sd->mission_count = 0;
  2593. clif_mission_info(sd, temp, 0);
  2594. }
  2595. pc_setglobalreg(sd, add_str(TKMISSIONCOUNT_VAR), sd->mission_count);
  2596. }
  2597. if (sd->status.party_id)
  2598. map_foreachinallrange(quest_update_objective_sub, &md->bl, AREA_SIZE, BL_PC, sd->status.party_id, md->mob_id);
  2599. else if (sd->avail_quests)
  2600. quest_update_objective(sd, md->mob_id);
  2601. if (achievement_db.mobexists(md->mob_id))
  2602. achievement_update_objective(sd, AG_BATTLE, 1, md->mob_id);
  2603. if (sd->md && src && src->type == BL_MER && mob_db(md->mob_id)->lv > sd->status.base_level / 2)
  2604. mercenary_kills(sd->md);
  2605. }
  2606. if( md->npc_event[0] && !md->state.npc_killmonster ) {
  2607. if( sd && battle_config.mob_npc_event_type ) {
  2608. pc_setparam(sd, SP_KILLEDGID, md->bl.id);
  2609. pc_setparam(sd, SP_KILLEDRID, md->mob_id);
  2610. pc_setparam(sd, SP_KILLERRID, sd->bl.id);
  2611. npc_event(sd,md->npc_event,0);
  2612. } else if( mvp_sd ) {
  2613. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2614. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2615. pc_setparam(mvp_sd, SP_KILLERRID, sd?sd->bl.id:0);
  2616. npc_event(mvp_sd,md->npc_event,0);
  2617. } else
  2618. npc_event_do(md->npc_event);
  2619. } else if( mvp_sd && !md->state.npc_killmonster ) {
  2620. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2621. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2622. npc_script_event(mvp_sd, NPCE_KILLNPC); // PCKillNPC [Lance]
  2623. }
  2624. }
  2625. if(md->deletetimer != INVALID_TIMER) {
  2626. delete_timer(md->deletetimer,mob_timer_delete);
  2627. md->deletetimer = INVALID_TIMER;
  2628. }
  2629. /**
  2630. * Only loops if necessary (e.g. a poring would never need to loop)
  2631. **/
  2632. if( md->can_summon )
  2633. mob_deleteslave(md);
  2634. map_freeblock_unlock();
  2635. if( !rebirth ) {
  2636. if( pcdb_checkid(md->vd->class_) ) {//Player mobs are not removed automatically by the client.
  2637. /* first we set them dead, then we delay the outsight effect */
  2638. clif_clearunit_area(&md->bl,CLR_DEAD);
  2639. clif_clearunit_delayed(&md->bl, CLR_OUTSIGHT,tick+3000);
  2640. } else
  2641. /**
  2642. * We give the client some time to breath and this allows it to display anything it'd like with the dead corpose
  2643. * For example, this delay allows it to display soul drain effect
  2644. **/
  2645. clif_clearunit_delayed(&md->bl, CLR_DEAD, tick+250);
  2646. }
  2647. if(!md->spawn){ //Tell status_damage to remove it from memory.
  2648. struct unit_data *ud = unit_bl2ud(&md->bl);
  2649. // If the unit is currently in a walk script, it will be removed there
  2650. return ud->state.walk_script ? 3 : 5; // Note: Actually, it's 4. Oh well...
  2651. }
  2652. // MvP tomb [GreenBox]
  2653. if (battle_config.mvp_tomb_enabled && md->spawn->state.boss && map_getmapflag(md->bl.m, MF_NOTOMB) != 1)
  2654. mvptomb_create(md, mvp_sd ? mvp_sd->status.name : NULL, time(NULL));
  2655. if( !rebirth )
  2656. mob_setdelayspawn(md); //Set respawning.
  2657. return 3; //Remove from map.
  2658. }
  2659. /**
  2660. * Resurect a mob with x hp (reset value and respawn on map)
  2661. * @param md : mob pointer
  2662. * @param hp : hp to resurect him with, @FIXME unused atm
  2663. */
  2664. void mob_revive(struct mob_data *md, unsigned int hp)
  2665. {
  2666. t_tick tick = gettick();
  2667. md->state.skillstate = MSS_IDLE;
  2668. md->last_thinktime = tick;
  2669. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  2670. md->last_linktime = tick;
  2671. md->last_pcneartime = 0;
  2672. memset(md->dmglog, 0, sizeof(md->dmglog)); // Reset the damage done on the rebirthed monster, otherwise will grant full exp + damage done. [Valaris]
  2673. md->tdmg = 0;
  2674. if (!md->bl.prev){
  2675. if(map_addblock(&md->bl))
  2676. return;
  2677. }
  2678. clif_spawn(&md->bl);
  2679. skill_unit_move(&md->bl,tick,1);
  2680. mobskill_use(md, tick, MSC_SPAWN);
  2681. if (battle_config.show_mob_info&3)
  2682. clif_name_area(&md->bl);
  2683. }
  2684. int mob_guardian_guildchange(struct mob_data *md)
  2685. {
  2686. struct guild *g;
  2687. nullpo_ret(md);
  2688. if (!md->guardian_data)
  2689. return 0;
  2690. if (md->guardian_data->castle->guild_id == 0)
  2691. { //Castle with no owner? Delete the guardians.
  2692. if (md->mob_id == MOBID_EMPERIUM)
  2693. { //But don't delete the emperium, just clear it's guild-data
  2694. md->guardian_data->guild_id = 0;
  2695. md->guardian_data->emblem_id = 0;
  2696. md->guardian_data->guild_name[0] = '\0';
  2697. } else {
  2698. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  2699. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2700. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  2701. }
  2702. return 0;
  2703. }
  2704. g = guild_search(md->guardian_data->castle->guild_id);
  2705. if (g == NULL)
  2706. { //Properly remove guardian info from Castle data.
  2707. ShowError("mob_guardian_guildchange: New Guild (id %d) does not exists!\n", md->guardian_data->guild_id);
  2708. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS)
  2709. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2710. unit_free(&md->bl,CLR_OUTSIGHT);
  2711. return 0;
  2712. }
  2713. md->guardian_data->guild_id = g->guild_id;
  2714. md->guardian_data->emblem_id = g->emblem_id;
  2715. md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
  2716. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  2717. return 1;
  2718. }
  2719. /*==========================================
  2720. * Pick a random class for the mob
  2721. *------------------------------------------*/
  2722. int mob_random_class(int *value, size_t count)
  2723. {
  2724. nullpo_ret(value);
  2725. // no count specified, look into the array manually, but take only max 5 elements
  2726. if (count < 1) {
  2727. count = 0;
  2728. while(count < 5 && mobdb_checkid(value[count])) count++;
  2729. if(count < 1) // nothing found
  2730. return 0;
  2731. } else {
  2732. // check if at least the first value is valid
  2733. if(mobdb_checkid(value[0]) == 0)
  2734. return 0;
  2735. }
  2736. //Pick a random value, hoping it exists. [Skotlex]
  2737. return mobdb_checkid(value[rnd()%count]);
  2738. }
  2739. /**
  2740. * Returns the SpawnInfos of the mob_db entry (mob_spawn_data[mobid])
  2741. * if mobid is not in mob_spawn_data returns empty spawn_info vector
  2742. * @param mob_id - Looking for spawns of this Monster ID
  2743. */
  2744. const std::vector<spawn_info> mob_get_spawns(uint16 mob_id)
  2745. {
  2746. auto mob_spawn_it = mob_spawn_data.find(mob_id);
  2747. if ( mob_spawn_it != mob_spawn_data.end() )
  2748. return mob_spawn_it->second;
  2749. return std::vector<spawn_info>();
  2750. }
  2751. /**
  2752. * Checks if a monster is spawned. Returns true if yes, false otherwise.
  2753. * @param mob_id - Monster ID which is checked
  2754. */
  2755. bool mob_has_spawn(uint16 mob_id)
  2756. {
  2757. // It's enough to check if the monster is in mob_spawn_data, because
  2758. // none or empty spawns are ignored. Thus the monster is spawned.
  2759. return mob_spawn_data.find(mob_id) != mob_spawn_data.end();
  2760. }
  2761. /**
  2762. * Adds a spawn info to the specific mob. (To mob_spawn_data)
  2763. * @param mob_id - Monster ID spawned
  2764. * @param new_spawn - spawn_info holding the map and quantity of the spawn
  2765. */
  2766. void mob_add_spawn(uint16 mob_id, const struct spawn_info& new_spawn)
  2767. {
  2768. unsigned short m = new_spawn.mapindex;
  2769. if( new_spawn.qty <= 0 )
  2770. return; //ignore empty spawns
  2771. std::vector<spawn_info>& spawns = mob_spawn_data[mob_id];
  2772. // Search if the map is already in spawns
  2773. auto itSameMap = std::find_if(spawns.begin(), spawns.end(),
  2774. [&m] (const spawn_info &s) { return (s.mapindex == m); });
  2775. if( itSameMap != spawns.end() )
  2776. itSameMap->qty += new_spawn.qty; // add quantity, if map is found
  2777. else
  2778. spawns.push_back(new_spawn); // else, add the whole spawn info
  2779. // sort spawns by spawn quantity
  2780. std::sort(spawns.begin(), spawns.end(),
  2781. [](const spawn_info & a, const spawn_info & b) -> bool
  2782. { return a.qty > b.qty; });
  2783. /** Note
  2784. Spawns are sorted after every addition. This makes reloadscript slower, but
  2785. some spawns may be added directly by loadscript or something similar.
  2786. */
  2787. }
  2788. /*==========================================
  2789. * Change mob base class
  2790. *------------------------------------------*/
  2791. int mob_class_change (struct mob_data *md, int mob_id)
  2792. {
  2793. t_tick tick = gettick();
  2794. int i, hp_rate;
  2795. nullpo_ret(md);
  2796. if( md->bl.prev == NULL )
  2797. return 0;
  2798. if (!mob_id || !mobdb_checkid(mob_id))
  2799. return 0;
  2800. //Disable class changing for some targets...
  2801. if (md->guardian_data)
  2802. return 0; //Guardians/Emperium
  2803. if (status_get_race2(&md->bl) == RC2_TREASURE)
  2804. return 0; //Treasure Boxes
  2805. if( md->special_state.ai > AI_ATTACK )
  2806. return 0; //Marine Spheres and Floras.
  2807. if( mob_is_clone(md->mob_id) )
  2808. return 0; //Clones
  2809. if( md->mob_id == mob_id )
  2810. return 0; //Nothing to change.
  2811. hp_rate = get_percentage(md->status.hp, md->status.max_hp);
  2812. md->mob_id = mob_id;
  2813. md->db = mob_db(mob_id);
  2814. if (battle_config.override_mob_names==1)
  2815. memcpy(md->name,md->db->name,NAME_LENGTH);
  2816. else
  2817. memcpy(md->name,md->db->jname,NAME_LENGTH);
  2818. status_change_end(&md->bl,SC_KEEPING,INVALID_TIMER); // End before calling status_calc_mob().
  2819. status_change_end(&md->bl,SC_BARRIER,INVALID_TIMER);
  2820. mob_stop_attack(md);
  2821. mob_stop_walking(md, 0);
  2822. unit_skillcastcancel(&md->bl, 0);
  2823. status_set_viewdata(&md->bl, mob_id);
  2824. clif_mob_class_change(md,md->vd->class_);
  2825. status_calc_mob(md,SCO_FIRST);
  2826. md->ud.state.speed_changed = 1; //Speed change update.
  2827. if (battle_config.monster_class_change_recover) {
  2828. memset(md->dmglog, 0, sizeof(md->dmglog));
  2829. md->tdmg = 0;
  2830. } else {
  2831. md->status.hp = md->status.max_hp*hp_rate/100;
  2832. if(md->status.hp < 1) md->status.hp = 1;
  2833. }
  2834. t_tick c = tick - MOB_MAX_DELAY;
  2835. for(i=0;i<MAX_MOBSKILL;i++)
  2836. md->skilldelay[i] = c;
  2837. if (md->lootitems == NULL && status_has_mode(&md->db->status,MD_LOOTER))
  2838. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  2839. //Targets should be cleared no morph
  2840. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  2841. //Need to update name display.
  2842. clif_name_area(&md->bl);
  2843. return 0;
  2844. }
  2845. /*==========================================
  2846. * mob heal, update display hp info of mob for players
  2847. *------------------------------------------*/
  2848. void mob_heal(struct mob_data *md,unsigned int heal)
  2849. {
  2850. if (battle_config.show_mob_info&3)
  2851. clif_name_area(&md->bl);
  2852. #if PACKETVER >= 20120404
  2853. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2854. int i;
  2855. for(i = 0; i < DAMAGELOG_SIZE; i++)// must show hp bar to all char who already hit the mob.
  2856. if( md->dmglog[i].id ) {
  2857. struct map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2858. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2859. clif_monster_hp_bar(md, sd->fd);
  2860. }
  2861. }
  2862. #endif
  2863. }
  2864. /*==========================================
  2865. * Added by RoVeRT
  2866. *------------------------------------------*/
  2867. int mob_warpslave_sub(struct block_list *bl,va_list ap)
  2868. {
  2869. struct mob_data *md=(struct mob_data *)bl;
  2870. struct block_list *master;
  2871. short x,y,range=0;
  2872. master = va_arg(ap, struct block_list*);
  2873. range = va_arg(ap, int);
  2874. if(md->master_id!=master->id)
  2875. return 0;
  2876. map_search_freecell(master, 0, &x, &y, range, range, 0);
  2877. unit_warp(&md->bl, master->m, x, y,CLR_TELEPORT);
  2878. return 1;
  2879. }
  2880. /*==========================================
  2881. * Added by RoVeRT
  2882. * Warps slaves. Range is the area around the master that they can
  2883. * appear in randomly.
  2884. *------------------------------------------*/
  2885. int mob_warpslave(struct block_list *bl, int range)
  2886. {
  2887. if (range < 1)
  2888. range = 1; //Min range needed to avoid crashes and stuff. [Skotlex]
  2889. return map_foreachinmap(mob_warpslave_sub, bl->m, BL_MOB, bl, range);
  2890. }
  2891. /*==========================================
  2892. * Counts slave sub, curently checking if mob master is the given ID.
  2893. *------------------------------------------*/
  2894. int mob_countslave_sub(struct block_list *bl,va_list ap)
  2895. {
  2896. int id;
  2897. struct mob_data *md;
  2898. id=va_arg(ap,int);
  2899. md = (struct mob_data *)bl;
  2900. if( md->master_id==id )
  2901. return 1;
  2902. return 0;
  2903. }
  2904. /*==========================================
  2905. * Counts the number of slaves a mob has on the map.
  2906. *------------------------------------------*/
  2907. int mob_countslave(struct block_list *bl)
  2908. {
  2909. return map_foreachinmap(mob_countslave_sub, bl->m, BL_MOB,bl->id);
  2910. }
  2911. /*==========================================
  2912. * Summons amount slaves contained in the value[5] array using round-robin. [adapted by Skotlex]
  2913. *------------------------------------------*/
  2914. int mob_summonslave(struct mob_data *md2,int *value,int amount,uint16 skill_id)
  2915. {
  2916. struct mob_data *md;
  2917. struct spawn_data data;
  2918. int count = 0,k=0,hp_rate=0;
  2919. nullpo_ret(md2);
  2920. nullpo_ret(value);
  2921. memset(&data, 0, sizeof(struct spawn_data));
  2922. data.m = md2->bl.m;
  2923. data.x = md2->bl.x;
  2924. data.y = md2->bl.y;
  2925. data.num = 1;
  2926. data.state.size = md2->special_state.size;
  2927. data.state.ai = md2->special_state.ai;
  2928. if(mobdb_checkid(value[0]) == 0)
  2929. return 0;
  2930. /**
  2931. * Flags this monster is able to summon; saves a worth amount of memory upon deletion
  2932. **/
  2933. md2->can_summon = 1;
  2934. while(count < 5 && mobdb_checkid(value[count])) count++;
  2935. if(count < 1) return 0;
  2936. if (amount > 0 && amount < count) { //Do not start on 0, pick some random sub subset [Skotlex]
  2937. k = rnd()%count;
  2938. amount+=k; //Increase final value by same amount to preserve total number to summon.
  2939. }
  2940. if (!battle_config.monster_class_change_recover &&
  2941. (skill_id == NPC_TRANSFORMATION || skill_id == NPC_METAMORPHOSIS))
  2942. hp_rate = get_percentage(md2->status.hp, md2->status.max_hp);
  2943. for(;k<amount;k++) {
  2944. short x,y;
  2945. data.id = value[k%count]; //Summon slaves in round-robin fashion. [Skotlex]
  2946. if (mobdb_checkid(data.id) == 0)
  2947. continue;
  2948. if (skill_id != NPC_DEATHSUMMON && map_search_freecell(&md2->bl, 0, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 0)) {
  2949. data.x = x;
  2950. data.y = y;
  2951. } else {
  2952. data.x = md2->bl.x;
  2953. data.y = md2->bl.y;
  2954. }
  2955. //These two need to be loaded from the db for each slave.
  2956. if(battle_config.override_mob_names==1)
  2957. strcpy(data.name,"--en--");
  2958. else
  2959. strcpy(data.name,"--ja--");
  2960. if (!mob_parse_dataset(&data))
  2961. continue;
  2962. md= mob_spawn_dataset(&data);
  2963. if(skill_id == NPC_SUMMONSLAVE){
  2964. md->master_id=md2->bl.id;
  2965. md->special_state.ai = md2->special_state.ai;
  2966. }
  2967. mob_spawn(md);
  2968. if (hp_rate) //Scale HP
  2969. md->status.hp = md->status.max_hp*hp_rate/100;
  2970. if (skill_id == NPC_SUMMONSLAVE) // Only appies to NPC_SUMMONSLAVE
  2971. status_calc_slave_mode(md, md2); // Inherit the aggressive mode of the master.
  2972. if (md2->state.copy_master_mode)
  2973. md->status.mode = md2->status.mode;
  2974. clif_skill_nodamage(&md->bl,&md->bl,skill_id,amount,1);
  2975. }
  2976. return 0;
  2977. }
  2978. /*==========================================
  2979. * MOBskill lookup (get skillindex through skill_id)
  2980. * Returns -1 if not found.
  2981. *------------------------------------------*/
  2982. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id)
  2983. {
  2984. int i, max = mob_db(mob_id)->maxskill;
  2985. struct mob_skill *ms=mob_db(mob_id)->skill;
  2986. if(ms==NULL)
  2987. return -1;
  2988. ARR_FIND( 0, max, i, ms[i].skill_id == skill_id );
  2989. return ( i < max ) ? i : -1;
  2990. }
  2991. /*==========================================
  2992. * Friendly Mob whose HP is decreasing by a nearby MOB is looked for.
  2993. *------------------------------------------*/
  2994. int mob_getfriendhprate_sub(struct block_list *bl,va_list ap)
  2995. {
  2996. int min_rate, max_rate,rate;
  2997. struct block_list **fr;
  2998. struct mob_data *md;
  2999. md = va_arg(ap,struct mob_data *);
  3000. min_rate=va_arg(ap,int);
  3001. max_rate=va_arg(ap,int);
  3002. fr=va_arg(ap,struct block_list **);
  3003. if( md->bl.id == bl->id && !(battle_config.mob_ai&0x10))
  3004. return 0;
  3005. if ((*fr) != NULL) //A friend was already found.
  3006. return 0;
  3007. if (battle_check_target(&md->bl,bl,BCT_ENEMY)>0)
  3008. return 0;
  3009. rate = get_percentage(status_get_hp(bl), status_get_max_hp(bl));
  3010. if (rate >= min_rate && rate <= max_rate)
  3011. (*fr) = bl;
  3012. return 1;
  3013. }
  3014. static struct block_list *mob_getfriendhprate(struct mob_data *md,int min_rate,int max_rate)
  3015. {
  3016. struct block_list *fr=NULL;
  3017. int type = BL_MOB;
  3018. nullpo_retr(NULL, md);
  3019. if (md->special_state.ai) //Summoned creatures. [Skotlex]
  3020. type = BL_PC;
  3021. map_foreachinallrange(mob_getfriendhprate_sub, &md->bl, 8, type,md,min_rate,max_rate,&fr);
  3022. return fr;
  3023. }
  3024. /*==========================================
  3025. * Check hp rate of its master
  3026. *------------------------------------------*/
  3027. struct block_list *mob_getmasterhpltmaxrate(struct mob_data *md,int rate)
  3028. {
  3029. if( md && md->master_id > 0 )
  3030. {
  3031. struct block_list *bl = map_id2bl(md->master_id);
  3032. if( bl && get_percentage(status_get_hp(bl), status_get_max_hp(bl)) < rate )
  3033. return bl;
  3034. }
  3035. return NULL;
  3036. }
  3037. /*==========================================
  3038. * What a status state suits by nearby MOB is looked for.
  3039. *------------------------------------------*/
  3040. int mob_getfriendstatus_sub(struct block_list *bl,va_list ap)
  3041. {
  3042. int cond1,cond2;
  3043. struct mob_data **fr, *md, *mmd;
  3044. int flag=0;
  3045. nullpo_ret(bl);
  3046. nullpo_ret(md=(struct mob_data *)bl);
  3047. nullpo_ret(mmd=va_arg(ap,struct mob_data *));
  3048. if( mmd->bl.id == bl->id && !(battle_config.mob_ai&0x10) )
  3049. return 0;
  3050. if (battle_check_target(&mmd->bl,bl,BCT_ENEMY)>0)
  3051. return 0;
  3052. cond1=va_arg(ap,int);
  3053. cond2=va_arg(ap,int);
  3054. fr=va_arg(ap,struct mob_data **);
  3055. if( cond2==-1 ){
  3056. int j;
  3057. for(j=SC_COMMON_MIN;j<=SC_COMMON_MAX && !flag;j++){
  3058. if ((flag=(md->sc.data[j] != NULL))) //Once an effect was found, break out. [Skotlex]
  3059. break;
  3060. }
  3061. }else
  3062. flag=( md->sc.data[cond2] != NULL );
  3063. if( flag^( cond1==MSC_FRIENDSTATUSOFF ) )
  3064. (*fr)=md;
  3065. return 0;
  3066. }
  3067. struct mob_data *mob_getfriendstatus(struct mob_data *md,int cond1,int cond2)
  3068. {
  3069. struct mob_data* fr = NULL;
  3070. nullpo_ret(md);
  3071. map_foreachinallrange(mob_getfriendstatus_sub, &md->bl, 8,BL_MOB, md,cond1,cond2,&fr);
  3072. return fr;
  3073. }
  3074. /*==========================================
  3075. * Skill use judging
  3076. *------------------------------------------*/
  3077. int mobskill_use(struct mob_data *md, t_tick tick, int event)
  3078. {
  3079. struct mob_skill *ms;
  3080. struct block_list *fbl = NULL; //Friend bl, which can either be a BL_PC or BL_MOB depending on the situation. [Skotlex]
  3081. struct block_list *bl;
  3082. struct mob_data *fmd = NULL;
  3083. int i,j,n;
  3084. short skill_target;
  3085. nullpo_ret(md);
  3086. nullpo_ret(ms = md->db->skill);
  3087. if (!battle_config.mob_skill_rate || md->ud.skilltimer != INVALID_TIMER || !md->db->maxskill || status_has_mode(&md->status,MD_NOCAST_SKILL))
  3088. return 0;
  3089. if (event == -1 && DIFF_TICK(md->ud.canact_tick, tick) > 0)
  3090. return 0; //Skill act delay only affects non-event skills.
  3091. //Pick a starting position and loop from that.
  3092. i = battle_config.mob_ai&0x100?rnd()%md->db->maxskill:0;
  3093. for (n = 0; n < md->db->maxskill; i++, n++) {
  3094. int c2, flag = 0;
  3095. if (i == md->db->maxskill)
  3096. i = 0;
  3097. if (DIFF_TICK(tick, md->skilldelay[i]) < ms[i].delay)
  3098. continue;
  3099. c2 = ms[i].cond2;
  3100. if (ms[i].state != md->state.skillstate) {
  3101. if (md->state.skillstate != MSS_DEAD && (ms[i].state == MSS_ANY ||
  3102. (ms[i].state == MSS_ANYTARGET && md->target_id && md->state.skillstate != MSS_LOOT)
  3103. )) //ANYTARGET works with any state as long as there's a target. [Skotlex]
  3104. ;
  3105. else
  3106. continue;
  3107. }
  3108. if (rnd() % 10000 > ms[i].permillage) //Lupus (max value = 10000)
  3109. continue;
  3110. if (ms[i].cond1 == event)
  3111. flag = 1; //Trigger skill.
  3112. else if (ms[i].cond1 == MSC_SKILLUSED)
  3113. flag = ((event & 0xffff) == MSC_SKILLUSED && ((event >> 16) == c2 || c2 == 0));
  3114. else if(event == -1){
  3115. //Avoid entering on defined events to avoid "hyper-active skill use" due to the overflow of calls to this function in battle.
  3116. switch (ms[i].cond1)
  3117. {
  3118. case MSC_ALWAYS:
  3119. flag = 1; break;
  3120. case MSC_MYHPLTMAXRATE: // HP< maxhp%
  3121. flag = get_percentage(md->status.hp, md->status.max_hp);
  3122. flag = (flag <= c2);
  3123. break;
  3124. case MSC_MYHPINRATE:
  3125. flag = get_percentage(md->status.hp, md->status.max_hp);
  3126. flag = (flag >= c2 && flag <= ms[i].val[0]);
  3127. break;
  3128. case MSC_MYSTATUSON: // status[num] on
  3129. case MSC_MYSTATUSOFF: // status[num] off
  3130. if (!md->sc.count) {
  3131. flag = 0;
  3132. } else if (ms[i].cond2 == -1) {
  3133. for (j = SC_COMMON_MIN; j <= SC_COMMON_MAX; j++)
  3134. if ((flag = (md->sc.data[j]!=NULL)) != 0)
  3135. break;
  3136. } else {
  3137. flag = (md->sc.data[ms[i].cond2]!=NULL);
  3138. }
  3139. flag ^= (ms[i].cond1 == MSC_MYSTATUSOFF); break;
  3140. case MSC_FRIENDHPLTMAXRATE: // friend HP < maxhp%
  3141. flag = ((fbl = mob_getfriendhprate(md, 0, ms[i].cond2)) != NULL); break;
  3142. case MSC_FRIENDHPINRATE :
  3143. flag = ((fbl = mob_getfriendhprate(md, ms[i].cond2, ms[i].val[0])) != NULL); break;
  3144. case MSC_FRIENDSTATUSON: // friend status[num] on
  3145. case MSC_FRIENDSTATUSOFF: // friend status[num] off
  3146. flag = ((fmd = mob_getfriendstatus(md, ms[i].cond1, ms[i].cond2)) != NULL); break;
  3147. case MSC_SLAVELT: // slave < num
  3148. flag = (mob_countslave(&md->bl) < c2 ); break;
  3149. case MSC_ATTACKPCGT: // attack pc > num
  3150. flag = (unit_counttargeted(&md->bl) > c2); break;
  3151. case MSC_SLAVELE: // slave <= num
  3152. flag = (mob_countslave(&md->bl) <= c2 ); break;
  3153. case MSC_ATTACKPCGE: // attack pc >= num
  3154. flag = (unit_counttargeted(&md->bl) >= c2); break;
  3155. case MSC_AFTERSKILL:
  3156. flag = (md->ud.skill_id == c2); break;
  3157. case MSC_RUDEATTACKED:
  3158. flag = (md->state.attacked_count >= RUDE_ATTACKED_COUNT);
  3159. if (flag) md->state.attacked_count = 0; //Rude attacked count should be reset after the skill condition is met. Thanks to Komurka [Skotlex]
  3160. break;
  3161. case MSC_MASTERHPLTMAXRATE:
  3162. flag = ((fbl = mob_getmasterhpltmaxrate(md, ms[i].cond2)) != NULL); break;
  3163. case MSC_MASTERATTACKED:
  3164. flag = (md->master_id > 0 && (fbl=map_id2bl(md->master_id)) && unit_counttargeted(fbl) > 0); break;
  3165. case MSC_ALCHEMIST:
  3166. flag = (md->state.alchemist);
  3167. break;
  3168. }
  3169. }
  3170. if (!flag)
  3171. continue; //Skill requisite failed to be fulfilled.
  3172. //Execute skill
  3173. skill_target = status_has_mode(&md->db->status,MD_RANDOMTARGET) ? MST_RANDOM : ms[i].target;
  3174. if (skill_get_casttype(ms[i].skill_id) == CAST_GROUND)
  3175. { //Ground skill.
  3176. short x, y;
  3177. switch (skill_target) {
  3178. case MST_RANDOM: //Pick a random enemy within skill range.
  3179. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3180. skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv, true));
  3181. break;
  3182. case MST_TARGET:
  3183. case MST_AROUND5:
  3184. case MST_AROUND6:
  3185. case MST_AROUND7:
  3186. case MST_AROUND8:
  3187. bl = map_id2bl(md->target_id);
  3188. break;
  3189. case MST_MASTER:
  3190. bl = &md->bl;
  3191. if (md->master_id)
  3192. bl = map_id2bl(md->master_id);
  3193. if (bl) //Otherwise, fall through.
  3194. break;
  3195. case MST_FRIEND:
  3196. bl = fbl?fbl:(fmd?&fmd->bl:&md->bl);
  3197. break;
  3198. default:
  3199. bl = &md->bl;
  3200. break;
  3201. }
  3202. if (!bl) continue;
  3203. x = bl->x;
  3204. y = bl->y;
  3205. // Look for an area to cast the spell around...
  3206. if (skill_target >= MST_AROUND5) {
  3207. j = skill_target >= MST_AROUND1?
  3208. (skill_target-MST_AROUND1) +1:
  3209. (skill_target-MST_AROUND5) +1;
  3210. map_search_freecell(&md->bl, md->bl.m, &x, &y, j, j, 3);
  3211. }
  3212. md->skill_idx = i;
  3213. map_freeblock_lock();
  3214. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv, true)) ||
  3215. !unit_skilluse_pos2(&md->bl, x, y, ms[i].skill_id, ms[i].skill_lv, ms[i].casttime, ms[i].cancel))
  3216. {
  3217. map_freeblock_unlock();
  3218. continue;
  3219. }
  3220. } else {
  3221. //Targetted skill
  3222. switch (skill_target) {
  3223. case MST_RANDOM: //Pick a random enemy within skill range.
  3224. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3225. skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv, true));
  3226. break;
  3227. case MST_TARGET:
  3228. bl = map_id2bl(md->target_id);
  3229. break;
  3230. case MST_MASTER:
  3231. bl = &md->bl;
  3232. if (md->master_id)
  3233. bl = map_id2bl(md->master_id);
  3234. if (bl) //Otherwise, fall through.
  3235. break;
  3236. case MST_FRIEND:
  3237. if (fbl) {
  3238. bl = fbl;
  3239. break;
  3240. } else if (fmd) {
  3241. bl = &fmd->bl;
  3242. break;
  3243. } // else fall through
  3244. default:
  3245. bl = &md->bl;
  3246. break;
  3247. }
  3248. if (!bl) continue;
  3249. md->skill_idx = i;
  3250. map_freeblock_lock();
  3251. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv, true)) ||
  3252. !unit_skilluse_id2(&md->bl, bl->id, ms[i].skill_id, ms[i].skill_lv, ms[i].casttime, ms[i].cancel))
  3253. {
  3254. map_freeblock_unlock();
  3255. continue;
  3256. }
  3257. }
  3258. //Skill used. Post-setups...
  3259. if ( ms[ i ].msg_id ){ //Display color message [SnakeDrak]
  3260. struct mob_chat *mc = mob_chat(ms[i].msg_id);
  3261. if (mc) {
  3262. std::string name = md->name, output;
  3263. std::size_t unique = name.find("#");
  3264. if (unique != std::string::npos)
  3265. name = name.substr(0, unique); // discard extra name identifier if present [Daegaladh]
  3266. output = name + " : " + mc->msg;
  3267. clif_messagecolor(&md->bl, mc->color, output.c_str(), true, AREA_CHAT_WOC);
  3268. }
  3269. }
  3270. if(!(battle_config.mob_ai&0x200)) { //pass on delay to same skill.
  3271. for (j = 0; j < md->db->maxskill; j++)
  3272. if (md->db->skill[j].skill_id == ms[i].skill_id)
  3273. md->skilldelay[j]=tick;
  3274. } else
  3275. md->skilldelay[i]=tick;
  3276. map_freeblock_unlock();
  3277. return 1;
  3278. }
  3279. //No skill was used.
  3280. md->skill_idx = -1;
  3281. return 0;
  3282. }
  3283. /*==========================================
  3284. * Skill use event processing
  3285. *------------------------------------------*/
  3286. int mobskill_event(struct mob_data *md, struct block_list *src, t_tick tick, int flag)
  3287. {
  3288. int target_id, res = 0;
  3289. if(md->bl.prev == NULL || md->status.hp == 0)
  3290. return 0;
  3291. target_id = md->target_id;
  3292. if (!target_id || battle_config.mob_changetarget_byskill)
  3293. md->target_id = src->id;
  3294. if (flag == -1)
  3295. res = mobskill_use(md, tick, MSC_CASTTARGETED);
  3296. else if ((flag&0xffff) == MSC_SKILLUSED)
  3297. res = mobskill_use(md, tick, flag);
  3298. else if (flag&BF_SHORT)
  3299. res = mobskill_use(md, tick, MSC_CLOSEDATTACKED);
  3300. else if (flag&BF_LONG && !(flag&BF_MAGIC)) //Long-attacked should not include magic.
  3301. res = mobskill_use(md, tick, MSC_LONGRANGEATTACKED);
  3302. if (!res)
  3303. //Restore previous target only if skill condition failed to trigger. [Skotlex]
  3304. md->target_id = target_id;
  3305. //Otherwise check if the target is an enemy, and unlock if needed.
  3306. else if (battle_check_target(&md->bl, src, BCT_ENEMY) <= 0)
  3307. md->target_id = target_id;
  3308. return res;
  3309. }
  3310. // Player cloned mobs. [Valaris]
  3311. int mob_is_clone(int mob_id)
  3312. {
  3313. if(mob_id < MOB_CLONE_START || mob_id > MOB_CLONE_END)
  3314. return 0;
  3315. if (mob_db(mob_id) == NULL)
  3316. return 0;
  3317. return mob_id;
  3318. }
  3319. /**
  3320. * Previously, using skill_nocast with flag 16
  3321. * @param skill_id
  3322. * @return True:If disabled, False:If enabled
  3323. * @!TODO : Move this hardcodes!
  3324. **/
  3325. static bool mob_clone_disabled_skills(uint16 skill_id) {
  3326. switch (skill_id) {
  3327. case PR_TURNUNDEAD:
  3328. case PR_MAGNUS:
  3329. return true;
  3330. }
  3331. return false;
  3332. }
  3333. //Flag values:
  3334. //&1: Set special ai (fight mobs, not players)
  3335. //If mode is not passed, a default aggressive mode is used.
  3336. //If master_id is passed, clone is attached to him.
  3337. //Returns: ID of newly crafted copy.
  3338. int mob_clone_spawn(struct map_session_data *sd, int16 m, int16 x, int16 y, const char *event, int master_id, enum e_mode mode, int flag, unsigned int duration)
  3339. {
  3340. int mob_id;
  3341. int i,j,inf, fd;
  3342. struct mob_data *md;
  3343. struct mob_skill *ms;
  3344. struct mob_db* db;
  3345. struct status_data *status;
  3346. nullpo_ret(sd);
  3347. if(pc_isdead(sd) && master_id && flag&1)
  3348. return 0;
  3349. ARR_FIND( MOB_CLONE_START, MOB_CLONE_END, mob_id, mob_db(mob_id) == NULL );
  3350. if(mob_id >= MOB_CLONE_END)
  3351. return 0;
  3352. try{
  3353. db = &mob_db_data[mob_id];
  3354. }catch( const std::bad_alloc& ){
  3355. ShowError( "mob_clone_spawn: Memory allocation for clone %hu failed.\n", mob_id );
  3356. return 0;
  3357. }
  3358. status = &db->status;
  3359. strcpy(db->sprite,sd->status.name);
  3360. strcpy(db->name,sd->status.name);
  3361. strcpy(db->jname,sd->status.name);
  3362. db->lv=status_get_lv(&sd->bl);
  3363. memcpy(status, &sd->base_status, sizeof(struct status_data));
  3364. status->rhw.atk2= status->dex + status->rhw.atk + status->rhw.atk2; //Max ATK
  3365. status->rhw.atk = status->dex; //Min ATK
  3366. if (status->lhw.atk) {
  3367. status->lhw.atk2= status->dex + status->lhw.atk + status->lhw.atk2; //Max ATK
  3368. status->lhw.atk = status->dex; //Min ATK
  3369. }
  3370. if (mode) //User provided mode.
  3371. status->mode = mode;
  3372. else if (flag&1) //Friendly Character, remove looting.
  3373. status->mode = static_cast<enum e_mode>(status->mode&(~MD_LOOTER));
  3374. status->hp = status->max_hp;
  3375. status->sp = status->max_sp;
  3376. memcpy(&db->vd, &sd->vd, sizeof(struct view_data));
  3377. db->base_exp=1;
  3378. db->job_exp=1;
  3379. db->range2=AREA_SIZE; //Let them have the same view-range as players.
  3380. db->range3=AREA_SIZE; //Min chase of a screen.
  3381. db->option=sd->sc.option;
  3382. //Skill copy [Skotlex]
  3383. ms = &db->skill[0];
  3384. /**
  3385. * We temporarily disable sd's fd so it doesn't receive the messages from skill_check_condition_castbegin
  3386. **/
  3387. fd = sd->fd;
  3388. sd->fd = 0;
  3389. //Go Backwards to give better priority to advanced skills.
  3390. for (i=0,j = MAX_SKILL_TREE-1;j>=0 && i< MAX_MOBSKILL ;j--) {
  3391. uint16 skill_id = skill_tree[pc_class2idx(sd->status.class_)][j].skill_id;
  3392. uint16 sk_idx = 0;
  3393. if (!skill_id || !(sk_idx = skill_get_index(skill_id)) || sd->status.skill[sk_idx].lv < 1 ||
  3394. (skill_get_inf2(skill_id)&(INF2_WEDDING_SKILL|INF2_GUILD_SKILL)) ||
  3395. mob_clone_disabled_skills(skill_id)
  3396. )
  3397. continue;
  3398. //Normal aggressive mob, disable skills that cannot help them fight
  3399. //against players (those with flags UF_NOMOB and UF_NOPC are specific
  3400. //to always aid players!) [Skotlex]
  3401. if (!(flag&1) &&
  3402. skill_get_unit_id(skill_id, 0) &&
  3403. skill_get_unit_flag(skill_id)&(UF_NOMOB|UF_NOPC))
  3404. continue;
  3405. /**
  3406. * The clone should be able to cast the skill (e.g. have the required weapon) bugreport:5299)
  3407. **/
  3408. if( !skill_check_condition_castbegin(sd,skill_id,sd->status.skill[sk_idx].lv) )
  3409. continue;
  3410. memset (&ms[i], 0, sizeof(struct mob_skill));
  3411. ms[i].skill_id = skill_id;
  3412. ms[i].skill_lv = sd->status.skill[sk_idx].lv;
  3413. ms[i].state = MSS_ANY;
  3414. ms[i].permillage = 500*battle_config.mob_skill_rate/100; //Default chance of all skills: 5%
  3415. ms[i].emotion = -1;
  3416. ms[i].cancel = 0;
  3417. ms[i].casttime = skill_castfix(&sd->bl,skill_id, ms[i].skill_lv);
  3418. ms[i].delay = 5000+skill_delayfix(&sd->bl,skill_id, ms[i].skill_lv);
  3419. ms[i].msg_id = 0;
  3420. inf = skill_get_inf(skill_id);
  3421. if (inf&INF_ATTACK_SKILL) {
  3422. ms[i].target = MST_TARGET;
  3423. ms[i].cond1 = MSC_ALWAYS;
  3424. if (skill_get_range(skill_id, ms[i].skill_lv) > 3)
  3425. ms[i].state = MSS_ANYTARGET;
  3426. else
  3427. ms[i].state = MSS_BERSERK;
  3428. } else if(inf&INF_GROUND_SKILL) {
  3429. if (skill_get_inf2(skill_id)&INF2_TRAP) { //Traps!
  3430. ms[i].state = MSS_IDLE;
  3431. ms[i].target = MST_AROUND2;
  3432. ms[i].delay = 60000;
  3433. } else if (skill_get_unit_target(skill_id) == BCT_ENEMY) { //Target Enemy
  3434. ms[i].state = MSS_ANYTARGET;
  3435. ms[i].target = MST_TARGET;
  3436. ms[i].cond1 = MSC_ALWAYS;
  3437. } else { //Target allies
  3438. ms[i].target = MST_FRIEND;
  3439. ms[i].cond1 = MSC_FRIENDHPLTMAXRATE;
  3440. ms[i].cond2 = 95;
  3441. }
  3442. } else if (inf&INF_SELF_SKILL) {
  3443. if (skill_get_inf2(skill_id)&INF2_NO_TARGET_SELF) { //auto-select target skill.
  3444. ms[i].target = MST_TARGET;
  3445. ms[i].cond1 = MSC_ALWAYS;
  3446. if (skill_get_range(skill_id, ms[i].skill_lv) > 3) {
  3447. ms[i].state = MSS_ANYTARGET;
  3448. } else {
  3449. ms[i].state = MSS_BERSERK;
  3450. }
  3451. } else { //Self skill
  3452. ms[i].target = MST_SELF;
  3453. ms[i].cond1 = MSC_MYHPLTMAXRATE;
  3454. ms[i].cond2 = 90;
  3455. ms[i].permillage = 2000;
  3456. //Delay: Remove the stock 5 secs and add half of the support time.
  3457. ms[i].delay += -5000 +(skill_get_time(skill_id, ms[i].skill_lv) + skill_get_time2(skill_id, ms[i].skill_lv))/2;
  3458. if (ms[i].delay < 5000)
  3459. ms[i].delay = 5000; //With a minimum of 5 secs.
  3460. }
  3461. } else if (inf&INF_SUPPORT_SKILL) {
  3462. ms[i].target = MST_FRIEND;
  3463. ms[i].cond1 = MSC_FRIENDHPLTMAXRATE;
  3464. ms[i].cond2 = 90;
  3465. if (skill_id == AL_HEAL)
  3466. ms[i].permillage = 5000; //Higher skill rate usage for heal.
  3467. else if (skill_id == ALL_RESURRECTION)
  3468. ms[i].cond2 = 1;
  3469. //Delay: Remove the stock 5 secs and add half of the support time.
  3470. ms[i].delay += -5000 +(skill_get_time(skill_id, ms[i].skill_lv) + skill_get_time2(skill_id, ms[i].skill_lv))/2;
  3471. if (ms[i].delay < 2000)
  3472. ms[i].delay = 2000; //With a minimum of 2 secs.
  3473. if (i+1 < MAX_MOBSKILL) { //duplicate this so it also triggers on self.
  3474. memcpy(&ms[i+1], &ms[i], sizeof(struct mob_skill));
  3475. db->maxskill = ++i;
  3476. ms[i].target = MST_SELF;
  3477. ms[i].cond1 = MSC_MYHPLTMAXRATE;
  3478. }
  3479. } else {
  3480. switch (skill_id) { //Certain Special skills that are passive, and thus, never triggered.
  3481. case MO_TRIPLEATTACK:
  3482. case TF_DOUBLE:
  3483. case GS_CHAINACTION:
  3484. ms[i].state = MSS_BERSERK;
  3485. ms[i].target = MST_TARGET;
  3486. ms[i].cond1 = MSC_ALWAYS;
  3487. ms[i].permillage = skill_id==MO_TRIPLEATTACK?(3000-ms[i].skill_lv*100):(ms[i].skill_lv*500);
  3488. ms[i].delay -= 5000; //Remove the added delay as these could trigger on "all hits".
  3489. break;
  3490. default: //Untreated Skill
  3491. continue;
  3492. }
  3493. }
  3494. if (battle_config.mob_skill_rate!= 100)
  3495. ms[i].permillage = ms[i].permillage*battle_config.mob_skill_rate/100;
  3496. if (battle_config.mob_skill_delay != 100)
  3497. ms[i].delay = ms[i].delay*battle_config.mob_skill_delay/100;
  3498. db->maxskill = ++i;
  3499. }
  3500. /**
  3501. * We grant the session it's fd value back.
  3502. **/
  3503. sd->fd = fd;
  3504. //Finally, spawn it.
  3505. md = mob_once_spawn_sub(&sd->bl, m, x, y, "--en--", mob_id, event, SZ_SMALL, AI_NONE);
  3506. if (!md) return 0; //Failed?
  3507. md->special_state.clone = 1;
  3508. if (master_id || flag || duration) { //Further manipulate crafted char.
  3509. if (flag&1) //Friendly Character
  3510. md->special_state.ai = AI_ATTACK;
  3511. if (master_id) //Attach to Master
  3512. md->master_id = master_id;
  3513. if (duration) //Auto Delete after a while.
  3514. {
  3515. if( md->deletetimer != INVALID_TIMER )
  3516. delete_timer(md->deletetimer, mob_timer_delete);
  3517. md->deletetimer = add_timer (gettick() + duration, mob_timer_delete, md->bl.id, 0);
  3518. }
  3519. }
  3520. mob_spawn(md);
  3521. return md->bl.id;
  3522. }
  3523. int mob_clone_delete(struct mob_data *md){
  3524. const int mob_id = md->mob_id;
  3525. if (mob_id >= MOB_CLONE_START && mob_id < MOB_CLONE_END
  3526. && mob_db(mob_id)!=NULL) {
  3527. mob_db_data.erase(mob_id);
  3528. //Clear references to the db
  3529. md->db = NULL;
  3530. md->vd = NULL;
  3531. return 1;
  3532. }
  3533. return 0;
  3534. }
  3535. //Adjusts the drop rate of item according to the criteria given. [Skotlex]
  3536. static unsigned int mob_drop_adjust(int baserate, int rate_adjust, unsigned short rate_min, unsigned short rate_max)
  3537. {
  3538. double rate = baserate;
  3539. if (battle_config.logarithmic_drops && rate_adjust > 0 && rate_adjust != 100 && baserate > 0) //Logarithmic drops equation by Ishizu-Chan
  3540. //Equation: Droprate(x,y) = x * (5 - log(x)) ^ (ln(y) / ln(5))
  3541. //x is the normal Droprate, y is the Modificator.
  3542. rate = rate * pow((5.0 - log10(rate)), (log(rate_adjust/100.) / log(5.0))) + 0.5;
  3543. else
  3544. //Classical linear rate adjustment.
  3545. rate = rate * rate_adjust/100;
  3546. return (unsigned int)cap_value(rate,rate_min,rate_max);
  3547. }
  3548. /**
  3549. * Check if global item drop rate is overriden for given item
  3550. * in db/mob_item_ratio.txt
  3551. * @param nameid ID of the item
  3552. * @param mob_id ID of the monster
  3553. * @param rate_adjust pointer to store ratio if found
  3554. */
  3555. static void item_dropratio_adjust(unsigned short nameid, int mob_id, int *rate_adjust)
  3556. {
  3557. struct s_mob_item_drop_ratio *item_ratio = (struct s_mob_item_drop_ratio *)idb_get(mob_item_drop_ratio, nameid);
  3558. if( item_ratio) {
  3559. if( item_ratio->mob_id[0] ) { // only for listed mobs
  3560. int i;
  3561. ARR_FIND(0, MAX_ITEMRATIO_MOBS, i, item_ratio->mob_id[i] == mob_id);
  3562. if( i < MAX_ITEMRATIO_MOBS ) // found
  3563. *rate_adjust = item_ratio->drop_ratio;
  3564. }
  3565. else // for all mobs
  3566. *rate_adjust = item_ratio->drop_ratio;
  3567. }
  3568. }
  3569. /*==========================================
  3570. * processes one mobdb entry
  3571. *------------------------------------------*/
  3572. static bool mob_parse_dbrow(char** str)
  3573. {
  3574. struct mob_db *db, entry;
  3575. struct status_data *status;
  3576. int mob_id, i;
  3577. double exp, maxhp;
  3578. struct mob_data data;
  3579. mob_id = atoi(str[0]);
  3580. if (!((mob_id > MIN_MOB_DB && mob_id < MAX_MOB_DB) || (mob_id > MIN_MOB_DB2 && mob_id < MAX_MOB_DB2))) {
  3581. ShowError("mob_parse_dbrow: Invalid monster ID %d, must be in range %d-%d or %d-%d.\n", mob_id, MIN_MOB_DB, MAX_MOB_DB, MIN_MOB_DB2, MAX_MOB_DB2);
  3582. return false;
  3583. }
  3584. memset(&entry, 0, sizeof(entry));
  3585. status = &entry.status;
  3586. entry.vd.class_ = mob_id;
  3587. safestrncpy(entry.sprite, str[1], sizeof(entry.sprite));
  3588. safestrncpy(entry.jname, str[2], sizeof(entry.jname));
  3589. safestrncpy(entry.name, str[3], sizeof(entry.name));
  3590. entry.lv = atoi(str[4]);
  3591. entry.lv = cap_value(entry.lv, 1, USHRT_MAX);
  3592. status->max_hp = atoi(str[5]);
  3593. status->max_sp = atoi(str[6]);
  3594. exp = (double)atoi(str[7]) * (double)battle_config.base_exp_rate / 100.;
  3595. entry.base_exp = (unsigned int)cap_value(exp, 0, UINT_MAX);
  3596. exp = (double)atoi(str[8]) * (double)battle_config.job_exp_rate / 100.;
  3597. entry.job_exp = (unsigned int)cap_value(exp, 0, UINT_MAX);
  3598. status->rhw.range = atoi(str[9]);
  3599. #ifdef RENEWAL
  3600. status->rhw.atk = atoi(str[10]); // BaseATK
  3601. status->rhw.matk = atoi(str[11]); // BaseMATK
  3602. #else
  3603. status->rhw.atk = atoi(str[10]); // MinATK
  3604. status->rhw.atk2 = atoi(str[11]); // MaxATK
  3605. #endif
  3606. status->def = atoi(str[12]);
  3607. status->mdef = atoi(str[13]);
  3608. status->str = atoi(str[14]);
  3609. status->agi = atoi(str[15]);
  3610. status->vit = atoi(str[16]);
  3611. status->int_ = atoi(str[17]);
  3612. status->dex = atoi(str[18]);
  3613. status->luk = atoi(str[19]);
  3614. //All status should be min 1 to prevent divisions by zero from some skills. [Skotlex]
  3615. if (status->str < 1) status->str = 1;
  3616. if (status->agi < 1) status->agi = 1;
  3617. if (status->vit < 1) status->vit = 1;
  3618. if (status->int_< 1) status->int_= 1;
  3619. if (status->dex < 1) status->dex = 1;
  3620. if (status->luk < 1) status->luk = 1;
  3621. entry.range2 = atoi(str[20]);
  3622. entry.range3 = atoi(str[21]);
  3623. if (battle_config.view_range_rate != 100) {
  3624. entry.range2 = entry.range2 * battle_config.view_range_rate / 100;
  3625. if (entry.range2 < 1)
  3626. entry.range2 = 1;
  3627. }
  3628. if (battle_config.chase_range_rate != 100) {
  3629. entry.range3 = entry.range3 * battle_config.chase_range_rate / 100;
  3630. if (entry.range3 < entry.range2)
  3631. entry.range3 = entry.range2;
  3632. }
  3633. //Tests showed that chase range is effectively 2 cells larger than expected [Playtester]
  3634. entry.range3 += 2;
  3635. status->size = atoi(str[22]);
  3636. status->race = atoi(str[23]);
  3637. i = atoi(str[24]); //Element
  3638. status->def_ele = i%20;
  3639. status->ele_lv = (unsigned char)floor(i/20.);
  3640. if (!CHK_ELEMENT(status->def_ele)) {
  3641. ShowError("mob_parse_dbrow: Invalid element type %d for monster ID %d (max=%d).\n", status->def_ele, mob_id, ELE_ALL-1);
  3642. return false;
  3643. }
  3644. if (!CHK_ELEMENT_LEVEL(status->ele_lv)) {
  3645. ShowError("mob_parse_dbrow: Invalid element level %d for monster ID %d, must be in range 1-%d.\n", status->ele_lv, mob_id, MAX_ELE_LEVEL);
  3646. return false;
  3647. }
  3648. status->mode = static_cast<enum e_mode>(strtol(str[25], NULL, 0));
  3649. if (!battle_config.monster_active_enable)
  3650. status->mode = static_cast<enum e_mode>(status->mode&(~MD_AGGRESSIVE));
  3651. if (status_has_mode(status,MD_STATUS_IMMUNE|MD_KNOCKBACK_IMMUNE|MD_DETECTOR))
  3652. status->class_ = CLASS_BOSS;
  3653. else // Store as Normal and overwrite in mob_race2_db for special Class
  3654. status->class_ = CLASS_NORMAL;
  3655. status->speed = atoi(str[26]);
  3656. status->aspd_rate = 1000;
  3657. i = atoi(str[27]);
  3658. status->adelay = cap_value(i, battle_config.monster_max_aspd*2, 4000);
  3659. i = atoi(str[28]);
  3660. status->amotion = cap_value(i, battle_config.monster_max_aspd, 2000);
  3661. //If the attack animation is longer than the delay, the client crops the attack animation!
  3662. //On aegis there is no real visible effect of having a recharge-time less than amotion anyway.
  3663. if (status->adelay < status->amotion)
  3664. status->adelay = status->amotion;
  3665. status->dmotion = atoi(str[29]);
  3666. if(battle_config.monster_damage_delay_rate != 100)
  3667. status->dmotion = status->dmotion * battle_config.monster_damage_delay_rate / 100;
  3668. // Fill in remaining status data by using a dummy monster.
  3669. data.bl.type = BL_MOB;
  3670. data.level = entry.lv;
  3671. memcpy(&data.status, status, sizeof(struct status_data));
  3672. status_calc_misc(&data.bl, status, entry.lv);
  3673. // MVP EXP Bonus: MEXP
  3674. // Some new MVP's MEXP multipled by high exp-rate cause overflow. [LuzZza]
  3675. exp = (double)atoi(str[30]) * (double)battle_config.mvp_exp_rate / 100.;
  3676. entry.mexp = (unsigned int)cap_value(exp, 0, UINT_MAX);
  3677. //Now that we know if it is an mvp or not, apply battle_config modifiers [Skotlex]
  3678. maxhp = (double)status->max_hp;
  3679. if (entry.mexp > 0) { //Mvp
  3680. if (battle_config.mvp_hp_rate != 100)
  3681. maxhp = maxhp * (double)battle_config.mvp_hp_rate / 100.;
  3682. } else //Normal mob
  3683. if (battle_config.monster_hp_rate != 100)
  3684. maxhp = maxhp * (double)battle_config.monster_hp_rate / 100.;
  3685. status->max_hp = (unsigned int)cap_value(maxhp, 1, UINT_MAX);
  3686. if(status->max_sp < 1) status->max_sp = 1;
  3687. //Since mobs always respawn with full life...
  3688. status->hp = status->max_hp;
  3689. status->sp = status->max_sp;
  3690. // MVP Drops: MVP1id,MVP1per,MVP2id,MVP2per,MVP3id,MVP3per
  3691. for(i = 0; i < MAX_MVP_DROP; i++) {
  3692. entry.mvpitem[i].nameid = atoi(str[31+i*2]);
  3693. if( entry.mvpitem[i].nameid ){
  3694. if( itemdb_search(entry.mvpitem[i].nameid) ){
  3695. entry.mvpitem[i].p = atoi(str[32+i*2]);
  3696. continue;
  3697. }else{
  3698. ShowWarning( "Monster \"%s\"(id: %d) is dropping an unknown item \"%s\"(MVP-Drop %d)\n", entry.name, mob_id, str[31+i*2], ( i / 2 ) + 1 );
  3699. }
  3700. }
  3701. // Delete the item
  3702. entry.mvpitem[i].nameid = 0;
  3703. entry.mvpitem[i].p = 0;
  3704. }
  3705. for(i = 0; i < MAX_MOB_DROP; i++) {
  3706. int k = 31 + MAX_MVP_DROP*2 + i*2;
  3707. entry.dropitem[i].nameid = atoi(str[k]);
  3708. if( entry.dropitem[i].nameid ){
  3709. if( itemdb_search( entry.dropitem[i].nameid ) ){
  3710. entry.dropitem[i].p = atoi(str[k+1]);
  3711. continue;
  3712. }else{
  3713. ShowWarning( "Monster \"%s\"(id: %d) is dropping an unknown item \"%s\"(Drop %d)\n", entry.name, mob_id, str[k], ( i / 2 ) + 1 );
  3714. }
  3715. }
  3716. // Delete the item
  3717. entry.dropitem[i].nameid = 0;
  3718. entry.dropitem[i].p = 0;
  3719. }
  3720. db = mob_db(mob_id);
  3721. // Finally insert monster's data into the database.
  3722. if (db == NULL) {
  3723. try{
  3724. db = &mob_db_data[mob_id];
  3725. }catch( const std::bad_alloc& ){
  3726. ShowError( "Memory allocation for monster %hu failed.\n", mob_id );
  3727. return false;
  3728. }
  3729. }
  3730. memcpy(db, &entry, sizeof(struct mob_db));
  3731. return true;
  3732. }
  3733. /*==========================================
  3734. * mob_db.txt reading
  3735. *------------------------------------------*/
  3736. static bool mob_readdb_sub(char* fields[], int columns, int current)
  3737. {
  3738. return mob_parse_dbrow(fields);
  3739. }
  3740. /*==========================================
  3741. * mob_db table reading
  3742. *------------------------------------------*/
  3743. static int mob_read_sqldb(void)
  3744. {
  3745. const char* mob_db_name[] = {
  3746. mob_table,
  3747. mob2_table };
  3748. int fi;
  3749. for( fi = 0; fi < ARRAYLENGTH(mob_db_name); ++fi ) {
  3750. uint32 lines = 0, count = 0;
  3751. // retrieve all rows from the mob database
  3752. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT * FROM `%s`", mob_db_name[fi]) ) {
  3753. Sql_ShowDebug(mmysql_handle);
  3754. continue;
  3755. }
  3756. // process rows one by one
  3757. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  3758. // wrap the result into a TXT-compatible format
  3759. char line[1024];
  3760. char* str[31+2*MAX_MVP_DROP+2*MAX_MOB_DROP];
  3761. char* p;
  3762. int i;
  3763. lines++;
  3764. for(i = 0, p = line; i < 31+2*MAX_MVP_DROP+2*MAX_MOB_DROP; i++)
  3765. {
  3766. char* data;
  3767. size_t len;
  3768. Sql_GetData(mmysql_handle, i, &data, &len);
  3769. strcpy(p, data);
  3770. str[i] = p;
  3771. p+= len + 1;
  3772. }
  3773. if (!mob_parse_dbrow(str))
  3774. continue;
  3775. count++;
  3776. }
  3777. // free the query result
  3778. Sql_FreeResult(mmysql_handle);
  3779. ShowStatus("Done reading '" CL_WHITE "%u" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_db_name[fi]);
  3780. }
  3781. return 0;
  3782. }
  3783. const std::string MobAvailDatabase::getDefaultLocation() {
  3784. return std::string(db_path) + "/" + DBIMPORT + "/mob_avail.yml";
  3785. }
  3786. /**
  3787. * Reads and parses an entry from the mob_avail.
  3788. * @param node: YAML node containing the entry.
  3789. * @return count of successfully parsed rows
  3790. */
  3791. uint64 MobAvailDatabase::parseBodyNode(const YAML::Node &node) {
  3792. std::string mob_name;
  3793. if (!this->asString(node, "Mob", mob_name))
  3794. return 0;
  3795. struct mob_db *mob = mobdb_search_aegisname(mob_name.c_str());
  3796. if (mob == nullptr) {
  3797. this->invalidWarning(node["Mob"], "Unknown mob %s.\n", mob_name.c_str());
  3798. return 0;
  3799. }
  3800. if (this->nodeExists(node, "Sprite")) {
  3801. std::string sprite;
  3802. if (!this->asString(node, "Sprite", sprite))
  3803. return 0;
  3804. int constant;
  3805. if (script_get_constant(sprite.c_str(), &constant)) {
  3806. if (npcdb_checkid(constant) == 0 && pcdb_checkid(constant) == 0) {
  3807. this->invalidWarning(node["Sprite"], "Unknown sprite constant %s.\n", sprite.c_str());
  3808. return 0;
  3809. }
  3810. } else {
  3811. struct mob_db *sprite_mob = mobdb_search_aegisname(sprite.c_str());
  3812. if (sprite_mob == nullptr) {
  3813. this->invalidWarning(node["Sprite"], "Unknown mob sprite constant %s.\n", sprite.c_str());
  3814. return 0;
  3815. }
  3816. constant = sprite_mob->vd.class_;
  3817. }
  3818. mob->vd.class_ = constant;
  3819. } else {
  3820. this->invalidWarning(node["Sprite"], "Sprite is missing.\n");
  3821. return 0;
  3822. }
  3823. if (this->nodeExists(node, "Sex")) {
  3824. if (pcdb_checkid(mob->vd.class_) == 0) {
  3825. this->invalidWarning(node["Sex"], "Sex is only applicable to Job sprites.\n");
  3826. return 0;
  3827. }
  3828. std::string sex;
  3829. if (!this->asString(node, "Sex", sex))
  3830. return 0;
  3831. std::string sex_constant = "SEX_" + sex;
  3832. int constant;
  3833. if (!script_get_constant(sex_constant.c_str(), &constant)) {
  3834. this->invalidWarning(node["Sex"], "Unknown sex constant %s.\n", sex.c_str());
  3835. return 0;
  3836. }
  3837. if (constant < SEX_FEMALE || constant > SEX_MALE) {
  3838. this->invalidWarning(node["Sex"], "Sex %s is not valid.\n", sex.c_str());
  3839. return 0;
  3840. }
  3841. mob->vd.sex = constant;
  3842. }
  3843. if (this->nodeExists(node, "HairStyle")) {
  3844. if (pcdb_checkid(mob->vd.class_) == 0) {
  3845. this->invalidWarning(node["HairStyle"], "HairStyle is only applicable to Job sprites.\n");
  3846. return 0;
  3847. }
  3848. uint16 hair_style;
  3849. if (!this->asUInt16(node, "HairStyle", hair_style))
  3850. return 0;
  3851. if (hair_style < MIN_HAIR_STYLE || hair_style > MAX_HAIR_STYLE) {
  3852. this->invalidWarning(node["HairStyle"], "HairStyle %d is out of range %d~%d. Setting to MIN_HAIR_STYLE.\n", hair_style, MIN_HAIR_STYLE, MAX_HAIR_STYLE);
  3853. hair_style = MIN_HAIR_STYLE;
  3854. }
  3855. mob->vd.hair_style = hair_style;
  3856. }
  3857. if (this->nodeExists(node, "HairColor")) {
  3858. if (pcdb_checkid(mob->vd.class_) == 0) {
  3859. this->invalidWarning(node["HairColor"], "HairColor is only applicable to Job sprites.\n");
  3860. return 0;
  3861. }
  3862. uint16 hair_color;
  3863. if (!this->asUInt16(node, "HairColor", hair_color))
  3864. return 0;
  3865. if (hair_color < MIN_HAIR_COLOR || hair_color > MAX_HAIR_COLOR) {
  3866. this->invalidWarning(node["HairColor"], "HairColor %d is out of range %d~%d. Setting to MIN_HAIR_COLOR.\n", hair_color, MIN_HAIR_COLOR, MAX_HAIR_COLOR);
  3867. hair_color = MIN_HAIR_COLOR;
  3868. }
  3869. mob->vd.hair_color = hair_color;
  3870. }
  3871. if (this->nodeExists(node, "ClothColor")) {
  3872. if (pcdb_checkid(mob->vd.class_) == 0) {
  3873. this->invalidWarning(node["ClothColor"], "ClothColor is only applicable to Job sprites.\n");
  3874. return 0;
  3875. }
  3876. uint32 cloth_color;
  3877. if (!this->asUInt32(node, "ClothColor", cloth_color))
  3878. return 0;
  3879. if (cloth_color < MIN_CLOTH_COLOR || cloth_color > MAX_CLOTH_COLOR) {
  3880. this->invalidWarning(node["ClothColor"], "ClothColor %d is out of range %d~%d. Setting to MIN_CLOTH_CLOR.\n", cloth_color, MIN_CLOTH_COLOR, MAX_CLOTH_COLOR);
  3881. cloth_color = MIN_CLOTH_COLOR;
  3882. }
  3883. mob->vd.cloth_color = cloth_color;
  3884. }
  3885. if (this->nodeExists(node, "Weapon")) {
  3886. if (pcdb_checkid(mob->vd.class_) == 0) {
  3887. this->invalidWarning(node["Weapon"], "Weapon is only applicable to Job sprites.\n");
  3888. return 0;
  3889. }
  3890. std::string weapon;
  3891. if (!this->asString(node, "Weapon", weapon))
  3892. return 0;
  3893. struct item_data *item = itemdb_searchname(weapon.c_str());
  3894. if (item == nullptr) {
  3895. this->invalidWarning(node["Weapon"], "Weapon %s is not a valid item.\n", weapon.c_str());
  3896. return 0;
  3897. }
  3898. mob->vd.weapon = item->nameid;
  3899. }
  3900. if (this->nodeExists(node, "Shield")) {
  3901. if (pcdb_checkid(mob->vd.class_) == 0) {
  3902. this->invalidWarning(node["Shield"], "Shield is only applicable to Job sprites.\n");
  3903. return 0;
  3904. }
  3905. std::string shield;
  3906. if (!this->asString(node, "Shield", shield))
  3907. return 0;
  3908. struct item_data *item = itemdb_searchname(shield.c_str());
  3909. if (item == nullptr) {
  3910. this->invalidWarning(node["Shield"], "Shield %s is not a valid item.\n", shield.c_str());
  3911. return 0;
  3912. }
  3913. mob->vd.shield = item->nameid;
  3914. }
  3915. if (this->nodeExists(node, "HeadTop")) {
  3916. if (pcdb_checkid(mob->vd.class_) == 0) {
  3917. this->invalidWarning(node["HeadTop"], "HeadTop is only applicable to Job sprites.\n");
  3918. return 0;
  3919. }
  3920. std::string head;
  3921. if (!this->asString(node, "HeadTop", head))
  3922. return 0;
  3923. struct item_data *item;
  3924. if ((item = itemdb_searchname(head.c_str())) == nullptr) {
  3925. this->invalidWarning(node["HeadTop"], "HeadTop %s is not a valid item.\n", head.c_str());
  3926. return 0;
  3927. }
  3928. mob->vd.head_top = item->look;
  3929. }
  3930. if (this->nodeExists(node, "HeadMid")) {
  3931. if (pcdb_checkid(mob->vd.class_) == 0) {
  3932. this->invalidWarning(node["HeadMid"], "HeadMid is only applicable to Job sprites.\n");
  3933. return 0;
  3934. }
  3935. std::string head;
  3936. if (!this->asString(node, "HeadMid", head))
  3937. return 0;
  3938. struct item_data *item = itemdb_searchname(head.c_str());
  3939. if (item == nullptr) {
  3940. this->invalidWarning(node["HeadMid"], "HeadMid %s is not a valid item.\n", head.c_str());
  3941. return 0;
  3942. }
  3943. mob->vd.head_mid = item->look;
  3944. }
  3945. if (this->nodeExists(node, "HeadLow")) {
  3946. if (pcdb_checkid(mob->vd.class_) == 0) {
  3947. this->invalidWarning(node["HeadLow"], "HeadLow is only applicable to Job sprites.\n");
  3948. return 0;
  3949. }
  3950. std::string head;
  3951. if (!this->asString(node, "HeadLow", head))
  3952. return 0;
  3953. struct item_data *item = itemdb_searchname(head.c_str());
  3954. if (item == nullptr) {
  3955. this->invalidWarning(node["HeadLow"], "HeadLow %s is not a valid item.\n", head.c_str());
  3956. return 0;
  3957. }
  3958. mob->vd.head_bottom = item->look;
  3959. }
  3960. if (this->nodeExists(node, "PetEquip")) {
  3961. std::shared_ptr<s_pet_db> pet_db_ptr = pet_db.find(mob->vd.class_);
  3962. if (pet_db_ptr == nullptr) {
  3963. this->invalidWarning(node["PetEquip"], "PetEquip is only applicable to defined pets.\n");
  3964. return 0;
  3965. }
  3966. std::string equipment;
  3967. if (!this->asString(node, "PetEquip", equipment))
  3968. return 0;
  3969. struct item_data *item = itemdb_searchname(equipment.c_str());
  3970. if (item == nullptr) {
  3971. this->invalidWarning(node["PetEquip"], "PetEquip %s is not a valid item.\n", equipment.c_str());
  3972. return 0;
  3973. }
  3974. mob->vd.head_bottom = item->nameid;
  3975. }
  3976. if (this->nodeExists(node, "Options")) {
  3977. for (const auto &optionNode : node["Options"]) {
  3978. std::string option = optionNode.first.as<std::string>();
  3979. std::string option_constant = "OPTION_" + option;
  3980. int constant;
  3981. if (!script_get_constant(option_constant.c_str(), &constant)) {
  3982. this->invalidWarning(optionNode, "Unknown option constant %s, skipping.\n", option.c_str());
  3983. continue;
  3984. }
  3985. bool active;
  3986. if (!this->asBool(node, option, active))
  3987. continue;
  3988. #ifdef NEW_CARTS
  3989. if (constant & OPTION_CART) {
  3990. this->invalidWarning(optionNode, "OPTION_CART was replace by SC_PUSH_CART, skipping.\n");
  3991. continue;
  3992. }
  3993. #endif
  3994. if (active)
  3995. mob->option |= constant;
  3996. else
  3997. mob->option &= ~constant;
  3998. }
  3999. mob->option &= ~(OPTION_HIDE | OPTION_CLOAK | OPTION_INVISIBLE | OPTION_CHASEWALK); // Remove hiding types
  4000. }
  4001. return 1;
  4002. }
  4003. MobAvailDatabase mob_avail_db;
  4004. /*==========================================
  4005. * Reading of random monster data
  4006. * MobGroup,MobID,DummyName,Rate
  4007. *------------------------------------------*/
  4008. static bool mob_readdb_group(char* str[], int columns, int current){
  4009. struct s_randomsummon_group *msummon = NULL;
  4010. int mob_id, group = 0;
  4011. unsigned short i = 0;
  4012. bool set_default = false;
  4013. if (ISDIGIT(str[0][0]) && ISDIGIT(str[0][1]))
  4014. group = atoi(str[0]);
  4015. else if (!script_get_constant(str[0], &group)) {
  4016. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4017. return false;
  4018. }
  4019. mob_id = atoi(str[1]);
  4020. if (mob_id != 0 && mob_db(mob_id) == NULL) {
  4021. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4022. return false;
  4023. }
  4024. else if (mob_id == 0){
  4025. mob_id = atoi(str[3]);
  4026. if (mob_db(mob_id) == NULL) {
  4027. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4028. return false;
  4029. }
  4030. set_default = true;
  4031. }
  4032. if (!(msummon = (struct s_randomsummon_group *)idb_get(mob_summon_db, group))) {
  4033. CREATE(msummon, struct s_randomsummon_group, 1);
  4034. CREATE(msummon->list, struct s_randomsummon_entry, (msummon->count = 1));
  4035. msummon->list[0].mob_id = mob_id;
  4036. msummon->list[0].rate = atoi(str[3]);
  4037. msummon->random_id = group;
  4038. idb_put(mob_summon_db, group, msummon);
  4039. }
  4040. else {
  4041. ARR_FIND(0, msummon->count, i, set_default || (i > 0 && msummon->list[i].mob_id == mob_id));
  4042. if (i >= msummon->count)
  4043. RECREATE(msummon->list, struct s_randomsummon_entry, ++msummon->count);
  4044. msummon->list[i].mob_id = mob_id;
  4045. msummon->list[i].rate = atoi(str[3]);
  4046. }
  4047. return true;
  4048. }
  4049. //processes one mob_chat_db entry [SnakeDrak]
  4050. //db struct: Line_ID,Color_Code,Dialog
  4051. static bool mob_parse_row_chatdb(char* fields[], int columns, int current)
  4052. {
  4053. char* msg;
  4054. struct mob_chat *ms;
  4055. int msg_id;
  4056. size_t len;
  4057. msg_id = atoi(fields[0]);
  4058. if (msg_id <= 0){
  4059. ShowError("mob_parse_row_chatdb: Invalid chat ID '%d' in line %d\n", msg_id, current);
  4060. return false;
  4061. }
  4062. ms = mob_chat(msg_id);
  4063. if( ms == NULL ){
  4064. try{
  4065. ms = &mob_chat_db[msg_id];
  4066. }catch( const std::bad_alloc& ){
  4067. ShowError( "mob_parse_row_chatdb: Memory allocation for chat ID '%d' failed.\n", msg_id );
  4068. return false;
  4069. }
  4070. }
  4071. //MSG ID
  4072. ms->msg_id=msg_id;
  4073. //Color
  4074. ms->color=strtoul(fields[1],NULL,0);
  4075. //Message
  4076. msg = fields[2];
  4077. len = strlen(msg);
  4078. while( len && ( msg[len-1]=='\r' || msg[len-1]=='\n' ) )
  4079. {// find EOL to strip
  4080. len--;
  4081. }
  4082. if(len>(CHAT_SIZE_MAX-1)){
  4083. ShowError("mob_parse_row_chatdb: Message too long! Line %d, id: %d\n", current, msg_id);
  4084. return false;
  4085. }
  4086. else if( !len ){
  4087. ShowWarning("mob_parse_row_chatdb: Empty message for id %d.\n", msg_id);
  4088. return false;
  4089. }
  4090. msg[len] = 0; // strip previously found EOL
  4091. safestrncpy(ms->msg, fields[2], CHAT_SIZE_MAX);
  4092. return true;
  4093. }
  4094. /*==========================================
  4095. * processes one mob_skill_db entry
  4096. *------------------------------------------*/
  4097. static bool mob_parse_row_mobskilldb(char** str, int columns, int current)
  4098. {
  4099. static const struct {
  4100. char str[32];
  4101. enum MobSkillState id;
  4102. } state[] = {
  4103. { "any", MSS_ANY }, //All states except Dead
  4104. { "idle", MSS_IDLE },
  4105. { "walk", MSS_WALK },
  4106. { "loot", MSS_LOOT },
  4107. { "dead", MSS_DEAD },
  4108. { "attack", MSS_BERSERK }, //Retaliating attack
  4109. { "angry", MSS_ANGRY }, //Preemptive attack (aggressive mobs)
  4110. { "chase", MSS_RUSH }, //Chase escaping target
  4111. { "follow", MSS_FOLLOW }, //Preemptive chase (aggressive mobs)
  4112. { "anytarget",MSS_ANYTARGET }, //Berserk+Angry+Rush+Follow
  4113. };
  4114. static const struct {
  4115. char str[32];
  4116. int id;
  4117. } cond1[] = {
  4118. // enum e_mob_skill_condition
  4119. { "always", MSC_ALWAYS },
  4120. { "myhpltmaxrate", MSC_MYHPLTMAXRATE },
  4121. { "myhpinrate", MSC_MYHPINRATE },
  4122. { "friendhpltmaxrate", MSC_FRIENDHPLTMAXRATE },
  4123. { "friendhpinrate", MSC_FRIENDHPINRATE },
  4124. { "mystatuson", MSC_MYSTATUSON },
  4125. { "mystatusoff", MSC_MYSTATUSOFF },
  4126. { "friendstatuson", MSC_FRIENDSTATUSON },
  4127. { "friendstatusoff", MSC_FRIENDSTATUSOFF },
  4128. { "attackpcgt", MSC_ATTACKPCGT },
  4129. { "attackpcge", MSC_ATTACKPCGE },
  4130. { "slavelt", MSC_SLAVELT },
  4131. { "slavele", MSC_SLAVELE },
  4132. { "closedattacked", MSC_CLOSEDATTACKED },
  4133. { "longrangeattacked", MSC_LONGRANGEATTACKED },
  4134. { "skillused", MSC_SKILLUSED },
  4135. { "afterskill", MSC_AFTERSKILL },
  4136. { "casttargeted", MSC_CASTTARGETED },
  4137. { "rudeattacked", MSC_RUDEATTACKED },
  4138. { "masterhpltmaxrate", MSC_MASTERHPLTMAXRATE },
  4139. { "masterattacked", MSC_MASTERATTACKED },
  4140. { "alchemist", MSC_ALCHEMIST },
  4141. { "onspawn", MSC_SPAWN },
  4142. }, cond2[] ={
  4143. { "anybad", -1 },
  4144. { "stone", SC_STONE },
  4145. { "freeze", SC_FREEZE },
  4146. { "stun", SC_STUN },
  4147. { "sleep", SC_SLEEP },
  4148. { "poison", SC_POISON },
  4149. { "curse", SC_CURSE },
  4150. { "silence", SC_SILENCE },
  4151. { "confusion", SC_CONFUSION },
  4152. { "blind", SC_BLIND },
  4153. { "hiding", SC_HIDING },
  4154. { "sight", SC_SIGHT },
  4155. }, target[] = {
  4156. // enum e_mob_skill_target
  4157. { "target", MST_TARGET },
  4158. { "randomtarget", MST_RANDOM },
  4159. { "self", MST_SELF },
  4160. { "friend", MST_FRIEND },
  4161. { "master", MST_MASTER },
  4162. { "around5", MST_AROUND5 },
  4163. { "around6", MST_AROUND6 },
  4164. { "around7", MST_AROUND7 },
  4165. { "around8", MST_AROUND8 },
  4166. { "around1", MST_AROUND1 },
  4167. { "around2", MST_AROUND2 },
  4168. { "around3", MST_AROUND3 },
  4169. { "around4", MST_AROUND4 },
  4170. { "around", MST_AROUND },
  4171. };
  4172. static int last_mob_id = 0; // ensures that only one error message per mob id is printed
  4173. struct s_mob_skill *skill = NULL;
  4174. struct mob_skill *ms = NULL;
  4175. int mob_id;
  4176. int i = 0, j, tmp;
  4177. struct mob_db *mob;
  4178. mob_id = atoi(str[0]);
  4179. if (mob_id > 0 && (mob = mob_db(mob_id)) == NULL)
  4180. {
  4181. if (mob_id != last_mob_id) {
  4182. ShowError("mob_parse_row_mobskilldb: Non existant Mob id %d\n", mob_id);
  4183. last_mob_id = mob_id;
  4184. }
  4185. return false;
  4186. }
  4187. else if (mob_id == 0)
  4188. return false;
  4189. // Looking for existing entry
  4190. if (!(skill = (struct s_mob_skill *)idb_get(mob_skill_db, mob_id)))
  4191. CREATE(skill, struct s_mob_skill, 1);
  4192. if( strcmp(str[1],"clear") == 0 && skill->mob_id != 0 ) {
  4193. idb_remove(mob_skill_db, skill->mob_id);
  4194. aFree(skill);
  4195. ShowInfo("Cleared skill for mob id '%d'\n", mob_id);
  4196. return true;
  4197. }
  4198. ARR_FIND( 0, MAX_MOBSKILL, i, skill->skill[i].skill_id == 0 );
  4199. if( i == MAX_MOBSKILL )
  4200. {
  4201. if (mob_id != last_mob_id) {
  4202. ShowError("mob_parse_row_mobskilldb: Too many skills for monster %d[%s]\n", mob_id, mob->sprite);
  4203. last_mob_id = mob_id;
  4204. }
  4205. return false;
  4206. }
  4207. ms = &skill->skill[i];
  4208. //State
  4209. ARR_FIND( 0, ARRAYLENGTH(state), j, strcmp(str[2],state[j].str) == 0 );
  4210. if( j < ARRAYLENGTH(state) )
  4211. ms->state = state[j].id;
  4212. else {
  4213. ShowError("mob_parse_row_mobskilldb: Unrecognized state '%s' in line %d\n", str[2], current);
  4214. return false;
  4215. }
  4216. //Skill ID
  4217. j = atoi(str[3]);
  4218. if (j <= 0 || j > MAX_SKILL_ID || !skill_get_index(j)) //fixed Lupus
  4219. {
  4220. if (mob_id < 0)
  4221. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for all mobs\n", j);
  4222. else
  4223. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for mob %d (%s)\n", j, mob_id, mob->sprite);
  4224. return false;
  4225. }
  4226. ms->skill_id = j;
  4227. //Skill lvl
  4228. j = atoi(str[4]) <= 0 ? 1 : atoi(str[4]);
  4229. ms->skill_lv = j > battle_config.mob_max_skilllvl ? battle_config.mob_max_skilllvl : j; //we strip max skill level
  4230. //Apply battle_config modifiers to rate (permillage) and delay [Skotlex]
  4231. tmp = atoi(str[5]);
  4232. if (battle_config.mob_skill_rate != 100)
  4233. tmp = tmp*battle_config.mob_skill_rate/100;
  4234. if (tmp > 10000)
  4235. ms->permillage = 10000;
  4236. else if (!tmp && battle_config.mob_skill_rate)
  4237. ms->permillage = 1;
  4238. else
  4239. ms->permillage = tmp;
  4240. ms->casttime = atoi(str[6]);
  4241. ms->delay = atoi(str[7]);
  4242. if (battle_config.mob_skill_delay != 100)
  4243. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  4244. if (ms->delay < 0 || ms->delay > MOB_MAX_DELAY) //time overflow?
  4245. ms->delay = MOB_MAX_DELAY;
  4246. ms->cancel = atoi(str[8]);
  4247. if( strcmp(str[8],"yes")==0 )
  4248. ms->cancel=1;
  4249. //Target
  4250. ARR_FIND( 0, ARRAYLENGTH(target), j, strcmp(str[9],target[j].str) == 0 );
  4251. if( j < ARRAYLENGTH(target) )
  4252. ms->target = target[j].id;
  4253. else {
  4254. ShowWarning("mob_parse_row_mobskilldb: Unrecognized target %s for %d\n", str[9], mob_id);
  4255. ms->target = MST_TARGET;
  4256. }
  4257. //Check that the target condition is right for the skill type. [Skotlex]
  4258. if (skill_get_casttype(ms->skill_id) == CAST_GROUND)
  4259. { //Ground skill.
  4260. if (ms->target > MST_AROUND)
  4261. {
  4262. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target for ground skill %d (%s) for %s.\n",
  4263. ms->skill_id, skill_get_name(ms->skill_id),
  4264. mob_id < 0 ? "all mobs" : mob->sprite);
  4265. ms->target = MST_TARGET;
  4266. }
  4267. } else if (ms->target > MST_MASTER) {
  4268. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target 'around' for non-ground skill %d (%s) for %s.\n",
  4269. ms->skill_id, skill_get_name(ms->skill_id),
  4270. mob_id < 0 ? "all mobs" : mob->sprite);
  4271. ms->target = MST_TARGET;
  4272. }
  4273. //Cond1
  4274. ARR_FIND( 0, ARRAYLENGTH(cond1), j, strcmp(str[10],cond1[j].str) == 0 );
  4275. if( j < ARRAYLENGTH(cond1) )
  4276. ms->cond1 = cond1[j].id;
  4277. else {
  4278. ShowWarning("mob_parse_row_mobskilldb: Unrecognized condition 1 %s for %d\n", str[10], mob_id);
  4279. ms->cond1 = -1;
  4280. }
  4281. //Cond2
  4282. // numeric value
  4283. ms->cond2 = atoi(str[11]);
  4284. // or special constant
  4285. ARR_FIND( 0, ARRAYLENGTH(cond2), j, strcmp(str[11],cond2[j].str) == 0 );
  4286. if( j < ARRAYLENGTH(cond2) )
  4287. ms->cond2 = cond2[j].id;
  4288. ms->val[0] = (int)strtol(str[12],NULL,0);
  4289. ms->val[1] = (int)strtol(str[13],NULL,0);
  4290. ms->val[2] = (int)strtol(str[14],NULL,0);
  4291. ms->val[3] = (int)strtol(str[15],NULL,0);
  4292. ms->val[4] = (int)strtol(str[16],NULL,0);
  4293. if(ms->skill_id == NPC_EMOTION && mob_id > 0 &&
  4294. ms->val[1] == mob_db(mob_id)->status.mode)
  4295. {
  4296. ms->val[1] = 0;
  4297. ms->val[4] = 1; //request to return mode to normal.
  4298. }
  4299. if(ms->skill_id == NPC_EMOTION_ON && mob_id > 0 && ms->val[1])
  4300. { //Adds a mode to the mob.
  4301. //Remove aggressive mode when the new mob type is passive.
  4302. if (!(ms->val[1]&MD_AGGRESSIVE))
  4303. ms->val[3] |= MD_AGGRESSIVE;
  4304. ms->val[2] |= ms->val[1]; //Add the new mode.
  4305. ms->val[1] = 0; //Do not "set" it.
  4306. }
  4307. if(*str[17])
  4308. ms->emotion = atoi(str[17]);
  4309. else
  4310. ms->emotion = -1;
  4311. if(str[18] != NULL && mob_chat(atoi(str[18]))!=NULL)
  4312. ms->msg_id = atoi(str[18]);
  4313. else
  4314. ms->msg_id = 0;
  4315. skill->count++;
  4316. if (!skill->mob_id) { // Insert new entry
  4317. skill->mob_id = mob_id;
  4318. idb_put(mob_skill_db, mob_id, skill);
  4319. }
  4320. return true;
  4321. }
  4322. /*==========================================
  4323. * mob_skill_db.txt reading
  4324. *------------------------------------------*/
  4325. static void mob_readskilldb(const char* basedir, bool silent) {
  4326. if( battle_config.mob_skill_rate == 0 ) {
  4327. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  4328. return;
  4329. }
  4330. sv_readdb(basedir, "mob_skill_db.txt", ',', 19, 19, -1, &mob_parse_row_mobskilldb, silent);
  4331. }
  4332. /**
  4333. * mob_skill_db table reading [CalciumKid]
  4334. * not overly sure if this is all correct
  4335. * seems to work though...
  4336. */
  4337. static int mob_read_sqlskilldb(void)
  4338. {
  4339. const char* mob_skill_db_name[] = {
  4340. mob_skill_table,
  4341. mob_skill2_table };
  4342. int fi;
  4343. if( battle_config.mob_skill_rate == 0 ) {
  4344. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  4345. return 0;
  4346. }
  4347. for( fi = 0; fi < ARRAYLENGTH(mob_skill_db_name); ++fi ) {
  4348. uint32 lines = 0, count = 0;
  4349. // retrieve all rows from the mob skill database
  4350. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT * FROM `%s`", mob_skill_db_name[fi]) ) {
  4351. Sql_ShowDebug(mmysql_handle);
  4352. continue;
  4353. }
  4354. // process rows one by one
  4355. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  4356. // wrap the result into a TXT-compatible format
  4357. char* str[19];
  4358. char dummy[255] = "";
  4359. int i;
  4360. ++lines;
  4361. for( i = 0; i < 19; ++i )
  4362. {
  4363. Sql_GetData(mmysql_handle, i, &str[i], NULL);
  4364. if( str[i] == NULL )
  4365. str[i] = dummy; // get rid of NULL columns
  4366. }
  4367. if (!mob_parse_row_mobskilldb(str, 19, count))
  4368. continue;
  4369. count++;
  4370. }
  4371. // free the query result
  4372. Sql_FreeResult(mmysql_handle);
  4373. ShowStatus("Done reading '" CL_WHITE "%u" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_skill_db_name[fi]);
  4374. }
  4375. return 0;
  4376. }
  4377. /*==========================================
  4378. * mob_race2_db.txt reading
  4379. *------------------------------------------*/
  4380. static bool mob_readdb_race2(char* fields[], int columns, int current)
  4381. {
  4382. int race, i;
  4383. if( ISDIGIT(fields[0][0]) )
  4384. race = atoi(fields[0]);
  4385. else if( !script_get_constant( fields[0], &race ) ){
  4386. ShowWarning("mob_readdb_race2: Unknown race2 constant \"%s\".\n", fields[0]);
  4387. return false;
  4388. }
  4389. if (!CHK_RACE2(race)) {
  4390. ShowWarning("mob_readdb_race2: Unknown race2 %d.\n", race);
  4391. return false;
  4392. }
  4393. for(i = 1; i < columns; i++) {
  4394. int mob_id = atoi(fields[i]);
  4395. struct mob_db* db = mob_db(mob_id);
  4396. if (db == NULL) {
  4397. ShowWarning("mob_readdb_race2: Unknown mob id %d for race2 %d.\n", mob_id, race);
  4398. continue;
  4399. }
  4400. db->race2 = (enum e_race2)race;
  4401. // Apply Aegis Class
  4402. if (race == RC2_GUARDIAN)
  4403. db->status.class_ = CLASS_GUARDIAN;
  4404. else if (race == RC2_BATTLEFIELD)
  4405. db->status.class_ = CLASS_BATTLEFIELD;
  4406. }
  4407. return true;
  4408. }
  4409. /**
  4410. * Read mob_item_ratio.txt
  4411. */
  4412. static bool mob_readdb_itemratio(char* str[], int columns, int current)
  4413. {
  4414. unsigned short nameid;
  4415. int ratio, i;
  4416. struct s_mob_item_drop_ratio *item_ratio;
  4417. nameid = atoi(str[0]);
  4418. if (itemdb_exists(nameid) == NULL) {
  4419. ShowWarning("mob_readdb_itemratio: Invalid item id %hu.\n", nameid);
  4420. return false;
  4421. }
  4422. ratio = atoi(str[1]);
  4423. if (!(item_ratio = (struct s_mob_item_drop_ratio *)idb_get(mob_item_drop_ratio,nameid)))
  4424. CREATE(item_ratio, struct s_mob_item_drop_ratio, 1);
  4425. item_ratio->drop_ratio = ratio;
  4426. memset(item_ratio->mob_id, 0, sizeof(item_ratio->mob_id));
  4427. for (i = 0; i < columns-2; i++) {
  4428. uint16 mob_id = atoi(str[i+2]);
  4429. if (mob_db(mob_id) == NULL)
  4430. ShowError("mob_readdb_itemratio: Invalid monster with ID %hu (Item:%hu Col:%d).\n", mob_id, nameid, columns);
  4431. else
  4432. item_ratio->mob_id[i] = atoi(str[i+2]);
  4433. }
  4434. if (!item_ratio->nameid) {
  4435. item_ratio->nameid = nameid;
  4436. idb_put(mob_item_drop_ratio, nameid, item_ratio);
  4437. }
  4438. return true;
  4439. }
  4440. /**
  4441. * Read additional monster drop from db file
  4442. * @author [Cydh]
  4443. **/
  4444. static bool mob_readdb_drop(char* str[], int columns, int current) {
  4445. unsigned short mobid, nameid;
  4446. int rate, i, size, flag = 0;
  4447. struct mob_db *mob;
  4448. struct s_mob_drop *drop;
  4449. mobid = atoi(str[0]);
  4450. if ((mob = mob_db(mobid)) == NULL) {
  4451. ShowError("mob_readdb_drop: Invalid monster ID %s.\n", str[0]);
  4452. return false;
  4453. }
  4454. nameid = atoi(str[1]);
  4455. if (itemdb_exists(nameid) == NULL) {
  4456. ShowWarning("mob_readdb_drop: Invalid item ID %s.\n", str[1]);
  4457. return false;
  4458. }
  4459. rate = atoi(str[2]);
  4460. if (columns > 4 && (flag = atoi(str[4])) == 2) {
  4461. drop = mob->mvpitem;
  4462. size = ARRAYLENGTH(mob->mvpitem);
  4463. }
  4464. else {
  4465. drop = mob->dropitem;
  4466. size = ARRAYLENGTH(mob->dropitem);
  4467. }
  4468. if (rate == 0) {
  4469. for (i = 0; i < size; i++) {
  4470. if (drop[i].nameid == nameid) {
  4471. memset(&drop[i], 0, sizeof(struct s_mob_drop));
  4472. ShowInfo("mob_readdb_drop: Removed item '%hu' from monster '%hu'.\n", nameid, mobid);
  4473. return true;
  4474. }
  4475. }
  4476. }
  4477. else {
  4478. ARR_FIND(0, size, i, drop[i].nameid == nameid);
  4479. if (i == size) { // Item is not dropped at all (search all item slots)
  4480. ARR_FIND(0, size, i, drop[i].nameid == 0);
  4481. if (i == size) { // No empty slots
  4482. ShowError("mob_readdb_drop: Cannot add item '%hu' to monster '%hu'. Max drop reached (%d).\n", nameid, mobid, size);
  4483. return true;
  4484. }
  4485. }
  4486. drop[i].nameid = nameid;
  4487. drop[i].p = rate;
  4488. drop[i].steal_protected = (flag) ? 1 : 0;
  4489. drop[i].randomopt_group = 0;
  4490. if (columns > 3) {
  4491. int randomopt_group = -1;
  4492. if (!script_get_constant(trim(str[3]), &randomopt_group)) {
  4493. ShowError("mob_readdb_drop: Invalid 'randopt_groupid' '%s' for monster '%hu'.\n", str[3], mobid);
  4494. return false;
  4495. }
  4496. if (randomopt_group == RDMOPTG_None)
  4497. return true;
  4498. if (!itemdb_randomopt_group_exists(randomopt_group)) {
  4499. ShowError("mob_readdb_drop: 'randopt_groupid' '%s' cannot be found in DB for monster '%hu'.\n", str[3], mobid);
  4500. return false;
  4501. }
  4502. drop[i].randomopt_group = randomopt_group;
  4503. }
  4504. }
  4505. return true;
  4506. }
  4507. /**
  4508. * Free drop ratio data
  4509. **/
  4510. static int mob_item_drop_ratio_free(DBKey key, DBData *data, va_list ap) {
  4511. struct s_mob_item_drop_ratio *item_ratio = (struct s_mob_item_drop_ratio *)db_data2ptr(data);
  4512. aFree(item_ratio);
  4513. return 0;
  4514. }
  4515. /**
  4516. * Adjust drop ratio for each monster
  4517. **/
  4518. static void mob_drop_ratio_adjust(void){
  4519. for( auto &pair : mob_db_data ){
  4520. struct mob_db *mob;
  4521. struct item_data *id;
  4522. unsigned short nameid;
  4523. int j, rate, rate_adjust = 0, mob_id;
  4524. mob_id = pair.first;
  4525. mob = &pair.second;
  4526. if( mob_is_clone( mob_id ) ){
  4527. continue;
  4528. }
  4529. for( j = 0; j < MAX_MVP_DROP_TOTAL; j++ ){
  4530. nameid = mob->mvpitem[j].nameid;
  4531. rate = mob->mvpitem[j].p;
  4532. if( nameid == 0 || rate == 0 ){
  4533. continue;
  4534. }
  4535. rate_adjust = battle_config.item_rate_mvp;
  4536. // Adjust the rate if there is an entry in mob_item_ratio
  4537. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  4538. // Adjust rate with given algorithms
  4539. rate = mob_drop_adjust( rate, rate_adjust, battle_config.item_drop_mvp_min, battle_config.item_drop_mvp_max );
  4540. // calculate and store Max available drop chance of the MVP item
  4541. if( rate ){
  4542. id = itemdb_search( nameid );
  4543. // Item is not known anymore(should never happen)
  4544. if( !id ){
  4545. ShowWarning( "Monster \"%s\"(id:%hu) is dropping an unknown item(id: %d)\n", mob->name, mob_id, nameid );
  4546. mob->mvpitem[j].nameid = 0;
  4547. mob->mvpitem[j].p = 0;
  4548. continue;
  4549. }
  4550. if( id->maxchance == -1 || ( id->maxchance < rate/10 + 1 ) ){
  4551. // item has bigger drop chance or sold in shops
  4552. id->maxchance = rate/10 + 1; // reduce MVP drop info to not spoil common drop rate
  4553. }
  4554. }
  4555. mob->mvpitem[j].p = rate;
  4556. }
  4557. for( j = 0; j < MAX_MOB_DROP_TOTAL; j++ ){
  4558. unsigned short ratemin, ratemax;
  4559. bool is_treasurechest;
  4560. nameid = mob->dropitem[j].nameid;
  4561. rate = mob->dropitem[j].p;
  4562. if( nameid == 0 || rate == 0 ){
  4563. continue;
  4564. }
  4565. id = itemdb_search( nameid );
  4566. // Item is not known anymore(should never happen)
  4567. if( !id ){
  4568. ShowWarning( "Monster \"%s\"(id:%hu) is dropping an unknown item(id: %d)\n", mob->name, mob_id, nameid );
  4569. mob->dropitem[j].nameid = 0;
  4570. mob->dropitem[j].p = 0;
  4571. continue;
  4572. }
  4573. if( battle_config.drop_rateincrease && rate < 5000 ){
  4574. rate++;
  4575. }
  4576. // Treasure box drop rates [Skotlex]
  4577. if (mob->race2 == RC2_TREASURE) {
  4578. is_treasurechest = true;
  4579. rate_adjust = battle_config.item_rate_treasure;
  4580. ratemin = battle_config.item_drop_treasure_min;
  4581. ratemax = battle_config.item_drop_treasure_max;
  4582. } else {
  4583. bool is_mvp = status_has_mode(&mob->status,MD_MVP);
  4584. bool is_boss = (mob->status.class_ == CLASS_BOSS);
  4585. is_treasurechest = false;
  4586. // Added suport to restrict normal drops of MVP's [Reddozen]
  4587. switch( id->type ){
  4588. case IT_HEALING:
  4589. rate_adjust = is_mvp ? battle_config.item_rate_heal_mvp : (is_boss ? battle_config.item_rate_heal_boss : battle_config.item_rate_heal);
  4590. ratemin = battle_config.item_drop_heal_min;
  4591. ratemax = battle_config.item_drop_heal_max;
  4592. break;
  4593. case IT_USABLE:
  4594. case IT_CASH:
  4595. rate_adjust = is_mvp ? battle_config.item_rate_use_mvp : (is_boss ? battle_config.item_rate_use_boss : battle_config.item_rate_use);
  4596. ratemin = battle_config.item_drop_use_min;
  4597. ratemax = battle_config.item_drop_use_max;
  4598. break;
  4599. case IT_WEAPON:
  4600. case IT_ARMOR:
  4601. case IT_PETARMOR:
  4602. rate_adjust = is_mvp ? battle_config.item_rate_equip_mvp : (is_boss ? battle_config.item_rate_equip_boss : battle_config.item_rate_equip);
  4603. ratemin = battle_config.item_drop_equip_min;
  4604. ratemax = battle_config.item_drop_equip_max;
  4605. break;
  4606. case IT_CARD:
  4607. rate_adjust = is_mvp ? battle_config.item_rate_card_mvp : (is_boss ? battle_config.item_rate_card_boss : battle_config.item_rate_card);
  4608. ratemin = battle_config.item_drop_card_min;
  4609. ratemax = battle_config.item_drop_card_max;
  4610. break;
  4611. default:
  4612. rate_adjust = is_mvp ? battle_config.item_rate_common_mvp : (is_boss ? battle_config.item_rate_common_boss : battle_config.item_rate_common);
  4613. ratemin = battle_config.item_drop_common_min;
  4614. ratemax = battle_config.item_drop_common_max;
  4615. break;
  4616. }
  4617. }
  4618. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  4619. rate = mob_drop_adjust( rate, rate_adjust, ratemin, ratemax );
  4620. // calculate and store Max available drop chance of the item
  4621. // but skip treasure chests.
  4622. if( rate && !is_treasurechest ){
  4623. unsigned short k;
  4624. if( id->maxchance == -1 || ( id->maxchance < rate ) ){
  4625. id->maxchance = rate; // item has bigger drop chance or sold in shops
  4626. }
  4627. for( k = 0; k < MAX_SEARCH; k++ ){
  4628. if( id->mob[k].chance <= rate ){
  4629. break;
  4630. }
  4631. }
  4632. if( k != MAX_SEARCH ){
  4633. if( id->mob[k].id != mob_id ){
  4634. memmove( &id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]) );
  4635. }
  4636. id->mob[k].chance = rate;
  4637. id->mob[k].id = mob_id;
  4638. }
  4639. }
  4640. mob->dropitem[j].p = rate;
  4641. }
  4642. }
  4643. // Now that we are done we can delete the stored item ratios
  4644. mob_item_drop_ratio->clear( mob_item_drop_ratio, mob_item_drop_ratio_free );
  4645. }
  4646. /**
  4647. * Copy skill from DB to monster
  4648. * @param mob Monster DB entry
  4649. * @param skill Monster skill entries
  4650. **/
  4651. static void mob_skill_db_set_single_sub(struct mob_db *mob, struct s_mob_skill *skill) {
  4652. uint8 i;
  4653. nullpo_retv(mob);
  4654. nullpo_retv(skill);
  4655. for (i = 0; mob->maxskill < MAX_MOBSKILL && i < skill->count; i++) {
  4656. mob->skill[mob->maxskill++] = skill->skill[i];
  4657. }
  4658. if (i < skill->count)
  4659. ShowWarning("Monster '%s' (%d, src:%d) reaches max skill limit %d. Ignores '%d' skills left.\n", mob->sprite, mob->vd.class_, skill->mob_id, MAX_MOBSKILL, skill->count-i);
  4660. }
  4661. /**
  4662. * Check the skill & monster id before put the skills
  4663. * @param skill
  4664. **/
  4665. static void mob_skill_db_set_single(struct s_mob_skill *skill) {
  4666. nullpo_retv(skill);
  4667. // Specific monster
  4668. if (skill->mob_id >= 0) {
  4669. struct mob_db *mob = mob_db(skill->mob_id);
  4670. if (mob != NULL)
  4671. mob_skill_db_set_single_sub(mob, skill);
  4672. }
  4673. // Global skill
  4674. else {
  4675. uint16 id = skill->mob_id;
  4676. id *= -1;
  4677. for( auto &pair : mob_db_data ){
  4678. if ( mob_is_clone(pair.first) ){
  4679. continue;
  4680. }
  4681. if ( (!(id&1) && status_has_mode(&pair.second.status,MD_STATUS_IMMUNE)) // Bosses
  4682. || (!(id&2) && !status_has_mode(&pair.second.status,MD_STATUS_IMMUNE)) // Normal monsters
  4683. )
  4684. continue;
  4685. mob_skill_db_set_single_sub(&pair.second, skill);
  4686. }
  4687. }
  4688. }
  4689. /**
  4690. * Free monster skill data
  4691. **/
  4692. static int mob_skill_db_free(DBKey key, DBData *data, va_list ap) {
  4693. struct s_mob_skill *skill = (struct s_mob_skill *)db_data2ptr(data);
  4694. if (skill)
  4695. aFree(skill);
  4696. return 0;
  4697. }
  4698. /**
  4699. * Free random summon data
  4700. **/
  4701. static int mob_summon_db_free(DBKey key, DBData *data, va_list ap) {
  4702. struct s_randomsummon_group *msummon = (struct s_randomsummon_group *)db_data2ptr(data);
  4703. if (msummon) {
  4704. if (msummon->list) {
  4705. aFree(msummon->list);
  4706. msummon->list = NULL;
  4707. msummon->count = 0;
  4708. }
  4709. aFree(msummon);
  4710. msummon = NULL;
  4711. }
  4712. return 0;
  4713. }
  4714. /**
  4715. * Set monster skills
  4716. **/
  4717. static void mob_skill_db_set(void) {
  4718. DBIterator *iter = db_iterator(mob_skill_db);
  4719. struct s_mob_skill *skill = NULL;
  4720. for (skill = (struct s_mob_skill *)dbi_first(iter); dbi_exists(iter); skill = (struct s_mob_skill *)dbi_next(iter)) {
  4721. mob_skill_db_set_single(skill);
  4722. }
  4723. dbi_destroy(iter);
  4724. //ShowStatus("Set skills to '%d' monsters.\n", db_size(mob_skill_db));
  4725. mob_skill_db->clear(mob_skill_db, mob_skill_db_free);
  4726. }
  4727. /**
  4728. * read all mob-related databases
  4729. */
  4730. static void mob_load(void)
  4731. {
  4732. const char* dbsubpath[] = {
  4733. "",
  4734. "/" DBIMPORT,
  4735. };
  4736. // First we parse all the possible monsters to add additional data in the second loop
  4737. if( db_use_sqldbs ){
  4738. mob_read_sqldb();
  4739. mob_read_sqlskilldb();
  4740. }else{
  4741. for(int i = 0; i < ARRAYLENGTH(dbsubpath); i++){
  4742. int n2 = strlen(db_path)+strlen(DBPATH)+strlen(dbsubpath[i])+1;
  4743. char* dbsubpath2 = (char*)aMalloc(n2+1);
  4744. bool silent = i > 0;
  4745. if( i == 0 ) {
  4746. safesnprintf(dbsubpath2,n2,"%s/%s%s",db_path,DBPATH,dbsubpath[i]);
  4747. } else {
  4748. safesnprintf(dbsubpath2,n2,"%s%s",db_path,dbsubpath[i]);
  4749. }
  4750. sv_readdb(dbsubpath2, "mob_db.txt", ',', 31+2*MAX_MVP_DROP+2*MAX_MOB_DROP, 31+2*MAX_MVP_DROP+2*MAX_MOB_DROP, -1, &mob_readdb_sub, silent);
  4751. aFree(dbsubpath2);
  4752. }
  4753. }
  4754. for(int i = 0; i < ARRAYLENGTH(dbsubpath); i++){
  4755. int n1 = strlen(db_path)+strlen(dbsubpath[i])+1;
  4756. int n2 = strlen(db_path)+strlen(DBPATH)+strlen(dbsubpath[i])+1;
  4757. char* dbsubpath1 = (char*)aMalloc(n1+1);
  4758. char* dbsubpath2 = (char*)aMalloc(n2+1);
  4759. bool silent = i > 0;
  4760. if(i==0) {
  4761. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  4762. safesnprintf(dbsubpath2,n2,"%s/%s%s",db_path,DBPATH,dbsubpath[i]);
  4763. } else {
  4764. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  4765. safesnprintf(dbsubpath2,n1,"%s%s",db_path,dbsubpath[i]);
  4766. }
  4767. if( !db_use_sqldbs ){
  4768. mob_readskilldb(dbsubpath2, silent);
  4769. }
  4770. sv_readdb(dbsubpath2, "mob_race2_db.txt", ',', 2, MAX_RACE2_MOBS, -1, &mob_readdb_race2, silent);
  4771. sv_readdb(dbsubpath1, "mob_item_ratio.txt", ',', 2, 2+MAX_ITEMRATIO_MOBS, -1, &mob_readdb_itemratio, silent);
  4772. sv_readdb(dbsubpath1, "mob_chat_db.txt", '#', 3, 3, -1, &mob_parse_row_chatdb, silent);
  4773. sv_readdb(dbsubpath2, "mob_random_db.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4774. sv_readdb(dbsubpath2, "mob_branch.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4775. sv_readdb(dbsubpath2, "mob_poring.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4776. sv_readdb(dbsubpath2, "mob_boss.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4777. sv_readdb(dbsubpath1, "mob_pouch.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4778. sv_readdb(dbsubpath1, "mob_mission.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4779. sv_readdb(dbsubpath1, "mob_classchange.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  4780. sv_readdb(dbsubpath2, "mob_drop.txt", ',', 3, 5, -1, &mob_readdb_drop, silent);
  4781. aFree(dbsubpath1);
  4782. aFree(dbsubpath2);
  4783. }
  4784. mob_avail_db.load();
  4785. mob_drop_ratio_adjust();
  4786. mob_skill_db_set();
  4787. }
  4788. /**
  4789. * Initialize monster data
  4790. */
  4791. void mob_db_load(bool is_reload){
  4792. if( !is_reload ) {
  4793. // on mobdbreload it's not neccessary to execute this
  4794. // item ers needs to be allocated only once
  4795. item_drop_ers = ers_new(sizeof(struct item_drop),"mob.cpp::item_drop_ers",ERS_OPT_CLEAN);
  4796. item_drop_list_ers = ers_new(sizeof(struct item_drop_list),"mob.cpp::item_drop_list_ers",ERS_OPT_NONE);
  4797. }
  4798. mob_item_drop_ratio = idb_alloc(DB_OPT_BASE);
  4799. mob_skill_db = idb_alloc(DB_OPT_BASE);
  4800. mob_summon_db = idb_alloc(DB_OPT_BASE);
  4801. mob_load();
  4802. }
  4803. /**
  4804. * Re-link monster drop data with item data
  4805. * Fixes the need of a @reloadmobdb after a @reloaditemdb
  4806. * @author Epoque
  4807. */
  4808. void mob_reload_itemmob_data(void) {
  4809. for( auto const &pair : mob_db_data ){
  4810. int d, k;
  4811. if( mob_is_clone( pair.first ) ){
  4812. continue;
  4813. }
  4814. for(d = 0; d < MAX_MOB_DROP_TOTAL; d++) {
  4815. struct item_data *id;
  4816. if( !pair.second.dropitem[d].nameid )
  4817. continue;
  4818. id = itemdb_search(pair.second.dropitem[d].nameid);
  4819. for (k = 0; k < MAX_SEARCH; k++) {
  4820. if (id->mob[k].chance <= pair.second.dropitem[d].p)
  4821. break;
  4822. }
  4823. if (k == MAX_SEARCH)
  4824. continue;
  4825. if (id->mob[k].id != pair.first)
  4826. memmove(&id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]));
  4827. id->mob[k].chance = pair.second.dropitem[d].p;
  4828. id->mob[k].id = pair.first;
  4829. }
  4830. }
  4831. }
  4832. /**
  4833. * Apply the proper view data on monsters during mob_db reload.
  4834. * @param md: Mob to adjust
  4835. * @param args: va_list of arguments
  4836. * @return 0
  4837. */
  4838. static int mob_reload_sub( struct mob_data *md, va_list args ){
  4839. // Relink the mob to the new database entry
  4840. md->db = mob_db(md->mob_id);
  4841. // Recalculate the monster status based on the new data
  4842. status_calc_mob(md, SCO_NONE);
  4843. // If the view data was not overwritten manually
  4844. if( !md->vd_changed ){
  4845. // Get the new view data from the mob database
  4846. md->vd = mob_get_viewdata(md->mob_id);
  4847. // If they are spawned right now
  4848. if( md->bl.prev != NULL ){
  4849. // Respawn all mobs on client side so that they are displayed correctly(if their view id changed)
  4850. clif_clearunit_area(&md->bl, CLR_OUTSIGHT);
  4851. clif_spawn(&md->bl);
  4852. }
  4853. }
  4854. return 0;
  4855. }
  4856. /**
  4857. * Apply the proper view data on NPCs during mob_db reload.
  4858. * @param md: NPC to adjust
  4859. * @param args: va_list of arguments
  4860. * @return 0
  4861. */
  4862. static int mob_reload_sub_npc( struct npc_data *nd, va_list args ){
  4863. // If the view data points to a mob
  4864. if( mobdb_checkid(nd->class_) ){
  4865. struct view_data *vd = mob_get_viewdata(nd->class_);
  4866. if (vd) // Get the new view data from the mob database
  4867. memcpy(&nd->vd, vd, sizeof(struct view_data));
  4868. if (nd->bl.prev) // If they are spawned right now
  4869. unit_refresh(&nd->bl); // Respawn all NPCs on client side so that they are displayed correctly(if their view id changed)
  4870. }
  4871. return 0;
  4872. }
  4873. /**
  4874. * Reload monster data
  4875. */
  4876. void mob_reload(void) {
  4877. do_final_mob(true);
  4878. mob_db_load(true);
  4879. map_foreachmob(mob_reload_sub);
  4880. map_foreachnpc(mob_reload_sub_npc);
  4881. }
  4882. /**
  4883. * Clear spawn data for all monsters
  4884. */
  4885. void mob_clear_spawninfo()
  4886. { //Clears spawn related information for a script reload.
  4887. mob_spawn_data.clear();
  4888. }
  4889. /*==========================================
  4890. * Circumference initialization of mob
  4891. *------------------------------------------*/
  4892. void do_init_mob(void){
  4893. mob_db_load(false);
  4894. add_timer_func_list(mob_delayspawn,"mob_delayspawn");
  4895. add_timer_func_list(mob_delay_item_drop,"mob_delay_item_drop");
  4896. add_timer_func_list(mob_ai_hard,"mob_ai_hard");
  4897. add_timer_func_list(mob_ai_lazy,"mob_ai_lazy");
  4898. add_timer_func_list(mob_timer_delete,"mob_timer_delete");
  4899. add_timer_func_list(mob_spawn_guardian_sub,"mob_spawn_guardian_sub");
  4900. add_timer_func_list(mob_respawn,"mob_respawn");
  4901. add_timer_func_list(mvptomb_delayspawn,"mvptomb_delayspawn");
  4902. add_timer_interval(gettick()+MIN_MOBTHINKTIME,mob_ai_hard,0,0,MIN_MOBTHINKTIME);
  4903. add_timer_interval(gettick()+MIN_MOBTHINKTIME*10,mob_ai_lazy,0,0,MIN_MOBTHINKTIME*10);
  4904. }
  4905. /*==========================================
  4906. * Clean memory usage.
  4907. *------------------------------------------*/
  4908. void do_final_mob(bool is_reload){
  4909. mob_db_data.clear();
  4910. mob_chat_db.clear();
  4911. mob_item_drop_ratio->destroy(mob_item_drop_ratio,mob_item_drop_ratio_free);
  4912. mob_skill_db->destroy(mob_skill_db, mob_skill_db_free);
  4913. mob_summon_db->destroy(mob_summon_db, mob_summon_db_free);
  4914. if( !is_reload ) {
  4915. ers_destroy(item_drop_ers);
  4916. ers_destroy(item_drop_list_ers);
  4917. }
  4918. }