mob.cpp 206 KB

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