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