mob.cpp 174 KB

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