mob.c 156 KB

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