mob.cpp 202 KB

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