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