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