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