a9de642863672b24bab677fa8dbdcba314ee0702
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / monsters / sv_monsters.qc
1 #if defined(CSQC)
2 #elif defined(MENUQC)
3 #elif defined(SVQC)
4         #include "../../dpdefs/progsdefs.qh"
5     #include "../../dpdefs/dpextensions.qh"
6     #include "../../warpzonelib/common.qh"
7     #include "../constants.qh"
8     #include "../teams.qh"
9     #include "../util.qh"
10     #include "all.qh"
11     #include "sv_monsters.qh"
12     #include "../weapons/all.qh"
13     #include "../../server/autocvars.qh"
14     #include "../../server/defs.qh"
15     #include "../deathtypes.qh"
16     #include "../../server/mutators/mutators_include.qh"
17     #include "../../server/tturrets/include/turrets_early.qh"
18     #include "../../server/vehicles/vehicle.qh"
19     #include "../../server/campaign.qh"
20     #include "../../server/command/common.qh"
21     #include "../../server/command/cmd.qh"
22         #include "../triggers/triggers.qh"
23     #include "../../csqcmodellib/sv_model.qh"
24     #include "../../server/round_handler.qh"
25     #include "../../server/tturrets/include/turrets.qh"
26 #endif
27
28 // =========================
29 //      SVQC Monster Properties
30 // =========================
31
32
33 void monster_dropitem()
34 {
35         if(!self.candrop || !self.monster_loot)
36                 return;
37
38         vector org = self.origin + ((self.mins + self.maxs) * 0.5);
39         entity e = spawn(), oldself = self;
40
41         e.monster_loot = self.monster_loot;
42
43         MUTATOR_CALLHOOK(MonsterDropItem, e);
44         e = other;
45
46         if(e && e.monster_loot)
47         {
48                 self = e;
49                 e.noalign = true;
50                 e.monster_loot();
51                 e.gravity = 1;
52                 e.movetype = MOVETYPE_TOSS;
53                 e.reset = SUB_Remove;
54                 setorigin(e, org);
55                 e.velocity = randomvec() * 175 + '0 0 325';
56                 e.item_spawnshieldtime = time + 0.7;
57                 e.classname = "droppedweapon"; // use weapon handling to remove it on touch
58                 SUB_SetFade(e, time + autocvar_g_monsters_drop_time, 1);
59                 self = oldself;
60         }
61 }
62
63 float Monster_SkillModifier()
64 {
65         float t = 0.5+self.monster_skill*((1.2-0.3)/10);
66
67         return t;
68 }
69
70 float monster_isvalidtarget (entity targ, entity ent)
71 {
72         if(!targ || !ent)
73                 return false; // someone doesn't exist
74
75         if(targ == ent)
76                 return false; // don't attack ourselves
77
78         //traceline(ent.origin, targ.origin, MOVE_NORMAL, ent);
79
80         //if(trace_ent != targ)
81                 //return false;
82
83         if(IS_VEHICLE(targ))
84         if(!((get_monsterinfo(ent.monsterid)).spawnflags & MON_FLAG_RANGED))
85                 return false; // melee attacks are useless against vehicles
86
87         if(time < game_starttime)
88                 return false; // monsters do nothing before the match has started
89
90         if(targ.takedamage == DAMAGE_NO)
91                 return false; // enemy can't be damaged
92
93         if(targ.items & IT_INVISIBILITY)
94                 return false; // enemy is invisible
95
96         if(substring(targ.classname, 0, 10) == "onslaught_")
97                 return false; // don't attack onslaught targets
98
99         if(IS_SPEC(targ) || IS_OBSERVER(targ))
100                 return false; // enemy is a spectator
101
102         if(!IS_VEHICLE(targ))
103         if(targ.deadflag != DEAD_NO || ent.deadflag != DEAD_NO || targ.health <= 0 || ent.health <= 0)
104                 return false; // enemy/self is dead
105
106         if(ent.monster_owner == targ)
107                 return false; // don't attack our master
108
109         if(targ.monster_owner == ent)
110                 return false; // don't attack our pet
111
112         if(!IS_VEHICLE(targ))
113         if(targ.flags & FL_NOTARGET)
114                 return false; // enemy can't be targeted
115
116         if(!autocvar_g_monsters_typefrag)
117         if(targ.BUTTON_CHAT)
118                 return false; // no typefragging!
119
120         if(SAME_TEAM(targ, ent))
121                 return false; // enemy is on our team
122
123         if (targ.frozen)
124                 return false; // ignore frozen
125
126         if(autocvar_g_monsters_target_infront || (ent.spawnflags & MONSTERFLAG_INFRONT))
127         if(ent.enemy != targ)
128         {
129                 float dot;
130
131                 makevectors (ent.angles);
132                 dot = normalize (targ.origin - ent.origin) * v_forward;
133
134                 if(dot <= 0.3)
135                         return false;
136         }
137
138         return true;
139 }
140
141 entity FindTarget (entity ent)
142 {
143         if(MUTATOR_CALLHOOK(MonsterFindTarget)) { return ent.enemy; } // Handled by a mutator
144
145         entity head, closest_target = world;
146         head = findradius(ent.origin, ent.target_range);
147         //head = WarpZone_FindRadius(ent.origin, ent.target_range, true);
148
149         while(head) // find the closest acceptable target to pass to
150         {
151                 if(head.monster_attack)
152                 if(monster_isvalidtarget(head, ent))
153                 {
154                         // if it's a player, use the view origin as reference (stolen from RadiusDamage functions in g_damage.qc)
155                         vector head_center = CENTER_OR_VIEWOFS(head);
156                         //vector head_center = WarpZone_UnTransformOrigin(head, CENTER_OR_VIEWOFS(head));
157                         vector ent_center = CENTER_OR_VIEWOFS(ent);
158
159                         traceline(ent_center, head_center, MOVE_NORMAL, ent);
160
161                         if(trace_ent == head)
162                         if(closest_target)
163                         {
164                                 vector closest_target_center = CENTER_OR_VIEWOFS(closest_target);
165                                 //vector closest_target_center = WarpZone_UnTransformOrigin(closest_target, CENTER_OR_VIEWOFS(closest_target));
166                                 if(vlen(ent_center - head_center) < vlen(ent_center - closest_target_center))
167                                         { closest_target = head; }
168                         }
169                         else { closest_target = head; }
170                 }
171
172                 head = head.chain;
173         }
174
175         return closest_target;
176 }
177
178 void MonsterTouch ()
179 {
180         if(other == world)
181                 return;
182
183         if(self.enemy != other)
184         if(!IS_MONSTER(other))
185         if(monster_isvalidtarget(other, self))
186                 self.enemy = other;
187 }
188
189 string get_monster_model_datafilename(string m, float sk, string fil)
190 {
191         if(m)
192                 m = strcat(m, "_");
193         else
194                 m = "models/monsters/*_";
195         if(sk >= 0)
196                 m = strcat(m, ftos(sk));
197         else
198                 m = strcat(m, "*");
199         return strcat(m, ".", fil);
200 }
201
202 void PrecacheMonsterSounds(string f)
203 {
204         float fh;
205         string s;
206         fh = fopen(f, FILE_READ);
207         if(fh < 0)
208                 return;
209         while((s = fgets(fh)))
210         {
211                 if(tokenize_console(s) != 3)
212                 {
213                         dprint("Invalid sound info line: ", s, "\n");
214                         continue;
215                 }
216                 PrecacheGlobalSound(strcat(argv(1), " ", argv(2)));
217         }
218         fclose(fh);
219 }
220
221 void precache_monstersounds()
222 {
223         string m = (get_monsterinfo(self.monsterid)).model;
224         float globhandle, n, i;
225         string f;
226
227         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
228         if (globhandle < 0)
229                 return;
230         n = search_getsize(globhandle);
231         for (i = 0; i < n; ++i)
232         {
233                 //print(search_getfilename(globhandle, i), "\n");
234                 f = search_getfilename(globhandle, i);
235                 PrecacheMonsterSounds(f);
236         }
237         search_end(globhandle);
238 }
239
240 void ClearMonsterSounds()
241 {
242 #define _MSOUND(m) if(self.monstersound_##m) { strunzone(self.monstersound_##m); self.monstersound_##m = string_null; }
243         ALLMONSTERSOUNDS
244 #undef _MSOUND
245 }
246
247 .string GetMonsterSoundSampleField(string type)
248 {
249         GetMonsterSoundSampleField_notFound = 0;
250         switch(type)
251         {
252 #define _MSOUND(m) case #m: return monstersound_##m;
253                 ALLMONSTERSOUNDS
254 #undef _MSOUND
255         }
256         GetMonsterSoundSampleField_notFound = 1;
257         return string_null;
258 }
259
260 float LoadMonsterSounds(string f, float first)
261 {
262         float fh;
263         string s;
264         var .string field;
265         fh = fopen(f, FILE_READ);
266         if(fh < 0)
267         {
268                 dprint("Monster sound file not found: ", f, "\n");
269                 return 0;
270         }
271         while((s = fgets(fh)))
272         {
273                 if(tokenize_console(s) != 3)
274                         continue;
275                 field = GetMonsterSoundSampleField(argv(0));
276                 if(GetMonsterSoundSampleField_notFound)
277                         continue;
278                 if (self.(field))
279                         strunzone(self.(field));
280                 self.(field) = strzone(strcat(argv(1), " ", argv(2)));
281         }
282         fclose(fh);
283         return 1;
284 }
285
286 .int skin_for_monstersound;
287 void UpdateMonsterSounds()
288 {
289         entity mon = get_monsterinfo(self.monsterid);
290
291         if(self.skin == self.skin_for_monstersound)
292                 return;
293         self.skin_for_monstersound = self.skin;
294         ClearMonsterSounds();
295         //LoadMonsterSounds("sound/monsters/default.sounds", 1);
296         if(!autocvar_g_debug_defaultsounds)
297         if(!LoadMonsterSounds(get_monster_model_datafilename(mon.model, self.skin, "sounds"), 0))
298                 LoadMonsterSounds(get_monster_model_datafilename(mon.model, 0, "sounds"), 0);
299 }
300
301 void MonsterSound(.string samplefield, float sound_delay, float delaytoo, float chan)
302 {
303         if(!autocvar_g_monsters_sounds) { return; }
304
305         if(delaytoo)
306         if(time < self.msound_delay)
307                 return; // too early
308         GlobalSound(self.(samplefield), chan, VOICETYPE_PLAYERSOUND);
309
310         self.msound_delay = time + sound_delay;
311 }
312
313 void monster_makevectors(entity e)
314 {
315         vector v;
316
317         v = e.origin + (e.mins + e.maxs) * 0.5;
318         self.v_angle = vectoangles(v - (self.origin + self.view_ofs));
319         self.v_angle_x = -self.v_angle.x;
320
321         makevectors(self.v_angle);
322 }
323
324 float monster_melee(entity targ, float damg, float anim, float er, float anim_finished, int deathtype, float dostop)
325 {
326         if (self.health <= 0)
327                 return false; // attacking while dead?!
328
329         if(dostop)
330         {
331                 self.velocity_x = 0;
332                 self.velocity_y = 0;
333                 self.state = MONSTER_STATE_ATTACK_MELEE;
334         }
335
336         self.frame = anim;
337
338         if(anim_finished != 0)
339                 self.attack_finished_single = time + anim_finished;
340
341         monster_makevectors(targ);
342
343         traceline(self.origin + self.view_ofs, self.origin + v_forward * er, 0, self);
344
345         if(trace_ent.takedamage)
346                 Damage(trace_ent, self, self, damg * Monster_SkillModifier(), deathtype, trace_ent.origin, normalize(trace_ent.origin - self.origin));
347
348         return true;
349 }
350
351 void Monster_CheckMinibossFlag ()
352 {
353         if(MUTATOR_CALLHOOK(MonsterCheckBossFlag))
354                 return;
355
356         float chance = random() * 100;
357
358         // g_monsters_miniboss_chance cvar or spawnflags 64 causes a monster to be a miniboss
359         if ((self.spawnflags & MONSTERFLAG_MINIBOSS) || (chance < autocvar_g_monsters_miniboss_chance))
360         {
361                 self.health += autocvar_g_monsters_miniboss_healthboost;
362                 self.effects |= EF_RED;
363                 if(!self.weapon)
364                         self.weapon = WEP_VORTEX.m_id;
365         }
366 }
367
368 float Monster_CanRespawn(entity ent)
369 {
370         other = ent;
371         if(ent.deadflag == DEAD_DEAD) // don't call when monster isn't dead
372         if(MUTATOR_CALLHOOK(MonsterRespawn, ent))
373                 return true; // enabled by a mutator
374
375         if(ent.spawnflags & MONSTERFLAG_NORESPAWN)
376                 return false;
377
378         if(!autocvar_g_monsters_respawn)
379                 return false;
380
381         return true;
382 }
383
384 void monster_respawn()
385 {
386         // is this function really needed?
387         monster_initialize(self.monsterid);
388 }
389
390 void Monster_Fade ()
391 {
392         if(Monster_CanRespawn(self))
393         {
394                 self.spawnflags |= MONSTERFLAG_RESPAWNED;
395                 self.think = monster_respawn;
396                 self.nextthink = time + self.respawntime;
397                 self.monster_lifetime = 0;
398                 self.deadflag = DEAD_RESPAWNING;
399                 if(self.spawnflags & MONSTER_RESPAWN_DEATHPOINT)
400                 {
401                         self.pos1 = self.origin;
402                         self.pos2 = self.angles;
403                 }
404                 self.event_damage = func_null;
405                 self.takedamage = DAMAGE_NO;
406                 setorigin(self, self.pos1);
407                 self.angles = self.pos2;
408                 self.health = self.max_health;
409                 setmodel(self, "null");
410         }
411         else
412         {
413                 // number of monsters spawned with mobspawn command
414                 totalspawned -= 1;
415
416                 SUB_SetFade(self, time + 3, 1);
417         }
418 }
419
420 float Monster_CanJump (vector vel)
421 {
422         if(self.state)
423                 return false; // already attacking
424         if(!(self.flags & FL_ONGROUND))
425                 return false; // not on the ground
426         if(self.health <= 0)
427                 return false; // called when dead?
428         if(time < self.attack_finished_single)
429                 return false; // still attacking
430
431         vector old = self.velocity;
432
433         self.velocity = vel;
434         tracetoss(self, self);
435         self.velocity = old;
436         if (trace_ent != self.enemy)
437                 return false;
438
439         return true;
440 }
441
442 float monster_leap (float anm, void() touchfunc, vector vel, float anim_finished)
443 {
444         if(!Monster_CanJump(vel))
445                 return false;
446
447         self.frame = anm;
448         self.state = MONSTER_STATE_ATTACK_LEAP;
449         self.touch = touchfunc;
450         self.origin_z += 1;
451         self.velocity = vel;
452         self.flags &= ~FL_ONGROUND;
453
454         self.attack_finished_single = time + anim_finished;
455
456         return true;
457 }
458
459 void monster_checkattack(entity e, entity targ)
460 {
461         if(e == world)
462                 return;
463         if(targ == world)
464                 return;
465
466         if(!e.monster_attackfunc)
467                 return;
468
469         if(time < e.attack_finished_single)
470                 return;
471
472         if(vlen(targ.origin - e.origin) <= e.attack_range)
473         if(e.monster_attackfunc(MONSTER_ATTACK_MELEE))
474         {
475                 MonsterSound(monstersound_melee, 0, false, CH_VOICE);
476                 return;
477         }
478
479         if(vlen(targ.origin - e.origin) > e.attack_range)
480         if(e.monster_attackfunc(MONSTER_ATTACK_RANGED))
481         {
482                 MonsterSound(monstersound_ranged, 0, false, CH_VOICE);
483                 return;
484         }
485 }
486
487 void monster_use ()
488 {
489         if(!self.enemy)
490         if(self.health > 0)
491         if(monster_isvalidtarget(activator, self))
492                 self.enemy = activator;
493 }
494
495 .float last_trace;
496 .float last_enemycheck; // for checking enemy
497 vector monster_pickmovetarget(entity targ)
498 {
499         // enemy is always preferred target
500         if(self.enemy)
501         {
502                 vector targ_origin = ((self.enemy.absmin + self.enemy.absmax) * 0.5);
503                 targ_origin = WarpZone_RefSys_TransformOrigin(self.enemy, self, targ_origin); // origin of target as seen by the monster (us)
504                 WarpZone_TraceLine(self.origin, targ_origin, MOVE_NOMONSTERS, self);
505
506                 if((self.enemy == world)
507                         || (self.enemy.deadflag != DEAD_NO || self.enemy.health < 1)
508                         || (self.enemy.frozen)
509                         || (self.enemy.flags & FL_NOTARGET)
510                         || (self.enemy.alpha < 0.5)
511                         || (self.enemy.takedamage == DAMAGE_NO)
512                         || (vlen(self.origin - targ_origin) > self.target_range)
513                         || ((trace_fraction < 1) && (trace_ent != self.enemy)))
514                         //|| (time > self.ctf_droptime + autocvar_g_ctf_pass_timelimit)) // TODO: chase timelimit?
515                 {
516                         self.enemy = world;
517                         self.pass_distance = 0;
518                 }
519
520                 if(self.enemy)
521                 {
522                         /*WarpZone_TrailParticles(world, particleeffectnum("red_pass"), self.origin, targ_origin);
523                         print("Trace origin: ", vtos(targ_origin), "\n");
524                         print("Target origin: ", vtos(self.enemy.origin), "\n");
525                         print("My origin: ", vtos(self.origin), "\n"); */
526
527                         self.monster_movestate = MONSTER_MOVE_ENEMY;
528                         self.last_trace = time + 1.2;
529                         return targ_origin;
530                 }
531
532                 /*makevectors(self.angles);
533                 self.monster_movestate = MONSTER_MOVE_ENEMY;
534                 self.last_trace = time + 1.2;
535                 return self.enemy.origin; */
536         }
537
538         switch(self.monster_moveflags)
539         {
540                 case MONSTER_MOVE_OWNER:
541                 {
542                         self.monster_movestate = MONSTER_MOVE_OWNER;
543                         self.last_trace = time + 0.3;
544                         return (self.monster_owner) ? self.monster_owner.origin : self.origin;
545                 }
546                 case MONSTER_MOVE_SPAWNLOC:
547                 {
548                         self.monster_movestate = MONSTER_MOVE_SPAWNLOC;
549                         self.last_trace = time + 2;
550                         return self.pos1;
551                 }
552                 case MONSTER_MOVE_NOMOVE:
553                 {
554                         self.monster_movestate = MONSTER_MOVE_NOMOVE;
555                         self.last_trace = time + 2;
556                         return self.origin;
557                 }
558                 default:
559                 case MONSTER_MOVE_WANDER:
560                 {
561                         vector pos;
562                         self.monster_movestate = MONSTER_MOVE_WANDER;
563
564                         if(targ)
565                         {
566                                 self.last_trace = time + 0.5;
567                                 pos = targ.origin;
568                         }
569                         else
570                         {
571                                 self.last_trace = time + self.wander_delay;
572
573                                 self.angles_y = rint(random() * 500);
574                                 makevectors(self.angles);
575                                 pos = self.origin + v_forward * self.wander_distance;
576
577                                 if(((self.flags & FL_FLY) && (self.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (self.flags & FL_SWIM))
578                                 {
579                                         pos.z = random() * 200;
580                                         if(random() >= 0.5)
581                                                 pos.z *= -1;
582                                 }
583                         }
584
585                         return pos;
586                 }
587         }
588 }
589
590 void monster_CalculateVelocity(entity mon, vector to, vector from, float turnrate, float movespeed)
591 {
592         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
593         float initial_height = 0; //min(50, (targ_distance * tanh(20)));
594         float current_height = (initial_height * min(1, self.pass_distance ? (current_distance / self.pass_distance) : 0));
595         //print("current_height = ", ftos(current_height), ", initial_height = ", ftos(initial_height), ".\n");
596
597         vector targpos;
598         if(current_height) // make sure we can actually do this arcing path
599         {
600                 targpos = (to + ('0 0 1' * current_height));
601                 WarpZone_TraceLine(mon.origin, targpos, MOVE_NOMONSTERS, mon);
602                 if(trace_fraction < 1)
603                 {
604                         //print("normal arc line failed, trying to find new pos...");
605                         WarpZone_TraceLine(to, targpos, MOVE_NOMONSTERS, mon);
606                         targpos = (trace_endpos + '0 0 -10');
607                         WarpZone_TraceLine(mon.origin, targpos, MOVE_NOMONSTERS, mon);
608                         if(trace_fraction < 1) { targpos = to; /* print(" ^1FAILURE^7, reverting to original direction.\n"); */ }
609                         /*else { print(" ^3SUCCESS^7, using new arc line.\n"); } */
610                 }
611         }
612         else { targpos = to; }
613
614         //mon.angles = normalize(('0 1 0' * to_y) - ('0 1 0' * from_y));
615
616         vector desired_direction = normalize(targpos - from);
617         if(turnrate) { mon.velocity = (normalize(normalize(mon.velocity) + (desired_direction * 50)) * movespeed); }
618         else { mon.velocity = (desired_direction * movespeed); }
619
620         //mon.steerto = steerlib_attract2(targpos, 0.5, 500, 0.95);
621         //mon.angles = vectoangles(mon.velocity);
622 }
623
624 void monster_move(float runspeed, float walkspeed, float stopspeed, float manim_run, float manim_walk, float manim_idle)
625 {
626         //fixedmakevectors(self.angles);
627
628         if(self.target2)
629                 self.goalentity = find(world, targetname, self.target2);
630
631         entity targ;
632
633         if(self.frozen == 2)
634         {
635                 self.revive_progress = bound(0, self.revive_progress + self.ticrate * self.revive_speed, 1);
636                 self.health = max(1, self.revive_progress * self.max_health);
637                 self.iceblock.alpha = bound(0.2, 1 - self.revive_progress, 1);
638
639                 WaypointSprite_UpdateHealth(self.sprite, self.health);
640
641                 movelib_beak_simple(stopspeed);
642                 self.frame = manim_idle;
643
644                 self.enemy = world;
645                 self.nextthink = time + self.ticrate;
646
647                 if(self.revive_progress >= 1)
648                         Unfreeze(self);
649
650                 return;
651         }
652         else if(self.frozen == 3)
653         {
654                 self.revive_progress = bound(0, self.revive_progress - self.ticrate * self.revive_speed, 1);
655                 self.health = max(0, autocvar_g_nades_ice_health + (self.max_health-autocvar_g_nades_ice_health) * self.revive_progress );
656
657                 WaypointSprite_UpdateHealth(self.sprite, self.health);
658
659                 movelib_beak_simple(stopspeed);
660                 self.frame = manim_idle;
661
662                 self.enemy = world;
663                 self.nextthink = time + self.ticrate;
664
665                 if(self.health < 1)
666                 {
667                         Unfreeze(self);
668                         self.health = 0;
669                         self.event_damage(self, self.frozen_by, 1, DEATH_NADE_ICE_FREEZE, self.origin, '0 0 0');
670                 }
671
672                 else if ( self.revive_progress <= 0 )
673                         Unfreeze(self);
674
675                 return;
676         }
677
678         if(self.flags & FL_SWIM)
679         {
680                 if(self.waterlevel < WATERLEVEL_WETFEET)
681                 {
682                         if(time >= self.last_trace)
683                         {
684                                 self.fish_wasdrowning = true;
685                                 self.last_trace = time + 0.4;
686
687                                 Damage (self, world, world, 2, DEATH_DROWN, self.origin, '0 0 0');
688                                 self.angles = '90 90 0';
689                                 if(random() < 0.5)
690                                 {
691                                         self.velocity_y += random() * 50;
692                                         self.velocity_x -= random() * 50;
693                                 }
694                                 else
695                                 {
696                                         self.velocity_y -= random() * 50;
697                                         self.velocity_x += random() * 50;
698                                 }
699                                 self.velocity_z += random() * 150;
700                         }
701
702
703                         self.movetype = MOVETYPE_BOUNCE;
704                         //self.velocity_z = -200;
705
706                         return;
707                 }
708                 else if(self.fish_wasdrowning)
709                 {
710                         self.fish_wasdrowning = false;
711                         self.angles_x = 0;
712                         self.movetype = MOVETYPE_WALK;
713                 }
714         }
715
716         targ = self.goalentity;
717
718         if (MUTATOR_CALLHOOK(MonsterMove, runspeed, walkspeed, targ)
719                 || gameover
720                 || self.draggedby != world
721                 || (round_handler_IsActive() && !round_handler_IsRoundStarted())
722                 || time < game_starttime
723                 || (autocvar_g_campaign && !campaign_bots_may_start)
724                 || time < self.spawn_time)
725         {
726                 runspeed = walkspeed = 0;
727                 if(time >= self.spawn_time)
728                         self.frame = manim_idle;
729                 movelib_beak_simple(stopspeed);
730                 return;
731         }
732
733         runspeed = bound(0, monster_speed_run * Monster_SkillModifier(), runspeed * 2); // limit maxspeed to prevent craziness
734         walkspeed = bound(0, monster_speed_walk * Monster_SkillModifier(), walkspeed * 2); // limit maxspeed to prevent craziness
735
736         if(time < self.spider_slowness)
737         {
738                 runspeed *= 0.5;
739                 walkspeed *= 0.5;
740         }
741
742         if(teamplay)
743         if(autocvar_g_monsters_teams)
744         if(DIFF_TEAM(self.monster_owner, self))
745                 self.monster_owner = world;
746
747         if(time >= self.last_enemycheck)
748         {
749                 if(!self.enemy)
750                 {
751                         self.enemy = FindTarget(self);
752                         if(self.enemy)
753                         {
754                                 WarpZone_RefSys_Copy(self.enemy, self);
755                                 WarpZone_RefSys_AddInverse(self.enemy, self); // wz1^-1 ... wzn^-1 receiver
756                                 self.moveto = WarpZone_RefSys_TransformOrigin(self.enemy, self, (0.5 * (self.enemy.absmin + self.enemy.absmax)));
757
758                                 self.pass_distance = vlen((('1 0 0' * self.enemy.origin.x) + ('0 1 0' * self.enemy.origin.y)) - (('1 0 0' *  self.origin.x) + ('0 1 0' *  self.origin.y)));
759                                 MonsterSound(monstersound_sight, 0, false, CH_VOICE);
760                         }
761                 }
762
763                 self.last_enemycheck = time + 1; // check for enemies every second
764         }
765
766         if(self.state == MONSTER_STATE_ATTACK_MELEE && time >= self.attack_finished_single)
767                 self.state = 0;
768
769         if(self.state != MONSTER_STATE_ATTACK_MELEE) // don't move if set
770         if(time >= self.last_trace || self.enemy) // update enemy instantly
771                 self.moveto = monster_pickmovetarget(targ);
772
773         if(!self.enemy)
774                 MonsterSound(monstersound_idle, 7, true, CH_VOICE);
775
776         if(self.state == MONSTER_STATE_ATTACK_LEAP && (self.flags & FL_ONGROUND))
777         {
778                 self.state = 0;
779                 self.touch = MonsterTouch;
780         }
781
782         if(self.state == MONSTER_STATE_ATTACK_MELEE)
783                 self.moveto = self.origin;
784
785         if(self.enemy && self.enemy.vehicle)
786                 runspeed = 0;
787
788         if(!(((self.flags & FL_FLY) && (self.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (self.flags & FL_SWIM)))
789                 //v_forward = normalize(self.moveto - self.origin);
790         //else
791                 self.moveto_z = self.origin.z;
792
793         if(vlen(self.origin - self.moveto) > 64)
794         {
795                 if((self.flags & FL_ONGROUND) || ((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
796                         monster_CalculateVelocity(self, self.moveto, self.origin, true, ((self.enemy) ? runspeed : walkspeed));
797
798                 /*&if(self.flags & FL_FLY || self.flags & FL_SWIM)
799                         movelib_move_simple(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6);
800                 else
801                         movelib_move_simple_gravity(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6); */
802
803                 if(time > self.pain_finished)
804                 if(time > self.attack_finished_single)
805                 if(vlen(self.velocity) > 10)
806                         self.frame = ((self.enemy) ? manim_run : manim_walk);
807                 else
808                         self.frame = manim_idle;
809         }
810         else
811         {
812                 entity e = find(world, targetname, self.target2);
813                 if(e.target2)
814                         self.target2 = e.target2;
815                 else if(e.target)
816                         self.target2 = e.target;
817
818                 movelib_beak_simple(stopspeed);
819                 if(time > self.attack_finished_single)
820                 if(time > self.pain_finished)
821                 if (vlen(self.velocity) <= 30)
822                         self.frame = manim_idle;
823         }
824
825         self.steerto = steerlib_attract2(self.moveto, 0.5, 500, 0.95);
826
827         vector real_angle = vectoangles(self.steerto) - self.angles;
828         float turny = 25;
829         if(self.state == MONSTER_STATE_ATTACK_MELEE)
830                 turny = 0;
831         if(turny)
832         {
833                 turny = bound(turny * -1, shortangle_f(real_angle.y, self.angles.y), turny);
834                 self.angles_y += turny;
835         }
836
837         monster_checkattack(self, self.enemy);
838 }
839
840 void monster_remove(entity mon)
841 {
842         if(!mon)
843                 return; // nothing to remove
844
845         Send_Effect("item_pickup", mon.origin, '0 0 0', 1);
846
847         if(mon.weaponentity)
848                 remove(mon.weaponentity);
849
850         if(mon.iceblock)
851                 remove(mon.iceblock);
852
853         WaypointSprite_Kill(mon.sprite);
854
855         remove(mon);
856 }
857
858 void monster_dead_think()
859 {
860         self.nextthink = time + self.ticrate;
861
862         CSQCMODEL_AUTOUPDATE();
863
864         if(self.monster_lifetime != 0)
865         if(time >= self.monster_lifetime)
866         {
867                 Monster_Fade();
868                 return;
869         }
870 }
871
872 void monsters_setstatus()
873 {
874         self.stat_monsters_total = monsters_total;
875         self.stat_monsters_killed = monsters_killed;
876 }
877
878 void Monster_Appear()
879 {
880         self.enemy = activator;
881         self.spawnflags &= ~MONSTERFLAG_APPEAR; // otherwise, we get an endless loop
882         monster_initialize(self.monsterid);
883 }
884
885 float Monster_CheckAppearFlags(entity ent, float monster_id)
886 {
887         if(!(ent.spawnflags & MONSTERFLAG_APPEAR))
888                 return false;
889
890         ent.think = func_null;
891         ent.monsterid = monster_id; // set so this monster is properly registered (otherwise, normal initialization is used)
892         ent.nextthink = 0;
893         ent.use = Monster_Appear;
894         ent.flags = FL_MONSTER; // set so this monster can get butchered
895
896         return true;
897 }
898
899 void monsters_reset()
900 {
901         setorigin(self, self.pos1);
902         self.angles = self.pos2;
903
904         Unfreeze(self); // remove any icy remains
905
906         self.health = self.max_health;
907         self.velocity = '0 0 0';
908         self.enemy = world;
909         self.goalentity = world;
910         self.attack_finished_single = 0;
911         self.moveto = self.origin;
912 }
913
914 void monsters_corpse_damage (entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
915 {
916         self.health -= damage;
917
918         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
919
920         if(self.health <= -100) // 100 health until gone?
921         {
922                 Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
923
924                 // number of monsters spawned with mobspawn command
925                 totalspawned -= 1;
926
927                 self.think = SUB_Remove;
928                 self.nextthink = time + 0.1;
929                 self.event_damage = func_null;
930         }
931 }
932
933 void monster_die(entity attacker, float gibbed)
934 {
935         self.think = monster_dead_think;
936         self.nextthink = time;
937         self.monster_lifetime = time + 5;
938
939         if(self.frozen)
940         {
941                 Unfreeze(self); // remove any icy remains
942                 self.health = 0; // reset by Unfreeze
943         }
944
945         monster_dropitem();
946
947         MonsterSound(monstersound_death, 0, false, CH_VOICE);
948
949         if(!(self.spawnflags & MONSTERFLAG_SPAWNED) && !(self.spawnflags & MONSTERFLAG_RESPAWNED))
950                 monsters_killed += 1;
951
952         if(IS_PLAYER(attacker))
953         if(autocvar_g_monsters_score_spawned || !((self.spawnflags & MONSTERFLAG_SPAWNED) || (self.spawnflags & MONSTERFLAG_RESPAWNED)))
954                 PlayerScore_Add(attacker, SP_SCORE, +autocvar_g_monsters_score_kill);
955
956         if(gibbed)
957         {
958                 // number of monsters spawned with mobspawn command
959                 totalspawned -= 1;
960         }
961
962         if(self.candrop && self.weapon)
963                 W_ThrowNewWeapon(self, self.weapon, 0, self.origin, randomvec() * 150 + '0 0 325');
964
965         self.event_damage       = ((gibbed) ? func_null : monsters_corpse_damage);
966         self.solid                      = SOLID_CORPSE;
967         self.takedamage         = DAMAGE_AIM;
968         self.deadflag           = DEAD_DEAD;
969         self.enemy                      = world;
970         self.movetype           = MOVETYPE_TOSS;
971         self.moveto                     = self.origin;
972         self.touch                      = MonsterTouch; // reset incase monster was pouncing
973         self.reset                      = func_null;
974         self.state                      = 0;
975         self.attack_finished_single = 0;
976
977         if(!((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
978                 self.velocity = '0 0 0';
979
980         MON_ACTION(self.monsterid, MR_DEATH);
981 }
982
983 void monsters_damage (entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
984 {
985         if(self.frozen && deathtype != DEATH_KILL && deathtype != DEATH_NADE_ICE_FREEZE)
986                 return;
987
988         if((self.spawnflags & MONSTERFLAG_INVINCIBLE) && deathtype != DEATH_KILL)
989                 return;
990
991         if(time < self.pain_finished && deathtype != DEATH_KILL)
992                 return;
993
994         if(time < self.spawnshieldtime && deathtype != DEATH_KILL)
995                 return;
996
997         if(deathtype == DEATH_FALL && self.draggedby != world)
998                 return;
999
1000         vector v;
1001         float take, save;
1002
1003         v = healtharmor_applydamage(self.armorvalue, self.m_armor_blockpercent, deathtype, damage);
1004         take = v.x;
1005         save = v.y;
1006
1007         self.health -= take;
1008
1009         WaypointSprite_UpdateHealth(self.sprite, self.health);
1010
1011         self.dmg_time = time;
1012
1013         if(sound_allowed(MSG_BROADCAST, attacker) && deathtype != DEATH_DROWN)
1014                 spamsound (self, CH_PAIN, "misc/bodyimpact1.wav", VOL_BASE, ATTEN_NORM);  // FIXME: PLACEHOLDER
1015
1016         self.velocity += force * self.damageforcescale;
1017
1018         if(deathtype != DEATH_DROWN)
1019         {
1020                 Violence_GibSplash_At(hitloc, force, 2, bound(0, take, 200) / 16, self, attacker);
1021                 if (take > 50)
1022                         Violence_GibSplash_At(hitloc, force * -0.1, 3, 1, self, attacker);
1023                 if (take > 100)
1024                         Violence_GibSplash_At(hitloc, force * -0.2, 3, 1, self, attacker);
1025         }
1026
1027         if(self.health <= 0)
1028         {
1029                 if(deathtype == DEATH_KILL)
1030                         self.candrop = false; // killed by mobkill command
1031
1032                 // TODO: fix this?
1033                 activator = attacker;
1034                 other = self.enemy;
1035                 SUB_UseTargets();
1036                 self.target2 = self.oldtarget2; // reset to original target on death, incase we respawn
1037
1038                 monster_die(attacker, (self.health <= -100 || deathtype == DEATH_KILL));
1039
1040                 WaypointSprite_Kill(self.sprite);
1041
1042                 frag_target = self;
1043                 MUTATOR_CALLHOOK(MonsterDies, attacker);
1044
1045                 if(self.health <= -100 || deathtype == DEATH_KILL) // check if we're already gibbed
1046                 {
1047                         Violence_GibSplash(self, 1, 0.5, attacker);
1048
1049                         self.think = SUB_Remove;
1050                         self.nextthink = time + 0.1;
1051                 }
1052         }
1053 }
1054
1055 void monster_setupcolors(entity mon)
1056 {
1057         if(IS_PLAYER(mon.monster_owner))
1058                 mon.colormap = mon.monster_owner.colormap;
1059         else if(teamplay && mon.team)
1060                 mon.colormap = 1024 + (mon.team - 1) * 17;
1061         else
1062         {
1063                 if(mon.monster_skill <= MONSTER_SKILL_EASY)
1064                         mon.colormap = 1029;
1065                 else if(mon.monster_skill <= MONSTER_SKILL_MEDIUM)
1066                         mon.colormap = 1027;
1067                 else if(mon.monster_skill <= MONSTER_SKILL_HARD)
1068                         mon.colormap = 1038;
1069                 else if(mon.monster_skill <= MONSTER_SKILL_INSANE)
1070                         mon.colormap = 1028;
1071                 else if(mon.monster_skill <= MONSTER_SKILL_NIGHTMARE)
1072                         mon.colormap = 1032;
1073                 else
1074                         mon.colormap = 1024;
1075         }
1076 }
1077
1078 void monster_changeteam(entity ent, float newteam)
1079 {
1080         if(!teamplay) { return; }
1081
1082         ent.team = newteam;
1083         ent.monster_attack = true; // new team, activate attacking
1084         monster_setupcolors(ent);
1085
1086         if(ent.sprite)
1087         {
1088                 WaypointSprite_UpdateTeamRadar(ent.sprite, RADARICON_DANGER, ((newteam) ? Team_ColorRGB(newteam) : '1 0 0'));
1089
1090                 ent.sprite.team = newteam;
1091                 ent.sprite.SendFlags |= 1;
1092         }
1093 }
1094
1095 void monster_think()
1096 {
1097         self.think = monster_think;
1098         self.nextthink = self.ticrate;
1099
1100         if(self.monster_lifetime)
1101         if(time >= self.monster_lifetime)
1102         {
1103                 Damage(self, self, self, self.health + self.max_health, DEATH_KILL, self.origin, self.origin);
1104                 return;
1105         }
1106
1107         MON_ACTION(self.monsterid, MR_THINK);
1108
1109         CSQCMODEL_AUTOUPDATE();
1110 }
1111
1112 float monster_spawn()
1113 {
1114         MON_ACTION(self.monsterid, MR_SETUP);
1115
1116         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1117         {
1118                 Monster_CheckMinibossFlag();
1119                 self.health *= Monster_SkillModifier();
1120         }
1121
1122         self.max_health = self.health;
1123         self.pain_finished = self.nextthink;
1124
1125         if(IS_PLAYER(self.monster_owner))
1126                 self.effects |= EF_DIMLIGHT;
1127
1128         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1129         if(!self.skin)
1130                 self.skin = rint(random() * 4);
1131
1132         if(!self.attack_range)
1133                 self.attack_range = autocvar_g_monsters_attack_range;
1134
1135         if(!self.wander_delay) { self.wander_delay = 2; }
1136         if(!self.wander_distance) { self.wander_distance = 600; }
1137
1138         precache_monstersounds();
1139         UpdateMonsterSounds();
1140
1141         if(teamplay)
1142                 self.monster_attack = true; // we can have monster enemies in team games
1143
1144         MonsterSound(monstersound_spawn, 0, false, CH_VOICE);
1145
1146         WaypointSprite_Spawn(M_NAME(self.monsterid), 0, 1024, self, '0 0 1' * (self.maxs.z + 15), world, self.team, self, sprite, true, RADARICON_DANGER, ((self.team) ? Team_ColorRGB(self.team) : '1 0 0'));
1147         if(!(self.spawnflags & MONSTERFLAG_INVINCIBLE))
1148         {
1149                 WaypointSprite_UpdateMaxHealth(self.sprite, self.max_health);
1150                 WaypointSprite_UpdateHealth(self.sprite, self.health);
1151         }
1152
1153         self.think = monster_think;
1154         self.nextthink = time + self.ticrate;
1155
1156         if(MUTATOR_CALLHOOK(MonsterSpawn))
1157                 return false;
1158
1159         return true;
1160 }
1161
1162 float monster_initialize(float mon_id)
1163 {
1164         if(!autocvar_g_monsters) { return false; }
1165         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) { MON_ACTION(mon_id, MR_PRECACHE); }
1166         if(Monster_CheckAppearFlags(self, mon_id)) { return true; } // return true so the monster isn't removed
1167
1168         entity mon = get_monsterinfo(mon_id);
1169
1170         if(!self.monster_skill)
1171                 self.monster_skill = cvar("g_monsters_skill");
1172
1173         // support for quake style removing monsters based on skill
1174         if(self.monster_skill == MONSTER_SKILL_EASY) if(self.spawnflags & MONSTERSKILL_NOTEASY) { return false; }
1175         if(self.monster_skill == MONSTER_SKILL_MEDIUM) if(self.spawnflags & MONSTERSKILL_NOTMEDIUM) { return false; }
1176         if(self.monster_skill == MONSTER_SKILL_HARD) if(self.spawnflags & MONSTERSKILL_NOTHARD) { return false; }
1177
1178         if(self.team && !teamplay)
1179                 self.team = 0;
1180
1181         if(!(self.spawnflags & MONSTERFLAG_SPAWNED)) // naturally spawned monster
1182         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) // don't count re-spawning monsters either
1183                 monsters_total += 1;
1184
1185         setmodel(self, mon.model);
1186         //setsize(self, mon.mins, mon.maxs);
1187         self.flags                              = FL_MONSTER;
1188         self.takedamage                 = DAMAGE_AIM;
1189         self.bot_attack                 = true;
1190         self.iscreature                 = true;
1191         self.teleportable               = true;
1192         self.damagedbycontents  = true;
1193         self.monsterid                  = mon_id;
1194         self.damageforcescale   = 0;
1195         self.event_damage               = monsters_damage;
1196         self.touch                              = MonsterTouch;
1197         self.use                                = monster_use;
1198         self.solid                              = SOLID_BBOX;
1199         self.movetype                   = MOVETYPE_WALK;
1200         self.spawnshieldtime    = time + autocvar_g_monsters_spawnshieldtime;
1201         self.enemy                              = world;
1202         self.velocity                   = '0 0 0';
1203         self.moveto                             = self.origin;
1204         self.pos1                               = self.origin;
1205         self.pos2                               = self.angles;
1206         self.reset                              = monsters_reset;
1207         self.netname                    = mon.netname;
1208         self.monster_name               = M_NAME(mon_id);
1209         self.candrop                    = true;
1210         self.view_ofs                   = '0 0 1' * (self.maxs.z * 0.5);
1211         self.oldtarget2                 = self.target2;
1212         self.pass_distance              = 0;
1213         self.deadflag                   = DEAD_NO;
1214         self.noalign                    = ((mon.spawnflags & MONSTER_TYPE_FLY) || (mon.spawnflags & MONSTER_TYPE_SWIM));
1215         self.spawn_time                 = time;
1216         self.spider_slowness    = 0;
1217         self.gravity                    = 1;
1218         self.dphitcontentsmask  = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP;
1219
1220         if(!self.scale)
1221                 self.scale = 1;
1222
1223         if(autocvar_g_monsters_edit)
1224                 self.grab = 1; // owner may carry their monster
1225
1226         if(autocvar_g_fullbrightplayers)
1227                 self.effects |= EF_FULLBRIGHT;
1228
1229         if(autocvar_g_nodepthtestplayers)
1230                 self.effects |= EF_NODEPTHTEST;
1231
1232         if(mon.spawnflags & MONSTER_TYPE_SWIM)
1233                 self.flags |= FL_SWIM;
1234
1235         if(mon.spawnflags & MONSTER_TYPE_FLY)
1236         {
1237                 self.flags |= FL_FLY;
1238                 self.movetype = MOVETYPE_FLY;
1239         }
1240
1241         if(mon.spawnflags & MONSTER_SIZE_BROKEN)
1242         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1243                 self.scale *= 1.3;
1244
1245         setsize(self, mon.mins * self.scale, mon.maxs * self.scale);
1246
1247         if(!self.ticrate)
1248                 self.ticrate = autocvar_g_monsters_think_delay;
1249
1250         self.ticrate = bound(sys_frametime, self.ticrate, 60);
1251
1252         if(!self.m_armor_blockpercent)
1253                 self.m_armor_blockpercent = 0.5;
1254
1255         if(!self.target_range)
1256                 self.target_range = autocvar_g_monsters_target_range;
1257
1258         if(!self.respawntime)
1259                 self.respawntime = autocvar_g_monsters_respawn_delay;
1260
1261         if(!self.monster_moveflags)
1262                 self.monster_moveflags = MONSTER_MOVE_WANDER;
1263
1264         if(!self.noalign)
1265         {
1266                 setorigin(self, self.origin + '0 0 20');
1267                 tracebox(self.origin + '0 0 64', self.mins, self.maxs, self.origin - '0 0 10000', MOVE_WORLDONLY, self);
1268                 setorigin(self, trace_endpos);
1269         }
1270
1271         if(!monster_spawn())
1272                 return false;
1273
1274         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1275                 monster_setupcolors(self);
1276
1277         CSQCMODEL_AUTOINIT();
1278
1279         return true;
1280 }