root/src/map/mob.c @ 11

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