]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/tturrets/system/system_main.qc
Merge remote branch 'origin/master' into tzork/turrets-csqc
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / tturrets / system / system_main.qc
1 #define cvar_base "g_turrets_unit_"
2 .float clientframe;
3 void turrets_setframe(float _frame, float client_only)
4 {        
5     if((client_only ? self.clientframe : self.frame ) != _frame)
6     {
7         self.SendFlags |= TNSF_ANIM;
8         self.anim_start_time = time;
9     }
10     
11      if(client_only)
12         self.clientframe = _frame;
13     else
14         self.frame = _frame;
15    
16 }
17
18 float turret_send(entity to, float sf)
19 {
20         
21         WriteByte(MSG_ENTITY, ENT_CLIENT_TURRET);    
22         WriteByte(MSG_ENTITY, sf);
23         if(sf & TNSF_SETUP)
24         {
25             WriteByte(MSG_ENTITY, self.turret_type);
26             
27             WriteCoord(MSG_ENTITY, self.origin_x);
28             WriteCoord(MSG_ENTITY, self.origin_y);
29             WriteCoord(MSG_ENTITY, self.origin_z);
30             
31             WriteAngle(MSG_ENTITY, self.angles_x);
32             WriteAngle(MSG_ENTITY, self.angles_y);
33     }
34     
35     if(sf & TNSF_ANG)
36     {
37         WriteShort(MSG_ENTITY, rint(self.tur_head.angles_x));
38         WriteShort(MSG_ENTITY, rint(self.tur_head.angles_y));
39     }
40     
41     if(sf & TNSF_AVEL)
42     {        
43         WriteShort(MSG_ENTITY, rint(self.tur_head.avelocity_x));
44         WriteShort(MSG_ENTITY, rint(self.tur_head.avelocity_y));
45     }
46     
47     if(sf & TNSF_MOVE)
48     {
49         WriteShort(MSG_ENTITY, rint(self.origin_x));
50         WriteShort(MSG_ENTITY, rint(self.origin_y));
51         WriteShort(MSG_ENTITY, rint(self.origin_z));
52
53         WriteShort(MSG_ENTITY, rint(self.velocity_x));
54         WriteShort(MSG_ENTITY, rint(self.velocity_y));
55         WriteShort(MSG_ENTITY, rint(self.velocity_z));        
56         
57         WriteShort(MSG_ENTITY, rint(self.angles_y));        
58     }
59     
60     if(sf & TNSF_ANIM)
61     {
62         WriteCoord(MSG_ENTITY, self.anim_start_time);
63         WriteByte(MSG_ENTITY, self.frame);
64     }
65     
66     if(sf & TNSF_STATUS)
67     {        
68         WriteByte(MSG_ENTITY, self.team);
69         if(self.health <= 0)
70             WriteByte(MSG_ENTITY, 0);
71         else
72             WriteByte(MSG_ENTITY, rint((self.health / self.tur_health) * 255)); // Send health as 0-255 insted of real value, where 255 = 100%
73     }
74     
75         return TRUE;
76 }
77
78 void load_unit_settings(entity ent, string unitname, float is_reload)
79 {
80     string sbase;
81
82     if (ent == world)
83         return;
84
85     if not (ent.turret_scale_damage)    ent.turret_scale_damage  = 1;
86     if not (ent.turret_scale_range)     ent.turret_scale_range   = 1;
87     if not (ent.turret_scale_refire)    ent.turret_scale_refire  = 1;
88     if not (ent.turret_scale_ammo)      ent.turret_scale_ammo    = 1;
89     if not (ent.turret_scale_aim)       ent.turret_scale_aim     = 1;
90     if not (ent.turret_scale_health)    ent.turret_scale_health  = 1;
91     if not (ent.turret_scale_respawn)   ent.turret_scale_respawn = 1;
92
93     sbase = strcat(cvar_base,unitname);
94     if (is_reload)
95     {
96         ent.enemy = world;
97         ent.tur_head.avelocity = '0 0 0';
98
99         ent.tur_head.angles = '0 0 0';
100     }
101
102     ent.health      = cvar(strcat(sbase,"_health")) * ent.turret_scale_health;
103     ent.respawntime = cvar(strcat(sbase,"_respawntime")) * ent.turret_scale_respawn;
104
105     ent.shot_dmg          = cvar(strcat(sbase,"_shot_dmg")) * ent.turret_scale_damage;
106     ent.shot_refire       = cvar(strcat(sbase,"_shot_refire")) * ent.turret_scale_refire;
107     ent.shot_radius       = cvar(strcat(sbase,"_shot_radius")) * ent.turret_scale_damage;
108     ent.shot_speed        = cvar(strcat(sbase,"_shot_speed"));
109     ent.shot_spread       = cvar(strcat(sbase,"_shot_spread"));
110     ent.shot_force        = cvar(strcat(sbase,"_shot_force")) * ent.turret_scale_damage;
111     ent.shot_volly        = cvar(strcat(sbase,"_shot_volly"));
112     ent.shot_volly_refire = cvar(strcat(sbase,"_shot_volly_refire")) * ent.turret_scale_refire;
113
114     ent.target_range         = cvar(strcat(sbase,"_target_range")) * ent.turret_scale_range;
115     ent.target_range_min     = cvar(strcat(sbase,"_target_range_min")) * ent.turret_scale_range;
116     ent.target_range_optimal = cvar(strcat(sbase,"_target_range_optimal")) * ent.turret_scale_range;
117     //ent.target_range_fire    = cvar(strcat(sbase,"_target_range_fire")) * ent.turret_scale_range;
118
119     ent.target_select_rangebias  = cvar(strcat(sbase,"_target_select_rangebias"));
120     ent.target_select_samebias   = cvar(strcat(sbase,"_target_select_samebias"));
121     ent.target_select_anglebias  = cvar(strcat(sbase,"_target_select_anglebias"));
122     ent.target_select_playerbias = cvar(strcat(sbase,"_target_select_playerbias"));
123     //ent.target_select_fov = cvar(cvar_gets(sbase,"_target_select_fov"));
124
125     ent.ammo_max      = cvar(strcat(sbase,"_ammo_max")) * ent.turret_scale_ammo;
126     ent.ammo_recharge = cvar(strcat(sbase,"_ammo_recharge")) * ent.turret_scale_ammo;
127
128     ent.aim_firetolerance_dist = cvar(strcat(sbase,"_aim_firetolerance_dist"));
129     ent.aim_speed    = cvar(strcat(sbase,"_aim_speed")) * ent.turret_scale_aim;
130     ent.aim_maxrot   = cvar(strcat(sbase,"_aim_maxrot"));
131     ent.aim_maxpitch = cvar(strcat(sbase,"_aim_maxpitch"));
132
133     ent.track_type        = cvar(strcat(sbase,"_track_type"));
134     ent.track_accel_pitch = cvar(strcat(sbase,"_track_accel_pitch"));
135     ent.track_accel_rot   = cvar(strcat(sbase,"_track_accel_rot"));
136     ent.track_blendrate   = cvar(strcat(sbase,"_track_blendrate"));
137
138     if(is_reload)
139         if(ent.turret_respawnhook)
140             ent.turret_respawnhook();
141 }
142
143
144 /**
145 ** updates enemy distances, predicted impact point/time
146 ** and updated aim<->predict impact distance.
147 **/
148 void turret_do_updates(entity t_turret)
149 {
150     vector enemy_pos, oldpos;
151     entity oldself;
152
153     oldself = self;
154     self = t_turret;
155
156     enemy_pos = real_origin(self.enemy);
157
158     turret_tag_fire_update();
159
160     self.tur_shotdir_updated = v_forward;
161     self.tur_dist_enemy  = vlen(self.tur_shotorg - enemy_pos);
162     self.tur_dist_aimpos = vlen(self.tur_shotorg - self.tur_aimpos);
163
164     if((self.firecheck_flags & TFL_FIRECHECK_VERIFIED) && (self.enemy))
165     {
166         oldpos = self.enemy.origin;
167         setorigin(self.enemy,self.tur_aimpos);
168         tracebox(self.tur_shotorg, '-1 -1 -1','1 1 1',self.tur_shotorg + (self.tur_shotdir_updated * self.tur_dist_aimpos),MOVE_NORMAL,self);
169         setorigin(self.enemy,oldpos);
170
171         if(trace_ent == self.enemy)
172             self.tur_dist_impact_to_aimpos = 0;
173         else
174             self.tur_dist_impact_to_aimpos = vlen(trace_endpos - self.tur_aimpos);
175     }
176     else
177         tracebox(self.tur_shotorg, '-1 -1 -1','1 1 1', self.tur_shotorg + (self.tur_shotdir_updated * self.tur_dist_aimpos),MOVE_NORMAL,self);
178         
179         self.tur_dist_impact_to_aimpos = vlen(trace_endpos - self.tur_aimpos) - (vlen(self.enemy.maxs - self.enemy.mins) * 0.5);                
180         self.tur_impactent             = trace_ent;
181         self.tur_impacttime            = vlen(self.tur_shotorg - trace_endpos) / self.shot_speed;
182
183     self = oldself;
184 }
185
186 /*
187 vector turret_fovsearch_pingpong()
188 {
189     vector wish_angle;
190     if(self.phase < time)
191     {
192         if( self.tur_head.phase )
193             self.tur_head.phase = 0;
194         else
195             self.tur_head.phase = 1;
196         self.phase = time + 5;
197     }
198
199     if( self.tur_head.phase)
200         wish_angle = self.idle_aim + '0 1 0' * (self.aim_maxrot * (self.target_select_fov / 360));
201     else
202         wish_angle = self.idle_aim - '0 1 0' * (self.aim_maxrot * (self.target_select_fov / 360));
203
204     return wish_angle;
205 }
206
207 vector turret_fovsearch_steprot()
208 {
209     vector wish_angle;
210     //float rot_add;
211
212     wish_angle   = self.tur_head.angles;
213     wish_angle_x = self.idle_aim_x;
214
215     if (self.phase < time)
216     {
217         //rot_add = self.aim_maxrot / self.target_select_fov;
218         wish_angle_y += (self.target_select_fov * 2);
219
220         if(wish_angle_y > 360)
221             wish_angle_y = wish_angle_y - 360;
222
223          self.phase = time + 1.5;
224     }
225
226     return wish_angle;
227 }
228
229 vector turret_fovsearch_random()
230 {
231     vector wish_angle;
232
233     if (self.phase < time)
234     {
235         wish_angle_y = random() * self.aim_maxrot;
236         if(random() < 0.5)
237             wish_angle_y *= -1;
238
239         wish_angle_x = random() * self.aim_maxpitch;
240         if(random() < 0.5)
241             wish_angle_x *= -1;
242
243         self.phase = time + 5;
244
245         self.tur_aimpos = wish_angle;
246     }
247
248     return self.idle_aim + self.tur_aimpos;
249 }
250 */
251
252 /**
253 ** Handles head rotation according to
254 ** the units .track_type and .track_flags
255 **/
256 .float turret_framecounter;
257 void turret_stdproc_track()
258 {
259     vector target_angle; // This is where we want to aim
260     vector move_angle;   // This is where we can aim
261     float f_tmp;
262     vector v1, v2;
263     v1 = self.tur_head.angles;
264     v2 = self.tur_head.avelocity;
265     
266     if (self.track_flags == TFL_TRACK_NO)
267         return;
268
269     if not (self.tur_active)
270         target_angle = self.idle_aim - ('1 0 0' * self.aim_maxpitch);
271     else if (self.enemy == world)
272     {
273         if(time > self.lip)
274             target_angle = self.idle_aim + self.angles;
275         else
276             target_angle = vectoangles(normalize(self.tur_aimpos - self.tur_shotorg));
277     }
278     else
279     {
280         target_angle = vectoangles(normalize(self.tur_aimpos - self.tur_shotorg)); 
281     }
282     
283     self.tur_head.angles_x = anglemods(self.tur_head.angles_x);
284     self.tur_head.angles_y = anglemods(self.tur_head.angles_y);
285
286     // Find the diffrence between where we currently aim and where we want to aim
287     move_angle = target_angle - (self.angles + self.tur_head.angles);
288     move_angle = shortangle_vxy(move_angle,(self.angles + self.tur_head.angles));
289
290     switch(self.track_type)
291     {
292         case TFL_TRACKTYPE_STEPMOTOR:
293             f_tmp = self.aim_speed * self.ticrate; // dgr/sec -> dgr/tic
294             if (self.track_flags & TFL_TRACK_PITCH)
295             {
296                 self.tur_head.angles_x += bound(-f_tmp,move_angle_x, f_tmp);
297                 if(self.tur_head.angles_x > self.aim_maxpitch)
298                     self.tur_head.angles_x = self.aim_maxpitch;
299
300                 if(self.tur_head.angles_x  < -self.aim_maxpitch)
301                     self.tur_head.angles_x = self.aim_maxpitch;
302             }
303
304             if (self.track_flags & TFL_TRACK_ROT)
305             {
306                 self.tur_head.angles_y += bound(-f_tmp, move_angle_y, f_tmp);
307                 if(self.tur_head.angles_y > self.aim_maxrot)
308                     self.tur_head.angles_y = self.aim_maxrot;
309
310                 if(self.tur_head.angles_y  < -self.aim_maxrot)
311                     self.tur_head.angles_y = self.aim_maxrot;
312             }
313             
314             // CSQC
315             self.SendFlags  = TNSF_ANG;
316             
317             return;
318
319         case TFL_TRACKTYPE_FLUIDINERTIA:
320             f_tmp = self.aim_speed * self.ticrate; // dgr/sec -> dgr/tic
321             move_angle_x = bound(-self.aim_speed, move_angle_x * self.track_accel_pitch * f_tmp, self.aim_speed);
322             move_angle_y = bound(-self.aim_speed, move_angle_y * self.track_accel_rot * f_tmp, self.aim_speed);
323             move_angle = (self.tur_head.avelocity * self.track_blendrate) + (move_angle * (1 - self.track_blendrate));
324             break;
325
326         case TFL_TRACKTYPE_FLUIDPRECISE:
327
328             move_angle_y = bound(-self.aim_speed, move_angle_y, self.aim_speed);
329             move_angle_x = bound(-self.aim_speed, move_angle_x, self.aim_speed);
330
331             break;
332     }
333
334     //  pitch
335     if (self.track_flags & TFL_TRACK_PITCH)
336     {
337         self.tur_head.avelocity_x = move_angle_x;
338         if((self.tur_head.angles_x + self.tur_head.avelocity_x * self.ticrate) > self.aim_maxpitch)
339         {
340             self.tur_head.avelocity_x = 0;
341             self.tur_head.angles_x = self.aim_maxpitch;
342             
343             self.SendFlags  |= TNSF_ANG;
344         }
345         
346         if((self.tur_head.angles_x + self.tur_head.avelocity_x * self.ticrate) < -self.aim_maxpitch)
347         {
348             self.tur_head.avelocity_x = 0;
349             self.tur_head.angles_x = -self.aim_maxpitch;
350                         
351             self.SendFlags  |= TNSF_ANG;
352         }
353     }
354
355     //  rot
356     if (self.track_flags & TFL_TRACK_ROT)
357     {
358         self.tur_head.avelocity_y = move_angle_y;
359
360         if((self.tur_head.angles_y + self.tur_head.avelocity_y * self.ticrate) > self.aim_maxrot)
361         {
362             self.tur_head.avelocity_y = 0;
363             self.tur_head.angles_y = self.aim_maxrot;
364             
365             self.SendFlags  |= TNSF_ANG;
366         }
367
368         if((self.tur_head.angles_y + self.tur_head.avelocity_y * self.ticrate) < -self.aim_maxrot)
369         {
370             self.tur_head.avelocity_y = 0;
371             self.tur_head.angles_y = -self.aim_maxrot;
372             
373             self.SendFlags  |= TNSF_ANG;
374         }
375     }
376         
377     self.SendFlags  |= TNSF_AVEL;
378     
379     // Force a angle update every 10'th frame
380     self.turret_framecounter += 1;
381     if(self.turret_framecounter >= 10)
382     {        
383         self.SendFlags |= TNSF_ANG;
384         self.turret_framecounter = 0;
385     }            
386 }
387
388
389 /*
390  + = implemented
391  - = not implemented
392
393  + TFL_FIRECHECK_NO
394  + TFL_FIRECHECK_WORLD
395  + TFL_FIRECHECK_DEAD
396  + TFL_FIRECHECK_DISTANCES
397  - TFL_FIRECHECK_LOS
398  + TFL_FIRECHECK_AIMDIST
399  + TFL_FIRECHECK_REALDIST
400  - TFL_FIRECHECK_ANGLEDIST
401  - TFL_FIRECHECK_TEAMCECK
402  + TFL_FIRECHECK_AFF
403  + TFL_FIRECHECK_OWM_AMMO
404  + TFL_FIRECHECK_OTHER_AMMO
405  + TFL_FIRECHECK_REFIRE
406 */
407
408 /**
409 ** Preforms pre-fire checks based on the uints firecheck_flags
410 **/
411 float turret_stdproc_firecheck()
412 {
413     // This one just dont care =)
414     if (self.firecheck_flags & TFL_FIRECHECK_NO) return 1;
415
416     // Ready?
417     if (self.firecheck_flags & TFL_FIRECHECK_REFIRE)
418         if (self.attack_finished_single > time) return 0;
419
420     // Special case: volly fire turret that has to fire a full volly if a shot was fired.
421     if (self.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
422         if (self.volly_counter != self.shot_volly)
423                         if(self.ammo >= self.shot_dmg)
424                                 return 1;               
425
426     // Lack of zombies makes shooting dead things unnecessary :P
427     if (self.firecheck_flags & TFL_FIRECHECK_DEAD)
428         if (self.enemy.deadflag != DEAD_NO)
429             return 0;
430
431     // Plz stop killing the world!
432     if (self.firecheck_flags & TFL_FIRECHECK_WORLD)
433         if (self.enemy == world)
434             return 0;
435
436     // Own ammo?
437     if (self.firecheck_flags & TFL_FIRECHECK_OWM_AMMO)
438         if (self.ammo < self.shot_dmg)
439             return 0;
440
441     // Other's ammo? (support-supply units)
442     if (self.firecheck_flags & TFL_FIRECHECK_OTHER_AMMO)
443         if (self.enemy.ammo >= self.enemy.ammo_max)
444             return 0;
445         
446         // Target of opertunity?
447         if(turret_validate_target(self, self.tur_impactent, self.target_validate_flags) > 0)
448         {
449                 self.enemy = self.tur_impactent;
450                 return 1;
451         }                               
452
453     if (self.firecheck_flags & TFL_FIRECHECK_DISTANCES)
454     {
455         // To close?
456         if (self.tur_dist_aimpos < self.target_range_min)
457                         if(turret_validate_target(self, self.tur_impactent, self.target_validate_flags) > 0)                    
458                                 return 1; // Target of opertunity?
459                         else 
460                                 return 0;                               
461     }
462
463     // Try to avoid FF?
464     if (self.firecheck_flags & TFL_FIRECHECK_AFF)
465         if (self.tur_impactent.team == self.team)
466             return 0;
467
468     // aim<->predicted impact
469     if (self.firecheck_flags & TFL_FIRECHECK_AIMDIST)
470         if (self.tur_dist_impact_to_aimpos > self.aim_firetolerance_dist)
471             return 0;
472
473     // Volly status
474     if (self.shot_volly > 1)
475         if (self.volly_counter == self.shot_volly)
476             if (self.ammo < (self.shot_dmg * self.shot_volly))
477                 return 0;
478
479     if(self.firecheck_flags & TFL_FIRECHECK_VERIFIED)
480         if(self.tur_impactent != self.enemy)
481             return 0;
482
483     return 1;
484 }
485
486 /*
487  + TFL_TARGETSELECT_NO
488  + TFL_TARGETSELECT_LOS
489  + TFL_TARGETSELECT_PLAYERS
490  + TFL_TARGETSELECT_MISSILES
491  - TFL_TARGETSELECT_TRIGGERTARGET
492  + TFL_TARGETSELECT_ANGLELIMITS
493  + TFL_TARGETSELECT_RANGELIMTS
494  + TFL_TARGETSELECT_TEAMCHECK
495  - TFL_TARGETSELECT_NOBUILTIN
496  + TFL_TARGETSELECT_OWNTEAM
497 */
498
499 /**
500 ** Evaluate a entity for target valitity based on validate_flags
501 ** NOTE: the caller must check takedamage before calling this, to inline this check.
502 **/
503 float turret_validate_target(entity e_turret, entity e_target, float validate_flags)
504 {
505     vector v_tmp;
506
507     //if(!validate_flags & TFL_TARGETSELECT_NOBUILTIN)
508     //    return -0.5;
509
510     if(e_target.owner == e_turret)
511         return -0.5;
512
513     if not(checkpvs(e_target.origin, e_turret))
514         return -1;
515
516     if not (e_target)
517         return -2;
518
519         if(g_onslaught)
520                 if (substring(e_target.classname, 0, 10) == "onslaught_") // don't attack onslaught targets, that's the player's job!
521                         return - 3;
522
523     if (validate_flags & TFL_TARGETSELECT_NO)
524         return -4;
525
526     // If only this was used more..
527     if (e_target.flags & FL_NOTARGET)
528         return -5;
529
530     // Cant touch this
531     if (e_target.health < 0)
532         return -6;
533
534     // player
535     if (e_target.flags & FL_CLIENT)
536     {
537         if not (validate_flags & TFL_TARGETSELECT_PLAYERS)
538             return -7;
539
540         if (e_target.deadflag != DEAD_NO)
541             return -8;
542     }
543
544         // enemy turrets
545         if (validate_flags & TFL_TARGETSELECT_NOTURRETS)
546         if (e_target.turret_firefunc || e_target.owner.tur_head == e_target)
547             if(e_target.team != e_turret.team) // Dont break support units.
548                 return -9;
549
550     // Missile
551     if (e_target.flags & FL_PROJECTILE)
552         if not (validate_flags & TFL_TARGETSELECT_MISSILES)
553             return -10;
554
555     if (validate_flags & TFL_TARGETSELECT_MISSILESONLY)
556         if not (e_target.flags & FL_PROJECTILE)
557             return -10.5;
558
559     // Team check
560     if (validate_flags & TFL_TARGETSELECT_TEAMCHECK)
561     {
562         if (validate_flags & TFL_TARGETSELECT_OWNTEAM)
563         {
564             if (e_target.team != e_turret.team)
565                 return -11;
566
567             if (e_turret.team != e_target.owner.team)
568                 return -12;
569         }
570         else
571         {
572             if (e_target.team == e_turret.team)
573                 return -13;
574
575             if (e_turret.team == e_target.owner.team)
576                 return -14;
577         }
578     }
579
580     // Range limits?
581     tvt_dist = vlen(e_turret.origin - real_origin(e_target));
582     if (validate_flags & TFL_TARGETSELECT_RANGELIMTS)
583     {
584         if (tvt_dist < e_turret.target_range_min)
585             return -15;
586
587         if (tvt_dist > e_turret.target_range)
588             return -16;
589     }
590
591     // Can we even aim this thing?
592     tvt_thadv = angleofs3(e_turret.tur_head.origin, e_turret.angles + e_turret.tur_head.angles, e_target);
593     tvt_tadv  = shortangle_vxy(angleofs(e_turret, e_target), e_turret.angles);
594     tvt_thadf = vlen(tvt_thadv);
595     tvt_tadf  = vlen(tvt_tadv);
596
597     /*
598     if(validate_flags & TFL_TARGETSELECT_FOV)
599     {
600         if(e_turret.target_select_fov < tvt_thadf)
601             return -21;
602     }
603     */
604
605     if (validate_flags & TFL_TARGETSELECT_ANGLELIMITS)
606     {
607         if (fabs(tvt_tadv_x) > e_turret.aim_maxpitch)
608             return -17;
609
610         if (fabs(tvt_tadv_y) > e_turret.aim_maxrot)
611             return -18;
612     }
613
614     // Line of sight?
615     if (validate_flags & TFL_TARGETSELECT_LOS)
616     {
617         v_tmp = real_origin(e_target) + ((e_target.mins + e_target.maxs) * 0.5);
618
619         traceline(e_turret.tur_shotorg, v_tmp, 0, e_turret);
620
621         if (e_turret.aim_firetolerance_dist < vlen(v_tmp - trace_endpos))
622             return -19;
623     }
624
625     if (e_target.classname == "grapplinghook")
626         return -20;
627
628     /*
629     if (e_target.classname == "func_button")
630         return -21;
631     */
632
633 #ifdef TURRET_DEBUG_TARGETSELECT
634     dprint("Target:",e_target.netname," is a valid target for ",e_turret.netname,"\n");
635 #endif
636
637     return 1;
638 }
639
640 entity turret_select_target()
641 {
642     entity e;        // target looper entity
643     float  score;    // target looper entity score
644     entity e_enemy;  // currently best scoreing target
645     float  m_score;  // currently best scoreing target's score
646
647     m_score = 0;
648     if(self.enemy)
649         if(self.enemy.takedamage)
650     if(turret_validate_target(self,self.enemy,self.target_validate_flags) > 0)
651     {
652         e_enemy = self.enemy;
653         m_score = self.turret_score_target(self,e_enemy) * self.target_select_samebias;
654     }
655     else
656         self.enemy = world;
657
658     e = findradius(self.origin, self.target_range);
659
660     // Nothing to aim at?
661     if (!e) 
662                 return world;
663
664     while (e)
665     {
666                 if(e.takedamage)
667                 {
668                         if (turret_validate_target(self, e, self.target_select_flags) > 0)
669                         {
670                                 score = self.turret_score_target(self,e);
671                                 if ((score > m_score) && (score > 0))
672                                 {
673                                         e_enemy = e;
674                                         m_score = score;
675                                 }
676                         }
677                 }
678         e = e.chain;
679     }
680
681     return e_enemy;
682 }
683
684 void turret_think()
685 {
686     entity e;
687
688     self.nextthink = time + self.ticrate;
689     //self.SendFlags = TNSF_UPDATE | TNSF_STATUS | TNSF_ANG | TNSF_AVEL;
690     
691     // ONS uses somewhat backwards linking.
692     if (teamplay)
693     {
694         if not (g_onslaught)
695             if (self.target)
696             {
697                 e = find(world, targetname,self.target);
698                 if (e != world)
699                     self.team = e.team;
700             }
701
702         if (self.team != self.tur_head.team)
703             turret_stdproc_respawn();
704     }
705
706 #ifdef TURRET_DEBUG
707     if (self.tur_dbg_tmr1 < time)
708     {
709         if (self.enemy) paint_target (self.enemy,128,self.tur_dbg_rvec,0.9);
710         paint_target(self,256,self.tur_dbg_rvec,0.9);
711         self.tur_dbg_tmr1 = time + 1;
712     }
713 #endif
714
715     // Handle ammo
716     if not (self.spawnflags & TSF_NO_AMMO_REGEN)
717     if (self.ammo < self.ammo_max)
718         self.ammo = min(self.ammo + self.ammo_recharge, self.ammo_max);
719                         
720     // Inactive turrets needs to run the think loop,
721     // So they can handle animation and wake up if need be.
722     if not (self.tur_active)
723     {
724         turret_stdproc_track();
725         return;
726     }
727
728     // This is typicaly used for zaping every target in range
729     // turret_fusionreactor uses this to recharge friendlys.
730     if (self.shoot_flags & TFL_SHOOT_HITALLVALID)
731     {
732         // Do a self.turret_fire for every valid target.
733         e = findradius(self.origin,self.target_range);
734         while (e)
735         {
736                         if(e.takedamage)
737                         {
738                                 if (turret_validate_target(self,e,self.target_validate_flags))
739                                 {
740                                         self.enemy = e;
741
742                                         turret_do_updates(self);
743
744                                         if (self.turret_firecheckfunc())
745                                                 turret_fire();
746                                 }
747                         }
748
749             e = e.chain;
750         }
751         self.enemy = world;
752     }
753     else if(self.shoot_flags & TFL_SHOOT_CUSTOM)
754     {
755         // This one is doing something.. oddball. assume its handles what needs to be handled.
756
757         // Predict?
758         if not(self.aim_flags & TFL_AIM_NO)
759             self.tur_aimpos = turret_stdproc_aim_generic();
760
761         // Turn & pitch?
762         if not(self.track_flags & TFL_TRACK_NO)
763             turret_stdproc_track();
764
765         turret_do_updates(self);
766
767         // Fire?
768         if (self.turret_firecheckfunc())
769             turret_fire();
770     }
771     else
772     {
773         // Special case for volly always. if it fired once it must compleate the volly.
774         if(self.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
775             if(self.volly_counter != self.shot_volly)
776             {
777                 // Predict or whatnot
778                 if not(self.aim_flags & TFL_AIM_NO)
779                     self.tur_aimpos = turret_stdproc_aim_generic();
780
781                 // Turn & pitch
782                 if not(self.track_flags & TFL_TRACK_NO)
783                     turret_stdproc_track();
784
785                 turret_do_updates(self);
786
787                 // Fire!
788                 if (self.turret_firecheckfunc() != 0)
789                     turret_fire();
790
791                 if(self.turret_postthink)
792                     self.turret_postthink();
793
794                 return;
795             }
796
797         // Check if we have a vailid enemy, and try to find one if we dont.
798
799         // g_turrets_targetscan_maxdelay forces a target re-scan at least this often
800         float do_target_scan;
801         if((self.target_select_time + autocvar_g_turrets_targetscan_maxdelay) < time)
802             do_target_scan = 1;
803
804         // Old target (if any) invalid?
805         if (turret_validate_target(self, self.enemy, self.target_validate_flags) <= 0)
806         {
807                 self.enemy = world;
808                 do_target_scan = 1;
809         }
810
811         // But never more often then g_turrets_targetscan_mindelay!
812         if (self.target_select_time + autocvar_g_turrets_targetscan_mindelay > time)
813             do_target_scan = 0;
814
815         if(do_target_scan)
816         {
817             self.enemy = turret_select_target();
818             self.target_select_time = time;
819         }
820
821         // No target, just go to idle, do any custom stuff and bail.
822         if (self.enemy == world)
823         {
824             // Turn & pitch
825             if not(self.track_flags & TFL_TRACK_NO)
826                 turret_stdproc_track();
827
828             // do any per-turret stuff
829             if(self.turret_postthink)
830                 self.turret_postthink();
831
832             // And bail.
833             return;
834         }
835         else
836             self.lip = time + autocvar_g_turrets_aimidle_delay; // Keep track of the last time we had a target.
837
838         // Predict?
839         if not(self.aim_flags & TFL_AIM_NO)
840             self.tur_aimpos = turret_stdproc_aim_generic();
841
842         // Turn & pitch?
843         if not(self.track_flags & TFL_TRACK_NO)
844             turret_stdproc_track();
845
846         turret_do_updates(self);
847
848         // Fire?
849         if (self.turret_firecheckfunc())
850             turret_fire();
851     }
852
853     // do any custom per-turret stuff
854     if(self.turret_postthink)
855         self.turret_postthink();
856 }
857
858 void turret_fire()
859 {
860     if (autocvar_g_turrets_nofire != 0)
861         return;
862
863     self.turret_firefunc();
864
865     self.attack_finished_single = time + self.shot_refire;
866     self.ammo -= self.shot_dmg;
867     self.volly_counter = self.volly_counter - 1;
868
869     if (self.volly_counter <= 0)
870     {
871         self.volly_counter = self.shot_volly;
872
873         if (self.shoot_flags & TFL_SHOOT_CLEARTARGET)
874             self.enemy = world;
875
876         if (self.shot_volly > 1)
877             self.attack_finished_single = time + self.shot_volly_refire;
878     }
879
880 #ifdef TURRET_DEBUG
881     if (self.enemy) paint_target3(self.tur_aimpos, 64, self.tur_dbg_rvec, self.tur_impacttime + 0.25);
882 #endif
883 }
884
885 void turret_stdproc_fire()
886 {
887     dprint("^1Bang, ^3your dead^7 ",self.enemy.netname,"! ^1(turret with no real firefunc)\n");
888 }
889
890 /*
891     When .used a turret switch team to activator.team.
892     If activator is world, the turret go inactive.
893 */
894 void turret_stdproc_use()
895 {
896     dprint("Turret ",self.netname, " used by ", activator.classname, "\n");
897
898     self.team = activator.team;
899
900     if(self.team == 0)
901         self.tur_active = 0;
902     else
903         self.tur_active = 1;
904
905 }
906
907 void turret_link()
908 {
909     Net_LinkEntity(self, TRUE, 0, turret_send);
910     self.think      = turret_think;
911     self.nextthink  = time;
912     self.tur_head.effects = EF_NODRAW;
913 }
914
915 void turrets_manager_think()
916 {
917     self.nextthink = time + 1;
918
919     entity e;
920     if (autocvar_g_turrets_reloadcvars == 1)
921     {
922         e = nextent(world);
923         while (e)
924         {
925             if (e.turrcaps_flags & TFL_TURRCAPS_ISTURRET)
926             {
927                 load_unit_settings(e,e.cvar_basename,1);
928                 if(e.turret_postthink)
929                     e.turret_postthink();
930             }
931
932             e = nextent(e);
933         }
934         cvar_set("g_turrets_reloadcvars","0");
935     }
936 }
937
938 /*
939 * Standard turret initialization. use this!
940 * (unless you have a very good reason not to)
941 * if the return value is 0, the turret should be removed.
942 */
943 float turret_stdproc_init (string cvar_base_name, string base, string head, float _turret_type)
944 {
945         entity e, ee;
946
947     // Are turrets allowed?
948     if (autocvar_g_turrets == 0)
949         return 0;
950     
951     if(_turret_type < 1 || _turret_type > TID_LAST)
952     {
953         dprint("Invalid / Unkown turret type\"", ftos(_turret_type), "\", aborting!\n");
954         return 0;
955     }    
956     self.turret_type = _turret_type;
957     
958     e = find(world, classname, "turret_manager");
959     if not (e)
960     {
961         e = spawn();
962
963         /*
964         setorigin(e,'0 0 0');
965         setmodel(e,"models/turrets/plasma.md3");
966         vector v;
967         v = gettaginfo(e,gettagindex(e,"tag_fire"));
968         if(v == '0 0 0')
969         {
970             //objerror("^1ERROR: Engine is borken! Turrets will NOT work. force g_turrets to 0 to run maps with turrets anyway.");
971             //crash();
972         }
973         setmodel(e,"");
974         */
975
976         e.classname = "turret_manager";
977         e.think = turrets_manager_think;
978         e.nextthink = time + 2;
979     }
980
981     /*
982     if(csqc_shared)
983     {
984         dprint("WARNING: turret requested csqc_shared but this is not implemented. Expect strange things to happen.\n");
985         csqc_shared = 0;
986     }
987     */
988     
989     if not (self.spawnflags & TSF_SUSPENDED)
990         droptofloor_builtin();
991
992     // Terrainbase spawnflag. This puts a enlongated model
993     // under the turret, so it looks ok on uneaven surfaces.
994     /*  TODO: Handle this with CSQC
995     if (self.spawnflags & TSF_TERRAINBASE)
996     {
997         entity tb;
998         tb = spawn();
999         setmodel(tb,"models/turrets/terrainbase.md3");
1000         setorigin(tb,self.origin);
1001         tb.solid = SOLID_BBOX;
1002     }
1003     */
1004
1005     self.cvar_basename = cvar_base_name;
1006     load_unit_settings(self, self.cvar_basename, 0);
1007
1008     self.effects = EF_NODRAW;
1009     
1010     // Handle turret teams.
1011     if (autocvar_g_assault != 0)
1012     {
1013         if not (self.team)
1014             self.team = 14; // Assume turrets are on the defending side if not explicitly set otehrwize
1015     }
1016     else if not (teamplay)
1017                 self.team = MAX_SHOT_DISTANCE; // Group all turrets into the same team, so they dont kill eachother.
1018         else if(g_onslaught && self.targetname)
1019         {
1020                 e = find(world,target,self.targetname);
1021                 if(e != world)
1022                 {
1023                         self.team = e.team;
1024                         ee = e;
1025                 }
1026         }
1027         else if(!self.team)
1028                 self.team = MAX_SHOT_DISTANCE; // Group all turrets into the same team, so they dont kill eachother.
1029
1030     /*
1031     * Try to guess some reasonaly defaults
1032     * for missing params and do sanety checks
1033     * thise checks could produce some "interesting" results
1034     * if it hits a glitch in my logic :P so try to set as mutch
1035     * as possible beforehand.
1036     */
1037     if (self.turrcaps_flags & TFL_TURRCAPS_SUPPORT)
1038         self.ticrate = 0.2;     // Support units generaly dont need to have a high speed ai-loop
1039     else
1040         self.ticrate = 0.1;     // 10 fps for normal turrets
1041
1042     self.ticrate = bound(sys_frametime, self.ticrate, 60);  // keep it sane
1043
1044 // General stuff
1045     if (self.netname == "")
1046         self.netname = self.classname;
1047
1048     if not (self.respawntime)
1049         self.respawntime = 60;
1050     self.respawntime = max(-1, self.respawntime);
1051
1052     if not (self.health)
1053         self.health = 1000;
1054     self.tur_health = max(1, self.health);
1055
1056     if not (self.turrcaps_flags)
1057         self.turrcaps_flags = TFL_TURRCAPS_RADIUSDMG | TFL_TURRCAPS_MEDPROJ | TFL_TURRCAPS_PLAYERKILL;
1058
1059     if not (self.damage_flags)
1060         self.damage_flags = TFL_DMG_YES | TFL_DMG_RETALIATE | TFL_DMG_AIMSHAKE;
1061
1062 // Shot stuff.
1063     if not (self.shot_refire)
1064         self.shot_refire = 1;
1065     self.shot_refire = bound(0.01, self.shot_refire, 9999);
1066
1067     if not (self.shot_dmg)
1068         self.shot_dmg  = self.shot_refire * 50;
1069     self.shot_dmg = max(1, self.shot_dmg);
1070
1071     if not (self.shot_radius)
1072         self.shot_radius = self.shot_dmg * 0.5;
1073     self.shot_radius = max(1, self.shot_radius);
1074
1075     if not (self.shot_speed)
1076         self.shot_speed = 2500;
1077     self.shot_speed = max(1, self.shot_speed);
1078
1079     if not (self.shot_spread)
1080         self.shot_spread = 0.0125;
1081     self.shot_spread = bound(0.0001, self.shot_spread, 500);
1082
1083     if not (self.shot_force)
1084         self.shot_force = self.shot_dmg * 0.5 + self.shot_radius * 0.5;
1085     self.shot_force = bound(0.001, self.shot_force, 5000);
1086
1087     if not (self.shot_volly)
1088         self.shot_volly = 1;
1089     self.shot_volly = bound(1, self.shot_volly, floor(self.ammo_max / self.shot_dmg));
1090
1091     if not (self.shot_volly_refire)
1092         self.shot_volly_refire = self.shot_refire * self.shot_volly;
1093     self.shot_volly_refire = bound(self.shot_refire, self.shot_volly_refire, 60);
1094
1095     if not (self.firecheck_flags)
1096         self.firecheck_flags = TFL_FIRECHECK_WORLD | TFL_FIRECHECK_DEAD | TFL_FIRECHECK_DISTANCES |
1097                                TFL_FIRECHECK_LOS | TFL_FIRECHECK_AIMDIST | TFL_FIRECHECK_TEAMCECK |
1098                                TFL_FIRECHECK_OWM_AMMO | TFL_FIRECHECK_REFIRE | TFL_FIRECHECK_WORLD;
1099
1100 // Range stuff.
1101     if not (self.target_range)
1102         self.target_range = self.shot_speed * 0.5;
1103     self.target_range = bound(0, self.target_range, MAX_SHOT_DISTANCE);
1104
1105     if not (self.target_range_min)
1106         self.target_range_min = self.shot_radius * 2;
1107     self.target_range_min = bound(0, self.target_range_min, MAX_SHOT_DISTANCE);
1108
1109     if not (self.target_range_optimal)
1110         self.target_range_optimal = self.target_range * 0.5;
1111     self.target_range_optimal = bound(0, self.target_range_optimal, MAX_SHOT_DISTANCE);
1112
1113
1114 // Aim stuff.
1115     if not (self.aim_maxrot)
1116         self.aim_maxrot = 90;
1117     self.aim_maxrot = bound(0, self.aim_maxrot, 360);
1118
1119     if not (self.aim_maxpitch)
1120         self.aim_maxpitch = 20;
1121     self.aim_maxpitch = bound(0, self.aim_maxpitch, 90);
1122
1123     if not (self.aim_speed)
1124         self.aim_speed = 36;
1125     self.aim_speed  = bound(0.1, self.aim_speed, 1000);
1126
1127     if not (self.aim_firetolerance_dist)
1128         self.aim_firetolerance_dist  = 5 + (self.shot_radius * 2);
1129     self.aim_firetolerance_dist = bound(0.1, self.aim_firetolerance_dist, MAX_SHOT_DISTANCE);
1130
1131     if not (self.aim_flags)
1132     {
1133         self.aim_flags = TFL_AIM_LEAD | TFL_AIM_SHOTTIMECOMPENSATE;
1134         if(self.turrcaps_flags & TFL_TURRCAPS_RADIUSDMG)
1135             self.aim_flags |= TFL_AIM_GROUND2;
1136     }
1137
1138     if not (self.track_type)
1139         self.track_type = TFL_TRACKTYPE_STEPMOTOR;
1140
1141     if (self.track_type != TFL_TRACKTYPE_STEPMOTOR)
1142     {
1143         // Fluid / Ineria mode. Looks mutch nicer.
1144         // Can reduce aim preformance alot, needs a bit diffrent aimspeed
1145
1146         if not (self.aim_speed)
1147             self.aim_speed = 180;
1148         self.aim_speed = bound(0.1, self.aim_speed, 1000);
1149
1150         if not (self.track_accel_pitch)
1151             self.track_accel_pitch = 0.5;
1152
1153         if not (self.track_accel_rot)
1154             self.track_accel_rot   = 0.5;
1155
1156         if not (self.track_blendrate)
1157             self.track_blendrate   = 0.35;
1158     }
1159
1160     if (!self.track_flags)
1161         self.track_flags = TFL_TRACK_PITCH | TFL_TRACK_ROT;
1162
1163
1164 // Target selection stuff.
1165     if not (self.target_select_rangebias)
1166         self.target_select_rangebias = 1;
1167     self.target_select_rangebias = bound(-10, self.target_select_rangebias, 10);
1168
1169     if not (self.target_select_samebias)
1170         self.target_select_samebias = 1;
1171     self.target_select_samebias = bound(-10, self.target_select_samebias, 10);
1172
1173     if not (self.target_select_anglebias)
1174         self.target_select_anglebias = 1;
1175     self.target_select_anglebias = bound(-10, self.target_select_anglebias, 10);
1176
1177     if not (self.target_select_missilebias)
1178         self.target_select_missilebias = -10;
1179
1180     self.target_select_missilebias = bound(-10, self.target_select_missilebias, 10);
1181     self.target_select_playerbias = bound(-10, self.target_select_playerbias, 10);
1182
1183     if not (self.target_select_flags)
1184     {
1185             self.target_select_flags = TFL_TARGETSELECT_LOS | TFL_TARGETSELECT_TEAMCHECK
1186                                      | TFL_TARGETSELECT_RANGELIMTS | TFL_TARGETSELECT_ANGLELIMITS;
1187
1188         if (self.turrcaps_flags & TFL_TURRCAPS_MISSILEKILL)
1189             self.target_select_flags |= TFL_TARGETSELECT_MISSILES;
1190
1191         if (self.turrcaps_flags & TFL_TURRCAPS_PLAYERKILL)
1192             self.target_select_flags |= TFL_TARGETSELECT_PLAYERS;
1193         //else
1194         //    self.target_select_flags = TFL_TARGETSELECT_NO;
1195     }
1196
1197     self.target_validate_flags = self.target_select_flags;
1198
1199 // Ammo stuff
1200     if not (self.ammo_max)
1201         self.ammo_max = self.shot_dmg * 10;
1202     self.ammo_max = max(self.shot_dmg, self.ammo_max);
1203
1204     if not (self.ammo)
1205         self.ammo = self.shot_dmg * 5;
1206     self.ammo = bound(0,self.ammo, self.ammo_max);
1207
1208     if not (self.ammo_recharge)
1209         self.ammo_recharge = self.shot_dmg * 0.5;
1210     self.ammo_recharge = max(0 ,self.ammo_recharge);
1211
1212     // Convert the recharge from X per sec to X per ticrate
1213     self.ammo_recharge = self.ammo_recharge * self.ticrate;
1214
1215     if not (self.ammo_flags)
1216         self.ammo_flags = TFL_AMMO_ENERGY | TFL_AMMO_RECHARGE;
1217
1218 // Damage stuff
1219     if(self.spawnflags & TSL_NO_RESPAWN)
1220         if not (self.damage_flags & TFL_DMG_DEATH_NORESPAWN)
1221             self.damage_flags |= TFL_DMG_DEATH_NORESPAWN;
1222
1223 // Offsets & origins
1224     if (!self.tur_shotorg)   self.tur_shotorg = '50 0 50';
1225     
1226     if (!self.health)
1227         self.health = 150;
1228
1229 // Game hooks
1230         if(MUTATOR_CALLHOOK(TurretSpawn))
1231                 return 0;
1232
1233 // End of default & sanety checks, start building the turret.
1234
1235 // Spawn extra bits
1236     self.tur_head         = spawn();
1237     self.tur_head.netname = self.tur_head.classname = "turret_head";
1238     self.tur_head.team    = self.team;
1239     self.tur_head.owner   = self;
1240
1241     setmodel(self, base);
1242     setmodel(self.tur_head, head);
1243
1244     setsize(self, '-32 -32 0', '32 32 64');
1245     setsize(self.tur_head, '0 0 0', '0 0 0');
1246
1247     setorigin(self.tur_head, '0 0 0');
1248     setattachment(self.tur_head, self, "tag_head");
1249
1250     self.tur_health          = self.health;
1251     self.solid               = SOLID_BBOX;
1252     self.tur_head.solid      = SOLID_NOT;
1253     self.takedamage          = DAMAGE_AIM;
1254     self.tur_head.takedamage = DAMAGE_NO;
1255     self.movetype            = MOVETYPE_NOCLIP;
1256     self.tur_head.movetype   = MOVETYPE_NOCLIP;
1257
1258     // Defend mode?
1259     if not (self.tur_defend)
1260     if (self.target != "")
1261     {
1262         self.tur_defend = find(world, targetname, self.target);
1263         if (self.tur_defend == world)
1264         {
1265             self.target = "";
1266             dprint("Turret has invalid defendpoint!\n");
1267         }
1268     }
1269
1270     // In target defend mode, aim on the spot to defend when idle.
1271     if (self.tur_defend)
1272         self.idle_aim  = self.tur_head.angles + angleofs(self.tur_head, self.tur_defend);
1273     else
1274         self.idle_aim  = '0 0 0';
1275
1276     // Attach stdprocs. override when and what needed
1277     self.turret_firecheckfunc   = turret_stdproc_firecheck;
1278     self.turret_firefunc        = turret_stdproc_fire;
1279     self.event_damage           = turret_stdproc_damage;
1280     
1281     if (self.turrcaps_flags & TFL_TURRCAPS_SUPPORT)
1282         self.turret_score_target    = turret_stdproc_targetscore_support;
1283     else
1284         self.turret_score_target    = turret_stdproc_targetscore_generic;
1285
1286     self.use = turret_stdproc_use;
1287     self.bot_attack = TRUE;
1288
1289     ++turret_count;
1290     self.nextthink = time + 1;
1291     self.nextthink +=  turret_count * sys_frametime;
1292
1293     self.tur_head.team = self.team;
1294     self.view_ofs = '0 0 0';
1295
1296 #ifdef TURRET_DEBUG
1297     self.tur_dbg_start = self.nextthink;
1298     while (vlen(self.tur_dbg_rvec) < 2)
1299         self.tur_dbg_rvec  = randomvec() * 4;
1300
1301     self.tur_dbg_rvec_x = fabs(self.tur_dbg_rvec_x);
1302     self.tur_dbg_rvec_y = fabs(self.tur_dbg_rvec_y);
1303     self.tur_dbg_rvec_z = fabs(self.tur_dbg_rvec_z);
1304 #endif
1305
1306     // Its all good.
1307     self.turrcaps_flags |= TFL_TURRCAPS_ISTURRET;
1308
1309     self.classname = "turret_main";
1310
1311     self.tur_active = 1;
1312
1313     // In ONS mode, and linked to a ONS ent. need to call the use to set team.
1314     if (g_onslaught && ee)
1315     {
1316         activator = ee;
1317         self.use();
1318     }
1319     
1320         turret_link();
1321         turret_stdproc_respawn();
1322             
1323     if (!turret_tag_fire_update())
1324         dprint("Warning: Turret ",self.classname, " faild to initialize md3 tags\n");
1325     
1326     return 1;
1327 }
1328
1329