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