]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/gamemodes/gamemode/onslaught/sv_onslaught.qc
Merge branch 'master' into Lyberta/AssaultIcons
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / gamemodes / gamemode / onslaught / sv_onslaught.qc
1 #include "sv_onslaught.qh"
2 #include "sv_controlpoint.qh"
3 #include "sv_generator.qh"
4
5 bool g_onslaught;
6
7 float autocvar_g_onslaught_teleport_wait;
8 bool autocvar_g_onslaught_spawn_at_controlpoints;
9 bool autocvar_g_onslaught_spawn_at_generator;
10 float autocvar_g_onslaught_cp_proxydecap;
11 float autocvar_g_onslaught_cp_proxydecap_distance = 512;
12 float autocvar_g_onslaught_cp_proxydecap_dps = 100;
13 float autocvar_g_onslaught_spawn_at_controlpoints_chance = 0.5;
14 float autocvar_g_onslaught_spawn_at_controlpoints_random;
15 float autocvar_g_onslaught_spawn_at_generator_chance;
16 float autocvar_g_onslaught_spawn_at_generator_random;
17 float autocvar_g_onslaught_cp_buildhealth;
18 float autocvar_g_onslaught_cp_buildtime;
19 float autocvar_g_onslaught_cp_health;
20 float autocvar_g_onslaught_cp_regen;
21 float autocvar_g_onslaught_gen_health;
22 float autocvar_g_onslaught_shield_force = 100;
23 float autocvar_g_onslaught_allow_vehicle_touch;
24 float autocvar_g_onslaught_round_timelimit;
25 float autocvar_g_onslaught_warmup;
26 float autocvar_g_onslaught_teleport_radius;
27 float autocvar_g_onslaught_spawn_choose;
28 float autocvar_g_onslaught_click_radius;
29
30 void FixSize(entity e);
31 entity cam;
32
33 // =======================
34 // CaptureShield Functions
35 // =======================
36
37 bool clientcamera_send(entity this, entity to, int sf)
38 {
39         WriteHeader(MSG_ENTITY, ENT_ONSCAMERA);
40
41         WriteVector(MSG_ENTITY, this.origin);
42
43         WriteAngle(MSG_ENTITY, this.angles_x);
44         WriteAngle(MSG_ENTITY, this.angles_y);
45         WriteAngle(MSG_ENTITY, this.angles_z);
46
47         return true;
48 }
49
50 bool ons_CaptureShield_Customize(entity this, entity client)
51 {
52         entity e = WaypointSprite_getviewentity(client);
53
54         if(!this.enemy.isshielded && (ons_ControlPoint_Attackable(this.enemy, e.team) > 0 || this.enemy.classname != "onslaught_controlpoint")) { return false; }
55         if(SAME_TEAM(this, e)) { return false; }
56
57         return true;
58 }
59
60 void ons_CaptureShield_Touch(entity this, entity toucher)
61 {
62         if(!this.enemy.isshielded && (ons_ControlPoint_Attackable(this.enemy, toucher.team) > 0 || this.enemy.classname != "onslaught_controlpoint")) { return; }
63         if(!IS_PLAYER(toucher)) { return; }
64         if(SAME_TEAM(toucher, this)) { return; }
65
66         vector mymid = (this.absmin + this.absmax) * 0.5;
67         vector theirmid = (toucher.absmin + toucher.absmax) * 0.5;
68
69         Damage(toucher, this, this, 0, DEATH_HURTTRIGGER.m_id, DMG_NOWEP, mymid, normalize(theirmid - mymid) * ons_captureshield_force);
70
71         if(IS_REAL_CLIENT(toucher))
72         {
73                 play2(toucher, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
74
75                 if(this.enemy.classname == "onslaught_generator")
76                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_GENERATOR_SHIELDED);
77                 else
78                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_CONTROLPOINT_SHIELDED);
79         }
80 }
81
82 void ons_CaptureShield_Reset(entity this)
83 {
84         this.colormap = this.enemy.colormap;
85         this.team = this.enemy.team;
86 }
87
88 void ons_CaptureShield_Spawn(entity generator, bool is_generator)
89 {
90         entity shield = new(ons_captureshield);
91         IL_PUSH(g_onsshields, shield);
92
93         shield.enemy = generator;
94         shield.team = generator.team;
95         shield.colormap = generator.colormap;
96         shield.reset = ons_CaptureShield_Reset;
97         settouch(shield, ons_CaptureShield_Touch);
98         setcefc(shield, ons_CaptureShield_Customize);
99         shield.effects = EF_ADDITIVE;
100         set_movetype(shield, MOVETYPE_NOCLIP);
101         shield.solid = SOLID_TRIGGER;
102         shield.avelocity = '7 0 11';
103         shield.scale = 1;
104         shield.model = ((is_generator) ? "models/onslaught/generator_shield.md3" : "models/onslaught/controlpoint_shield.md3");
105
106         precache_model(shield.model);
107         setorigin(shield, generator.origin);
108         _setmodel(shield, shield.model);
109         setsize(shield, shield.scale * shield.mins, shield.scale * shield.maxs);
110 }
111
112
113 // ==========
114 // Junk Pile
115 // ==========
116
117 void setmodel_fixsize(entity e, Model m)
118 {
119         setmodel(e, m);
120         FixSize(e);
121 }
122
123 void onslaught_updatelinks()
124 {
125         entity l;
126         // first check if the game has ended
127         LOG_DEBUG("--- updatelinks ---");
128         // mark generators as being shielded and networked
129         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
130         {
131                 if (l.iscaptured)
132                         LOG_DEBUG(etos(l), " (generator) belongs to team ", ftos(l.team));
133                 else
134                         LOG_DEBUG(etos(l), " (generator) is destroyed");
135                 l.islinked = l.iscaptured;
136                 l.isshielded = l.iscaptured;
137                 l.sprite.SendFlags |= 16;
138         }
139         // mark points as shielded and not networked
140         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
141         {
142                 l.islinked = false;
143                 l.isshielded = true;
144                 l.aregensneighbor = 0;
145                 l.arecpsneighbor = 0;
146                 LOG_DEBUG(etos(l), " (point) belongs to team ", ftos(l.team));
147                 l.sprite.SendFlags |= 16;
148         }
149         // flow power outward from the generators through the network
150         bool stop = false;
151         while (!stop)
152         {
153                 stop = true;
154                 for(l = ons_worldlinklist; l; l = l.ons_worldlinknext)
155                 {
156                         // if both points are captured by the same team, and only one of
157                         // them is powered, mark the other one as powered as well
158                         if (l.enemy.iscaptured && l.goalentity.iscaptured)
159                                 if (l.enemy.islinked != l.goalentity.islinked)
160                                         if(SAME_TEAM(l.enemy, l.goalentity))
161                                         {
162                                                 if (!l.goalentity.islinked)
163                                                 {
164                                                         stop = false;
165                                                         l.goalentity.islinked = true;
166                                                         LOG_DEBUG(etos(l), " (link) is marking ", etos(l.goalentity), " (point) because its team matches ", etos(l.enemy), " (point)");
167                                                 }
168                                                 else if (!l.enemy.islinked)
169                                                 {
170                                                         stop = false;
171                                                         l.enemy.islinked = true;
172                                                         LOG_DEBUG(etos(l), " (link) is marking ", etos(l.enemy), " (point) because its team matches ", etos(l.goalentity), " (point)");
173                                                 }
174                                         }
175                 }
176         }
177         // now that we know which points are powered we can mark their neighbors
178         // as unshielded if team differs
179         for(l = ons_worldlinklist; l; l = l.ons_worldlinknext)
180         {
181                 if (l.goalentity.islinked)
182                 {
183                         if(DIFF_TEAM(l.goalentity, l.enemy))
184                         {
185                                 LOG_DEBUG(etos(l), " (link) is unshielding ", etos(l.enemy), " (point) because its team does not match ", etos(l.goalentity), " (point)");
186                                 l.enemy.isshielded = false;
187                         }
188                         if(l.goalentity.classname == "onslaught_generator")
189                                 l.enemy.aregensneighbor |= BIT(l.goalentity.team);
190                         else
191                                 l.enemy.arecpsneighbor |= BIT(l.goalentity.team);
192                 }
193                 if (l.enemy.islinked)
194                 {
195                         if(DIFF_TEAM(l.goalentity, l.enemy))
196                         {
197                                 LOG_DEBUG(etos(l), " (link) is unshielding ", etos(l.goalentity), " (point) because its team does not match ", etos(l.enemy), " (point)");
198                                 l.goalentity.isshielded = false;
199                         }
200                         if(l.enemy.classname == "onslaught_generator")
201                                 l.goalentity.aregensneighbor |= BIT(l.enemy.team);
202                         else
203                                 l.goalentity.arecpsneighbor |= BIT(l.enemy.team);
204                 }
205         }
206         // now update the generators
207         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
208         {
209                 if (l.isshielded)
210                 {
211                         LOG_DEBUG(etos(l), " (generator) is shielded");
212                         l.takedamage = DAMAGE_NO;
213                         if(l.bot_attack)
214                                 IL_REMOVE(g_bot_targets, l);
215                         l.bot_attack = false;
216                 }
217                 else
218                 {
219                         LOG_DEBUG(etos(l), " (generator) is not shielded");
220                         l.takedamage = DAMAGE_AIM;
221                         if(!l.bot_attack)
222                                 IL_PUSH(g_bot_targets, l);
223                         l.bot_attack = true;
224                 }
225
226                 ons_Generator_UpdateSprite(l);
227         }
228         // now update the takedamage and alpha variables on control point icons
229         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
230         {
231                 if (l.isshielded)
232                 {
233                         LOG_DEBUG(etos(l), " (point) is shielded");
234                         if (l.goalentity)
235                         {
236                                 l.goalentity.takedamage = DAMAGE_NO;
237                                 if(l.goalentity.bot_attack)
238                                         IL_REMOVE(g_bot_targets, l.goalentity);
239                                 l.goalentity.bot_attack = false;
240                         }
241                 }
242                 else
243                 {
244                         LOG_DEBUG(etos(l), " (point) is not shielded");
245                         if (l.goalentity)
246                         {
247                                 l.goalentity.takedamage = DAMAGE_AIM;
248                                 if(!l.goalentity.bot_attack)
249                                         IL_PUSH(g_bot_targets, l.goalentity);
250                                 l.goalentity.bot_attack = true;
251                         }
252                 }
253                 ons_ControlPoint_UpdateSprite(l);
254         }
255         IL_EACH(g_onsshields, true,
256         {
257                 it.team = it.enemy.team;
258                 it.colormap = it.enemy.colormap;
259         });
260 }
261
262
263 // ===================
264 // Main Link Functions
265 // ===================
266
267 bool ons_Link_Send(entity this, entity to, int sendflags)
268 {
269         WriteHeader(MSG_ENTITY, ENT_CLIENT_RADARLINK);
270         WriteByte(MSG_ENTITY, sendflags);
271         if(sendflags & 1)
272         {
273                 WriteVector(MSG_ENTITY, this.goalentity.origin);
274         }
275         if(sendflags & 2)
276         {
277                 WriteVector(MSG_ENTITY, this.enemy.origin);
278         }
279         if(sendflags & 4)
280         {
281                 WriteByte(MSG_ENTITY, this.clientcolors); // which is goalentity's color + enemy's color * 16
282         }
283         return true;
284 }
285
286 void ons_Link_CheckUpdate(entity this)
287 {
288         // TODO check if the two sides have moved (currently they won't move anyway)
289         float cc = 0, cc1 = 0, cc2 = 0;
290
291         if(this.goalentity.islinked || this.goalentity.iscaptured) { cc1 = (this.goalentity.team - 1) * 0x01; }
292         if(this.enemy.islinked || this.enemy.iscaptured) { cc2 = (this.enemy.team - 1) * 0x10; }
293
294         cc = cc1 + cc2;
295
296         if(cc != this.clientcolors)
297         {
298                 this.clientcolors = cc;
299                 this.SendFlags |= 4;
300         }
301
302         this.nextthink = time;
303 }
304
305 void ons_DelayedLinkSetup(entity this)
306 {
307         this.goalentity = find(NULL, targetname, this.target);
308         this.enemy = find(NULL, targetname, this.target2);
309         if(!this.goalentity) { objerror(this, "can not find target\n"); }
310         if(!this.enemy) { objerror(this, "can not find target2\n"); }
311
312         LOG_DEBUG(etos(this.goalentity), " linked with ", etos(this.enemy));
313         this.SendFlags |= 3;
314         setthink(this, ons_Link_CheckUpdate);
315         this.nextthink = time;
316 }
317
318
319 // =============================
320 // Main Control Point Functions
321 // =============================
322
323 int ons_ControlPoint_CanBeLinked(entity cp, int teamnumber)
324 {
325         if(cp.aregensneighbor & BIT(teamnumber)) return 2;
326         if(cp.arecpsneighbor & BIT(teamnumber)) return 1;
327
328         return 0;
329 }
330
331 int ons_ControlPoint_Attackable(entity cp, int teamnumber)
332         // -2: SAME TEAM, attackable by enemy!
333         // -1: SAME TEAM!
334         // 0: off limits
335         // 1: attack it
336         // 2: touch it
337         // 3: attack it (HIGH PRIO)
338         // 4: touch it (HIGH PRIO)
339 {
340         int a;
341
342         if(cp.isshielded)
343         {
344                 return 0;
345         }
346         else if(cp.goalentity)
347         {
348                 // if there's already an icon built, nothing happens
349                 if(cp.team == teamnumber)
350                 {
351                         a = ons_ControlPoint_CanBeLinked(cp, teamnumber);
352                         if(a) // attackable by enemy?
353                                 return -2; // EMERGENCY!
354                         return -1;
355                 }
356                 // we know it can be linked, so no need to check
357                 // but...
358                 a = ons_ControlPoint_CanBeLinked(cp, teamnumber);
359                 if(a == 2) // near our generator?
360                         return 3; // EMERGENCY!
361                 return 1;
362         }
363         else
364         {
365                 // free point
366                 if(ons_ControlPoint_CanBeLinked(cp, teamnumber))
367                 {
368                         a = ons_ControlPoint_CanBeLinked(cp, teamnumber); // why was this here NUM_TEAM_1 + NUM_TEAM_2 - t
369                         if(a == 2)
370                                 return 4; // GET THIS ONE NOW!
371                         else
372                                 return 2; // TOUCH ME
373                 }
374         }
375         return 0;
376 }
377
378 void ons_ControlPoint_Icon_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
379 {
380         if(damage <= 0) { return; }
381
382         if (this.owner.isshielded)
383         {
384                 // this is protected by a shield, so ignore the damage
385                 if (time > this.pain_finished)
386                         if (IS_PLAYER(attacker))
387                         {
388                                 play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
389                                 this.pain_finished = time + 1;
390                                 attacker.typehitsound += 1; // play both sounds (shield is way too quiet)
391                         }
392
393                 return;
394         }
395
396         if(IS_PLAYER(attacker))
397         if(time - ons_notification_time[this.team] > 10)
398         {
399                 play2team(this.team, SND(ONS_CONTROLPOINT_UNDERATTACK));
400                 ons_notification_time[this.team] = time;
401         }
402
403         TakeResource(this, RESOURCE_HEALTH, damage);
404         if(this.owner.iscaptured)
405                 WaypointSprite_UpdateHealth(this.owner.sprite, GetResourceAmount(this, RESOURCE_HEALTH));
406         else
407                 WaypointSprite_UpdateBuildFinished(this.owner.sprite, time + (this.max_health - GetResourceAmount(this, RESOURCE_HEALTH)) / (this.count / ONS_CP_THINKRATE));
408         this.pain_finished = time + 1;
409         // particles on every hit
410         pointparticles(EFFECT_SPARKS, hitloc, force*-1, 1);
411         //sound on every hit
412         if (random() < 0.5)
413                 sound(this, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE+0.3, ATTEN_NORM);
414         else
415                 sound(this, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE+0.3, ATTEN_NORM);
416
417         if (GetResourceAmount(this, RESOURCE_HEALTH) < 0)
418         {
419                 sound(this, CH_TRIGGER, SND_GRENADE_IMPACT, VOL_BASE, ATTEN_NORM);
420                 pointparticles(EFFECT_ROCKET_EXPLODE, this.origin, '0 0 0', 1);
421                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_CPDESTROYED), this.owner.message, attacker.netname);
422
423                 GameRules_scoring_add(attacker, ONS_TAKES, 1);
424                 GameRules_scoring_add(attacker, SCORE, 10);
425
426                 this.owner.goalentity = NULL;
427                 this.owner.islinked = false;
428                 this.owner.iscaptured = false;
429                 this.owner.team = 0;
430                 this.owner.colormap = 1024;
431
432                 WaypointSprite_UpdateMaxHealth(this.owner.sprite, 0);
433
434                 onslaught_updatelinks();
435
436                 // Use targets now (somebody make sure this is in the right place..)
437                 SUB_UseTargets(this.owner, this, NULL);
438
439                 this.owner.waslinked = this.owner.islinked;
440                 if(this.owner.model != "models/onslaught/controlpoint_pad.md3")
441                         setmodel_fixsize(this.owner, MDL_ONS_CP_PAD1);
442                 //setsize(this, '-32 -32 0', '32 32 8');
443
444                 delete(this);
445         }
446
447         this.SendFlags |= CPSF_STATUS;
448 }
449
450 bool ons_ControlPoint_Icon_Heal(entity targ, entity inflictor, float amount, float limit)
451 {
452         float hlth = GetResourceAmount(targ, RESOURCE_HEALTH);
453         float true_limit = ((limit != RESOURCE_LIMIT_NONE) ? limit : targ.max_health);
454         if (hlth <= 0 || hlth >= true_limit)
455                 return false;
456
457         GiveResourceWithLimit(targ, RESOURCE_HEALTH, amount, true_limit);
458         hlth = GetResourceAmount(targ, RESOURCE_HEALTH);
459         if(targ.owner.iscaptured)
460                 WaypointSprite_UpdateHealth(targ.owner.sprite, hlth);
461         else
462                 WaypointSprite_UpdateBuildFinished(targ.owner.sprite, time + (targ.max_health - hlth) / (targ.count / ONS_CP_THINKRATE));
463         targ.SendFlags |= CPSF_STATUS;
464         return true;
465 }
466
467 void ons_ControlPoint_Icon_Think(entity this)
468 {
469         this.nextthink = time + ONS_CP_THINKRATE;
470
471         if(autocvar_g_onslaught_cp_proxydecap)
472         {
473                 int _enemy_count = 0;
474                 int _friendly_count = 0;
475
476                 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), {
477                         if(vdist(it.origin - this.origin, <, autocvar_g_onslaught_cp_proxydecap_distance))
478                         {
479                                 if(SAME_TEAM(it, this))
480                                         ++_friendly_count;
481                                 else
482                                         ++_enemy_count;
483                         }
484                 });
485
486                 _friendly_count = _friendly_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
487                 _enemy_count = _enemy_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
488
489                 GiveResourceWithLimit(this, RESOURCE_HEALTH, (_friendly_count - _enemy_count), this.max_health);
490                 this.SendFlags |= CPSF_STATUS;
491                 if(GetResourceAmount(this, RESOURCE_HEALTH) <= 0)
492                 {
493                         ons_ControlPoint_Icon_Damage(this, this, this, 1, 0, DMG_NOWEP, this.origin, '0 0 0');
494                         return;
495                 }
496         }
497
498         if (time > this.pain_finished + 5)
499         {
500                 if(GetResourceAmount(this, RESOURCE_HEALTH) < this.max_health)
501                 {
502                         GiveResourceWithLimit(this, RESOURCE_HEALTH, this.count, this.max_health);
503                         WaypointSprite_UpdateHealth(this.owner.sprite, GetResourceAmount(this, RESOURCE_HEALTH));
504                 }
505         }
506
507         if(this.owner.islinked != this.owner.waslinked)
508         {
509                 // unteam the spawnpoint if needed
510                 int t = this.owner.team;
511                 if(!this.owner.islinked)
512                         this.owner.team = 0;
513
514                 SUB_UseTargets(this.owner, this, NULL);
515
516                 this.owner.team = t;
517
518                 this.owner.waslinked = this.owner.islinked;
519         }
520
521         // damaged fx
522         if(random() < 0.6 - GetResourceAmount(this, RESOURCE_HEALTH) / this.max_health)
523         {
524                 Send_Effect(EFFECT_ELECTRIC_SPARKS, this.origin + randompos('-10 -10 -20', '10 10 20'), '0 0 0', 1);
525
526                 if(random() > 0.8)
527                         sound(this, CH_PAIN, SND_ONS_SPARK1, VOL_BASE, ATTEN_NORM);
528                 else if (random() > 0.5)
529                         sound(this, CH_PAIN, SND_ONS_SPARK2, VOL_BASE, ATTEN_NORM);
530         }
531 }
532
533 void ons_ControlPoint_Icon_BuildThink(entity this)
534 {
535         int a;
536
537         this.nextthink = time + ONS_CP_THINKRATE;
538
539         // only do this if there is power
540         a = ons_ControlPoint_CanBeLinked(this.owner, this.owner.team);
541         if(!a)
542                 return;
543
544         GiveResource(this, RESOURCE_HEALTH, this.count);
545
546         this.SendFlags |= CPSF_STATUS;
547
548         if (GetResourceAmount(this, RESOURCE_HEALTH) >= this.max_health)
549         {
550                 SetResourceAmountExplicit(this, RESOURCE_HEALTH, this.max_health);
551                 this.count = autocvar_g_onslaught_cp_regen * ONS_CP_THINKRATE; // slow repair rate from now on
552                 setthink(this, ons_ControlPoint_Icon_Think);
553                 sound(this, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILT, VOL_BASE, ATTEN_NORM);
554                 this.owner.iscaptured = true;
555                 this.solid = SOLID_BBOX;
556
557                 Send_Effect(EFFECT_CAP(this.owner.team), this.owner.origin, '0 0 0', 1);
558
559                 WaypointSprite_UpdateMaxHealth(this.owner.sprite, this.max_health);
560                 WaypointSprite_UpdateHealth(this.owner.sprite, GetResourceAmount(this, RESOURCE_HEALTH));
561
562                 if(IS_PLAYER(this.owner.ons_toucher))
563                 {
564                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ONSLAUGHT_CAPTURE, this.owner.ons_toucher.netname, this.owner.message);
565                         Send_Notification(NOTIF_ALL_EXCEPT, this.owner.ons_toucher, MSG_CENTER, APP_TEAM_NUM(this.owner.ons_toucher.team, CENTER_ONS_CAPTURE_TEAM), this.owner.message);
566                         Send_Notification(NOTIF_ONE, this.owner.ons_toucher, MSG_CENTER, CENTER_ONS_CAPTURE, this.owner.message);
567                         GameRules_scoring_add(this.owner.ons_toucher, ONS_CAPS, 1);
568                         GameRules_scoring_add_team(this.owner.ons_toucher, SCORE, 10);
569                 }
570
571                 this.owner.ons_toucher = NULL;
572
573                 onslaught_updatelinks();
574
575                 // Use targets now (somebody make sure this is in the right place..)
576                 SUB_UseTargets(this.owner, this, NULL);
577
578                 this.SendFlags |= CPSF_SETUP;
579         }
580         if(this.owner.model != MDL_ONS_CP_PAD2.model_str())
581                 setmodel_fixsize(this.owner, MDL_ONS_CP_PAD2);
582
583         if(random() < 0.9 - GetResourceAmount(this, RESOURCE_HEALTH) / this.max_health)
584                 Send_Effect(EFFECT_RAGE, this.origin + 10 * randomvec(), '0 0 -1', 1);
585 }
586
587 void onslaught_controlpoint_icon_link(entity e, void(entity this) spawnproc);
588
589 void ons_ControlPoint_Icon_Spawn(entity cp, entity player)
590 {
591         entity e = new(onslaught_controlpoint_icon);
592
593         setsize(e, CPICON_MIN, CPICON_MAX);
594         setorigin(e, cp.origin + CPICON_OFFSET);
595
596         e.owner = cp;
597         e.max_health = autocvar_g_onslaught_cp_health;
598         SetResourceAmountExplicit(e, RESOURCE_HEALTH, autocvar_g_onslaught_cp_buildhealth);
599         e.solid = SOLID_NOT;
600         e.takedamage = DAMAGE_AIM;
601         e.bot_attack = true;
602         IL_PUSH(g_bot_targets, e);
603         e.event_damage = ons_ControlPoint_Icon_Damage;
604         e.event_heal = ons_ControlPoint_Icon_Heal;
605         e.team = player.team;
606         e.colormap = 1024 + (e.team - 1) * 17;
607         e.count = (e.max_health - GetResourceAmount(e, RESOURCE_HEALTH)) * ONS_CP_THINKRATE / autocvar_g_onslaught_cp_buildtime; // how long it takes to build
608
609         sound(e, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILD, VOL_BASE, ATTEN_NORM);
610
611         cp.goalentity = e;
612         cp.team = e.team;
613         cp.colormap = e.colormap;
614
615         Send_Effect(EFFECT_FLAG_TOUCH(player.team), e.origin, '0 0 0', 1);
616
617         WaypointSprite_UpdateBuildFinished(cp.sprite, time + (e.max_health - GetResourceAmount(e, RESOURCE_HEALTH)) / (e.count / ONS_CP_THINKRATE));
618         WaypointSprite_UpdateRule(cp.sprite,cp.team,SPRITERULE_TEAMPLAY);
619         cp.sprite.SendFlags |= 16;
620
621         onslaught_controlpoint_icon_link(e, ons_ControlPoint_Icon_BuildThink);
622 }
623
624 entity ons_ControlPoint_Waypoint(entity e)
625 {
626         if(e.team)
627         {
628                 int a = ons_ControlPoint_Attackable(e, e.team);
629
630                 if(a == -2) { return WP_OnsCPDefend; } // defend now
631                 if(a == -1 || a == 1 || a == 2) { return WP_OnsCP; } // touch
632                 if(a == 3 || a == 4) { return WP_OnsCPAttack; } // attack
633         }
634         else
635                 return WP_OnsCP;
636
637         return WP_Null;
638 }
639
640 void ons_ControlPoint_UpdateSprite(entity e)
641 {
642         entity s1 = ons_ControlPoint_Waypoint(e);
643         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
644
645         bool sh;
646         sh = !(ons_ControlPoint_CanBeLinked(e, NUM_TEAM_1) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_2) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_3) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_4));
647
648         if(e.lastteam != e.team + 2 || e.lastshielded != sh || e.iscaptured != e.lastcaptured)
649         {
650                 if(e.iscaptured) // don't mess up build bars!
651                 {
652                         if(sh)
653                         {
654                                 WaypointSprite_UpdateMaxHealth(e.sprite, 0);
655                         }
656                         else
657                         {
658                                 WaypointSprite_UpdateMaxHealth(e.sprite, e.goalentity.max_health);
659                                 WaypointSprite_UpdateHealth(e.sprite, GetResourceAmount(e.goalentity, RESOURCE_HEALTH));
660                         }
661                 }
662                 if(e.lastshielded)
663                 {
664                         if(e.team)
665                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, 0.5 * colormapPaletteColor(e.team - 1, false));
666                         else
667                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.5 0.5 0.5');
668                 }
669                 else
670                 {
671                         if(e.team)
672                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, colormapPaletteColor(e.team - 1, false));
673                         else
674                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.75 0.75 0.75');
675                 }
676                 WaypointSprite_Ping(e.sprite);
677
678                 e.lastteam = e.team + 2;
679                 e.lastshielded = sh;
680                 e.lastcaptured = e.iscaptured;
681         }
682 }
683
684 void ons_ControlPoint_Touch(entity this, entity toucher)
685 {
686         int attackable;
687
688         if(IS_VEHICLE(toucher) && toucher.owner)
689         if(autocvar_g_onslaught_allow_vehicle_touch)
690                 toucher = toucher.owner;
691         else
692                 return;
693
694         if(!IS_PLAYER(toucher)) { return; }
695         if(STAT(FROZEN, toucher)) { return; }
696         if(IS_DEAD(toucher)) { return; }
697
698         if ( SAME_TEAM(this,toucher) )
699         if ( this.iscaptured )
700         {
701                 if(time <= toucher.teleport_antispam)
702                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT_ANTISPAM, rint(toucher.teleport_antispam - time));
703                 else
704                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT);
705         }
706
707         attackable = ons_ControlPoint_Attackable(this, toucher.team);
708         if(attackable != 2 && attackable != 4)
709                 return;
710         // we've verified that this player has a legitimate claim to this point,
711         // so start building the captured point icon (which only captures this
712         // point if it successfully builds without being destroyed first)
713         ons_ControlPoint_Icon_Spawn(this, toucher);
714
715         this.ons_toucher = toucher;
716
717         onslaught_updatelinks();
718 }
719
720 void ons_ControlPoint_Think(entity this)
721 {
722         this.nextthink = time + ONS_CP_THINKRATE;
723         CSQCMODEL_AUTOUPDATE(this);
724 }
725
726 void ons_ControlPoint_Reset(entity this)
727 {
728         if(this.goalentity)
729                 delete(this.goalentity);
730
731         this.goalentity = NULL;
732         this.team = 0;
733         this.colormap = 1024;
734         this.iscaptured = false;
735         this.islinked = false;
736         this.isshielded = true;
737         setthink(this, ons_ControlPoint_Think);
738         this.ons_toucher = NULL;
739         this.nextthink = time + ONS_CP_THINKRATE;
740         setmodel_fixsize(this, MDL_ONS_CP_PAD1);
741
742         WaypointSprite_UpdateMaxHealth(this.sprite, 0);
743         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
744
745         onslaught_updatelinks();
746
747         SUB_UseTargets(this, this, NULL); // to reset the structures, playerspawns etc.
748
749         CSQCMODEL_AUTOUPDATE(this);
750 }
751
752 void ons_DelayedControlPoint_Setup(entity this)
753 {
754         onslaught_updatelinks();
755
756         // captureshield setup
757         ons_CaptureShield_Spawn(this, false);
758
759         CSQCMODEL_AUTOINIT(this);
760 }
761
762 void ons_ControlPoint_Setup(entity cp)
763 {
764         // main setup
765         cp.ons_worldcpnext = ons_worldcplist; // link control point into ons_worldcplist
766         ons_worldcplist = cp;
767
768         cp.netname = "Control point";
769         cp.team = 0;
770         cp.solid = SOLID_BBOX;
771         set_movetype(cp, MOVETYPE_NONE);
772         settouch(cp, ons_ControlPoint_Touch);
773         setthink(cp, ons_ControlPoint_Think);
774         cp.nextthink = time + ONS_CP_THINKRATE;
775         cp.reset = ons_ControlPoint_Reset;
776         cp.colormap = 1024;
777         cp.iscaptured = false;
778         cp.islinked = false;
779         cp.isshielded = true;
780
781         if(cp.message == "") { cp.message = "a"; }
782
783         // appearence
784         setmodel_fixsize(cp, MDL_ONS_CP_PAD1);
785
786         // control point placement
787         if((cp.spawnflags & 1) || cp.noalign) // don't drop to floor, just stay at fixed location
788         {
789                 cp.noalign = true;
790                 set_movetype(cp, MOVETYPE_NONE);
791         }
792         else // drop to floor, automatically find a platform and set that as spawn origin
793         {
794                 setorigin(cp, cp.origin + '0 0 20');
795                 cp.noalign = false;
796                 droptofloor(cp);
797                 set_movetype(cp, MOVETYPE_TOSS);
798         }
799
800         // waypointsprites
801         WaypointSprite_SpawnFixed(WP_Null, cp.origin + CPGEN_WAYPOINT_OFFSET, cp, sprite, RADARICON_NONE);
802         WaypointSprite_UpdateRule(cp.sprite, cp.team, SPRITERULE_TEAMPLAY);
803
804         InitializeEntity(cp, ons_DelayedControlPoint_Setup, INITPRIO_SETLOCATION);
805 }
806
807
808 // =========================
809 // Main Generator Functions
810 // =========================
811
812 entity ons_Generator_Waypoint(entity e)
813 {
814         if (e.isshielded)
815                 return WP_OnsGenShielded;
816         return WP_OnsGen;
817 }
818
819 void ons_Generator_UpdateSprite(entity e)
820 {
821         entity s1 = ons_Generator_Waypoint(e);
822         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
823
824         if(e.lastteam != e.team + 2 || e.lastshielded != e.isshielded)
825         {
826                 e.lastteam = e.team + 2;
827                 e.lastshielded = e.isshielded;
828                 if(e.lastshielded)
829                 {
830                         if(e.team)
831                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, 0.5 * colormapPaletteColor(e.team - 1, false));
832                         else
833                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.5 0.5 0.5');
834                 }
835                 else
836                 {
837                         if(e.team)
838                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, colormapPaletteColor(e.team - 1, false));
839                         else
840                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.75 0.75 0.75');
841                 }
842                 WaypointSprite_Ping(e.sprite);
843         }
844 }
845
846 void ons_camSetup(entity this)
847 {
848         vector dir;
849         vector ang = '0 0 0';
850         vector best_ang = '0 0 0';
851         float best_trace_fraction = 0;
852         while(ang.y < 360)
853         {
854                 dir = vec2(cos(ang.y * DEG2RAD), sin(ang.y * DEG2RAD));
855                 dir *= 500;
856                 traceline(this.origin, this.origin - dir, MOVE_WORLDONLY, this);
857                 if(trace_fraction > best_trace_fraction)
858                 {
859                         best_trace_fraction = trace_fraction;
860                         best_ang = ang;
861                         if(trace_fraction == 1)
862                                 break;
863                 }
864                 ang.y += 90;
865                 if(ang.y == 360)
866                         ang.y = 45;
867         }
868         cam.origin = this.origin;
869         setorigin(cam, cam.origin);
870         cam.angles = best_ang;
871         Net_LinkEntity(cam, false, 0, clientcamera_send);
872
873         FOREACH_CLIENT(true, it.clientcamera = cam;);
874
875         WriteByte(MSG_ALL, SVC_SETVIEWANGLES);
876         WriteAngle(MSG_ALL, cam.angles_x);
877         WriteAngle(MSG_ALL, cam.angles_y);
878         WriteAngle(MSG_ALL, cam.angles_z);
879 }
880
881 void ons_GeneratorDamage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
882 {
883         if(damage <= 0) return;
884         if(warmup_stage || game_stopped) return;
885         if(!round_handler_IsRoundStarted()) return;
886
887         if (attacker != this)
888         {
889                 if (this.isshielded)
890                 {
891                         // generator is protected by a shield, so ignore the damage
892                         if (time > this.pain_finished)
893                                 if (IS_PLAYER(attacker))
894                                 {
895                                         play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
896                                         attacker.typehitsound += 1;
897                                         this.pain_finished = time + 1;
898                                 }
899                         return;
900                 }
901                 if (time > this.pain_finished)
902                 {
903                         this.pain_finished = time + 10;
904                         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && SAME_TEAM(it, this), Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_GENERATOR_UNDERATTACK));
905                         play2team(this.team, SND(ONS_GENERATOR_UNDERATTACK));
906                 }
907         }
908         TakeResource(this, RESOURCE_HEALTH, damage);
909         float hlth = GetResourceAmount(this, RESOURCE_HEALTH);
910         WaypointSprite_UpdateHealth(this.sprite, hlth);
911         // choose an animation frame based on health
912         this.frame = 10 * bound(0, (1 - hlth / this.max_health), 1);
913         // see if the generator is still functional, or dying
914         if (hlth > 0)
915         {
916                 this.lasthealth = hlth;
917         }
918         else
919         {
920                 if (attacker == this)
921                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_GENDESTROYED_OVERTIME));
922                 else
923                 {
924                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_GENDESTROYED));
925                         GameRules_scoring_add(attacker, SCORE, 100);
926                 }
927                 this.iscaptured = false;
928                 this.islinked = false;
929                 this.isshielded = false;
930                 this.takedamage = DAMAGE_NO; // can't be hurt anymore
931                 this.event_damage = func_null; // won't do anything if hurt
932                 this.event_heal = func_null;
933                 this.count = 0; // reset counter
934                 setthink(this, func_null);
935                 this.nextthink = 0;
936                 //this.think(); // do the first explosion now
937
938                 WaypointSprite_UpdateMaxHealth(this.sprite, 0);
939                 WaypointSprite_Ping(this.sprite);
940                 //WaypointSprite_Kill(this.sprite); // can't do this yet, code too poor
941
942                 onslaught_updatelinks();
943
944                 ons_camSetup(this);
945         }
946
947         // Throw some flaming gibs on damage, more damage = more chance for gib
948         if(random() < damage/220)
949         {
950                 sound(this, CH_TRIGGER, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
951         }
952         else
953         {
954                 // particles on every hit
955                 Send_Effect(EFFECT_SPARKS, hitloc, force * -1, 1);
956
957                 //sound on every hit
958                 if (random() < 0.5)
959                         sound(this, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE, ATTEN_NORM);
960                 else
961                         sound(this, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE, ATTEN_NORM);
962         }
963
964         this.SendFlags |= GSF_STATUS;
965 }
966
967 bool ons_GeneratorHeal(entity targ, entity inflictor, float amount, float limit)
968 {
969         float true_limit = ((limit != RESOURCE_LIMIT_NONE) ? limit : targ.max_health);
970         float hlth = GetResourceAmount(targ, RESOURCE_HEALTH);
971         if (hlth <= 0 || hlth >= true_limit)
972                 return false;
973
974         GiveResourceWithLimit(targ, RESOURCE_HEALTH, amount, true_limit);
975         hlth = GetResourceAmount(targ, RESOURCE_HEALTH);
976         WaypointSprite_UpdateHealth(targ.sprite, hlth);
977         targ.frame = 10 * bound(0, (1 - hlth / targ.max_health), 1);
978         targ.lasthealth = hlth;
979         targ.SendFlags |= GSF_STATUS;
980         return true;
981 }
982
983 void ons_GeneratorThink(entity this)
984 {
985         this.nextthink = time + GEN_THINKRATE;
986
987         if (game_stopped || this.isshielded || time < this.wait)
988                 return;
989
990         this.wait = time + 5;
991         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it),
992         {
993                 if (SAME_TEAM(it, this))
994                 {
995                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_ONS_NOTSHIELDED_TEAM);
996                         msg_entity = it;
997                         soundto(MSG_ONE, this, CHAN_AUTO, SND(KH_ALARM), VOL_BASE, ATTEN_NONE); // FIXME: unique sound?
998                 }
999                 else
1000                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_TEAM_NUM(this.team, CENTER_ONS_NOTSHIELDED));
1001         });
1002 }
1003
1004 void ons_GeneratorReset(entity this)
1005 {
1006         this.team = this.team_saved;
1007         SetResourceAmountExplicit(this, RESOURCE_HEALTH, autocvar_g_onslaught_gen_health);
1008         this.lasthealth = this.max_health = autocvar_g_onslaught_gen_health;
1009         this.takedamage = DAMAGE_AIM;
1010         this.bot_attack = true;
1011         if(!IL_CONTAINS(g_bot_targets, this))
1012                 IL_PUSH(g_bot_targets, this);
1013         this.iscaptured = true;
1014         this.islinked = true;
1015         this.isshielded = true;
1016         this.event_damage = ons_GeneratorDamage;
1017         this.event_heal = ons_GeneratorHeal;
1018         setthink(this, ons_GeneratorThink);
1019         this.nextthink = time + GEN_THINKRATE;
1020
1021         Net_LinkEntity(this, false, 0, generator_send);
1022
1023         this.SendFlags = GSF_SETUP; // just incase
1024         this.SendFlags |= GSF_STATUS;
1025
1026         WaypointSprite_UpdateMaxHealth(this.sprite, this.max_health);
1027         WaypointSprite_UpdateHealth(this.sprite, GetResourceAmount(this, RESOURCE_HEALTH));
1028         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
1029
1030         onslaught_updatelinks();
1031 }
1032
1033 void ons_DelayedGeneratorSetup(entity this)
1034 {
1035         // bot waypoints
1036         waypoint_spawnforitem_force(this, this.origin);
1037         this.nearestwaypointtimeout = 0; // activate waypointing again
1038         this.bot_basewaypoint = this.nearestwaypoint;
1039
1040         // captureshield setup
1041         ons_CaptureShield_Spawn(this, true);
1042
1043         onslaught_updatelinks();
1044
1045         Net_LinkEntity(this, false, 0, generator_send);
1046 }
1047
1048
1049 void onslaught_generator_touch(entity this, entity toucher)
1050 {
1051         if ( IS_PLAYER(toucher) )
1052         if ( SAME_TEAM(this,toucher) )
1053         if ( this.iscaptured )
1054         {
1055                 Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT);
1056         }
1057 }
1058
1059 void ons_GeneratorSetup(entity gen) // called when spawning a generator entity on the map as a spawnfunc
1060 {
1061         // declarations
1062         int teamnumber = gen.team;
1063
1064         // main setup
1065         gen.ons_worldgeneratornext = ons_worldgeneratorlist; // link generator into ons_worldgeneratorlist
1066         ons_worldgeneratorlist = gen;
1067
1068         gen.netname = sprintf("%s generator", Team_ColoredFullName(teamnumber));
1069         gen.classname = "onslaught_generator";
1070         gen.solid = SOLID_BBOX;
1071         gen.team_saved = teamnumber;
1072         IL_PUSH(g_saved_team, gen);
1073         set_movetype(gen, MOVETYPE_NONE);
1074         gen.lasthealth = gen.max_health = autocvar_g_onslaught_gen_health;
1075         SetResourceAmountExplicit(gen, RESOURCE_HEALTH, autocvar_g_onslaught_gen_health);
1076         gen.takedamage = DAMAGE_AIM;
1077         gen.bot_attack = true;
1078         IL_PUSH(g_bot_targets, gen);
1079         gen.event_damage = ons_GeneratorDamage;
1080         gen.event_heal = ons_GeneratorHeal;
1081         gen.reset = ons_GeneratorReset;
1082         setthink(gen, ons_GeneratorThink);
1083         gen.nextthink = time + GEN_THINKRATE;
1084         gen.iscaptured = true;
1085         gen.islinked = true;
1086         gen.isshielded = true;
1087         settouch(gen, onslaught_generator_touch);
1088
1089         // appearence
1090         // model handled by CSQC
1091         setsize(gen, GENERATOR_MIN, GENERATOR_MAX);
1092         setorigin(gen, (gen.origin + CPGEN_SPAWN_OFFSET));
1093         gen.colormap = 1024 + (teamnumber - 1) * 17;
1094
1095         // generator placement
1096         droptofloor(gen);
1097
1098         // waypointsprites
1099         WaypointSprite_SpawnFixed(WP_Null, gen.origin + CPGEN_WAYPOINT_OFFSET, gen, sprite, RADARICON_NONE);
1100         WaypointSprite_UpdateRule(gen.sprite, gen.team, SPRITERULE_TEAMPLAY);
1101         WaypointSprite_UpdateMaxHealth(gen.sprite, gen.max_health);
1102         WaypointSprite_UpdateHealth(gen.sprite, GetResourceAmount(gen, RESOURCE_HEALTH));
1103
1104         InitializeEntity(gen, ons_DelayedGeneratorSetup, INITPRIO_SETLOCATION);
1105 }
1106
1107
1108 // ===============
1109 //  Round Handler
1110 // ===============
1111
1112 int total_generators;
1113 void Onslaught_count_generators()
1114 {
1115         entity e;
1116         total_generators = 0;
1117         for (int i = 1; i <= NUM_TEAMS; ++i)
1118         {
1119                 Team_SetNumberOfControlPoints(Team_GetTeamFromIndex(i), 0);
1120         }
1121         for(e = ons_worldgeneratorlist; e; e = e.ons_worldgeneratornext)
1122         {
1123                 ++total_generators;
1124                 if (GetResourceAmount(e, RESOURCE_HEALTH) < 1)
1125                 {
1126                         continue;
1127                 }
1128                 entity team_ = Entity_GetTeam(e);
1129                 int num_control_points = Team_GetNumberOfControlPoints(team_);
1130                 ++num_control_points;
1131                 Team_SetNumberOfControlPoints(team_, num_control_points);
1132         }
1133 }
1134
1135 int Onslaught_GetWinnerTeam()
1136 {
1137         int winner_team = 0;
1138         if (Team_GetNumberOfControlPoints(Team_GetTeamFromIndex(1)) >= 1)
1139         {
1140                 winner_team = NUM_TEAM_1;
1141         }
1142         for (int i = 2; i <= NUM_TEAMS; ++i)
1143         {
1144                 if (Team_GetNumberOfControlPoints(Team_GetTeamFromIndex(i)) >= 1)
1145                 {
1146                         if (winner_team != 0)
1147                         {
1148                                 return 0;
1149                         }
1150                         winner_team = Team_IndexToTeam(i);
1151                 }
1152         }
1153         if (winner_team)
1154         {
1155                 return winner_team;
1156         }
1157         return -1; // no generators left?
1158 }
1159
1160 void nades_Clear(entity e);
1161
1162 bool Onslaught_CheckWinner()
1163 {
1164         if ((autocvar_timelimit && time > game_starttime + autocvar_timelimit * 60) || (round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0))
1165         {
1166                 ons_stalemate = true;
1167
1168                 if (!wpforenemy_announced)
1169                 {
1170                         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT);
1171                         sound(NULL, CH_INFO, SND_ONS_GENERATOR_DECAY, VOL_BASE, ATTEN_NONE);
1172
1173                         wpforenemy_announced = true;
1174                 }
1175
1176                 entity tmp_entity; // temporary entity
1177                 float d;
1178                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext) if(time >= tmp_entity.ons_overtime_damagedelay)
1179                 {
1180                         // tmp_entity.max_health / 300 gives 5 minutes of overtime.
1181                         // control points reduce the overtime duration.
1182                         d = 1;
1183                         entity e;
1184                         for(e = ons_worldcplist; e; e = e.ons_worldcpnext)
1185                         {
1186                                 if(DIFF_TEAM(e, tmp_entity))
1187                                 if(e.islinked)
1188                                         d = d + 1;
1189                         }
1190
1191                         if(autocvar_g_campaign && autocvar__campaign_testrun)
1192                                 d = d * tmp_entity.max_health;
1193                         else
1194                                 d = d * tmp_entity.max_health / max(30, 60 * autocvar_timelimit_suddendeath);
1195
1196                         Damage(tmp_entity, tmp_entity, tmp_entity, d, DEATH_HURTTRIGGER.m_id, DMG_NOWEP, tmp_entity.origin, '0 0 0');
1197
1198                         tmp_entity.sprite.SendFlags |= 16;
1199
1200                         tmp_entity.ons_overtime_damagedelay = time + 1;
1201                 }
1202         }
1203         else { wpforenemy_announced = false; ons_stalemate = false; }
1204
1205         Onslaught_count_generators();
1206
1207         if (Team_GetNumberOfTeamsWithControlPoints() > 1)
1208         {
1209                 return 0;
1210         }
1211
1212         int winner_team = Onslaught_GetWinnerTeam();
1213
1214         if(winner_team > 0)
1215         {
1216                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN));
1217                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN));
1218                 TeamScore_AddToTeam(winner_team, ST_ONS_CAPS, +1);
1219         }
1220         else if(winner_team == -1)
1221         {
1222                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_TIED);
1223                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_TIED);
1224         }
1225
1226         ons_stalemate = false;
1227
1228         play2all(SND(CTF_CAPTURE(winner_team)));
1229
1230         round_handler_Init(7, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
1231
1232         FOREACH_CLIENT(IS_PLAYER(it), {
1233                 STAT(ROUNDLOST, it) = true;
1234                 it.player_blocked = true;
1235
1236                 nades_Clear(it);
1237         });
1238
1239         game_stopped = true;
1240         return 1;
1241 }
1242
1243 bool Onslaught_CheckPlayers()
1244 {
1245         return 1;
1246 }
1247
1248 void Onslaught_RoundStart()
1249 {
1250         entity tmp_entity;
1251         FOREACH_CLIENT(IS_PLAYER(it), it.player_blocked = false);
1252
1253         for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1254                 tmp_entity.sprite.SendFlags |= 16;
1255
1256         for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1257                 tmp_entity.sprite.SendFlags |= 16;
1258 }
1259
1260
1261 // ================
1262 // Bot player logic
1263 // ================
1264
1265 // NOTE: LEGACY CODE, needs to be re-written!
1266
1267 void havocbot_goalrating_ons_offenseitems(entity this, float ratingscale, vector org, float sradius)
1268 {
1269         bool needarmor = false, needweapons = false;
1270
1271         // Needs armor/health?
1272         if(GetResourceAmount(this, RESOURCE_HEALTH) < 100)
1273                 needarmor = true;
1274
1275         // Needs weapons?
1276         int c = 0;
1277         FOREACH(Weapons, it != WEP_Null, {
1278                 if(STAT(WEAPONS, this) & (it.m_wepset))
1279                 if(++c >= 4)
1280                         break;
1281         });
1282
1283         if(c<4)
1284                 needweapons = true;
1285
1286         if(!needweapons && !needarmor)
1287                 return;
1288
1289         LOG_DEBUG(this.netname, " needs weapons ", ftos(needweapons));
1290         LOG_DEBUG(this.netname, " needs armor ", ftos(needarmor));
1291
1292         // See what is around
1293         IL_EACH(g_items, it.bot_pickup,
1294         {
1295                 // gather health and armor only
1296                 if (it.solid)
1297                 if ( ((GetResourceAmount(it, RESOURCE_HEALTH) || GetResourceAmount(it, RESOURCE_ARMOR)) && needarmor) || (STAT(WEAPONS, it) && needweapons ) )
1298                 if (vdist(it.origin - org, <, sradius))
1299                 {
1300                         int t = it.bot_pickupevalfunc(this, it);
1301                         if (t > 0)
1302                                 navigation_routerating(this, it, t * ratingscale, 500);
1303                 }
1304         });
1305 }
1306
1307 void havocbot_role_ons_setrole(entity this, int role)
1308 {
1309         LOG_DEBUG(this.netname," switched to ");
1310         switch(role)
1311         {
1312                 case HAVOCBOT_ONS_ROLE_DEFENSE:
1313                         LOG_DEBUG("defense");
1314                         this.havocbot_role = havocbot_role_ons_defense;
1315                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_DEFENSE;
1316                         this.havocbot_role_timeout = 0;
1317                         break;
1318                 case HAVOCBOT_ONS_ROLE_ASSISTANT:
1319                         LOG_DEBUG("assistant");
1320                         this.havocbot_role = havocbot_role_ons_assistant;
1321                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_ASSISTANT;
1322                         this.havocbot_role_timeout = 0;
1323                         break;
1324                 case HAVOCBOT_ONS_ROLE_OFFENSE:
1325                         LOG_DEBUG("offense");
1326                         this.havocbot_role = havocbot_role_ons_offense;
1327                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_OFFENSE;
1328                         this.havocbot_role_timeout = 0;
1329                         break;
1330         }
1331         LOG_DEBUG("");
1332 }
1333
1334 void havocbot_goalrating_ons_controlpoints_attack(entity this, float ratingscale)
1335 {
1336         entity cp, cp1, cp2, best, wp;
1337         float radius, bestvalue;
1338         int c;
1339         bool found;
1340
1341         // Filter control points
1342         for(cp2 = ons_worldcplist; cp2; cp2 = cp2.ons_worldcpnext)
1343         {
1344                 cp2.wpcost = c = 0;
1345                 cp2.wpconsidered = false;
1346
1347                 if(cp2.isshielded)
1348                         continue;
1349
1350                 // Ignore owned controlpoints
1351                 if(!((cp2.aregensneighbor & BIT(this.team)) || (cp2.arecpsneighbor & BIT(this.team))))
1352                         continue;
1353
1354                 // Count team mates interested in this control point
1355                 // (easier and cleaner than keeping counters per cp and teams)
1356                 FOREACH_CLIENT(IS_PLAYER(it), {
1357                         if(SAME_TEAM(it, this))
1358                         if(it.havocbot_role_flags & HAVOCBOT_ONS_ROLE_OFFENSE)
1359                         if(it.havocbot_ons_target == cp2)
1360                                 ++c;
1361                 });
1362
1363                 // NOTE: probably decrease the cost of attackable control points
1364                 cp2.wpcost = c;
1365                 cp2.wpconsidered = true;
1366         }
1367
1368         // We'll consider only the best case
1369         bestvalue = 99999999999;
1370         cp = NULL;
1371         for(cp1 = ons_worldcplist; cp1; cp1 = cp1.ons_worldcpnext)
1372         {
1373                 if (!cp1.wpconsidered)
1374                         continue;
1375
1376                 if(cp1.wpcost<bestvalue)
1377                 {
1378                         bestvalue = cp1.wpcost;
1379                         cp = cp1;
1380                         this.havocbot_ons_target = cp1;
1381                 }
1382         }
1383
1384         if (!cp)
1385                 return;
1386
1387         LOG_DEBUG(this.netname, " chose cp ranked ", ftos(bestvalue));
1388
1389         if(cp.goalentity)
1390         {
1391                 // Should be attacked
1392                 // Rate waypoints near it
1393                 found = false;
1394                 best = NULL;
1395                 bestvalue = 99999999999;
1396                 for(radius=0; radius<1000 && !found; radius+=500)
1397                 {
1398                         for(wp=findradius(cp.origin,radius); wp; wp=wp.chain)
1399                         {
1400                                 if(!(wp.wpflags & WAYPOINTFLAG_GENERATED))
1401                                 if(wp.classname=="waypoint")
1402                                 if(checkpvs(wp.origin,cp))
1403                                 {
1404                                         found = true;
1405                                         if(wp.cnt<bestvalue)
1406                                         {
1407                                                 best = wp;
1408                                                 bestvalue = wp.cnt;
1409                                         }
1410                                 }
1411                         }
1412                 }
1413
1414                 if(best)
1415                 {
1416                         navigation_routerating(this, best, ratingscale, 10000);
1417                         best.cnt += 1;
1418
1419                         this.havocbot_attack_time = 0;
1420                         if(checkpvs(this.origin + this.view_ofs, cp))
1421                         if(checkpvs(this.origin + this.view_ofs, best))
1422                                 this.havocbot_attack_time = time + 2;
1423                 }
1424                 else
1425                 {
1426                         navigation_routerating(this, cp, ratingscale, 10000);
1427                 }
1428                 LOG_DEBUG(this.netname, " found an attackable controlpoint at ", vtos(cp.origin));
1429         }
1430         else
1431         {
1432                 // Should be touched
1433                 LOG_DEBUG(this.netname, " found a touchable controlpoint at ", vtos(cp.origin));
1434                 found = false;
1435
1436                 // Look for auto generated waypoint
1437                 if (!bot_waypoints_for_items)
1438                 for (wp = findradius(cp.origin,100); wp; wp = wp.chain)
1439                 {
1440                         if(wp.classname=="waypoint")
1441                         {
1442                                 navigation_routerating(this, wp, ratingscale, 10000);
1443                                 found = true;
1444                         }
1445                 }
1446
1447                 // Nothing found, rate the controlpoint itself
1448                 if (!found)
1449                         navigation_routerating(this, cp, ratingscale, 10000);
1450         }
1451 }
1452
1453 bool havocbot_goalrating_ons_generator_attack(entity this, float ratingscale)
1454 {
1455         entity g, wp, bestwp;
1456         bool found;
1457         int best;
1458
1459         for(g = ons_worldgeneratorlist; g; g = g.ons_worldgeneratornext)
1460         {
1461                 if(SAME_TEAM(g, this) || g.isshielded)
1462                         continue;
1463
1464                 // Should be attacked
1465                 // Rate waypoints near it
1466                 found = false;
1467                 bestwp = NULL;
1468                 best = 99999999999;
1469
1470                 for(wp=findradius(g.origin,400); wp; wp=wp.chain)
1471                 {
1472                         if(wp.classname=="waypoint")
1473                         if(checkpvs(wp.origin,g))
1474                         {
1475                                 found = true;
1476                                 if(wp.cnt<best)
1477                                 {
1478                                         bestwp = wp;
1479                                         best = wp.cnt;
1480                                 }
1481                         }
1482                 }
1483
1484                 if(bestwp)
1485                 {
1486                         LOG_DEBUG("waypoints found around generator");
1487                         navigation_routerating(this, bestwp, ratingscale, 10000);
1488                         bestwp.cnt += 1;
1489
1490                         this.havocbot_attack_time = 0;
1491                         if(checkpvs(this.origin + this.view_ofs, g))
1492                         if(checkpvs(this.origin + this.view_ofs, bestwp))
1493                                 this.havocbot_attack_time = time + 5;
1494
1495                         return true;
1496                 }
1497                 else
1498                 {
1499                         LOG_DEBUG("generator found without waypoints around");
1500                         // if there aren't waypoints near the generator go straight to it
1501                         navigation_routerating(this, g, ratingscale, 10000);
1502                         this.havocbot_attack_time = 0;
1503                         return true;
1504                 }
1505         }
1506         return false;
1507 }
1508
1509 void havocbot_role_ons_offense(entity this)
1510 {
1511         if(IS_DEAD(this))
1512         {
1513                 this.havocbot_attack_time = 0;
1514                 havocbot_ons_reset_role(this);
1515                 return;
1516         }
1517
1518         // Set the role timeout if necessary
1519         if (!this.havocbot_role_timeout)
1520                 this.havocbot_role_timeout = time + 120;
1521
1522         if (time > this.havocbot_role_timeout)
1523         {
1524                 havocbot_ons_reset_role(this);
1525                 return;
1526         }
1527
1528         if(this.havocbot_attack_time>time)
1529                 return;
1530
1531         if (navigation_goalrating_timeout(this))
1532         {
1533                 navigation_goalrating_start(this);
1534                 havocbot_goalrating_enemyplayers(this, 20000, this.origin, 650);
1535                 if(!havocbot_goalrating_ons_generator_attack(this, 20000))
1536                         havocbot_goalrating_ons_controlpoints_attack(this, 20000);
1537                 havocbot_goalrating_ons_offenseitems(this, 10000, this.origin, 10000);
1538                 navigation_goalrating_end(this);
1539
1540                 navigation_goalrating_timeout_set(this);
1541         }
1542 }
1543
1544 void havocbot_role_ons_assistant(entity this)
1545 {
1546         havocbot_ons_reset_role(this);
1547 }
1548
1549 void havocbot_role_ons_defense(entity this)
1550 {
1551         havocbot_ons_reset_role(this);
1552 }
1553
1554 void havocbot_ons_reset_role(entity this)
1555 {
1556         if(IS_DEAD(this))
1557                 return;
1558
1559         this.havocbot_ons_target = NULL;
1560
1561         // TODO: Defend control points or generator if necessary
1562
1563         havocbot_role_ons_setrole(this, HAVOCBOT_ONS_ROLE_OFFENSE);
1564 }
1565
1566
1567 /*
1568  * Find control point or generator owned by the same team self which is nearest to pos
1569  * if max_dist is positive, only control points within this range will be considered
1570  */
1571 entity ons_Nearest_ControlPoint(entity this, vector pos, float max_dist)
1572 {
1573         entity closest_target = NULL;
1574         for(entity cp = ons_worldcplist; cp; cp = cp.ons_worldcpnext)
1575         {
1576                 if(SAME_TEAM(cp, this))
1577                 if(cp.iscaptured)
1578                 if(max_dist <= 0 || vdist(cp.origin - pos, <=, max_dist))
1579                 if(vlen2(cp.origin - pos) <= vlen2(closest_target.origin - pos) || closest_target == NULL)
1580                         closest_target = cp;
1581         }
1582         for(entity gen = ons_worldgeneratorlist; gen; gen = gen.ons_worldgeneratornext)
1583         {
1584                 if(SAME_TEAM(gen, this))
1585                 if(max_dist <= 0 || vdist(gen.origin - pos, <, max_dist))
1586                 if(vlen2(gen.origin - pos) <= vlen2(closest_target.origin - pos) || closest_target == NULL)
1587                         closest_target = gen;
1588         }
1589
1590         return closest_target;
1591 }
1592
1593 /*
1594  * Find control point or generator owned by the same team self which is nearest to pos
1595  * if max_dist is positive, only control points within this range will be considered
1596  * This function only check distances on the XY plane, disregarding Z
1597  */
1598 entity ons_Nearest_ControlPoint_2D(entity this, vector pos, float max_dist)
1599 {
1600         entity closest_target = NULL;
1601         vector delta;
1602         float smallest_distance = 0, distance;
1603
1604         for(entity cp = ons_worldcplist; cp; cp = cp.ons_worldcpnext)
1605         {
1606                 delta = cp.origin - pos;
1607                 delta_z = 0;
1608                 distance = vlen(delta);
1609
1610                 if(SAME_TEAM(cp, this))
1611                 if(cp.iscaptured)
1612                 if(max_dist <= 0 || distance <= max_dist)
1613                 if(closest_target == NULL || distance <= smallest_distance )
1614                 {
1615                         closest_target = cp;
1616                         smallest_distance = distance;
1617                 }
1618         }
1619         for(entity gen = ons_worldgeneratorlist; gen; gen = gen.ons_worldgeneratornext)
1620         {
1621                 delta = gen.origin - pos;
1622                 delta_z = 0;
1623                 distance = vlen(delta);
1624
1625                 if(SAME_TEAM(gen, this))
1626                 if(max_dist <= 0 || distance <= max_dist)
1627                 if(closest_target == NULL || distance <= smallest_distance )
1628                 {
1629                         closest_target = gen;
1630                         smallest_distance = distance;
1631                 }
1632         }
1633
1634         return closest_target;
1635 }
1636 /**
1637  * find the number of control points and generators in the same team as this
1638  */
1639 int ons_Count_SelfControlPoints(entity this)
1640 {
1641         int n = 0;
1642         for(entity cp = ons_worldcplist; cp; cp = cp.ons_worldcpnext)
1643         {
1644                 if(SAME_TEAM(cp, this))
1645                 if(cp.iscaptured)
1646                         n++;
1647         }
1648         for(entity gen = ons_worldgeneratorlist; gen; gen = gen.ons_worldgeneratornext)
1649         {
1650                 if(SAME_TEAM(gen, this))
1651                         n++;
1652         }
1653         return n;
1654 }
1655
1656 /**
1657  * Teleport player to a random position near tele_target
1658  * if tele_effects is true, teleport sound+particles are created
1659  * return false on failure
1660  */
1661 bool ons_Teleport(entity player, entity tele_target, float range, bool tele_effects)
1662 {
1663         if ( !tele_target )
1664                 return false;
1665
1666         int i;
1667         vector loc;
1668         float theta;
1669         // narrow the range for each iteration to increase chances that a spawnpoint
1670         // can be found even if there's little room around the control point
1671         float iteration_scale = 1;
1672         for(i = 0; i < 16; ++i)
1673         {
1674                 iteration_scale -= i / 16;
1675                 theta = random() * 2 * M_PI;
1676                 loc_y = sin(theta);
1677                 loc_x = cos(theta);
1678                 loc_z = 0;
1679                 loc *= random() * range * iteration_scale;
1680
1681                 loc += tele_target.origin + '0 0 128' * iteration_scale;
1682
1683                 tracebox(loc, STAT(PL_MIN, player), STAT(PL_MAX, player), loc, MOVE_NORMAL, player);
1684                 if(trace_fraction == 1.0 && !trace_startsolid)
1685                 {
1686                         traceline(tele_target.origin, loc, MOVE_NOMONSTERS, tele_target); // double check to make sure we're not spawning outside the NULL
1687                         if(trace_fraction == 1.0 && !trace_startsolid)
1688                         {
1689                                 if ( tele_effects )
1690                                 {
1691                                         Send_Effect(EFFECT_TELEPORT, player.origin, '0 0 0', 1);
1692                                         sound (player, CH_TRIGGER, SND_TELEPORT, VOL_BASE, ATTEN_NORM);
1693                                 }
1694                                 setorigin(player, loc);
1695                                 player.angles = '0 1 0' * ( theta * RAD2DEG + 180 );
1696                                 makevectors(player.angles);
1697                                 player.fixangle = true;
1698                                 player.teleport_antispam = time + autocvar_g_onslaught_teleport_wait;
1699
1700                                 if ( tele_effects )
1701                                         Send_Effect(EFFECT_TELEPORT, player.origin + v_forward * 32, '0 0 0', 1);
1702                                 return true;
1703                         }
1704                 }
1705         }
1706
1707         return false;
1708 }
1709
1710 // ==============
1711 // Hook Functions
1712 // ==============
1713
1714 MUTATOR_HOOKFUNCTION(ons, reset_map_global)
1715 {
1716         FOREACH_CLIENT(IS_PLAYER(it), {
1717                 STAT(ROUNDLOST, it) = false;
1718                 it.ons_deathloc = '0 0 0';
1719                 PutClientInServer(it);
1720                 it.clientcamera = it;
1721         });
1722         return false;
1723 }
1724
1725 MUTATOR_HOOKFUNCTION(ons, ClientDisconnect)
1726 {
1727         entity player = M_ARGV(0, entity);
1728
1729         player.ons_deathloc = '0 0 0';
1730 }
1731
1732 MUTATOR_HOOKFUNCTION(ons, MakePlayerObserver)
1733 {
1734         entity player = M_ARGV(0, entity);
1735
1736         player.ons_deathloc = '0 0 0';
1737 }
1738
1739 MUTATOR_HOOKFUNCTION(ons, PlayerSpawn)
1740 {
1741         entity player = M_ARGV(0, entity);
1742
1743         if(!round_handler_IsRoundStarted())
1744         {
1745                 player.player_blocked = true;
1746                 return false;
1747         }
1748
1749         entity l;
1750         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1751         {
1752                 l.sprite.SendFlags |= 16;
1753         }
1754         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1755         {
1756                 l.sprite.SendFlags |= 16;
1757         }
1758
1759         if(ons_stalemate) { Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT); }
1760
1761         if ( autocvar_g_onslaught_spawn_choose )
1762         if ( player.ons_spawn_by )
1763         if ( ons_Teleport(player,player.ons_spawn_by,autocvar_g_onslaught_teleport_radius,false) )
1764         {
1765                 player.ons_spawn_by = NULL;
1766                 return false;
1767         }
1768
1769         if(autocvar_g_onslaught_spawn_at_controlpoints)
1770         if(random() <= autocvar_g_onslaught_spawn_at_controlpoints_chance)
1771         {
1772                 float random_target = autocvar_g_onslaught_spawn_at_controlpoints_random;
1773                 entity tmp_entity, closest_target = NULL;
1774                 vector spawn_loc = player.ons_deathloc;
1775
1776                 // new joining player or round reset, don't bother checking
1777                 if(spawn_loc == '0 0 0') { return false; }
1778
1779                 if(random_target) { RandomSelection_Init(); }
1780
1781                 for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1782                 {
1783                         if(SAME_TEAM(tmp_entity, player))
1784                         if(random_target)
1785                                 RandomSelection_AddEnt(tmp_entity, 1, 1);
1786                         else if(vlen2(tmp_entity.origin - spawn_loc) <= vlen2(closest_target.origin - spawn_loc) || closest_target == NULL)
1787                                 closest_target = tmp_entity;
1788                 }
1789
1790                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1791
1792                 if(closest_target)
1793                 {
1794                         float i;
1795                         vector loc;
1796                         float iteration_scale = 1;
1797                         for(i = 0; i < 10; ++i)
1798                         {
1799                                 iteration_scale -= i / 10;
1800                                 loc = closest_target.origin + '0 0 96' * iteration_scale;
1801                                 loc += ('0 1 0' * random()) * 128 * iteration_scale;
1802                                 tracebox(loc, STAT(PL_MIN, player), STAT(PL_MAX, player), loc, MOVE_NORMAL, player);
1803                                 if(trace_fraction == 1.0 && !trace_startsolid)
1804                                 {
1805                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the NULL
1806                                         if(trace_fraction == 1.0 && !trace_startsolid)
1807                                         {
1808                                                 setorigin(player, loc);
1809                                                 player.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1810                                                 return false;
1811                                         }
1812                                 }
1813                         }
1814                 }
1815         }
1816
1817         if(autocvar_g_onslaught_spawn_at_generator)
1818         if(random() <= autocvar_g_onslaught_spawn_at_generator_chance)
1819         {
1820                 float random_target = autocvar_g_onslaught_spawn_at_generator_random;
1821                 entity tmp_entity, closest_target = NULL;
1822                 vector spawn_loc = player.ons_deathloc;
1823
1824                 // new joining player or round reset, don't bother checking
1825                 if(spawn_loc == '0 0 0') { return false; }
1826
1827                 if(random_target) { RandomSelection_Init(); }
1828
1829                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1830                 {
1831                         if(random_target)
1832                                 RandomSelection_AddEnt(tmp_entity, 1, 1);
1833                         else
1834                         {
1835                                 if(SAME_TEAM(tmp_entity, player))
1836                                 if(vlen2(tmp_entity.origin - spawn_loc) <= vlen2(closest_target.origin - spawn_loc) || closest_target == NULL)
1837                                         closest_target = tmp_entity;
1838                         }
1839                 }
1840
1841                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1842
1843                 if(closest_target)
1844                 {
1845                         float i;
1846                         vector loc;
1847                         float iteration_scale = 1;
1848                         for(i = 0; i < 10; ++i)
1849                         {
1850                                 iteration_scale -= i / 10;
1851                                 loc = closest_target.origin + '0 0 128' * iteration_scale;
1852                                 loc += ('0 1 0' * random()) * 256 * iteration_scale;
1853                                 tracebox(loc, STAT(PL_MIN, player), STAT(PL_MAX, player), loc, MOVE_NORMAL, player);
1854                                 if(trace_fraction == 1.0 && !trace_startsolid)
1855                                 {
1856                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the NULL
1857                                         if(trace_fraction == 1.0 && !trace_startsolid)
1858                                         {
1859                                                 setorigin(player, loc);
1860                                                 player.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1861                                                 return false;
1862                                         }
1863                                 }
1864                         }
1865                 }
1866         }
1867
1868         return false;
1869 }
1870
1871 MUTATOR_HOOKFUNCTION(ons, PlayerDies)
1872 {
1873         entity frag_target = M_ARGV(2, entity);
1874
1875         frag_target.ons_deathloc = frag_target.origin;
1876         entity l;
1877         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1878         {
1879                 l.sprite.SendFlags |= 16;
1880         }
1881         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1882         {
1883                 l.sprite.SendFlags |= 16;
1884         }
1885
1886         if ( autocvar_g_onslaught_spawn_choose )
1887         if ( ons_Count_SelfControlPoints(frag_target) > 1 )
1888                 stuffcmd(frag_target, "qc_cmd_cl hud clickradar\n");
1889
1890         return false;
1891 }
1892
1893 MUTATOR_HOOKFUNCTION(ons, MonsterMove)
1894 {
1895         entity mon = M_ARGV(0, entity);
1896
1897         entity e = find(NULL, targetname, mon.target);
1898         if (e != NULL)
1899                 mon.team = e.team;
1900 }
1901
1902 void ons_MonsterSpawn_Delayed(entity this)
1903 {
1904         entity own = this.owner;
1905
1906         if(!own) { delete(this); return; }
1907
1908         if(own.targetname)
1909         {
1910                 entity e = find(NULL, target, own.targetname);
1911                 if(e != NULL)
1912                 {
1913                         own.team = e.team;
1914
1915                         own.use(own, e, NULL);
1916                 }
1917         }
1918
1919         delete(this);
1920 }
1921
1922 MUTATOR_HOOKFUNCTION(ons, MonsterSpawn)
1923 {
1924         entity mon = M_ARGV(0, entity);
1925
1926         entity e = spawn();
1927         e.owner = mon;
1928         InitializeEntity(e, ons_MonsterSpawn_Delayed, INITPRIO_FINDTARGET);
1929 }
1930
1931 void ons_TurretSpawn_Delayed(entity this)
1932 {
1933         entity own = this.owner;
1934
1935         if(!own) { delete(this); return; }
1936
1937         if(own.targetname)
1938         {
1939                 entity e = find(NULL, target, own.targetname);
1940                 if(e != NULL)
1941                 {
1942                         own.team = e.team;
1943                         own.active = ACTIVE_NOT;
1944
1945                         own.use(own, e, NULL);
1946                 }
1947         }
1948
1949         delete(this);
1950 }
1951
1952 MUTATOR_HOOKFUNCTION(ons, TurretSpawn)
1953 {
1954         entity turret = M_ARGV(0, entity);
1955
1956         entity e = spawn();
1957         e.owner = turret;
1958         InitializeEntity(e, ons_TurretSpawn_Delayed, INITPRIO_FINDTARGET);
1959
1960         return false;
1961 }
1962
1963 MUTATOR_HOOKFUNCTION(ons, HavocBot_ChooseRole)
1964 {
1965         entity bot = M_ARGV(0, entity);
1966
1967         havocbot_ons_reset_role(bot);
1968         return true;
1969 }
1970
1971 MUTATOR_HOOKFUNCTION(ons, TeamBalance_CheckAllowedTeams)
1972 {
1973         // onslaught is special
1974         for(entity tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1975         {
1976                 if (Team_IsValidTeam(tmp_entity.team))
1977                 {
1978                         M_ARGV(0, float) |= Team_TeamToBit(tmp_entity.team);
1979                 }
1980         }
1981
1982         return true;
1983 }
1984
1985 MUTATOR_HOOKFUNCTION(ons, SpectateCopy)
1986 {
1987         entity spectatee = M_ARGV(0, entity);
1988         entity client = M_ARGV(1, entity);
1989
1990         STAT(ROUNDLOST, client) = STAT(ROUNDLOST, spectatee); // make spectators see it too
1991 }
1992
1993 MUTATOR_HOOKFUNCTION(ons, SV_ParseClientCommand)
1994 {
1995         if(MUTATOR_RETURNVALUE) // command was already handled?
1996                 return false;
1997
1998         entity player = M_ARGV(0, entity);
1999         string cmd_name = M_ARGV(1, string);
2000         int cmd_argc = M_ARGV(2, int);
2001
2002         if ( cmd_name == "ons_spawn" )
2003         {
2004                 vector pos = player.origin;
2005                 if(cmd_argc > 1)
2006                         pos_x = stof(argv(1));
2007                 if(cmd_argc > 2)
2008                         pos_y = stof(argv(2));
2009                 if(cmd_argc > 3)
2010                         pos_z = stof(argv(3));
2011
2012                 if ( IS_PLAYER(player) )
2013                 {
2014                         if ( !STAT(FROZEN, player) )
2015                         {
2016                                 entity source_point = ons_Nearest_ControlPoint(player, player.origin, autocvar_g_onslaught_teleport_radius);
2017
2018                                 if ( !source_point && GetResourceAmount(player, RESOURCE_HEALTH) > 0 )
2019                                 {
2020                                         sprint(player, "\nYou need to be next to a control point\n");
2021                                         return true;
2022                                 }
2023
2024
2025                                 entity closest_target = ons_Nearest_ControlPoint_2D(player, pos, autocvar_g_onslaught_click_radius);
2026
2027                                 if ( closest_target == NULL )
2028                                 {
2029                                         sprint(player, "\nNo control point found\n");
2030                                         return true;
2031                                 }
2032
2033                                 if ( GetResourceAmount(player, RESOURCE_HEALTH) <= 0 )
2034                                 {
2035                                         player.ons_spawn_by = closest_target;
2036                                         player.respawn_flags = player.respawn_flags | RESPAWN_FORCE;
2037                                 }
2038                                 else
2039                                 {
2040                                         if ( source_point == closest_target )
2041                                         {
2042                                                 sprint(player, "\nTeleporting to the same point\n");
2043                                                 return true;
2044                                         }
2045
2046                                         if ( !ons_Teleport(player,closest_target,autocvar_g_onslaught_teleport_radius,true) )
2047                                                 sprint(player, "\nUnable to teleport there\n");
2048                                 }
2049
2050                                 return true;
2051                         }
2052
2053                         sprint(player, "\nNo teleportation for you\n");
2054                 }
2055
2056                 return true;
2057         }
2058         return false;
2059 }
2060
2061 MUTATOR_HOOKFUNCTION(ons, PlayerUseKey)
2062 {
2063         if(MUTATOR_RETURNVALUE || game_stopped) return false;
2064
2065         entity player = M_ARGV(0, entity);
2066
2067         if((time > player.teleport_antispam) && (!IS_DEAD(player)) && !player.vehicle)
2068         {
2069                 entity source_point = ons_Nearest_ControlPoint(player, player.origin, autocvar_g_onslaught_teleport_radius);
2070                 if ( source_point )
2071                 {
2072                         stuffcmd(player, "qc_cmd_cl hud clickradar\n");
2073                         return true;
2074                 }
2075         }
2076 }
2077
2078 MUTATOR_HOOKFUNCTION(ons, PlayHitsound)
2079 {
2080         entity frag_victim = M_ARGV(0, entity);
2081
2082         return (frag_victim.classname == "onslaught_generator" && !frag_victim.isshielded)
2083                 || (frag_victim.classname == "onslaught_controlpoint_icon" && !frag_victim.owner.isshielded);
2084 }
2085
2086 MUTATOR_HOOKFUNCTION(ons, SendWaypoint)
2087 {
2088     entity wp = M_ARGV(0, entity);
2089     entity to = M_ARGV(1, entity);
2090     int sf = M_ARGV(2, int);
2091     int wp_flag = M_ARGV(3, int);
2092
2093         if(sf & 16)
2094         {
2095                 if(wp.owner.classname == "onslaught_controlpoint")
2096                 {
2097                         entity wp_owner = wp.owner;
2098                         entity e = WaypointSprite_getviewentity(to);
2099                         if(SAME_TEAM(e, wp_owner) && GetResourceAmount(wp_owner.goalentity, RESOURCE_HEALTH) >= wp_owner.goalentity.max_health) { wp_flag |= 2; }
2100                         if(!ons_ControlPoint_Attackable(wp_owner, e.team)) { wp_flag |= 2; }
2101                 }
2102                 if(wp.owner.classname == "onslaught_generator")
2103                 {
2104                         entity wp_owner = wp.owner;
2105                         if(wp_owner.isshielded && GetResourceAmount(wp_owner, RESOURCE_HEALTH) >= wp_owner.max_health) { wp_flag |= 2; }
2106                         if(GetResourceAmount(wp_owner, RESOURCE_HEALTH) <= 0) { wp_flag |= 2; }
2107                 }
2108         }
2109
2110         M_ARGV(3, int) = wp_flag;
2111 }
2112
2113 MUTATOR_HOOKFUNCTION(ons, TurretValidateTarget)
2114 {
2115         entity turret_target = M_ARGV(1, entity);
2116
2117         if(substring(turret_target.classname, 0, 10) == "onslaught_") // don't attack onslaught targets, that's the player's job!
2118         {
2119                 M_ARGV(3, float) = -3;
2120                 return true;
2121         }
2122
2123         return false;
2124 }
2125
2126 MUTATOR_HOOKFUNCTION(ons, TurretThink)
2127 {
2128     entity turret = M_ARGV(0, entity);
2129
2130         // ONS uses somewhat backwards linking.
2131         if(turret.target)
2132         {
2133                 entity e = find(NULL, targetname, turret.target);
2134                 if (e != NULL)
2135                         turret.team = e.team;
2136         }
2137
2138         if(turret.team != turret.tur_head.team)
2139                 turret_respawn(turret);
2140 }
2141
2142
2143 // ==========
2144 // Spawnfuncs
2145 // ==========
2146
2147 /*QUAKED spawnfunc_onslaught_link (0 .5 .8) (-16 -16 -16) (16 16 16)
2148   Link between control points.
2149
2150   This entity targets two different spawnfunc_onslaught_controlpoint or spawnfunc_onslaught_generator entities, and suppresses shielding on both if they are owned by different teams.
2151
2152 keys:
2153 "target" - first control point.
2154 "target2" - second control point.
2155  */
2156 spawnfunc(onslaught_link)
2157 {
2158         if(!g_onslaught) { delete(this); return; }
2159
2160         if (this.target == "" || this.target2 == "")
2161                 objerror(this, "target and target2 must be set\n");
2162
2163         this.ons_worldlinknext = ons_worldlinklist; // link into ons_worldlinklist
2164         ons_worldlinklist = this;
2165
2166         InitializeEntity(this, ons_DelayedLinkSetup, INITPRIO_FINDTARGET);
2167         Net_LinkEntity(this, false, 0, ons_Link_Send);
2168 }
2169
2170 /*QUAKED spawnfunc_onslaught_controlpoint (0 .5 .8) (-32 -32 0) (32 32 128)
2171   Control point. Be sure to give this enough clearance so that the shootable part has room to exist
2172
2173   This should link to an spawnfunc_onslaught_controlpoint entity or spawnfunc_onslaught_generator entity.
2174
2175 keys:
2176 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2177 "target" - target any entities that are tied to this control point, such as vehicles and buildable structure entities.
2178 "message" - name of this control point (should reflect the location in the map, such as "center bridge", "north tower", etc)
2179  */
2180
2181 spawnfunc(onslaught_controlpoint)
2182 {
2183         if(!g_onslaught) { delete(this); return; }
2184
2185         ons_ControlPoint_Setup(this);
2186 }
2187
2188 /*QUAKED spawnfunc_onslaught_generator (0 .5 .8) (-32 -32 -24) (32 32 64)
2189   Base generator.
2190
2191   spawnfunc_onslaught_link entities can target this.
2192
2193 keys:
2194 "team" - team that owns this generator (5 = red, 14 = blue, etc), MUST BE SET.
2195 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2196  */
2197 spawnfunc(onslaught_generator)
2198 {
2199         if(!g_onslaught) { delete(this); return; }
2200         if(!this.team) { objerror(this, "team must be set"); }
2201
2202         ons_GeneratorSetup(this);
2203 }
2204
2205 // scoreboard setup
2206 void ons_ScoreRules()
2207 {
2208         entity balance = TeamBalance_CheckAllowedTeams(NULL);
2209         int teams = TeamBalance_GetAllowedTeams(balance);
2210         TeamBalance_Destroy(balance);
2211         GameRules_scoring(teams, SFL_SORT_PRIO_PRIMARY, 0, {
2212             field_team(ST_ONS_CAPS, "destroyed", SFL_SORT_PRIO_PRIMARY);
2213             field(SP_ONS_CAPS, "caps", SFL_SORT_PRIO_SECONDARY);
2214             field(SP_ONS_TAKES, "takes", 0);
2215         });
2216 }
2217
2218 void ons_DelayedInit(entity this) // Do this check with a delay so we can wait for teams to be set up
2219 {
2220         ons_ScoreRules();
2221
2222         round_handler_Spawn(Onslaught_CheckPlayers, Onslaught_CheckWinner, Onslaught_RoundStart);
2223         round_handler_Init(5, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
2224 }
2225
2226 void ons_Initialize()
2227 {
2228         g_onslaught = true;
2229         ons_captureshield_force = autocvar_g_onslaught_shield_force;
2230
2231         cam = new(objective_camera);
2232
2233         InitializeEntity(NULL, ons_DelayedInit, INITPRIO_GAMETYPE);
2234 }