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