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