]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/monsters/sv_monsters.qc
483f6a1ac31896a48f4248224bf55c5fad741efb
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / monsters / sv_monsters.qc
1 #include "sv_monsters.qh"
2
3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/items/_mod.qh>
6 #include <common/mapobjects/teleporters.qh>
7 #include <common/mapobjects/triggers.qh>
8 #include <common/monsters/all.qh>
9 #include <common/mutators/mutator/nades/nades.qh>
10 #include <common/mutators/mutator/status_effects/_mod.qh>
11 #include <common/physics/movelib.qh>
12 #include <common/stats.qh>
13 #include <common/teams.qh>
14 #include <common/turrets/sv_turrets.qh>
15 #include <common/turrets/util.qh>
16 #include <common/util.qh>
17 #include <common/vehicles/all.qh>
18 #include <common/weapons/_all.qh>
19 #include <common/weapons/_mod.qh>
20 #include <lib/csqcmodel/sv_model.qh>
21 #include <lib/warpzone/common.qh>
22 #include <server/campaign.qh>
23 #include <server/cheats.qh>
24 #include <server/client.qh>
25 #include <server/command/_mod.qh>
26 #include <server/damage.qh>
27 #include <server/items/items.qh>
28 #include <server/mutators/_mod.qh>
29 #include <server/round_handler.qh>
30 #include <server/steerlib.qh>
31 #include <server/weapons/_mod.qh>
32
33 void monsters_setstatus(entity this)
34 {
35         STAT(MONSTERS_TOTAL, this) = monsters_total;
36         STAT(MONSTERS_KILLED, this) = monsters_killed;
37 }
38
39 void monster_dropitem(entity this, entity attacker)
40 {
41         if(!this.candrop || !this.monster_loot)
42                 return;
43
44         vector org = CENTER_OR_VIEWOFS(this);
45         entity e = spawn();
46         Item_SetLoot(e, true);
47         e.spawnfunc_checked = true;
48
49         e.monster_loot = this.monster_loot;
50
51         MUTATOR_CALLHOOK(MonsterDropItem, this, e, attacker);
52         e = M_ARGV(1, entity);
53
54         if(e && e.monster_loot)
55         {
56                 e.noalign = true;
57                 StartItem(e, e.monster_loot);
58                 e.gravity = 1;
59                 setorigin(e, org);
60                 e.velocity = randomvec() * 175 + '0 0 325';
61                 e.item_spawnshieldtime = time + 0.7;
62                 SUB_SetFade(e, time + autocvar_g_monsters_drop_time, 1);
63         }
64 }
65
66 bool monster_facing(entity this, entity targ)
67 {
68         // relies on target having an origin
69         makevectors(this.angles);
70         vector targ_org = targ.origin, my_org = this.origin;
71         if(autocvar_g_monsters_target_infront_2d)
72         {
73                 targ_org = vec2(targ_org);
74                 my_org = vec2(my_org);
75         }
76         float dot = normalize(targ_org - my_org) * v_forward;
77
78         return !(dot <= autocvar_g_monsters_target_infront_range);
79 }
80
81 void monster_makevectors(entity this, entity targ)
82 {
83         if(IS_MONSTER(this))
84         {
85                 vector v = targ.origin + (targ.mins + targ.maxs) * 0.5;
86                 this.v_angle = vectoangles(v - (this.origin + this.view_ofs));
87                 this.v_angle_x = -this.v_angle_x;
88         }
89
90         makevectors(this.v_angle);
91 }
92
93 // ===============
94 // Target handling
95 // ===============
96
97 bool Monster_ValidTarget(entity this, entity targ, bool skipfacing)
98 {
99         // ensure we're not checking nonexistent monster/target
100         if(!this || !targ) { return false; }
101
102         if((targ == this)
103         || (IS_VEHICLE(targ) && !(this.monsterdef.spawnflags & MON_FLAG_RANGED)) // melee vs vehicle is useless
104         || (time < game_starttime) // monsters do nothing before match has started
105         || (targ.takedamage == DAMAGE_NO)
106         || (game_stopped)
107         || (IS_SPEC(targ) || IS_OBSERVER(targ)) // don't attack spectators
108         || (!IS_VEHICLE(targ) && (IS_DEAD(targ) || IS_DEAD(this) || GetResource(targ, RES_HEALTH) <= 0 || GetResource(this, RES_HEALTH) <= 0))
109         || (this.monster_follow == targ || targ.monster_follow == this)
110         || (!IS_VEHICLE(targ) && (targ.flags & FL_NOTARGET))
111         || (!autocvar_g_monsters_typefrag && PHYS_INPUT_BUTTON_CHAT(targ))
112         || (SAME_TEAM(targ, this))
113         || (STAT(FROZEN, targ))
114         || (targ.alpha != 0 && targ.alpha < 0.5)
115         || (autocvar_g_monsters_lineofsight && !checkpvs(this.origin + this.view_ofs, targ)) // enemy cannot be seen
116         || (MUTATOR_CALLHOOK(MonsterValidTarget, this, targ))
117         )
118         {
119                 // if any of the above checks fail, target is not valid
120                 return false;
121         }
122
123         vector targ_origin = ((targ.absmin + targ.absmax) * 0.5);
124         traceline(this.origin + this.view_ofs, targ_origin, MOVE_NOMONSTERS, this); // TODO: maybe we can rely a bit on PVS data instead?
125
126         if(trace_fraction < 1 && trace_ent != targ)
127                 return false; // solid
128
129         if(!skipfacing && (autocvar_g_monsters_target_infront || (this.spawnflags & MONSTERFLAG_INFRONT)))
130         if(this.enemy != targ)
131         {
132                 if(!monster_facing(this, targ))
133                         return false;
134         }
135
136         return true; // this target is valid!
137 }
138
139 entity Monster_FindTarget(entity this)
140 {
141         if(MUTATOR_CALLHOOK(MonsterFindTarget)) { return this.enemy; } // Handled by a mutator
142
143         entity closest_target = NULL;
144         vector my_center = CENTER_OR_VIEWOFS(this);
145
146         // find the closest acceptable target to pass to
147         IL_EACH(g_monster_targets, it.monster_attack,
148         {
149                 float trange = this.target_range;
150                 if(PHYS_INPUT_BUTTON_CROUCH(it))
151                         trange *= 0.75; // TODO cvar this
152                 vector theirmid = (it.absmin + it.absmax) * 0.5;
153                 if(vdist(theirmid - this.origin, >, trange))
154                         continue;
155                 if(!Monster_ValidTarget(this, it, false))
156                         continue;
157
158                 // if it's a player, use the view origin as reference (stolen from RadiusDamage functions in g_damage.qc)
159                 vector targ_center = CENTER_OR_VIEWOFS(it);
160
161                 if(closest_target)
162                 {
163                         vector closest_target_center = CENTER_OR_VIEWOFS(closest_target);
164                         if(vlen2(my_center - targ_center) < vlen2(my_center - closest_target_center))
165                                 { closest_target = it; }
166                 }
167                 else { closest_target = it; }
168         });
169
170         return closest_target;
171 }
172
173 void monster_setupcolors(entity this)
174 {
175         if(IS_PLAYER(this.realowner))
176                 this.colormap = this.realowner.colormap;
177         else if(teamplay && this.team)
178                 this.colormap = 1024 + (this.team - 1) * 17;
179         else
180         {
181                 if(this.monster_skill <= MONSTER_SKILL_EASY)
182                         this.colormap = 1126;
183                 else if(this.monster_skill <= MONSTER_SKILL_MEDIUM)
184                         this.colormap = 1075;
185                 else if(this.monster_skill <= MONSTER_SKILL_HARD)
186                         this.colormap = 1228;
187                 else if(this.monster_skill <= MONSTER_SKILL_INSANE)
188                         this.colormap = 1092;
189                 else if(this.monster_skill <= MONSTER_SKILL_NIGHTMARE)
190                         this.colormap = 1160;
191                 else
192                         this.colormap = 1024;
193         }
194
195         if(this.colormap > 0)
196                 this.glowmod = colormapPaletteColor(this.colormap & 0x0F, false);
197         else
198                 this.glowmod = '1 1 1';
199 }
200
201 void monster_changeteam(entity this, int newteam)
202 {
203         if(!teamplay) { return; }
204
205         this.team = newteam;
206         if(!this.monster_attack)
207                 IL_PUSH(g_monster_targets, this);
208         this.monster_attack = true; // new team, activate attacking
209         monster_setupcolors(this);
210
211         if(this.sprite)
212         {
213                 WaypointSprite_UpdateTeamRadar(this.sprite, RADARICON_DANGER, ((newteam) ? Team_ColorRGB(newteam) : '1 0 0'));
214
215                 this.sprite.team = newteam;
216                 this.sprite.SendFlags |= 1;
217         }
218 }
219
220 .void(entity) monster_delayedfunc;
221 void Monster_Delay_Action(entity this)
222 {
223         // TODO: maybe do check for facing here
224         if(Monster_ValidTarget(this.owner, this.owner.enemy, false))
225         {
226                 monster_makevectors(this.owner, this.owner.enemy);
227                 this.monster_delayedfunc(this.owner);
228         }
229
230         if(this.cnt > 1)
231         {
232                 this.cnt -= 1;
233                 setthink(this, Monster_Delay_Action);
234                 this.nextthink = time + this.count;
235         }
236         else
237         {
238                 setthink(this, SUB_Remove);
239                 this.nextthink = time;
240         }
241 }
242
243 void Monster_Delay(entity this, int repeat_count, float defer_amnt, void(entity) func)
244 {
245         // deferred attacking, checks if monster is still alive and target is still valid before attacking
246         entity e = new_pure(Monster_Delay);
247
248         setthink(e, Monster_Delay_Action);
249         e.nextthink = time + defer_amnt;
250         e.count = defer_amnt;
251         e.owner = this;
252         e.monster_delayedfunc = func;
253         e.cnt = repeat_count;
254 }
255
256
257 // ==============
258 // Monster sounds
259 // ==============
260
261 string get_monster_model_datafilename(string m, float sk, string fil)
262 {
263         if(m)
264                 m = strcat(m, "_");
265         else
266                 m = "models/monsters/*_";
267         if(sk >= 0)
268                 m = strcat(m, ftos(sk));
269         else
270                 m = strcat(m, "*");
271         return strcat(m, ".", fil);
272 }
273
274 void Monster_Sound_Precache(string f)
275 {
276         float fh;
277         string s;
278         fh = fopen(f, FILE_READ);
279         if(fh < 0)
280                 return;
281         while((s = fgets(fh)))
282         {
283                 if(tokenize_console(s) != 3)
284                 {
285                         //LOG_DEBUG("Invalid sound info line: ", s); // probably a comment, no need to spam warnings
286                         continue;
287                 }
288                 PrecacheGlobalSound(strcat(argv(1), " ", argv(2)));
289         }
290         fclose(fh);
291 }
292
293 void Monster_Sounds_Precache(entity this)
294 {
295         string m = this.monsterdef.m_model.model_str();
296         float globhandle, n, i;
297         string f;
298
299         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
300         if (globhandle < 0)
301                 return;
302         n = search_getsize(globhandle);
303         for (i = 0; i < n; ++i)
304         {
305                 //print(search_getfilename(globhandle, i), "\n");
306                 f = search_getfilename(globhandle, i);
307                 Monster_Sound_Precache(f);
308         }
309         search_end(globhandle);
310 }
311
312 void Monster_Sounds_Clear(entity this)
313 {
314 #define _MSOUND(m) strfree(this.monstersound_##m);
315         ALLMONSTERSOUNDS
316 #undef _MSOUND
317 }
318
319 .string Monster_Sound_SampleField(string type)
320 {
321         GetMonsterSoundSampleField_notFound = 0;
322         switch(type)
323         {
324 #define _MSOUND(m) case #m: return monstersound_##m;
325                 ALLMONSTERSOUNDS
326 #undef _MSOUND
327         }
328         GetMonsterSoundSampleField_notFound = 1;
329         return string_null;
330 }
331
332 bool Monster_Sounds_Load(entity this, string f, int first)
333 {
334         string s;
335         var .string field;
336         float fh = fopen(f, FILE_READ);
337         if(fh < 0)
338         {
339                 //LOG_DEBUG("Monster sound file not found: ", f); // no biggie, monster has no sounds, let's not spam it
340                 return false;
341         }
342         while((s = fgets(fh)))
343         {
344                 if(tokenize_console(s) != 3)
345                         continue;
346                 field = Monster_Sound_SampleField(argv(0));
347                 if(GetMonsterSoundSampleField_notFound)
348                         continue;
349                 strcpy(this.(field), strcat(argv(1), " ", argv(2)));
350         }
351         fclose(fh);
352         return true;
353 }
354
355 .int skin_for_monstersound;
356 void Monster_Sounds_Update(entity this)
357 {
358         if(this.skin == this.skin_for_monstersound) { return; }
359
360         this.skin_for_monstersound = this.skin;
361         Monster_Sounds_Clear(this);
362         if(!Monster_Sounds_Load(this, get_monster_model_datafilename(this.model, this.skin, "sounds"), 0))
363                 Monster_Sounds_Load(this, get_monster_model_datafilename(this.model, 0, "sounds"), 0);
364 }
365
366 void Monster_Sound(entity this, .string samplefield, float sound_delay, bool delaytoo, float chan)
367 {
368         if(!autocvar_g_monsters_sounds) { return; }
369
370         if(delaytoo)
371         if(time < this.msound_delay)
372                 return; // too early
373         string sample = this.(samplefield);
374         if (sample != "") sample = GlobalSound_sample(sample, random());
375         float myscale = ((this.scale) ? this.scale : 1); // safety net
376         sound7(this, chan, sample, VOL_BASE, ATTEN_NORM, 100 / myscale, 0);
377
378         this.msound_delay = time + sound_delay;
379 }
380
381
382 // =======================
383 // Monster attack handlers
384 // =======================
385
386 bool Monster_Attack_Melee(entity this, entity targ, float damg, vector anim, float er, float animtime, int deathtype, bool dostop)
387 {
388         if(dostop && IS_MONSTER(this)) { this.state = MONSTER_ATTACK_MELEE; }
389
390         setanim(this, anim, false, true, false);
391
392         if(this.animstate_endtime > time && IS_MONSTER(this))
393                 this.attack_finished_single[0] = this.anim_finished = this.animstate_endtime;
394         else
395                 this.attack_finished_single[0] = this.anim_finished = time + animtime;
396
397         traceline(this.origin + this.view_ofs, this.origin + v_forward * er, 0, this);
398
399         if(trace_ent.takedamage)
400                 Damage(trace_ent, this, this, damg * MONSTER_SKILLMOD(this), deathtype, DMG_NOWEP, trace_ent.origin, normalize(trace_ent.origin - this.origin));
401
402         return true;
403 }
404
405 bool Monster_Attack_Leap_Check(entity this, vector vel)
406 {
407         if(this.state && IS_MONSTER(this))
408                 return false; // already attacking
409         if(!IS_ONGROUND(this))
410                 return false; // not on the ground
411         if(GetResource(this, RES_HEALTH) <= 0 || IS_DEAD(this))
412                 return false; // called when dead?
413         if(time < this.attack_finished_single[0])
414                 return false; // still attacking
415
416         vector old = this.velocity;
417
418         this.velocity = vel;
419         tracetoss(this, this);
420         this.velocity = old;
421         if(trace_ent != this.enemy)
422                 return false;
423
424         return true;
425 }
426
427 bool Monster_Attack_Leap(entity this, vector anm, void(entity this, entity toucher) touchfunc, vector vel, float animtime)
428 {
429         if(!Monster_Attack_Leap_Check(this, vel))
430                 return false;
431
432         setanim(this, anm, false, true, false);
433
434         if(this.animstate_endtime > time && IS_MONSTER(this))
435                 this.attack_finished_single[0] = this.anim_finished = this.animstate_endtime;
436         else
437                 this.attack_finished_single[0] = this.anim_finished = time + animtime;
438
439         if(IS_MONSTER(this))
440                 this.state = MONSTER_ATTACK_RANGED;
441         settouch(this, touchfunc);
442         this.origin_z += 1;
443         this.velocity = vel;
444         UNSET_ONGROUND(this);
445
446         return true;
447 }
448
449 void Monster_Attack_Check(entity this, entity targ, .entity weaponentity)
450 {
451         int slot = weaponslot(weaponentity);
452
453         if((!this || !targ)
454         || (!this.monster_attackfunc)
455         || (game_stopped)
456         || (time < this.attack_finished_single[slot])
457         || ((autocvar_g_monsters_target_infront || (this.spawnflags & MONSTERFLAG_INFRONT)) && !monster_facing(this, targ))
458         ) { return; }
459
460         if(vdist(targ.origin - this.origin, <=, this.attack_range))
461         {
462                 monster_makevectors(this, targ);
463                 int attack_success = this.monster_attackfunc(MONSTER_ATTACK_MELEE, this, targ, weaponentity);
464                 if(attack_success == 1)
465                         Monster_Sound(this, monstersound_melee, 0, false, CH_VOICE);
466                 else if(attack_success > 0)
467                         return;
468         }
469
470         if(vdist(targ.origin - this.origin, >, this.attack_range))
471         {
472                 monster_makevectors(this, targ);
473                 int attack_success = this.monster_attackfunc(MONSTER_ATTACK_RANGED, this, targ, weaponentity);
474                 if(attack_success == 1)
475                         Monster_Sound(this, monstersound_melee, 0, false, CH_VOICE);
476                 else if(attack_success > 0)
477                         return;
478         }
479 }
480
481
482 // ======================
483 // Main monster functions
484 // ======================
485
486 void Monster_UpdateModel(entity this)
487 {
488         // assume some defaults
489         /*this.anim_idle   = animfixfps(this, '0 1 0.01', '0 0 0');
490         this.anim_walk   = animfixfps(this, '1 1 0.01', '0 0 0');
491         this.anim_run    = animfixfps(this, '2 1 0.01', '0 0 0');
492         this.anim_fire1  = animfixfps(this, '3 1 0.01', '0 0 0');
493         this.anim_fire2  = animfixfps(this, '4 1 0.01', '0 0 0');
494         this.anim_melee  = animfixfps(this, '5 1 0.01', '0 0 0');
495         this.anim_pain1  = animfixfps(this, '6 1 0.01', '0 0 0');
496         this.anim_pain2  = animfixfps(this, '7 1 0.01', '0 0 0');
497         this.anim_die1   = animfixfps(this, '8 1 0.01', '0 0 0');
498         this.anim_die2   = animfixfps(this, '9 1 0.01', '0 0 0');*/
499
500         // then get the real values
501         Monster mon = this.monsterdef;
502         mon.mr_anim(mon, this);
503 }
504
505 void Monster_Touch(entity this, entity toucher)
506 {
507         if(!toucher) { return; }
508
509         if(toucher.monster_attack && this.enemy != toucher && !IS_MONSTER(toucher) && time >= this.spawn_time)
510         if(Monster_ValidTarget(this, toucher, true))
511                 this.enemy = toucher;
512 }
513
514 void Monster_Miniboss_Check(entity this)
515 {
516         if(MUTATOR_CALLHOOK(MonsterCheckBossFlag, this))
517                 return;
518
519         float chance = random() * 100;
520
521         // g_monsters_miniboss_chance cvar or spawnflags 64 causes a monster to be a miniboss
522         if ((this.spawnflags & MONSTERFLAG_MINIBOSS) || (chance < autocvar_g_monsters_miniboss_chance))
523         {
524                 GiveResource(this, RES_HEALTH, autocvar_g_monsters_miniboss_healthboost);
525                 this.effects |= EF_RED;
526                 if(!this.weapon)
527                         this.weapon = WEP_VORTEX.m_id;
528         }
529 }
530
531 bool Monster_Respawn_Check(entity this)
532 {
533         if(this.deadflag == DEAD_DEAD) // don't call when monster isn't dead
534         if(MUTATOR_CALLHOOK(MonsterRespawn, this))
535                 return true; // enabled by a mutator
536
537         if(this.spawnflags & MONSTERFLAG_NORESPAWN)
538                 return false;
539
540         if(!autocvar_g_monsters_respawn)
541                 return false;
542
543         return true;
544 }
545
546 void Monster_Respawn(entity this) { Monster_Spawn(this, true, this.monsterdef); }
547
548 .vector pos1, pos2;
549
550 void Monster_Dead_Fade(entity this)
551 {
552         if(Monster_Respawn_Check(this))
553         {
554                 this.spawnflags |= MONSTERFLAG_RESPAWNED;
555                 setthink(this, Monster_Respawn);
556                 this.nextthink = time + this.respawntime;
557                 this.monster_lifetime = 0;
558                 this.deadflag = DEAD_RESPAWNING;
559                 if(this.spawnflags & MONSTER_RESPAWN_DEATHPOINT)
560                 {
561                         this.pos1 = this.origin;
562                         this.pos2 = this.angles;
563                 }
564                 this.event_damage = func_null;
565                 this.event_heal = func_null;
566                 this.takedamage = DAMAGE_NO;
567                 setorigin(this, this.pos1);
568                 this.angles = this.pos2;
569                 SetResourceExplicit(this, RES_HEALTH, this.max_health);
570                 setmodel(this, MDL_Null);
571         }
572         else
573         {
574                 // number of monsters spawned with mobspawn command
575                 totalspawned -= 1;
576
577                 SUB_SetFade(this, time + 3, 1);
578         }
579 }
580
581 void Monster_Use(entity this, entity actor, entity trigger)
582 {
583         if(Monster_ValidTarget(this, actor, true)) { this.enemy = actor; }
584 }
585
586 vector Monster_Move_Target(entity this, entity targ)
587 {
588         // enemy is always preferred target
589         if(this.enemy)
590         {
591                 vector targ_origin = ((this.enemy.absmin + this.enemy.absmax) * 0.5);
592                 targ_origin = WarpZone_RefSys_TransformOrigin(this.enemy, this, targ_origin); // origin of target as seen by the monster (us)
593                 WarpZone_TraceLine(this.origin, targ_origin, MOVE_NOMONSTERS, this);
594
595                 // cases where the enemy may have changed their state (don't need to check everything here)
596                 if(    (IS_DEAD(this.enemy) || GetResource(this.enemy, RES_HEALTH) < 1)
597                         || (STAT(FROZEN, this.enemy))
598                         || (this.enemy.flags & FL_NOTARGET)
599                         || (this.enemy.alpha < 0.5 && this.enemy.alpha != 0)
600                         || (this.enemy.takedamage == DAMAGE_NO)
601                         || (vdist(this.origin - targ_origin, >, this.target_range))
602                         || ((trace_fraction < 1) && (trace_ent != this.enemy))
603                         )
604                 {
605                         this.enemy = NULL;
606                 }
607
608                 if(this.enemy)
609                 {
610                         /*WarpZone_TrailParticles(NULL, particleeffectnum(EFFECT_RED_PASS), this.origin, targ_origin);
611                         print("Trace origin: ", vtos(targ_origin), "\n");
612                         print("Target origin: ", vtos(this.enemy.origin), "\n");
613                         print("My origin: ", vtos(this.origin), "\n"); */
614
615                         this.monster_movestate = MONSTER_MOVE_ENEMY;
616                         this.last_trace = time + 1.2;
617                         if(this.monster_moveto)
618                                 return this.monster_moveto; // assumes code is properly setting this when monster has an enemy
619                         else
620                                 return targ_origin;
621                 }
622
623                 /*makevectors(this.angles);
624                 this.monster_movestate = MONSTER_MOVE_ENEMY;
625                 this.last_trace = time + 1.2;
626                 return this.enemy.origin; */
627         }
628
629         switch(this.monster_moveflags)
630         {
631                 case MONSTER_MOVE_FOLLOW:
632                 {
633                         this.monster_movestate = MONSTER_MOVE_FOLLOW;
634                         this.last_trace = time + 0.3;
635                         return (this.monster_follow) ? this.monster_follow.origin : this.origin;
636                 }
637                 case MONSTER_MOVE_SPAWNLOC:
638                 {
639                         this.monster_movestate = MONSTER_MOVE_SPAWNLOC;
640                         this.last_trace = time + 2;
641                         return this.pos1;
642                 }
643                 case MONSTER_MOVE_NOMOVE:
644                 {
645                         if(this.monster_moveto)
646                         {
647                                 this.last_trace = time + 0.5;
648                                 return this.monster_moveto;
649                         }
650                         else
651                         {
652                                 this.monster_movestate = MONSTER_MOVE_NOMOVE;
653                                 this.last_trace = time + 2;
654                         }
655                         return this.origin;
656                 }
657                 default:
658                 case MONSTER_MOVE_WANDER:
659                 {
660                         vector pos;
661                         this.monster_movestate = MONSTER_MOVE_WANDER;
662
663                         if(this.monster_moveto)
664                         {
665                                 this.last_trace = time + 0.5;
666                                 pos = this.monster_moveto;
667                         }
668                         else if(targ)
669                         {
670                                 this.last_trace = time + 0.5;
671                                 pos = targ.origin;
672                         }
673                         else
674                         {
675                                 this.last_trace = time + this.wander_delay;
676
677                                 this.angles_y = rint(random() * 500);
678                                 makevectors(this.angles);
679                                 pos = this.origin + v_forward * this.wander_distance;
680
681                                 if(((this.flags & FL_FLY) && (this.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (this.flags & FL_SWIM))
682                                 {
683                                         pos.z = random() * 200;
684                                         if(random() >= 0.5)
685                                                 pos.z *= -1;
686                                 }
687                         }
688
689                         return pos;
690                 }
691         }
692 }
693
694 .entity draggedby;
695
696 void Monster_Move(entity this, float runspeed, float walkspeed, float stpspeed)
697 {
698         // update goal entity if lost
699         if(this.target2 && this.target2 != "" && this.goalentity.targetname != this.target2)
700                 this.goalentity = find(NULL, targetname, this.target2);
701
702         if(STAT(FROZEN, this))
703         {
704                 movelib_brake_simple(this, stpspeed);
705                 setanim(this, this.anim_idle, true, false, false);
706                 return; // no physics while frozen!
707         }
708
709         if(this.flags & FL_SWIM)
710         {
711                 if(this.waterlevel < WATERLEVEL_WETFEET)
712                 {
713                         if(time >= this.last_trace)
714                         {
715                                 this.last_trace = time + 0.4;
716
717                                 Damage (this, NULL, NULL, 2, DEATH_DROWN.m_id, DMG_NOWEP, this.origin, '0 0 0');
718                                 this.angles = '90 90 0';
719                                 if(random() < 0.5)
720                                 {
721                                         this.velocity_y += random() * 50;
722                                         this.velocity_x -= random() * 50;
723                                 }
724                                 else
725                                 {
726                                         this.velocity_y -= random() * 50;
727                                         this.velocity_x += random() * 50;
728                                 }
729                                 this.velocity_z += random() * 150;
730                         }
731
732
733                         set_movetype(this, MOVETYPE_BOUNCE);
734                         //this.velocity_z = -200;
735
736                         return;
737                 }
738                 else if(this.move_movetype == MOVETYPE_BOUNCE)
739                 {
740                         this.angles_x = 0;
741                         set_movetype(this, MOVETYPE_WALK);
742                 }
743         }
744
745         entity targ = this.goalentity;
746
747         if (MUTATOR_CALLHOOK(MonsterMove, this, runspeed, walkspeed, targ)
748                 || game_stopped
749                 || this.draggedby != NULL
750                 || (round_handler_IsActive() && !round_handler_IsRoundStarted())
751                 || time < game_starttime
752                 || (autocvar_g_campaign && !campaign_bots_may_start)
753                 || time < this.spawn_time)
754         {
755                 runspeed = walkspeed = 0;
756                 if(time >= this.spawn_time)
757                         setanim(this, this.anim_idle, true, false, false);
758                 movelib_brake_simple(this, stpspeed);
759                 return;
760         }
761
762         targ = M_ARGV(3, entity);
763         runspeed = bound(0, M_ARGV(1, float) * MONSTER_SKILLMOD(this), runspeed * 2.5); // limit maxspeed to prevent craziness
764         walkspeed = bound(0, M_ARGV(2, float) * MONSTER_SKILLMOD(this), walkspeed * 2.5); // limit maxspeed to prevent craziness
765
766         if(teamplay && autocvar_g_monsters_teams)
767         if(DIFF_TEAM(this.monster_follow, this))
768                 this.monster_follow = NULL;
769
770         if(this.state == MONSTER_ATTACK_RANGED && IS_ONGROUND(this))
771         {
772                 this.state = 0;
773                 settouch(this, Monster_Touch);
774         }
775
776         if(this.state && time >= this.attack_finished_single[0])
777                 this.state = 0; // attack is over
778
779         if(this.state != MONSTER_ATTACK_MELEE) // don't move if set
780         if(time >= this.last_trace || this.enemy) // update enemy or rider instantly
781                 this.moveto = Monster_Move_Target(this, targ);
782
783         if(!this.enemy)
784                 Monster_Sound(this, monstersound_idle, 7, true, CH_VOICE);
785
786         if(this.state == MONSTER_ATTACK_MELEE)
787                 this.moveto = this.origin;
788
789         if(this.enemy && this.enemy.vehicle)
790                 runspeed = 0;
791
792         if(!(this.spawnflags & MONSTERFLAG_FLY_VERTICAL) && !(this.flags & FL_SWIM))
793                 this.moveto_z = this.origin_z;
794
795         fixedmakevectors(this.angles);
796         float vz = this.velocity_z;
797
798         if(!turret_closetotarget(this, this.moveto, 16))
799         {
800                 bool do_run = (this.enemy || this.monster_moveto);
801                 movelib_move_simple(this, v_forward, ((do_run) ? runspeed : walkspeed), 0.4);
802
803                 if(time > this.pain_finished && time > this.anim_finished)
804                 if(!this.state)
805                 {
806                         if(vdist(this.velocity, >, 10))
807                                 setanim(this, ((do_run) ? this.anim_run : this.anim_walk), true, false, false);
808                         else
809                                 setanim(this, this.anim_idle, true, false, false);
810                 }
811         }
812         else
813         {
814                 entity e = this.goalentity; //find(NULL, targetname, this.target2);
815                 if(e.target2 && e.target2 != "")
816                         this.target2 = e.target2;
817                 else if(e.target && e.target != "") // compatibility
818                         this.target2 = e.target;
819
820                 movelib_brake_simple(this, stpspeed);
821                 if(time > this.anim_finished && time > this.pain_finished)
822                 if(!this.state)
823                 if(vdist(this.velocity, <=, 30))
824                         setanim(this, this.anim_idle, true, false, false);
825         }
826
827         if(!((this.flags & FL_FLY) || (this.flags & FL_SWIM)))
828                 this.velocity_z = vz;
829
830         this.steerto = steerlib_attract2(this, ((this.monster_face) ? this.monster_face : this.moveto), 0.5, 500, 0.95);
831
832         vector real_angle = vectoangles(this.steerto) - this.angles;
833         float turny = 25;
834         if(this.state == MONSTER_ATTACK_MELEE)
835                 turny = 0;
836         if(turny)
837         {
838                 turny = bound(turny * -1, shortangle_f(real_angle.y, this.angles.y), turny);
839                 this.angles_y += turny;
840         }
841 }
842
843 void Monster_Remove(entity this)
844 {
845         if(IS_CLIENT(this))
846                 return; // don't remove it?
847
848         if(!this) { return; }
849
850         if(!MUTATOR_CALLHOOK(MonsterRemove, this))
851                 Send_Effect(EFFECT_ITEM_PICKUP, this.origin, '0 0 0', 1);
852
853         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
854         {
855                 .entity weaponentity = weaponentities[slot];
856                 if(this.(weaponentity))
857                         delete(this.(weaponentity));
858         }
859         if(this.iceblock) { delete(this.iceblock); }
860         WaypointSprite_Kill(this.sprite);
861         delete(this);
862 }
863
864 void Monster_Dead_Think(entity this)
865 {
866         this.nextthink = time + this.ticrate;
867
868         Monster mon = REGISTRY_GET(Monsters, this.monsterid);
869         mon.mr_deadthink(mon, this);
870
871         if(this.monster_lifetime != 0)
872         if(time >= this.monster_lifetime)
873         {
874                 Monster_Dead_Fade(this);
875                 return;
876         }
877 }
878
879 void Monster_Appear(entity this, entity actor, entity trigger)
880 {
881         this.enemy = actor;
882         Monster_Spawn(this, false, this.monsterdef);
883 }
884
885 bool Monster_Appear_Check(entity this, Monster monster_id)
886 {
887         if(!(this.spawnflags & MONSTERFLAG_APPEAR))
888                 return false;
889
890         setthink(this, func_null);
891         this.monsterdef = monster_id; // set so this monster is properly registered (otherwise, normal initialization is used)
892         this.nextthink = 0;
893         this.use = Monster_Appear;
894         this.flags = FL_MONSTER; // set so this monster can get butchered
895
896         return true;
897 }
898
899 void Monster_Reset(entity this)
900 {
901         setorigin(this, this.pos1);
902         this.angles = this.pos2;
903
904         Unfreeze(this, false); // remove any icy remains
905
906         SetResourceExplicit(this, RES_HEALTH, this.max_health);
907         this.velocity = '0 0 0';
908         this.enemy = NULL;
909         this.goalentity = NULL;
910         this.attack_finished_single[0] = 0;
911         this.moveto = this.origin;
912 }
913
914 void Monster_Dead_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
915 {
916         TakeResource(this, RES_HEALTH, damage);
917
918         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, this, attacker);
919
920         if(GetResource(this, RES_HEALTH) <= -50) // 100 health until gone?
921         {
922                 Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, this, attacker);
923
924                 // number of monsters spawned with mobspawn command
925                 totalspawned -= 1;
926
927                 setthink(this, SUB_Remove);
928                 this.nextthink = time + 0.1;
929                 this.event_damage = func_null;
930         }
931 }
932
933 void Monster_Dead(entity this, entity attacker, float gibbed)
934 {
935         setthink(this, Monster_Dead_Think);
936         this.nextthink = time;
937         this.monster_lifetime = time + 5;
938
939         if(STAT(FROZEN, this))
940                 Unfreeze(this, false); // remove any icy remains
941
942         monster_dropitem(this, attacker);
943
944         Monster_Sound(this, monstersound_death, 0, false, CH_VOICE);
945
946         if(!(this.spawnflags & MONSTERFLAG_SPAWNED) && !(this.spawnflags & MONSTERFLAG_RESPAWNED))
947                 monsters_killed += 1;
948
949         if(IS_PLAYER(attacker))
950         if(autocvar_g_monsters_score_spawned || !((this.spawnflags & MONSTERFLAG_SPAWNED) || (this.spawnflags & MONSTERFLAG_RESPAWNED)))
951                 GameRules_scoring_add(attacker, SCORE, +autocvar_g_monsters_score_kill);
952
953         if(gibbed)
954         {
955                 // number of monsters spawned with mobspawn command
956                 totalspawned -= 1;
957         }
958
959         if(!gibbed && this.mdl_dead && this.mdl_dead != "")
960                 _setmodel(this, this.mdl_dead);
961
962         this.event_damage       = ((gibbed) ? func_null : Monster_Dead_Damage);
963         this.event_heal         = func_null;
964         this.solid                      = SOLID_CORPSE;
965         this.takedamage         = DAMAGE_AIM;
966         this.deadflag           = DEAD_DEAD;
967         this.enemy                      = NULL;
968         set_movetype(this, MOVETYPE_TOSS);
969         this.moveto                     = this.origin;
970         settouch(this, Monster_Touch); // reset incase monster was pouncing
971         this.reset                      = func_null;
972         this.state                      = 0;
973         this.attack_finished_single[0] = 0;
974         this.effects = 0;
975         this.dphitcontentsmask &= ~DPCONTENTS_BODY;
976
977         if(!((this.flags & FL_FLY) || (this.flags & FL_SWIM)))
978                 this.velocity = '0 0 0';
979
980         CSQCModel_UnlinkEntity(this);
981
982         Monster mon = this.monsterdef;
983         mon.mr_death(mon, this);
984
985         if(this.candrop && this.weapon)
986         {
987                 .entity weaponentity = weaponentities[0]; // TODO: unhardcode
988                 W_ThrowNewWeapon(this, this.weapon, 0, this.origin, randomvec() * 150 + '0 0 325', weaponentity);
989         }
990 }
991
992 void Monster_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
993 {
994         if((this.spawnflags & MONSTERFLAG_INVINCIBLE) && deathtype != DEATH_KILL.m_id && !ITEM_DAMAGE_NEEDKILL(deathtype))
995                 return;
996
997         if(STAT(FROZEN, this) && deathtype != DEATH_KILL.m_id && deathtype != DEATH_NADE_ICE_FREEZE.m_id)
998                 return;
999
1000         //if(time < this.pain_finished && deathtype != DEATH_KILL.m_id)
1001                 //return;
1002
1003         if(StatusEffects_active(STATUSEFFECT_SpawnShield, this) && deathtype != DEATH_KILL.m_id)
1004                 return;
1005
1006         if(deathtype == DEATH_FALL.m_id && this.draggedby != NULL)
1007                 return;
1008
1009         vector v = healtharmor_applydamage(100, GetResource(this, RES_ARMOR) / 100, deathtype, damage);
1010         float take = v.x;
1011         //float save = v.y;
1012
1013         Monster mon = this.monsterdef;
1014         take = mon.mr_pain(mon, this, take, attacker, deathtype);
1015
1016         if(take)
1017         {
1018                 TakeResource(this, RES_HEALTH, take);
1019                 Monster_Sound(this, monstersound_pain, 1.2, true, CH_PAIN);
1020         }
1021
1022         if(this.sprite)
1023                 WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1024
1025         this.dmg_time = time;
1026
1027         if(deathtype != DEATH_DROWN.m_id && deathtype != DEATH_FIRE.m_id && sound_allowed(MSG_BROADCAST, attacker))
1028                 spamsound (this, CH_PAIN, SND_BODYIMPACT1, VOL_BASE, ATTEN_NORM);  // FIXME: PLACEHOLDER
1029
1030         this.velocity += force * this.damageforcescale;
1031
1032         if(deathtype != DEATH_DROWN.m_id && take)
1033         {
1034                 Violence_GibSplash_At(hitloc, force, 2, bound(0, take, 200) / 16, this, attacker);
1035                 if (take > 50)
1036                         Violence_GibSplash_At(hitloc, force * -0.1, 3, 1, this, attacker);
1037                 if (take > 100)
1038                         Violence_GibSplash_At(hitloc, force * -0.2, 3, 1, this, attacker);
1039         }
1040
1041         if(GetResource(this, RES_HEALTH) <= 0)
1042         {
1043                 if(deathtype == DEATH_KILL.m_id)
1044                         this.candrop = false; // killed by mobkill command
1045
1046                 // TODO: fix this?
1047                 SUB_UseTargets(this, attacker, this.enemy);
1048                 this.target2 = this.oldtarget2; // reset to original target on death, incase we respawn
1049
1050                 Monster_Dead(this, attacker, (GetResource(this, RES_HEALTH) <= -100 || deathtype == DEATH_KILL.m_id));
1051
1052                 WaypointSprite_Kill(this.sprite);
1053
1054                 MUTATOR_CALLHOOK(MonsterDies, this, attacker, deathtype);
1055
1056                 if(GetResource(this, RES_HEALTH) <= -100 || deathtype == DEATH_KILL.m_id) // check if we're already gibbed
1057                 {
1058                         Violence_GibSplash(this, 1, 0.5, attacker);
1059
1060                         setthink(this, SUB_Remove);
1061                         this.nextthink = time + 0.1;
1062                 }
1063         }
1064 }
1065
1066 bool Monster_Heal(entity targ, entity inflictor, float amount, float limit)
1067 {
1068         float true_limit = ((limit != RES_LIMIT_NONE) ? limit : targ.max_health);
1069         if(GetResource(targ, RES_HEALTH) <= 0 || GetResource(targ, RES_HEALTH) >= true_limit)
1070                 return false;
1071
1072         GiveResourceWithLimit(targ, RES_HEALTH, amount, true_limit);
1073         if(targ.sprite)
1074                 WaypointSprite_UpdateHealth(targ.sprite, GetResource(targ, RES_HEALTH));
1075         return true;
1076 }
1077
1078 // don't check for enemies, just keep walking in a straight line
1079 void Monster_Move_2D(entity this, float mspeed, bool allow_jumpoff)
1080 {
1081         if(game_stopped || (round_handler_IsActive() && !round_handler_IsRoundStarted()) || this.draggedby != NULL || time < game_starttime || (autocvar_g_campaign && !campaign_bots_may_start) || time < this.spawn_time)
1082         {
1083                 mspeed = 0;
1084                 if(time >= this.spawn_time)
1085                         setanim(this, this.anim_idle, true, false, false);
1086                 movelib_brake_simple(this, 0.6);
1087                 return;
1088         }
1089
1090         makevectors(this.angles);
1091         vector a = CENTER_OR_VIEWOFS(this);
1092         vector b = CENTER_OR_VIEWOFS(this) + v_forward * 32;
1093
1094         traceline(a, b, MOVE_NORMAL, this);
1095
1096         bool reverse = false;
1097         if(trace_fraction != 1.0)
1098                 reverse = true;
1099         if(trace_ent && IS_PLAYER(trace_ent))
1100                 reverse = false;
1101         if(trace_ent && IS_MONSTER(trace_ent))
1102                 reverse = true;
1103
1104         if(!allow_jumpoff && IS_ONGROUND(this))
1105         {
1106                 traceline(b, b - '0 0 32', MOVE_NORMAL, this);
1107                 if(trace_fraction == 1.0)
1108                         reverse = true;
1109         }
1110
1111         if(reverse)
1112         {
1113                 this.angles_y = anglemods(this.angles_y - 180);
1114                 makevectors(this.angles);
1115         }
1116
1117         movelib_move_simple_gravity(this, v_forward, mspeed, 1);
1118
1119         if(time > this.pain_finished && time > this.attack_finished_single[0])
1120         {
1121                 if(vdist(this.velocity, >, 10))
1122                         setanim(this, this.anim_walk, true, false, false);
1123                 else
1124                         setanim(this, this.anim_idle, true, false, false);
1125         }
1126 }
1127
1128 void Monster_Anim(entity this)
1129 {
1130         int deadbits = (this.anim_state & (ANIMSTATE_DEAD1 | ANIMSTATE_DEAD2));
1131         if(IS_DEAD(this))
1132         {
1133                 if (!deadbits)
1134                 {
1135                         // Decide on which death animation to use.
1136                         if(random() < 0.5)
1137                                 deadbits = ANIMSTATE_DEAD1;
1138                         else
1139                                 deadbits = ANIMSTATE_DEAD2;
1140                 }
1141         }
1142         else
1143         {
1144                 // Clear a previous death animation.
1145                 deadbits = 0;
1146         }
1147         int animbits = deadbits;
1148         if(STAT(FROZEN, this))
1149                 animbits |= ANIMSTATE_FROZEN;
1150         if(IS_DUCKED(this))
1151                 animbits |= ANIMSTATE_DUCK; // not that monsters can crouch currently...
1152         animdecide_setstate(this, animbits, false);
1153         animdecide_setimplicitstate(this, (IS_ONGROUND(this)));
1154
1155         /* // weapon entities for monsters?
1156         if (this.weaponentity)
1157         {
1158                 updateanim(this.weaponentity);
1159                 if (!this.weaponentity.animstate_override)
1160                         setanim(this.weaponentity, this.weaponentity.anim_idle, true, false, false);
1161         }
1162         */
1163 }
1164
1165 void Monster_Frozen_Think(entity this)
1166 {
1167         if (STAT(FROZEN, this) == FROZEN_TEMP_REVIVING)
1168         {
1169                 STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) + this.ticrate * this.revive_speed, 1);
1170                 SetResourceExplicit(this, RES_HEALTH, max(1, STAT(REVIVE_PROGRESS, this) * this.max_health));
1171                 if (this.iceblock)
1172                         this.iceblock.alpha = bound(0.2, 1 - STAT(REVIVE_PROGRESS, this), 1);
1173
1174                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE) && this.sprite)
1175                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1176
1177                 if(STAT(REVIVE_PROGRESS, this) >= 1)
1178                         Unfreeze(this, false);
1179         }
1180         else if (STAT(FROZEN, this) == FROZEN_TEMP_DYING)
1181         {
1182                 STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) - this.ticrate * this.revive_speed, 1);
1183                 SetResourceExplicit(this, RES_HEALTH, max(0, autocvar_g_nades_ice_health + (this.max_health-autocvar_g_nades_ice_health) * STAT(REVIVE_PROGRESS, this)));
1184
1185                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE) && this.sprite)
1186                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1187
1188                 if(GetResource(this, RES_HEALTH) < 1)
1189                 {
1190                         Unfreeze(this, false);
1191                         if(this.event_damage)
1192                                 this.event_damage(this, this, this.frozen_by, 1, DEATH_NADE_ICE_FREEZE.m_id, DMG_NOWEP, this.origin, '0 0 0');
1193                 }
1194                 else if ( STAT(REVIVE_PROGRESS, this) <= 0 )
1195                         Unfreeze(this, false);
1196         }
1197         // otherwise, no revival!
1198
1199         this.enemy = NULL; // TODO: save enemy, and attack when revived?
1200 }
1201
1202 void Monster_Enemy_Check(entity this)
1203 {
1204         if(this.enemy)
1205                 return;
1206
1207         this.enemy = Monster_FindTarget(this);
1208         if(this.enemy)
1209         {
1210                 WarpZone_RefSys_Copy(this.enemy, this);
1211                 WarpZone_RefSys_AddInverse(this.enemy, this); // wz1^-1 ... wzn^-1 receiver
1212                 // update move target immediately?
1213                 this.moveto = WarpZone_RefSys_TransformOrigin(this.enemy, this, (0.5 * (this.enemy.absmin + this.enemy.absmax)));
1214                 this.monster_moveto = '0 0 0';
1215                 this.monster_face = '0 0 0';
1216
1217                 Monster_Sound(this, monstersound_sight, 0, false, CH_VOICE);
1218         }
1219 }
1220
1221 void Monster_Think(entity this)
1222 {
1223         setthink(this, Monster_Think);
1224         this.nextthink = time + this.ticrate;
1225
1226         if(this.monster_lifetime && time >= this.monster_lifetime)
1227         {
1228                 Damage(this, this, this, GetResource(this, RES_HEALTH) + this.max_health, DEATH_KILL.m_id, DMG_NOWEP, this.origin, this.origin);
1229                 return;
1230         }
1231
1232         if(STAT(FROZEN, this))
1233                 Monster_Frozen_Think(this);
1234         else if(time >= this.last_enemycheck)
1235         {
1236                 Monster_Enemy_Check(this);
1237                 this.last_enemycheck = time + 1; // check for enemies every second
1238         }
1239
1240         Monster mon = this.monsterdef;
1241         if(mon.mr_think(mon, this))
1242         {
1243                 Monster_Move(this, this.speed2, this.speed, this.stopspeed);
1244
1245                 .entity weaponentity = weaponentities[0]; // TODO?
1246                 Monster_Attack_Check(this, this.enemy, weaponentity);
1247         }
1248
1249         Monster_Anim(this);
1250
1251         CSQCMODEL_AUTOUPDATE(this);
1252 }
1253
1254 bool Monster_Spawn_Setup(entity this)
1255 {
1256         Monster mon = this.monsterdef;
1257         mon.mr_setup(mon, this);
1258
1259         // ensure some basic needs are met
1260         if(!GetResource(this, RES_HEALTH)) { SetResourceExplicit(this, RES_HEALTH, 100); }
1261         if(!GetResource(this, RES_ARMOR)) { SetResourceExplicit(this, RES_ARMOR, bound(0.2, 0.5 * MONSTER_SKILLMOD(this), 0.9)); }
1262         if(!this.target_range) { this.target_range = autocvar_g_monsters_target_range; }
1263         if(!this.respawntime) { this.respawntime = autocvar_g_monsters_respawn_delay; }
1264         if(!this.monster_moveflags) { this.monster_moveflags = MONSTER_MOVE_WANDER; }
1265         if(!this.attack_range) { this.attack_range = autocvar_g_monsters_attack_range; }
1266         if(!this.damageforcescale) { this.damageforcescale = autocvar_g_monsters_damageforcescale; }
1267
1268         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED))
1269         {
1270                 Monster_Miniboss_Check(this);
1271                 SetResourceExplicit(this, RES_HEALTH, GetResource(this, RES_HEALTH) * MONSTER_SKILLMOD(this));
1272
1273                 if(!this.skin)
1274                         this.skin = rint(random() * 4);
1275         }
1276
1277         this.max_health = GetResource(this, RES_HEALTH);
1278         this.pain_finished = this.nextthink;
1279         this.last_enemycheck = this.spawn_time + random(); // slight delay
1280
1281         if(IS_PLAYER(this.monster_follow))
1282                 this.effects |= EF_DIMLIGHT;
1283
1284         if(!this.wander_delay) { this.wander_delay = 2; }
1285         if(!this.wander_distance) { this.wander_distance = 600; }
1286
1287         Monster_Sounds_Precache(this);
1288         Monster_Sounds_Update(this);
1289
1290         if(teamplay)
1291         {
1292                 if(!this.monster_attack)
1293                         IL_PUSH(g_monster_targets, this);
1294                 this.monster_attack = true; // we can have monster enemies in team games
1295         }
1296
1297         Monster_Sound(this, monstersound_spawn, 0, false, CH_VOICE);
1298
1299         if(autocvar_g_monsters_healthbars)
1300         {
1301                 entity wp = WaypointSprite_Spawn(WP_Monster, 0, 1024, this, '0 0 1' * (this.maxs.z + 15), NULL, this.team, this, sprite, true, RADARICON_DANGER);
1302                 wp.wp_extra = this.monsterdef.monsterid;
1303                 wp.colormod = ((this.team) ? Team_ColorRGB(this.team) : '1 0 0');
1304                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE))
1305                 {
1306                         WaypointSprite_UpdateMaxHealth(this.sprite, this.max_health);
1307                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1308                 }
1309         }
1310
1311         setthink(this, Monster_Think);
1312         this.nextthink = time + this.ticrate;
1313
1314         if(MUTATOR_CALLHOOK(MonsterSpawn, this))
1315                 return false;
1316
1317         return true;
1318 }
1319
1320 bool Monster_Spawn(entity this, bool check_appear, Monster mon)
1321 {
1322         // setup the basic required properties for a monster
1323
1324         if(!mon || mon == MON_Null) { return false; } // invalid monster
1325         if(!autocvar_g_monsters) { Monster_Remove(this); return false; }
1326
1327         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED) && !(this.flags & FL_MONSTER))
1328         {
1329                 IL_PUSH(g_monsters, this);
1330                 if(this.mdl && this.mdl != "")
1331                         precache_model(this.mdl);
1332                 if(this.mdl_dead && this.mdl_dead != "")
1333                         precache_model(this.mdl_dead);
1334         }
1335
1336         if(check_appear && Monster_Appear_Check(this, mon)) { return true; } // return true so the monster isn't removed
1337
1338         if(!this.monster_skill)
1339                 this.monster_skill = cvar("g_monsters_skill");
1340
1341         // support for quake style removing monsters based on skill
1342         if(this.monster_skill == MONSTER_SKILL_EASY) if(this.spawnflags & MONSTERSKILL_NOTEASY) { Monster_Remove(this); return false; }
1343         if(this.monster_skill == MONSTER_SKILL_MEDIUM) if(this.spawnflags & MONSTERSKILL_NOTMEDIUM) { Monster_Remove(this); return false; }
1344         if(this.monster_skill == MONSTER_SKILL_HARD) if(this.spawnflags & MONSTERSKILL_NOTHARD) { Monster_Remove(this); return false; }
1345
1346         if(this.team && !teamplay)
1347                 this.team = 0;
1348
1349         if(!(this.spawnflags & MONSTERFLAG_SPAWNED)) // naturally spawned monster
1350         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED)) // don't count re-spawning monsters either
1351                 monsters_total += 1;
1352
1353         if(this.mdl && this.mdl != "")
1354                 _setmodel(this, this.mdl);
1355         else
1356                 setmodel(this, mon.m_model);
1357
1358         if(!this.monster_name || this.monster_name == "")
1359                 this.monster_name = mon.monster_name;
1360
1361         if(this.statuseffects && this.statuseffects.owner == this)
1362         {
1363                 StatusEffects_clearall(this.statuseffects);
1364                 StatusEffects_update(this);
1365         }
1366         else
1367                 this.statuseffects = NULL;
1368
1369         this.flags                              = FL_MONSTER;
1370         this.classname                  = "monster";
1371         this.takedamage                 = DAMAGE_AIM;
1372         if(!this.bot_attack)
1373                 IL_PUSH(g_bot_targets, this);
1374         this.bot_attack                 = true;
1375         this.iscreature                 = true;
1376         this.teleportable               = true;
1377         if(!this.damagedbycontents)
1378                 IL_PUSH(g_damagedbycontents, this);
1379         this.damagedbycontents  = true;
1380         this.monsterdef                 = mon;
1381         this.event_damage               = Monster_Damage;
1382         this.event_heal                 = Monster_Heal;
1383         settouch(this, Monster_Touch);
1384         this.use                                = Monster_Use;
1385         this.solid                              = SOLID_BBOX;
1386         set_movetype(this, MOVETYPE_WALK);
1387         StatusEffects_apply(STATUSEFFECT_SpawnShield, this, time + autocvar_g_monsters_spawnshieldtime, 0);
1388         this.enemy                              = NULL;
1389         this.velocity                   = '0 0 0';
1390         this.moveto                             = this.origin;
1391         this.pos1                               = this.origin;
1392         this.pos2                               = this.angles;
1393         this.reset                              = Monster_Reset;
1394         this.netname                    = mon.netname;
1395         this.monster_attackfunc = mon.monster_attackfunc;
1396         this.candrop                    = true;
1397         this.oldtarget2                 = this.target2;
1398         this.deadflag                   = DEAD_NO;
1399         this.spawn_time                 = time;
1400         this.gravity                    = 1;
1401         this.monster_moveto             = '0 0 0';
1402         this.monster_face               = '0 0 0';
1403         this.dphitcontentsmask  = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP;
1404
1405         if(!this.noalign) { this.noalign = ((mon.spawnflags & MONSTER_TYPE_FLY) || (mon.spawnflags & MONSTER_TYPE_SWIM)); }
1406         if(!this.scale) { this.scale = 1; }
1407         if(autocvar_g_monsters_edit) { this.grab = 1; }
1408         if(autocvar_g_fullbrightplayers) { this.effects |= EF_FULLBRIGHT; }
1409         if(autocvar_g_nodepthtestplayers) { this.effects |= EF_NODEPTHTEST; }
1410         if(mon.spawnflags & MONSTER_TYPE_SWIM) { this.flags |= FL_SWIM; }
1411
1412         if(autocvar_g_monsters_playerclip_collisions)
1413                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
1414
1415         if(mon.spawnflags & MONSTER_TYPE_FLY)
1416         {
1417                 this.flags |= FL_FLY;
1418                 set_movetype(this, MOVETYPE_FLY);
1419         }
1420
1421         if((mon.spawnflags & MONSTER_SIZE_QUAKE) && autocvar_g_monsters_quake_resize && !(this.spawnflags & MONSTERFLAG_RESPAWNED))
1422                 this.scale *= 1.3;
1423
1424         setsize(this, mon.m_mins * this.scale, mon.m_maxs * this.scale);
1425         this.view_ofs                   = '0 0 0.7' * (this.maxs_z * 0.5);
1426
1427         this.ticrate = bound(sys_frametime, ((!this.ticrate) ? autocvar_g_monsters_think_delay : this.ticrate), 60);
1428
1429         Monster_UpdateModel(this);
1430
1431         if(!Monster_Spawn_Setup(this))
1432         {
1433                 Monster_Remove(this);
1434                 return false;
1435         }
1436
1437         if(!this.noalign)
1438         {
1439                 setorigin(this, this.origin + '0 0 20');
1440                 tracebox(this.origin + '0 0 64', this.mins, this.maxs, this.origin - '0 0 10000', MOVE_WORLDONLY, this);
1441                 setorigin(this, trace_endpos);
1442         }
1443
1444         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED))
1445                 monster_setupcolors(this);
1446
1447         CSQCMODEL_AUTOINIT(this);
1448
1449         return true;
1450 }