mob.c 140 KB

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