]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/turrets/sv_turrets.qc
Some more defs.qh cleanup, update gameplay hash (again)
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / turrets / sv_turrets.qc
1 #include "sv_turrets.qh"
2 #ifdef SVQC
3 #include <server/autocvars.qh>
4 #include <server/g_damage.qh>
5 #include <server/weapons/common.qh>
6 #include <server/weapons/weaponsystem.qh>
7 #include <common/mapobjects/defs.qh>
8
9 // Generic aiming
10 vector turret_aim_generic(entity this)
11 {
12
13         vector pre_pos, prep;
14         float distance, impact_time = 0, i, mintime;
15
16         turret_tag_fire_update(this);
17
18         if(this.aim_flags & TFL_AIM_SIMPLE)
19                 return real_origin(this.enemy);
20
21         mintime = max(this.attack_finished_single[0] - time,0) + sys_frametime;
22
23         // Baseline
24         pre_pos = real_origin(this.enemy);
25
26         // Lead?
27         if (this.aim_flags & TFL_AIM_LEAD)
28         {
29                 if (this.aim_flags & TFL_AIM_SHOTTIMECOMPENSATE)           // Need to conpensate for shot traveltime
30                 {
31                         prep = pre_pos;
32
33                         distance = vlen(prep - this.tur_shotorg);
34                         impact_time = distance / this.shot_speed;
35
36                         prep = pre_pos + (this.enemy.velocity * (impact_time + mintime));
37
38                         if(this.aim_flags & TFL_AIM_ZPREDICT)
39                         if(!IS_ONGROUND(this.enemy))
40                         if(this.enemy.move_movetype == MOVETYPE_WALK || this.enemy.move_movetype == MOVETYPE_TOSS || this.enemy.move_movetype == MOVETYPE_BOUNCE)
41                         {
42                                 float vz;
43                                 prep_z = pre_pos_z;
44                                 vz = this.enemy.velocity_z;
45                                 for(i = 0; i < impact_time; i += sys_frametime)
46                                 {
47                                         vz = vz - (autocvar_sv_gravity * sys_frametime);
48                                         prep_z = prep_z + vz * sys_frametime;
49                                 }
50                         }
51                         pre_pos = prep;
52                 }
53                 else
54                         pre_pos = pre_pos + this.enemy.velocity * mintime;
55         }
56
57         if(this.aim_flags & TFL_AIM_SPLASH)
58         {
59                 //tracebox(pre_pos + '0 0 32',this.enemy.mins,this.enemy.maxs,pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
60                 traceline(pre_pos + '0 0 32',pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
61                 if(trace_fraction != 1.0)
62                         pre_pos = trace_endpos;
63         }
64
65         return pre_pos;
66 }
67
68 float turret_targetscore_support(entity _turret,entity _target)
69 {
70         float score;            // Total score
71         float s_score = 0, d_score;
72
73         if (_turret.enemy == _target) s_score = 1;
74
75         d_score = min(_turret.target_range_optimal,tvt_dist) / max(_turret.target_range_optimal,tvt_dist);
76
77         score = (d_score * _turret.target_select_rangebias) +
78                         (s_score * _turret.target_select_samebias);
79
80         return score;
81 }
82
83 /*
84 * Generic bias aware score system.
85 */
86 float turret_targetscore_generic(entity _turret, entity _target)
87 {
88         float d_dist;      // Defendmode Distance
89         float score;            // Total score
90         float d_score;    // Distance score
91         float a_score;    // Angular score
92         float m_score = 0;  // missile score
93         float p_score = 0;  // player score
94         float ikr;                // ideal kill range
95
96         if (_turret.tur_defend)
97         {
98                 d_dist = vlen(real_origin(_target) - _turret.tur_defend.origin);
99                 ikr = vlen(_turret.origin - _turret.tur_defend.origin);
100                 d_score = 1 - d_dist / _turret.target_range;
101         }
102         else
103         {
104                 // Make a normlized value base on the targets distance from our optimal killzone
105                 ikr = _turret.target_range_optimal;
106                 d_score = min(ikr, tvt_dist) / max(ikr, tvt_dist);
107         }
108
109         a_score = 1 - tvt_thadf / _turret.aim_maxrot;
110
111         if ((_turret.target_select_missilebias > 0) && (_target.flags & FL_PROJECTILE))
112                 m_score = 1;
113
114         if ((_turret.target_select_playerbias > 0) && IS_CLIENT(_target))
115                 p_score = 1;
116
117         d_score = max(d_score, 0);
118         a_score = max(a_score, 0);
119         m_score = max(m_score, 0);
120         p_score = max(p_score, 0);
121
122         score = (d_score * _turret.target_select_rangebias) +
123                         (a_score * _turret.target_select_anglebias) +
124                         (m_score * _turret.target_select_missilebias) +
125                         (p_score * _turret.target_select_playerbias);
126
127         if(vdist((_turret.tur_shotorg - real_origin(_target)), >, _turret.target_range))
128         {
129                 //dprint("Wtf?\n");
130                 score *= 0.001;
131         }
132
133 #ifdef TURRET_DEBUG
134         string sd,sa,sm,sp,ss;
135         string sdt,sat,smt,spt;
136
137         sd = ftos(d_score);
138         d_score *= _turret.target_select_rangebias;
139         sdt = ftos(d_score);
140
141         //sv = ftos(v_score);
142         //v_score *= _turret.target_select_samebias;
143         //svt = ftos(v_score);
144
145         sa = ftos(a_score);
146         a_score *= _turret.target_select_anglebias;
147         sat = ftos(a_score);
148
149         sm = ftos(m_score);
150         m_score *= _turret.target_select_missilebias;
151         smt = ftos(m_score);
152
153         sp = ftos(p_score);
154         p_score *= _turret.target_select_playerbias;
155         spt = ftos(p_score);
156
157
158         ss = ftos(score);
159         bprint("^3Target scores^7 \[  ",_turret.netname, "  \] ^3for^7 \[  ", _target.netname,"  \]\n");
160         bprint("^5Range:\[  ",sd,  "  \]^2+bias:\[  ",sdt,"  \]\n");
161         bprint("^5Angle:\[  ",sa,  "  \]^2+bias:\[  ",sat,"  \]\n");
162         bprint("^5Missile:\[  ",sm,"  \]^2+bias:\[  ",smt,"  \]\n");
163         bprint("^5Player:\[  ",sp, "  \]^2+bias:\[  ",spt,"  \]\n");
164         bprint("^3Total (w/bias):\[^1",ss,"\]\n");
165
166 #endif
167
168         return score;
169 }
170
171 // Generic damage handling
172 void turret_hide(entity this)
173 {
174         this.effects   |= EF_NODRAW;
175         this.nextthink = time + this.respawntime - 0.2;
176         setthink(this, turret_respawn);
177 }
178
179 void turret_die(entity this)
180 {
181         this.deadflag             = DEAD_DEAD;
182         this.tur_head.deadflag = this.deadflag;
183
184 // Unsolidify and hide real parts
185         this.solid                       = SOLID_NOT;
186         this.tur_head.solid      = this.solid;
187
188         this.event_damage                 = func_null;
189         this.event_heal = func_null;
190         this.takedamage                  = DAMAGE_NO;
191
192         SetResourceExplicit(this, RES_HEALTH, 0);
193
194 // Go boom
195         //RadiusDamage (this,this, min(this.ammo,50),min(this.ammo,50) * 0.25,250,NULL,min(this.ammo,50)*5,DEATH_TURRET,NULL);
196
197         Turret tur = get_turretinfo(this.m_id);
198         if(this.damage_flags & TFL_DMG_DEATH_NORESPAWN)
199         {
200                 // do a simple explosion effect here, since CSQC can't do it on a to-be-removed entity
201                 sound(this, CH_SHOTS, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
202                 Send_Effect(EFFECT_ROCKET_EXPLODE, this.origin, '0 0 0', 1);
203
204                 tur.tr_death(tur, this);
205
206                 delete(this.tur_head);
207                 delete(this);
208         }
209         else
210         {
211                 // Setup respawn
212                 this.SendFlags    |= TNSF_STATUS;
213                 this.nextthink   = time + 0.2;
214                 setthink(this, turret_hide);
215
216                 tur.tr_death(tur, this);
217         }
218 }
219
220 void turret_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
221 {
222         // Enough already!
223         if(this.deadflag == DEAD_DEAD)
224                 return;
225
226         // Inactive turrets take no damage. (hm..)
227         if(!this.active)
228                 return;
229
230         if(SAME_TEAM(this, attacker))
231         {
232                 if(autocvar_g_friendlyfire)
233                         damage = damage * autocvar_g_friendlyfire;
234                 else
235                         return;
236         }
237
238         TakeResource(this, RES_HEALTH, damage);
239
240         // thorw head slightly off aim when hit?
241         if (this.damage_flags & TFL_DMG_HEADSHAKE)
242         {
243                 this.tur_head.angles_x = this.tur_head.angles_x + (-0.5 + random()) * damage;
244                 this.tur_head.angles_y = this.tur_head.angles_y + (-0.5 + random()) * damage;
245
246                 this.SendFlags  |= TNSF_ANG;
247         }
248
249         if (this.turret_flags & TUR_FLAG_MOVE)
250                 this.velocity = this.velocity + vforce;
251
252         if (GetResource(this, RES_HEALTH) <= 0)
253         {
254                 this.event_damage                 = func_null;
255                 this.tur_head.event_damage = func_null;
256                 this.event_heal = func_null;
257                 this.tur_head.event_heal = func_null;
258                 this.takedamage                  = DAMAGE_NO;
259                 this.nextthink = time;
260                 setthink(this, turret_die);
261         }
262
263         this.SendFlags  |= TNSF_STATUS;
264 }
265
266 bool turret_heal(entity targ, entity inflictor, float amount, float limit)
267 {
268         float true_limit = ((limit != RES_LIMIT_NONE) ? limit : targ.max_health);
269         if(GetResource(targ, RES_HEALTH) <= 0 || GetResource(targ, RES_HEALTH) >= true_limit)
270                 return false;
271
272         GiveResourceWithLimit(targ, RES_HEALTH, amount, true_limit);
273         targ.SendFlags |= TNSF_STATUS;
274         return true;
275 }
276
277 void turret_think(entity this);
278 void turret_respawn(entity this)
279 {
280         // Make sure all parts belong to the same team since
281         // this function doubles as "teamchange" function.
282         this.tur_head.team      = this.team;
283         this.effects                       &= ~EF_NODRAW;
284         this.deadflag                           = DEAD_NO;
285         this.effects                            = EF_LOWPRECISION;
286         this.solid                                      = SOLID_BBOX;
287         this.takedamage                         = DAMAGE_AIM;
288         this.event_damage                       = turret_damage;
289         this.event_heal                         = turret_heal;
290         this.avelocity                          = '0 0 0';
291         this.tur_head.avelocity         = this.avelocity;
292         this.tur_head.angles            = this.idle_aim;
293         SetResourceExplicit(this, RES_HEALTH, this.max_health);
294         this.enemy                                      = NULL;
295         this.volly_counter                      = this.shot_volly;
296         this.ammo                                       = this.ammo_max;
297
298         this.nextthink = time + this.ticrate;
299         setthink(this, turret_think);
300
301         this.SendFlags = TNSF_FULL_UPDATE;
302
303         Turret tur = get_turretinfo(this.m_id);
304         tur.tr_setup(tur, this);
305 }
306
307
308 // Main functions
309 .float clientframe;
310 void turrets_setframe(entity this, float _frame, float client_only)
311 {
312         if((client_only ? this.clientframe : this.frame ) != _frame)
313         {
314                 this.SendFlags |= TNSF_ANIM;
315                 this.anim_start_time = time;
316         }
317
318          if(client_only)
319                 this.clientframe = _frame;
320         else
321                 this.frame = _frame;
322
323 }
324
325 bool turret_send(entity this, entity to, float sf)
326 {
327         WriteHeader(MSG_ENTITY, ENT_CLIENT_TURRET);
328         WriteByte(MSG_ENTITY, sf);
329         if(sf & TNSF_SETUP)
330         {
331                 WriteByte(MSG_ENTITY, this.m_id);
332
333                 WriteVector(MSG_ENTITY, this.origin);
334
335                 WriteAngleVector2D(MSG_ENTITY, this.angles);
336         }
337
338         if(sf & TNSF_ANG)
339         {
340                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_x));
341                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_y));
342         }
343
344         if(sf & TNSF_AVEL)
345         {
346                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_x));
347                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_y));
348         }
349
350         if(sf & TNSF_MOVE)
351         {
352                 WriteVector(MSG_ENTITY, this.origin);
353
354                 WriteVector(MSG_ENTITY, this.velocity);
355
356                 WriteShort(MSG_ENTITY, rint(this.angles_y));
357         }
358
359         if(sf & TNSF_ANIM)
360         {
361                 WriteCoord(MSG_ENTITY, this.anim_start_time);
362                 WriteByte(MSG_ENTITY, this.frame);
363         }
364
365         if(sf & TNSF_STATUS)
366         {
367                 WriteByte(MSG_ENTITY, this.team);
368
369                 if(GetResource(this, RES_HEALTH) <= 0)
370                         WriteByte(MSG_ENTITY, 0);
371                 else
372                         WriteByte(MSG_ENTITY, ceil((GetResource(this, RES_HEALTH) / this.max_health) * 255));
373         }
374
375         return true;
376 }
377
378 void load_unit_settings(entity ent, bool is_reload)
379 {
380         if (ent == NULL)
381                 return;
382
383         if(!ent.turret_scale_damage)    ent.turret_scale_damage = 1;
384         if(!ent.turret_scale_range)             ent.turret_scale_range  = 1;
385         if(!ent.turret_scale_refire)    ent.turret_scale_refire = 1;
386         if(!ent.turret_scale_ammo)              ent.turret_scale_ammo   = 1;
387         if(!ent.turret_scale_aim)               ent.turret_scale_aim     = 1;
388         if(!ent.turret_scale_health)    ent.turret_scale_health = 1;
389         if(!ent.turret_scale_respawn)   ent.turret_scale_respawn = 1;
390
391         if (is_reload)
392         {
393                 ent.enemy = NULL;
394                 ent.tur_head.avelocity = '0 0 0';
395
396                 ent.tur_head.angles = '0 0 0';
397         }
398
399         string unitname = ent.netname;
400         #define X(class, prefix, fld, type) ent.fld = cvar(strcat("g_turrets_unit_", prefix, "_", #fld));
401         TR_PROPS_COMMON(X, , unitname)
402         #undef X
403
404         ent.ammo_max             *= ent.turret_scale_ammo;
405         ent.ammo_recharge        *= ent.turret_scale_ammo;
406         ent.aim_speed            *= ent.turret_scale_aim;
407         SetResourceExplicit(ent, RES_HEALTH, GetResource(ent, RES_HEALTH) * ent.turret_scale_health);
408         ent.respawntime          *= ent.turret_scale_respawn;
409         ent.shot_dmg             *= ent.turret_scale_damage;
410         ent.shot_refire          *= ent.turret_scale_refire;
411         ent.shot_radius          *= ent.turret_scale_damage;
412         ent.shot_force           *= ent.turret_scale_damage;
413         ent.shot_volly_refire    *= ent.turret_scale_refire;
414         ent.target_range         *= ent.turret_scale_range;
415         ent.target_range_min     *= ent.turret_scale_range;
416         ent.target_range_optimal *= ent.turret_scale_range;
417
418         if(is_reload) {
419                 Turret tur = get_turretinfo(ent.m_id);
420                 tur.tr_setup(tur, ent);
421         }
422 }
423
424 void turret_projectile_explode(entity this)
425 {
426
427         this.takedamage = DAMAGE_NO;
428         this.event_damage = func_null;
429 #ifdef TURRET_DEBUG
430         float d;
431         d = RadiusDamage (this, this.owner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.projectiledeathtype, DMG_NOWEP, NULL);
432         this.owner.tur_debug_dmg_t_h = this.owner.tur_debug_dmg_t_h + d;
433         this.owner.tur_debug_dmg_t_f = this.owner.tur_debug_dmg_t_f + this.owner.shot_dmg;
434 #else
435         RadiusDamage (this, this.realowner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.projectiledeathtype, DMG_NOWEP, NULL);
436 #endif
437         delete(this);
438 }
439
440 void turret_projectile_touch(entity this, entity toucher)
441 {
442         PROJECTILE_TOUCH(this, toucher);
443         turret_projectile_explode(this);
444 }
445
446 void turret_projectile_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
447 {
448         this.velocity  += vforce;
449         TakeResource(this, RES_HEALTH, damage);
450         //this.realowner = attacker; // Dont change realowner, it does not make much sense for turrets
451         if(GetResource(this, RES_HEALTH) <= 0)
452                 W_PrepareExplosionByDamage(this, this.owner, turret_projectile_explode);
453 }
454
455 entity turret_projectile(entity actor, Sound _snd, float _size, float _health, float _death, float _proj_type, float _cull, float _cli_anim)
456 {
457         TC(Sound, _snd);
458         entity proj;
459
460         sound (actor, CH_WEAPON_A, _snd, VOL_BASE, ATTEN_NORM);
461         proj                             = spawn ();
462         setorigin(proj, actor.tur_shotorg);
463         setsize(proj, '-0.5 -0.5 -0.5' * _size, '0.5 0.5 0.5' * _size);
464         proj.owner                = actor;
465         proj.realowner    = actor;
466         proj.bot_dodge    = true;
467         proj.bot_dodgerating = actor.shot_dmg;
468         setthink(proj, turret_projectile_explode);
469         settouch(proj, turret_projectile_touch);
470         proj.nextthink    = time + 9;
471         set_movetype(proj, MOVETYPE_FLYMISSILE);
472         proj.velocity           = normalize(actor.tur_shotdir_updated + randomvec() * actor.shot_spread) * actor.shot_speed;
473         proj.flags = FL_PROJECTILE;
474         IL_PUSH(g_projectiles, proj);
475         IL_PUSH(g_bot_dodge, proj);
476         proj.enemy                = actor.enemy;
477         proj.projectiledeathtype         = _death;
478         PROJECTILE_MAKETRIGGER(proj);
479         if(_health)
480         {
481                 SetResourceExplicit(proj, RES_HEALTH, _health);
482                 proj.takedamage  = DAMAGE_YES;
483                 proj.event_damage  = turret_projectile_damage;
484         }
485         else
486                 proj.flags |= FL_NOTARGET;
487
488         CSQCProjectile(proj, _cli_anim, _proj_type, _cull);
489
490         return proj;
491 }
492
493 /**
494 ** updates enemy distances, predicted impact point/time
495 ** and updated aim<->predict impact distance.
496 **/
497 void turret_do_updates(entity t_turret)
498 {
499         vector enemy_pos = real_origin(t_turret.enemy);
500
501         turret_tag_fire_update(t_turret);
502
503         t_turret.tur_shotdir_updated = v_forward;
504         t_turret.tur_dist_enemy = vlen(t_turret.tur_shotorg - enemy_pos);
505         t_turret.tur_dist_aimpos = vlen(t_turret.tur_shotorg - t_turret.tur_aimpos);
506
507         /*if((t_turret.firecheck_flags & TFL_FIRECHECK_VERIFIED) && (t_turret.enemy))
508         {
509                 oldpos = t_turret.enemy.origin;
510                 setorigin(t_turret.enemy, t_turret.tur_aimpos);
511                 tracebox(t_turret.tur_shotorg, '-1 -1 -1', '1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
512                 setorigin(t_turret.enemy, oldpos);
513
514                 if(trace_ent == t_turret.enemy)
515                         t_turret.tur_dist_impact_to_aimpos = 0;
516                 else
517                         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos);
518         }
519         else*/
520                 tracebox(t_turret.tur_shotorg, '-1 -1 -1','1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
521
522         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos) - (vlen(t_turret.enemy.maxs - t_turret.enemy.mins) * 0.5);
523         t_turret.tur_impactent                   = trace_ent;
524         t_turret.tur_impacttime                 = vlen(t_turret.tur_shotorg - trace_endpos) / t_turret.shot_speed;
525 }
526
527 /**
528 ** Handles head rotation according to
529 ** the units .track_type and .track_flags
530 **/
531 .float turret_framecounter;
532 void turret_track(entity this)
533 {
534         vector target_angle; // This is where we want to aim
535         vector move_angle;   // This is where we can aim
536         float f_tmp;
537         vector v1, v2;
538         v1 = this.tur_head.angles;
539         v2 = this.tur_head.avelocity;
540
541         if (this.track_flags == TFL_TRACK_NO)
542                 return;
543
544         if(!this.active)
545                 target_angle = this.idle_aim - ('1 0 0' * this.aim_maxpitch);
546         else if (this.enemy == NULL)
547         {
548                 if(time > this.lip)
549                         target_angle = this.idle_aim + this.angles;
550                 else
551                         target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
552         }
553         else
554         {
555                 target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
556         }
557
558         this.tur_head.angles_x = anglemods(this.tur_head.angles_x);
559         this.tur_head.angles_y = anglemods(this.tur_head.angles_y);
560
561         // Find the diffrence between where we currently aim and where we want to aim
562         //move_angle = target_angle - (this.angles + this.tur_head.angles);
563         //move_angle = shortangle_vxy(move_angle,(this.angles + this.tur_head.angles));
564
565         move_angle = AnglesTransform_ToAngles(AnglesTransform_LeftDivide(AnglesTransform_FromAngles(this.angles), AnglesTransform_FromAngles(target_angle))) - this.tur_head.angles;
566         move_angle = shortangle_vxy(move_angle, this.tur_head.angles);
567
568         switch(this.track_type)
569         {
570                 case TFL_TRACKTYPE_STEPMOTOR:
571                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
572                         if (this.track_flags & TFL_TRACK_PITCH)
573                         {
574                                 this.tur_head.angles_x += bound(-f_tmp,move_angle_x, f_tmp);
575                                 if(this.tur_head.angles_x > this.aim_maxpitch)
576                                         this.tur_head.angles_x = this.aim_maxpitch;
577
578                                 if(this.tur_head.angles_x  < -this.aim_maxpitch)
579                                         this.tur_head.angles_x = this.aim_maxpitch;
580                         }
581
582                         if (this.track_flags & TFL_TRACK_ROTATE)
583                         {
584                                 this.tur_head.angles_y += bound(-f_tmp, move_angle_y, f_tmp);
585                                 if(this.tur_head.angles_y > this.aim_maxrot)
586                                         this.tur_head.angles_y = this.aim_maxrot;
587
588                                 if(this.tur_head.angles_y  < -this.aim_maxrot)
589                                         this.tur_head.angles_y = this.aim_maxrot;
590                         }
591
592                         // CSQC
593                         this.SendFlags  |= TNSF_ANG;
594
595                         return;
596
597                 case TFL_TRACKTYPE_FLUIDINERTIA:
598                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
599                         move_angle_x = bound(-this.aim_speed, move_angle_x * this.track_accel_pitch * f_tmp, this.aim_speed);
600                         move_angle_y = bound(-this.aim_speed, move_angle_y * this.track_accel_rot * f_tmp, this.aim_speed);
601                         move_angle = (this.tur_head.avelocity * this.track_blendrate) + (move_angle * (1 - this.track_blendrate));
602                         break;
603
604                 case TFL_TRACKTYPE_FLUIDPRECISE:
605
606                         move_angle_y = bound(-this.aim_speed, move_angle_y, this.aim_speed);
607                         move_angle_x = bound(-this.aim_speed, move_angle_x, this.aim_speed);
608
609                         break;
610         }
611
612         //  pitch
613         if (this.track_flags & TFL_TRACK_PITCH)
614         {
615                 this.tur_head.avelocity_x = move_angle_x;
616                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) > this.aim_maxpitch)
617                 {
618                         this.tur_head.avelocity_x = 0;
619                         this.tur_head.angles_x = this.aim_maxpitch;
620
621                         this.SendFlags  |= TNSF_ANG;
622                 }
623
624                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) < -this.aim_maxpitch)
625                 {
626                         this.tur_head.avelocity_x = 0;
627                         this.tur_head.angles_x = -this.aim_maxpitch;
628
629                         this.SendFlags  |= TNSF_ANG;
630                 }
631         }
632
633         //  rot
634         if (this.track_flags & TFL_TRACK_ROTATE)
635         {
636                 this.tur_head.avelocity_y = move_angle_y;
637
638                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) > this.aim_maxrot)
639                 {
640                         this.tur_head.avelocity_y = 0;
641                         this.tur_head.angles_y = this.aim_maxrot;
642
643                         this.SendFlags  |= TNSF_ANG;
644                 }
645
646                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) < -this.aim_maxrot)
647                 {
648                         this.tur_head.avelocity_y = 0;
649                         this.tur_head.angles_y = -this.aim_maxrot;
650
651                         this.SendFlags  |= TNSF_ANG;
652                 }
653         }
654
655         this.SendFlags  |= TNSF_AVEL;
656
657         // Force a angle update every 10'th frame
658         this.turret_framecounter += 1;
659         if(this.turret_framecounter >= 10)
660         {
661                 this.SendFlags |= TNSF_ANG;
662                 this.turret_framecounter = 0;
663         }
664 }
665
666 /*
667  + TFL_TARGETSELECT_NO
668  + TFL_TARGETSELECT_LOS
669  + TFL_TARGETSELECT_PLAYERS
670  + TFL_TARGETSELECT_MISSILES
671  + TFL_TARGETSELECT_VEHICLES
672  - TFL_TARGETSELECT_TRIGGERTARGET
673  + TFL_TARGETSELECT_ANGLELIMITS
674  + TFL_TARGETSELECT_RANGELIMITS
675  + TFL_TARGETSELECT_TEAMCHECK
676  - TFL_TARGETSELECT_NOBUILTIN
677  + TFL_TARGETSELECT_OWNTEAM
678 */
679
680 /**
681 ** Evaluate a entity for target valitity based on validate_flags
682 ** NOTE: the caller must check takedamage before calling this, to inline this check.
683 **/
684 float turret_validate_target(entity e_turret, entity e_target, float validate_flags)
685 {
686         vector v_tmp;
687
688         //if(!validate_flags & TFL_TARGETSELECT_NOBUILTIN)
689         //      return -0.5;
690
691         if(!e_target)
692                 return -2;
693
694         if(e_target.owner == e_turret)
695                 return -0.5;
696
697         if(!checkpvs(e_target.origin, e_turret))
698                 return -1;
699
700         if(e_target.alpha != 0 && e_target.alpha <= 0.3)
701                 return -1;
702
703         if(MUTATOR_CALLHOOK(TurretValidateTarget, e_turret, e_target, validate_flags))
704                 return M_ARGV(3, float);
705
706         if (validate_flags & TFL_TARGETSELECT_NO)
707                 return -4;
708
709         // If only this was used more..
710         if (e_target.flags & FL_NOTARGET)
711                 return -5;
712
713         // Cant touch this
714         if (GetResource(e_target, RES_HEALTH) <= 0)
715                 return -6;
716         else if (STAT(FROZEN, e_target))
717                 return -6;
718
719         // vehicle
720         if(IS_VEHICLE(e_target))
721         {
722                 if ((validate_flags & TFL_TARGETSELECT_VEHICLES) && !e_target.owner)
723                         return -7;
724         }
725
726         // player
727         if (IS_CLIENT(e_target))
728         {
729                 if(!(validate_flags & TFL_TARGETSELECT_PLAYERS))
730                         return -7;
731
732                 if (IS_DEAD(e_target))
733                         return -8;
734         }
735
736         // enemy turrets
737         if(validate_flags & TFL_TARGETSELECT_NOTURRETS)
738         if(e_target.owner.tur_head == e_target)
739         if(e_target.team != e_turret.team) // Dont break support units.
740                 return -9;
741
742         // Missile
743         if (e_target.flags & FL_PROJECTILE)
744         if(!(validate_flags & TFL_TARGETSELECT_MISSILES))
745                 return -10;
746
747         if (validate_flags & TFL_TARGETSELECT_MISSILESONLY)
748         if(!(e_target.flags & FL_PROJECTILE))
749                 return -10.5;
750
751         // Team check
752         if (validate_flags & TFL_TARGETSELECT_TEAMCHECK)
753         {
754                 if (validate_flags & TFL_TARGETSELECT_OWNTEAM)
755                 {
756                         if (e_target.team != e_turret.team)
757                                 return -11;
758
759                         if (e_turret.team != e_target.owner.team)
760                                 return -12;
761
762                         if (e_turret.team != e_target.aiment.team)
763                                 return -12; // portals
764                 }
765                 else
766                 {
767                         if (e_target.team == e_turret.team)
768                                 return -13;
769
770                         if (e_turret.team == e_target.owner.team)
771                                 return -14;
772
773                         if (e_turret.team == e_target.aiment.team)
774                                 return -14; // portals
775                 }
776         }
777
778         // Range limits?
779         tvt_dist = vlen(e_turret.origin - real_origin(e_target));
780         if (validate_flags & TFL_TARGETSELECT_RANGELIMITS)
781         {
782                 if (tvt_dist < e_turret.target_range_min)
783                         return -15;
784
785                 if (tvt_dist > e_turret.target_range)
786                         return -16;
787         }
788
789         // Can we even aim this thing?
790         tvt_thadv = angleofs3(e_turret.tur_head.origin, e_turret.angles + e_turret.tur_head.angles, e_target.origin);
791         tvt_tadv = shortangle_vxy(angleofs(e_turret, e_target), e_turret.angles);
792         tvt_thadf = vlen(tvt_thadv);
793
794         /*
795         if(validate_flags & TFL_TARGETSELECT_FOV)
796         {
797                 if(e_turret.target_select_fov < tvt_thadf)
798                         return -21;
799         }
800         */
801
802         if (validate_flags & TFL_TARGETSELECT_ANGLELIMITS)
803         {
804                 if (fabs(tvt_tadv_x) > e_turret.aim_maxpitch)
805                         return -17;
806
807                 if (fabs(tvt_tadv_y) > e_turret.aim_maxrot)
808                         return -18;
809         }
810
811         // Line of sight?
812         if (validate_flags & TFL_TARGETSELECT_LOS)
813         {
814                 v_tmp = real_origin(e_target) + ((e_target.mins + e_target.maxs) * 0.5);
815
816                 traceline(e_turret.origin + '0 0 16', v_tmp, 0, e_turret);
817
818                 if(vdist(v_tmp - trace_endpos, >, e_turret.aim_firetolerance_dist))
819                         return -19;
820         }
821
822         if (e_target.classname == "grapplinghook")
823                 return -20;
824
825         /*
826         if (e_target.classname == "func_button")
827                 return -21;
828         */
829
830 #ifdef TURRET_DEBUG_TARGETSELECT
831         LOG_TRACE("Target:",e_target.netname," is a valid target for ",e_turret.netname);
832 #endif
833
834         return 1;
835 }
836
837 entity turret_select_target(entity this)
838 {
839         entity e;               // target looper entity
840         float  score;   // target looper entity score
841         entity e_enemy;  // currently best scoreing target
842         float  m_score;  // currently best scoreing target's score
843
844         m_score = 0;
845         if(this.enemy && this.enemy.takedamage && turret_validate_target(this,this.enemy,this.target_validate_flags) > 0)
846         {
847                 e_enemy = this.enemy;
848                 m_score = this.turret_score_target(this,e_enemy) * this.target_select_samebias;
849         }
850         else
851                 e_enemy = this.enemy = NULL;
852
853         e = findradius(this.origin, this.target_range);
854
855         // Nothing to aim at?
856         if (!e)
857                 return NULL;
858
859         while (e)
860         {
861                 if(e.takedamage)
862                 {
863                         float f = turret_validate_target(this, e, this.target_select_flags);
864                         //dprint("F is: ", ftos(f), "\n");
865                         if ( f > 0)
866                         {
867                                 score = this.turret_score_target(this,e);
868                                 if ((score > m_score) && (score > 0))
869                                 {
870                                         e_enemy = e;
871                                         m_score = score;
872                                 }
873                         }
874                 }
875                 e = e.chain;
876         }
877
878         return e_enemy;
879 }
880
881
882 /*
883  + = implemented
884  - = not implemented
885
886  + TFL_FIRECHECK_NO
887  + TFL_FIRECHECK_WORLD
888  + TFL_FIRECHECK_DEAD
889  + TFL_FIRECHECK_DISTANCES
890  - TFL_FIRECHECK_LOS
891  + TFL_FIRECHECK_AIMDIST
892  + TFL_FIRECHECK_REALDIST
893  - TFL_FIRECHECK_ANGLEDIST
894  - TFL_FIRECHECK_TEAMCECK
895  + TFL_FIRECHECK_AFF
896  + TFL_FIRECHECK_AMMO_OWN
897  + TFL_FIRECHECK_AMMO_OTHER
898  + TFL_FIRECHECK_REFIRE
899 */
900
901 /**
902 ** Preforms pre-fire checks based on the uints firecheck_flags
903 **/
904 bool turret_firecheck(entity this)
905 {
906         // This one just dont care =)
907         if (this.firecheck_flags & TFL_FIRECHECK_NO)
908                 return true;
909
910         if (this.enemy == NULL)
911                 return false;
912
913         // Ready?
914         if (this.firecheck_flags & TFL_FIRECHECK_REFIRE)
915                 if (this.attack_finished_single[0] > time) return false;
916
917         // Special case: volly fire turret that has to fire a full volly if a shot was fired.
918         if (this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
919                 if (this.volly_counter != this.shot_volly)
920                         if(this.ammo >= this.shot_dmg)
921                                 return true;
922
923         // Lack of zombies makes shooting dead things unnecessary :P
924         if (this.firecheck_flags & TFL_FIRECHECK_DEAD)
925                 if (IS_DEAD(this.enemy))
926                         return false;
927
928         // Own ammo?
929         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OWN)
930                 if (this.ammo < this.shot_dmg)
931                         return false;
932
933         // Other's ammo? (support-supply units)
934         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OTHER)
935                 if (this.enemy.ammo >= this.enemy.ammo_max)
936                         return false;
937
938         // Target of opertunity?
939         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
940         {
941                 this.enemy = this.tur_impactent;
942                 return true;
943         }
944
945         if (this.firecheck_flags & TFL_FIRECHECK_DISTANCES)
946         {
947                 // To close?
948                 if (this.tur_dist_aimpos < this.target_range_min)
949                 {
950                         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
951                                 return true; // Target of opertunity?
952                         return false;
953                 }
954         }
955
956         // Try to avoid FF?
957         if (this.firecheck_flags & TFL_FIRECHECK_AFF)
958                 if (this.tur_impactent.team == this.team)
959                         return false;
960
961         // aim<->predicted impact
962         if (this.firecheck_flags & TFL_FIRECHECK_AIMDIST)
963                 if (this.tur_dist_impact_to_aimpos > this.aim_firetolerance_dist)
964                         return false;
965
966         // Volly status
967         if (this.shot_volly > 1)
968                 if (this.volly_counter == this.shot_volly)
969                         if (this.ammo < (this.shot_dmg * this.shot_volly))
970                                 return false;
971
972         /*if(this.firecheck_flags & TFL_FIRECHECK_VERIFIED)
973                 if(this.tur_impactent != this.enemy)
974                         return false;*/
975
976         return true;
977 }
978
979 bool turret_checkfire(entity this)
980 {
981         if(MUTATOR_CALLHOOK(Turret_CheckFire, this))
982                 return M_ARGV(1, bool);
983
984         return this.turret_firecheckfunc(this);
985 }
986
987 void turret_fire(entity this)
988 {
989         if (autocvar_g_turrets_nofire != 0)
990                 return;
991
992         if(MUTATOR_CALLHOOK(TurretFire, this))
993                 return;
994
995         Turret info = get_turretinfo(this.m_id);
996         info.tr_attack(info, this);
997
998         this.attack_finished_single[0] = time + this.shot_refire;
999         this.ammo -= this.shot_dmg;
1000         this.volly_counter = this.volly_counter - 1;
1001
1002         if (this.volly_counter <= 0)
1003         {
1004                 this.volly_counter = this.shot_volly;
1005
1006                 if (this.shoot_flags & TFL_SHOOT_CLEARTARGET)
1007                         this.enemy = NULL;
1008
1009                 if (this.shot_volly > 1)
1010                         this.attack_finished_single[0] = time + this.shot_volly_refire;
1011         }
1012
1013 #ifdef TURRET_DEBUG
1014         if (this.enemy) paint_target3(this.tur_aimpos, 64, this.tur_debug_rvec, this.tur_impacttime + 0.25);
1015 #endif
1016 }
1017
1018 void turret_think(entity this)
1019 {
1020         this.nextthink = time + this.ticrate;
1021
1022         MUTATOR_CALLHOOK(TurretThink, this);
1023
1024 #ifdef TURRET_DEBUG
1025         if (this.tur_debug_tmr1 < time)
1026         {
1027                 if (this.enemy) paint_target (this.enemy,128,this.tur_debug_rvec,0.9);
1028                 paint_target(this,256,this.tur_debug_rvec,0.9);
1029                 this.tur_debug_tmr1 = time + 1;
1030         }
1031 #endif
1032
1033         // Handle ammo
1034         if (!(this.spawnflags & TSF_NO_AMMO_REGEN))
1035         if (this.ammo < this.ammo_max)
1036                 this.ammo = min(this.ammo + this.ammo_recharge, this.ammo_max);
1037
1038         // Inactive turrets needs to run the think loop,
1039         // So they can handle animation and wake up if need be.
1040         if(!this.active)
1041         {
1042                 turret_track(this);
1043                 return;
1044         }
1045
1046         // This is typicaly used for zaping every target in range
1047         // turret_fusionreactor uses this to recharge friendlys.
1048         if (this.shoot_flags & TFL_SHOOT_HITALLVALID)
1049         {
1050                 // Do a this.turret_fire for every valid target.
1051                 entity e = findradius(this.origin,this.target_range);
1052                 while (e)
1053                 {
1054                         if(e.takedamage)
1055                         {
1056                                 if (turret_validate_target(this,e,this.target_validate_flags))
1057                                 {
1058                                         this.enemy = e;
1059
1060                                         turret_do_updates(this);
1061
1062                                         if (turret_checkfire(this))
1063                                                 turret_fire(this);
1064                                 }
1065                         }
1066
1067                         e = e.chain;
1068                 }
1069                 this.enemy = NULL;
1070         }
1071         else if(this.shoot_flags & TFL_SHOOT_CUSTOM)
1072         {
1073                 // This one is doing something.. oddball. assume its handles what needs to be handled.
1074
1075                 // Predict?
1076                 if(!(this.aim_flags & TFL_AIM_NO))
1077                         this.tur_aimpos = turret_aim_generic(this);
1078
1079                 // Turn & pitch?
1080                 if(!(this.track_flags & TFL_TRACK_NO))
1081                         turret_track(this);
1082
1083                 turret_do_updates(this);
1084
1085                 // Fire?
1086                 if (turret_checkfire(this))
1087                         turret_fire(this);
1088         }
1089         else
1090         {
1091                 // Special case for volly always. if it fired once it must compleate the volly.
1092                 if(this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
1093                         if(this.volly_counter != this.shot_volly)
1094                         {
1095                                 // Predict or whatnot
1096                                 if(!(this.aim_flags & TFL_AIM_NO))
1097                                         this.tur_aimpos = turret_aim_generic(this);
1098
1099                                 // Turn & pitch
1100                                 if(!(this.track_flags & TFL_TRACK_NO))
1101                                         turret_track(this);
1102
1103                                 turret_do_updates(this);
1104
1105                                 // Fire!
1106                                 if (turret_checkfire(this))
1107                                         turret_fire(this);
1108
1109                                 Turret tur = get_turretinfo(this.m_id);
1110                                 tur.tr_think(tur, this);
1111
1112                                 return;
1113                         }
1114
1115                 // Check if we have a vailid enemy, and try to find one if we dont.
1116
1117                 // g_turrets_targetscan_maxdelay forces a target re-scan at least this often
1118                 float do_target_scan = 0;
1119                 if((this.target_select_time + autocvar_g_turrets_targetscan_maxdelay) < time)
1120                         do_target_scan = 1;
1121
1122                 // Old target (if any) invalid?
1123                 if(this.target_validate_time < time)
1124                 if (turret_validate_target(this, this.enemy, this.target_validate_flags) <= 0)
1125                 {
1126                         this.enemy = NULL;
1127                         this.target_validate_time = time + 0.5;
1128                         do_target_scan = 1;
1129                 }
1130
1131                 // But never more often then g_turrets_targetscan_mindelay!
1132                 if (this.target_select_time + autocvar_g_turrets_targetscan_mindelay > time)
1133                         do_target_scan = 0;
1134
1135                 if(do_target_scan)
1136                 {
1137                         this.enemy = turret_select_target(this);
1138                         this.target_select_time = time;
1139                 }
1140
1141                 // No target, just go to idle, do any custom stuff and bail.
1142                 if (this.enemy == NULL)
1143                 {
1144                         // Turn & pitch
1145                         if(!(this.track_flags & TFL_TRACK_NO))
1146                                 turret_track(this);
1147
1148                         Turret tur = get_turretinfo(this.m_id);
1149                         tur.tr_think(tur, this);
1150
1151                         // And bail.
1152                         return;
1153                 }
1154                 else
1155                         this.lip = time + autocvar_g_turrets_aimidle_delay; // Keep track of the last time we had a target.
1156
1157                 // Predict?
1158                 if(!(this.aim_flags & TFL_AIM_NO))
1159                         this.tur_aimpos = turret_aim_generic(this);
1160
1161                 // Turn & pitch?
1162                 if(!(this.track_flags & TFL_TRACK_NO))
1163                         turret_track(this);
1164
1165                 turret_do_updates(this);
1166
1167                 // Fire?
1168                 if (turret_checkfire(this))
1169                         turret_fire(this);
1170         }
1171
1172         Turret tur = get_turretinfo(this.m_id);
1173         tur.tr_think(tur, this);
1174 }
1175
1176 /*
1177         When .used a turret switch team to activator.team.
1178         If activator is NULL, the turret go inactive.
1179 */
1180 void turret_use(entity this, entity actor, entity trigger)
1181 {
1182         LOG_TRACE("Turret ",this.netname, " used by ", actor.classname);
1183
1184         this.team = actor.team;
1185
1186         if(this.team == 0)
1187                 this.active = ACTIVE_NOT;
1188         else
1189                 this.active = ACTIVE_ACTIVE;
1190
1191 }
1192
1193 void turret_link(entity this)
1194 {
1195         Net_LinkEntity(this, true, 0, turret_send);
1196         setthink(this, turret_think);
1197         this.nextthink = time;
1198         this.tur_head.effects = EF_NODRAW;
1199 }
1200
1201 void turrets_manager_think(entity this)
1202 {
1203         this.nextthink = time + 1;
1204
1205         if (autocvar_g_turrets_reloadcvars == 1)
1206         {
1207                 IL_EACH(g_turrets, true,
1208                 {
1209                         load_unit_settings(it, true);
1210                         Turret tur = get_turretinfo(it.m_id);
1211                         tur.tr_think(tur, it);
1212                 });
1213                 cvar_set("g_turrets_reloadcvars", "0");
1214         }
1215 }
1216
1217 void turret_initparams(entity tur)
1218 {
1219         #define TRY(x) (x) ? (x)
1220         tur.respawntime                 = max  (-1,              (TRY(tur.respawntime)               :  60                                         ));
1221         tur.shot_refire                 = bound(0.01,            (TRY(tur.shot_refire)               :  1                                          ), 9999);
1222         tur.shot_dmg                    = max  (1,               (TRY(tur.shot_dmg)                  :  tur.shot_refire * 50                       ));
1223         tur.shot_radius                 = max  (1,               (TRY(tur.shot_radius)               :  tur.shot_dmg * 0.5                         ));
1224         tur.shot_speed                  = max  (1,               (TRY(tur.shot_speed)                :  2500                                       ));
1225         tur.shot_spread                 = bound(0.0001,          (TRY(tur.shot_spread)               :  0.0125                                     ), 500);
1226         tur.shot_force                  = bound(0.001,           (TRY(tur.shot_force)                :  tur.shot_dmg * 0.5 + tur.shot_radius * 0.5 ), 5000);
1227         tur.shot_volly                  = bound(1,               (TRY(tur.shot_volly)                :  1                                          ), floor(tur.ammo_max / tur.shot_dmg));
1228         tur.shot_volly_refire           = bound(tur.shot_refire, (TRY(tur.shot_volly_refire)         :  tur.shot_refire * tur.shot_volly           ), 60);
1229         tur.target_range                = bound(0,               (TRY(tur.target_range)              :  tur.shot_speed * 0.5                       ), max_shot_distance);
1230         tur.target_range_min            = bound(0,               (TRY(tur.target_range_min)          :  tur.shot_radius * 2                        ), max_shot_distance);
1231         tur.target_range_optimal        = bound(0,               (TRY(tur.target_range_optimal)      :  tur.target_range * 0.5                     ), max_shot_distance);
1232         tur.aim_maxrot                  = bound(0,               (TRY(tur.aim_maxrot)                :  90                                         ), 360);
1233         tur.aim_maxpitch                = bound(0,               (TRY(tur.aim_maxpitch)              :  20                                         ), 90);
1234         tur.aim_speed                   = bound(0.1,             (TRY(tur.aim_speed)                 :  36                                         ), 1000);
1235         tur.aim_firetolerance_dist      = bound(0.1,             (TRY(tur.aim_firetolerance_dist)    :  5 + (tur.shot_radius * 2)                  ), max_shot_distance);
1236         tur.target_select_rangebias     = bound(-10,             (TRY(tur.target_select_rangebias)   :  1                                          ), 10);
1237         tur.target_select_samebias      = bound(-10,             (TRY(tur.target_select_samebias)    :  1                                          ), 10);
1238         tur.target_select_anglebias     = bound(-10,             (TRY(tur.target_select_anglebias)   :  1                                          ), 10);
1239         tur.target_select_missilebias   = bound(-10,             (TRY(tur.target_select_missilebias) :  1                                          ), 10);
1240         tur.target_select_playerbias    = bound(-10,             (TRY(tur.target_select_playerbias)  :  1                                          ), 10);
1241         tur.ammo_max                    = max  (tur.shot_dmg,    (TRY(tur.ammo_max)                  :  tur.shot_dmg * 10                          ));
1242         tur.ammo_recharge               = max  (0,               (TRY(tur.ammo_recharge)             :  tur.shot_dmg * 0.5                         ));
1243         #undef TRY
1244 }
1245
1246 bool turret_closetotarget(entity this, vector targ)
1247 {
1248         vector path_extra_size = '64 64 64';
1249         return boxesoverlap(targ - path_extra_size, targ + path_extra_size, this.absmin - path_extra_size, this.absmax + path_extra_size);
1250 }
1251
1252 void turret_findtarget(entity this)
1253 {
1254         entity e = find(NULL, classname, "turret_manager");
1255         if(!e)
1256         {
1257                 e = new(turret_manager);
1258                 setthink(e, turrets_manager_think);
1259                 e.nextthink = time + 2;
1260         }
1261
1262         entity targ = find(NULL, targetname, this.target);
1263         if(targ.classname == "turret_checkpoint")
1264                 return; // turrets don't defend checkpoints?
1265
1266         if (!targ)
1267         {
1268                 this.target = "";
1269                 LOG_TRACE("Turret has invalid defendpoint!");
1270         }
1271
1272         this.tur_defend = targ;
1273         this.idle_aim = this.tur_head.angles + angleofs(this.tur_head, targ);
1274 }
1275
1276 void turret_reset(entity this)
1277 {
1278         turret_respawn(this);
1279 }
1280
1281 bool turret_initialize(entity this, Turret tur)
1282 {
1283         if(!autocvar_g_turrets)
1284                 return false;
1285
1286         if(tur.m_id == 0)
1287                 return false; // invalid turret
1288
1289         // if tur_head exists, we can assume this turret re-spawned
1290         if(!this.tur_head) {
1291                 tur.tr_precache(tur);
1292                 IL_PUSH(g_turrets, this);
1293                 IL_PUSH(g_bot_targets, this);
1294         }
1295
1296         if(!(this.spawnflags & TSF_SUSPENDED))
1297                 droptofloor(this);
1298
1299         this.netname = tur.netname;
1300         load_unit_settings(this, 0);
1301
1302         if(!this.team || !teamplay)             { this.team = FLOAT_MAX; }
1303         if(!this.ticrate)                               { this.ticrate = ((this.turret_flags & TUR_FLAG_SUPPORT) ? 0.2 : 0.1); }
1304         if(!GetResource(this, RES_HEALTH)) { SetResourceExplicit(this, RES_HEALTH, 1000); }
1305         if(!this.shot_refire)                   { this.shot_refire = 1; }
1306         if(!this.tur_shotorg)                   { this.tur_shotorg = '50 0 50'; }
1307         if(!this.turret_flags)                  { this.turret_flags = TUR_FLAG_SPLASH | TUR_FLAG_MEDPROJ | TUR_FLAG_PLAYER; }
1308         if(!this.damage_flags)                  { this.damage_flags = TFL_DMG_YES | TFL_DMG_RETALIATE | TFL_DMG_AIMSHAKE; }
1309         if(!this.aim_flags)                             { this.aim_flags = TFL_AIM_LEAD | TFL_AIM_SHOTTIMECOMPENSATE; }
1310         if(!this.track_type)                    { this.track_type = TFL_TRACKTYPE_STEPMOTOR; }
1311         if(!this.track_flags)                   { this.track_flags = TFL_TRACK_PITCH | TFL_TRACK_ROTATE; }
1312         if(!this.ammo_flags)                    { this.ammo_flags = TFL_AMMO_ENERGY | TFL_AMMO_RECHARGE; }
1313         if(!this.target_select_flags)   { this.target_select_flags = TFL_TARGETSELECT_LOS | TFL_TARGETSELECT_TEAMCHECK | TFL_TARGETSELECT_RANGELIMITS | TFL_TARGETSELECT_ANGLELIMITS; }
1314         if(!this.firecheck_flags)               { this.firecheck_flags = TFL_FIRECHECK_DEAD | TFL_FIRECHECK_DISTANCES | TFL_FIRECHECK_LOS
1315                                                                                                                    | TFL_FIRECHECK_AIMDIST | TFL_FIRECHECK_TEAMCHECK | TFL_FIRECHECK_AMMO_OWN | TFL_FIRECHECK_REFIRE; }
1316
1317         if(this.track_type != TFL_TRACKTYPE_STEPMOTOR)
1318         {
1319                 // Fluid / Ineria mode. Looks mutch nicer.
1320                 // Can reduce aim preformance alot, needs a bit diffrent aimspeed
1321
1322                 this.aim_speed = bound(0.1, ((!this.aim_speed) ? 180 : this.aim_speed), 1000);
1323
1324                 if(!this.track_accel_pitch)             { this.track_accel_pitch = 0.5; }
1325                 if(!this.track_accel_rot)               { this.track_accel_rot = 0.5; }
1326                 if(!this.track_blendrate)               { this.track_blendrate = 0.35; }
1327         }
1328
1329         turret_initparams(this);
1330
1331         this.turret_flags = TUR_FLAG_ISTURRET | (tur.spawnflags);
1332
1333         if(this.turret_flags & TUR_FLAG_SPLASH)
1334                 this.aim_flags |= TFL_AIM_SPLASH;
1335
1336         if(this.turret_flags & TUR_FLAG_MISSILE)
1337                 this.target_select_flags |= TFL_TARGETSELECT_MISSILES;
1338
1339         if(this.turret_flags & TUR_FLAG_PLAYER)
1340                 this.target_select_flags |= TFL_TARGETSELECT_PLAYERS;
1341
1342         if(this.spawnflags & TSL_NO_RESPAWN)
1343                 this.damage_flags |= TFL_DMG_DEATH_NORESPAWN;
1344
1345         if (this.turret_flags & TUR_FLAG_SUPPORT)
1346                 this.turret_score_target = turret_targetscore_support;
1347         else
1348                 this.turret_score_target = turret_targetscore_generic;
1349
1350         ++turret_count;
1351
1352         _setmodel(this, tur.model);
1353         setsize(this, tur.m_mins, tur.m_maxs);
1354
1355         this.m_id                                       = tur.m_id;
1356         this.active                                     = ACTIVE_ACTIVE;
1357         this.effects                            = EF_NODRAW;
1358         this.netname                            = tur.turret_name;
1359         this.ticrate                            = bound(sys_frametime, this.ticrate, 60);
1360         this.max_health                         = GetResource(this, RES_HEALTH);
1361         this.target_validate_flags      = this.target_select_flags;
1362         this.ammo                                       = this.ammo_max;
1363         this.ammo_recharge                 *= this.ticrate;
1364         this.solid                                      = SOLID_BBOX;
1365         this.takedamage                         = DAMAGE_AIM;
1366         set_movetype(this, MOVETYPE_NOCLIP);
1367         this.view_ofs                           = '0 0 0';
1368         this.idle_aim                           = '0 0 0';
1369         this.turret_firecheckfunc       = turret_firecheck;
1370         this.event_damage                       = turret_damage;
1371         this.event_heal                         = turret_heal;
1372         this.use                                        = turret_use;
1373         this.bot_attack                         = true;
1374         this.nextthink                          = time + 1 + turret_count * sys_frametime;
1375         this.reset                                      = turret_reset;
1376
1377         this.tur_head = new(turret_head);
1378         _setmodel(this.tur_head, tur.head_model);
1379         setsize(this.tur_head, '0 0 0', '0 0 0');
1380         setorigin(this.tur_head, '0 0 0');
1381         setattachment(this.tur_head, this, "tag_head");
1382
1383         this.tur_head.netname           = this.tur_head.classname;
1384         this.tur_head.team                      = this.team;
1385         this.tur_head.owner                     = this;
1386         this.tur_head.takedamage        = DAMAGE_NO;
1387         this.tur_head.solid                     = SOLID_NOT;
1388         set_movetype(this.tur_head, this.move_movetype);
1389
1390         this.weaponentities[0] = this; // lol
1391
1392         if(!this.tur_defend && this.target != "")
1393                 InitializeEntity(this, turret_findtarget, INITPRIO_FINDTARGET);
1394
1395 #ifdef TURRET_DEBUG
1396         this.tur_debug_start = this.nextthink;
1397         while(vdist(this.tur_debug_rvec, <, 2))
1398                 this.tur_debug_rvec = randomvec() * 4;
1399
1400         this.tur_debug_rvec_x = fabs(this.tur_debug_rvec_x);
1401         this.tur_debug_rvec_y = fabs(this.tur_debug_rvec_y);
1402         this.tur_debug_rvec_z = fabs(this.tur_debug_rvec_z);
1403 #endif
1404
1405         turret_link(this);
1406         turret_respawn(this);
1407         turret_tag_fire_update(this);
1408
1409         tur.tr_setup(tur, this);
1410
1411         if(MUTATOR_CALLHOOK(TurretSpawn, this))
1412                 return false;
1413
1414         return true;
1415 }
1416 #endif