PageRenderTime 198ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/src/map/mob.c

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