]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/mutators/gamemode_ctf.qc
Debugging some stuff, etc
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / mutators / gamemode_ctf.qc
1 // ================================================================
2 //  Official capture the flag game mode coding, reworked by Samual
3 //  Last updated: March 27th, 2012
4 // ================================================================
5
6 float ctf_ReadScore(string parameter) // make this obsolete
7 {
8         //if(g_ctf_win_mode != 2)
9                 return cvar(strcat("g_ctf_personal", parameter));
10         //else
11         //      return cvar(strcat("g_ctf_flag", parameter));
12 }
13
14 void ctf_FakeTimeLimit(entity e, float t)
15 {
16         msg_entity = e;
17         WriteByte(MSG_ONE, 3); // svc_updatestat
18         WriteByte(MSG_ONE, 236); // STAT_TIMELIMIT
19         if(t < 0)
20                 WriteCoord(MSG_ONE, autocvar_timelimit);
21         else
22                 WriteCoord(MSG_ONE, (t + 1) / 60);
23 }
24
25 void ctf_EventLog(string mode, float flagteam, entity actor) // use an alias for easy changing and quick editing later
26 {
27         if(autocvar_sv_eventlog)
28                 GameLogEcho(strcat(":ctf:", mode, ":", ftos(flagteam), ((actor != world) ? (strcat(":", ftos(actor.playerid))) : "")));
29 }
30
31
32 // =======================
33 // CaptureShield Functions 
34 // =======================
35
36 float ctf_CaptureShield_CheckStatus(entity p) 
37 {
38         float s, se;
39         entity e;
40         float players_worseeq, players_total;
41
42         if(ctf_captureshield_max_ratio <= 0)
43                 return FALSE;
44
45         s = PlayerScore_Add(p, SP_SCORE, 0);
46         if(s >= -ctf_captureshield_min_negscore)
47                 return FALSE;
48
49         players_total = players_worseeq = 0;
50         FOR_EACH_PLAYER(e)
51         {
52                 if(e.team != p.team)
53                         continue;
54                 se = PlayerScore_Add(e, SP_SCORE, 0);
55                 if(se <= s)
56                         ++players_worseeq;
57                 ++players_total;
58         }
59
60         // player is in the worse half, if >= half the players are better than him, or consequently, if < half of the players are worse
61         // use this rule here
62         
63         if(players_worseeq >= players_total * ctf_captureshield_max_ratio)
64                 return FALSE;
65
66         return TRUE;
67 }
68
69 void ctf_CaptureShield_Update(entity player, float wanted_status)
70 {
71         float updated_status = ctf_CaptureShield_CheckStatus(player);
72         if((wanted_status == player.ctf_captureshielded) && (updated_status != wanted_status)) // 0: shield only, 1: unshield only
73         {
74                 if(updated_status) // TODO csqc notifier for this // Samual: How?
75                         Send_CSQC_Centerprint_Generic(player, CPID_CTF_CAPTURESHIELD, "^3You are now ^4shielded^3 from the flag\n^3for ^1too many unsuccessful attempts^3 to capture.\n\n^3Make some defensive scores before trying again.", 5, 0);
76                 else
77                         Send_CSQC_Centerprint_Generic(player, CPID_CTF_CAPTURESHIELD, "^3You are now free.\n\n^3Feel free to ^1try to capture^3 the flag again\n^3if you think you will succeed.", 5, 0);
78                         
79                 player.ctf_captureshielded = updated_status;
80         }
81 }
82
83 float ctf_CaptureShield_Customize()
84 {
85         if not(other.ctf_captureshielded)
86                 return FALSE;
87         if(self.team == other.team)
88                 return FALSE;
89         return TRUE;
90 }
91
92 void ctf_CaptureShield_Touch()
93 {
94         if not(other.ctf_captureshielded)
95                 return;
96         if(self.team == other.team)
97                 return;
98         vector mymid;
99         vector othermid;
100         mymid = (self.absmin + self.absmax) * 0.5;
101         othermid = (other.absmin + other.absmax) * 0.5;
102         Damage(other, self, self, 0, DEATH_HURTTRIGGER, mymid, normalize(othermid - mymid) * ctf_captureshield_force);
103         Send_CSQC_Centerprint_Generic(other, CPID_CTF_CAPTURESHIELD, "^3You are ^4shielded^3 from the flag\n^3for ^1too many unsuccessful attempts^3 to capture.\n\n^3Get some defensive scores before trying again.", 5, 0);
104 }
105
106 void ctf_CaptureShield_Spawn(entity flag)
107 {
108         entity e;
109         e = spawn();
110         e.enemy = self;
111         e.team = self.team;
112         e.touch = ctf_CaptureShield_Touch;
113         e.customizeentityforclient = ctf_CaptureShield_Customize;
114         e.classname = "ctf_captureshield";
115         e.effects = EF_ADDITIVE;
116         e.movetype = MOVETYPE_NOCLIP;
117         e.solid = SOLID_TRIGGER;
118         e.avelocity = '7 0 11';
119         setorigin(e, self.origin);
120         setmodel(e, "models/ctf/shield.md3");
121         e.scale = 0.5;
122         setsize(e, e.scale * e.mins, e.scale * e.maxs);
123 }
124
125
126 // ==============
127 // Event Handlers
128 // ==============
129
130 void ctf_Handle_Drop(entity player)
131 {
132         print("ctf_Handle_Drop() called.\n");
133         
134         entity flag = player.flagcarried;
135
136         if(!flag) { return; }
137         if(flag.speedrunning) { ctf_RespawnFlag(flag); return; }
138         
139         // reset the flag
140         setattachment(flag, world, "");
141         setorigin(flag, player.origin - '0 0 24' + '0 0 37');
142         flag.owner.flagcarried = world;
143         flag.owner = world;
144         flag.movetype = MOVETYPE_TOSS;
145         flag.solid = SOLID_TRIGGER;
146         flag.takedamage = DAMAGE_YES;
147         flag.velocity = ('0 0 200' + ('0 100 0' * crandom()) + ('100 0 0' * crandom()));
148         flag.pain_finished = time + autocvar_g_ctf_flag_returntime; // replace this later
149         
150         flag.ctf_droptime = time;
151         flag.ctf_dropperid = player.playerid;
152         flag.ctf_status = FLAG_DROPPED;
153
154         // messages and sounds
155         Send_KillNotification(player.netname, flag.netname, "", INFO_LOSTFLAG, MSG_INFO);
156         sound(flag, CH_TRIGGER, flag.noise4, VOL_BASE, ATTN_NONE);
157         ctf_EventLog("dropped", player.team, player);
158         
159         // scoring
160         PlayerTeamScore_AddScore(player, -ctf_ReadScore("penalty_drop"));       
161         PlayerScore_Add(player, SP_CTF_DROPS, 1);
162
163         // waypoints
164         WaypointSprite_Spawn("flagdropped", 0, 0, flag, '0 0 64', world, player.team, flag, wps_flagdropped, FALSE, RADARICON_FLAG, '0 1 1'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
165         WaypointSprite_Ping(player.wps_flagcarrier);
166         WaypointSprite_Kill(player.wps_flagcarrier);
167
168         // captureshield
169         ctf_CaptureShield_Update(player, 0); // shield only
170
171         // check if the flag will fall off the map
172         trace_startsolid = FALSE;
173         tracebox(flag.origin, flag.mins, flag.maxs, flag.origin, TRUE, flag);
174         if(trace_startsolid)
175                 dprint("FLAG FALLTHROUGH will happen SOON\n");
176 }
177
178 void ctf_Handle_Capture(entity flag, entity player)
179 {
180         print("ctf_Handle_Capture() called.\n");
181         
182         // declarations
183         float cap_time, cap_record, success;
184         string cap_message, refername;
185
186         // records
187         if((autocvar_g_ctf_captimerecord_always) || (player_count - currentbots)) {
188                 cap_record = ctf_captimerecord;
189                 cap_time = (time - player.flagcarried.ctf_pickuptime);
190
191                 refername = db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"));
192                 refername = ((refername == player.netname) ? "their" : strcat(refername, "^7's"));
193
194                 if(!ctf_captimerecord) 
195                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds"); success = TRUE; }
196                 else if(cap_time < cap_record) 
197                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, breaking ", refername, " previous record of ", ftos_decimals(cap_record, 2), " seconds"); success = TRUE; }
198                 else
199                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, failing to break ", refername, " record of ", ftos_decimals(cap_record, 2), " seconds"); success = FALSE; }
200
201                 if(success) {
202                         ctf_captimerecord = cap_time;
203                         db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time"), ftos(cap_time));
204                         db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"), player.netname);
205                         write_recordmarker(player, (time - cap_time), cap_time); } }
206         
207         // messages and sounds
208         Send_KillNotification(player.netname, player.flagcarried.netname, cap_message, INFO_CAPTUREFLAG, MSG_INFO);
209         sound(player, CH_TRIGGER, flag.noise2, VOL_BASE, ATTN_NONE); // "ctf/*_capture.wav"
210         ctf_EventLog("capture", player.flagcarried.team, player);
211         
212         // scoring
213         PlayerTeamScore_AddScore(player, ctf_ReadScore("score_capture"));
214         PlayerTeamScore_Add(player, SP_CTF_CAPS, ST_CTF_CAPS, 1);
215
216         // effects
217         if (autocvar_g_ctf_flag_capture_effects) 
218         {
219                 pointparticles(particleeffectnum((player.team == COLOR_TEAM1) ? "red_ground_quake" : "blue_ground_quake"), flag.origin, '0 0 0', 1);
220                 //shockwave_spawn("models/ctf/shockwavetransring.md3", flag.origin - '0 0 15', -0.8, 0, 1);
221         }
222
223         // waypointsprites
224         WaypointSprite_Kill(player.wps_flagcarrier);
225
226         // reset the flag
227         if(flag.speedrunning) { ctf_FakeTimeLimit(player, -1); }
228         
229         ctf_RespawnFlag(player.flagcarried);
230 }
231
232 void ctf_Handle_Return(entity flag, entity player)
233 {
234         print("ctf_Handle_Return() called.\n");
235         
236         // messages and sounds
237         Send_KillNotification (player.netname, flag.netname, "", INFO_RETURNFLAG, MSG_INFO);
238         sound(player, CH_TRIGGER, flag.noise1, VOL_BASE, ATTN_NONE);
239         ctf_EventLog("return", flag.team, player);
240
241         // scoring
242         PlayerTeamScore_AddScore(player, ctf_ReadScore(strcat("score_return", ((player.playerid == flag.playerid) ? "_by_killer" : "")))); // reward for return
243         PlayerScore_Add(player, SP_CTF_RETURNS, 1); // add to count of returns
244
245         TeamScore_AddToTeam(((flag.team == COLOR_TEAM1) ? COLOR_TEAM2 : COLOR_TEAM1), ST_SCORE, -ctf_ReadScore("penalty_returned")); // punish the team who was last carrying it
246         FOR_EACH_PLAYER(player) if(player.playerid == flag.ctf_dropperid) // punish the player who dropped the flag
247         {
248                 PlayerScore_Add(player, SP_SCORE, -ctf_ReadScore("penalty_returned"));
249                 ctf_CaptureShield_Update(player, 0); // shield only
250         }
251
252         // waypointsprites 
253         WaypointSprite_Kill(flag.wps_flagdropped);
254         
255         // reset the flag
256         ctf_RespawnFlag(flag);
257 }
258
259 void ctf_Handle_Pickup_Base(entity flag, entity player)
260 {
261         print("ctf_Handle_Pickup_Base() called.\n");
262         
263         entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
264         string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
265
266         // attach the flag to the player
267         flag.owner = player;
268         player.flagcarried = flag;
269         setattachment(flag, player, "");
270         setorigin(flag, FLAG_CARRY_POS);
271         
272         // set up the flag
273         flag.movetype = MOVETYPE_NONE;
274         flag.takedamage = DAMAGE_NO;
275         flag.solid = SOLID_NOT;
276         flag.angles = '0 0 0';
277         flag.ctf_pickuptime = time; // used for timing runs
278         flag.ctf_pickupid = player.playerid;
279         flag.ctf_status = FLAG_CARRY;
280         
281         // messages and sounds
282         Send_KillNotification (player.netname, flag.netname, "", INFO_GOTFLAG, MSG_INFO);
283         sound(player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
284         ctf_EventLog("steal", flag.team, player);
285         verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : ""); // replace TRUE with an autocvar for it.
286         FOR_EACH_PLAYER(tmp_player)
287                 if(tmp_player.team == flag.team)
288                         centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
289                 else if((tmp_player.team == player.team) && (tmp_player != player))
290                         centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
291         
292         // scoring
293         PlayerTeamScore_AddScore(player, ctf_ReadScore("score_pickup_base"));
294         PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
295         
296         // speedrunning
297         flag.speedrunning = player.speedrunning; // if speedrunning, flag will flag-return and teleport the owner back after the record
298         if((player.speedrunning) && (ctf_captimerecord))
299                 ctf_FakeTimeLimit(player, time + ctf_captimerecord);
300                 
301         // effects
302         if (autocvar_g_ctf_flag_pickup_effects)
303         {
304                 pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1);
305         }
306         
307         // waypoints 
308         WaypointSprite_Spawn("flagcarrier", 0, 0, player, '0 0 64', world, player.team, player, wps_flagcarrier, FALSE, RADARICON_FLAG, '1 1 0'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
309         WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
310         WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
311         WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
312         WaypointSprite_Ping(player.wps_flagcarrier);
313 }
314  
315 void ctf_Handle_Pickup_Dropped(entity flag, entity player) // make sure this works
316 {
317         print("ctf_Handle_Pickup_Dropped() called.\n");
318         
319         // declarations
320         float returnscore = bound(0, (flag.pain_finished - time) / autocvar_g_ctf_flag_returntime, 1); // can this be division by zero?
321         entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
322         string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
323
324         // attach the flag to the player
325         flag.owner = player;
326         player.flagcarried = flag;
327         setattachment(flag, player, "");
328         setorigin(flag, FLAG_CARRY_POS);
329         
330         // set up the flag
331         flag.movetype = MOVETYPE_NONE;
332         flag.takedamage = DAMAGE_NO;
333         flag.solid = SOLID_NOT;
334         flag.angles = '0 0 0';
335         //flag.ctf_pickuptime = time; // don't update pickuptime since this isn't a real steal. 
336         flag.ctf_pickupid = player.playerid;
337         flag.ctf_status = FLAG_CARRY;
338
339         // messages and sounds
340         Send_KillNotification (player.netname, flag.netname, "", INFO_PICKUPFLAG, MSG_INFO);
341         sound (player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
342         ctf_EventLog("pickup", flag.team, player);
343         verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : "");
344         FOR_EACH_PLAYER(tmp_player)
345                 if(tmp_player.team == flag.team)
346                         centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
347                 else if((tmp_player.team == player.team) && (tmp_player != player))
348                         centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
349
350         // scoring
351         returnscore = floor((ctf_ReadScore("score_pickup_dropped_late") * (1-returnscore) + ctf_ReadScore("score_pickup_dropped_early") * returnscore) + 0.5);
352         print("score is ", ftos(returnscore), "\n");
353         PlayerTeamScore_AddScore(player, returnscore);
354         PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
355
356         // effects
357         if (autocvar_g_ctf_flag_pickup_effects) // field pickup effect
358         {
359                 pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1); 
360         }
361
362         // waypoints
363         WaypointSprite_Kill(flag.wps_flagdropped);
364         WaypointSprite_Spawn("flagcarrier", 0, 0, player, '0 0 64', world, player.team, player, wps_flagcarrier, FALSE, RADARICON_FLAG, '1 1 0'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
365         WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
366         WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
367         WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
368         WaypointSprite_Ping(player.wps_flagcarrier);
369 }
370
371
372 // ===================
373 // Main Flag Functions
374 // ===================
375
376 void ctf_FlagThink()
377 {
378         // declarations
379         entity tmp_entity;
380
381         self.nextthink = time + 0.1; // only 10 fps, more is unnecessary.
382
383         // captureshield
384         if(self == ctf_worldflaglist) // only for the first flag
385                 FOR_EACH_CLIENT(tmp_entity)
386                         ctf_CaptureShield_Update(tmp_entity, 1); // release shield only
387
388         // sanity checks
389         if(self.mins != FLAG_MIN || self.maxs != FLAG_MAX) { // reset the flag boundaries in case it got squished
390                 dprint("wtf the flag got squished?\n");
391                 tracebox(self.origin, FLAG_MIN, FLAG_MAX, self.origin, MOVE_NOMONSTERS, self);
392                 if(!trace_startsolid) // can we resize it without getting stuck?
393                         setsize(self, FLAG_MIN, FLAG_MAX); }
394
395         if(self.owner.classname != "player" || (self.owner.deadflag) || (self.owner.flagcarried != self)) {
396                 dprint("CANNOT HAPPEN - player dead and STILL had a flag!\n");
397                 ctf_Handle_Drop(self.owner);
398                 return; }
399
400         // main think method
401         switch(self.ctf_status) 
402         {       
403                 case FLAG_BASE: // nothing to do here
404                         return;
405                 
406                 case FLAG_DROPPED:
407                         // flag fallthrough? FIXME remove this if bug is really fixed now
408                         if(self.origin_z < -131072)
409                         {
410                                 dprint("FLAG FALLTHROUGH just happened\n");
411                                 self.pain_finished = 0;
412                         }
413                         setattachment(self, world, "");
414                         if(time > self.pain_finished)
415                         {
416                                 bprint("The ", self.netname, " has returned to base\n");
417                                 sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
418                                 ctf_EventLog("returned", self.team, world);
419                                 ctf_RespawnFlag(self);
420                         }
421                         return;
422                                 
423                 case FLAG_CARRY:
424                         if((self.owner) && (self.speedrunning) && (ctf_captimerecord) && (time >= self.ctf_pickuptime + ctf_captimerecord)) 
425                         {
426                                 bprint("The ", self.netname, " became impatient after ", ftos_decimals(ctf_captimerecord, 2), " seconds and returned itself\n");
427                                 sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
428
429                                 self.owner.impulse = 141; // returning!
430
431                                 tmp_entity = self;
432                                 self = self.owner;
433                                 ctf_RespawnFlag(tmp_entity);
434                                 ImpulseCommands();
435                                 self = tmp_entity;
436                         }
437                         return;
438
439                 default: // this should never happen
440                         dprint("Think: Flag exists with no status?\n");
441                         return;
442         }
443 }
444
445 void ctf_FlagTouch()
446 {
447         if(gameover) { return; }
448         if(!self) { return; }
449         if((trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))// || (trace_dphitcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA)))
450         { // The flag fell off the map or into lava/slime, respawn it since players can't get to it
451                 ctf_RespawnFlag(self);
452                 return;
453         }
454         if(other.deadflag != DEAD_NO) { return; }
455         if(other.classname != "player") 
456         {  // The flag just touched an object, most likely the world
457                 pointparticles(particleeffectnum("kaball_sparks"), self.origin, '0 0 0', 1);
458                 sound(self, CH_TRIGGER, "keepaway/touch.wav", VOL_BASE, ATTN_NORM);
459                 return; 
460         }
461         else if(self.wait > time) { return; }
462
463         switch(self.ctf_status) 
464         {       
465                 case FLAG_BASE:
466                         if((other.team == self.team) && (other.flagcarried) && (other.flagcarried.team != self.team))
467                                 ctf_Handle_Capture(self, other); // other just captured the enemies flag to his base
468                         else if((other.team != self.team) && (!other.flagcarried) && (!other.ctf_captureshielded))
469                                 ctf_Handle_Pickup_Base(self, other); // other just stole the enemies flag
470                         break;
471                 
472                 case FLAG_DROPPED:
473                         if(other.team == self.team)
474                                 ctf_Handle_Return(self, other); // other just returned his own flag
475                         else if((!other.flagcarried) && ((other.playerid != self.ctf_dropperid) || (time > self.ctf_droptime + autocvar_g_balance_ctf_delay_collect)))
476                                 ctf_Handle_Pickup_Dropped(self, other); // other just picked up a dropped enemy flag
477                         break;
478                                 
479                 case FLAG_CARRY:
480                         dprint("Someone touched a flag even though it was being carried?\n");
481                         break;
482
483                 default: // this should never happen
484                         dprint("Touch: Flag exists with no status?\n");
485                         break;
486         }
487 }
488
489 void ctf_RespawnFlag(entity flag)
490 {
491         print("ctf_RespawnFlag() called.\n");
492         
493         // reset the player (if there is one)
494         if((flag.owner) && (flag.owner.flagcarried == flag))
495         {
496                 WaypointSprite_Kill(flag.wps_flagcarrier);
497                 flag.owner.flagcarried = world;
498
499                 if(flag.speedrunning)
500                         ctf_FakeTimeLimit(flag.owner, -1);
501         }
502
503         // reset the flag
504         setattachment(flag, world, "");
505         setorigin(flag, flag.ctf_spawnorigin); // replace with flag.ctf_spawnorigin
506         flag.movetype = ((flag.noalign) ? MOVETYPE_NONE : MOVETYPE_TOSS);
507         flag.takedamage = DAMAGE_NO;
508         flag.solid = SOLID_TRIGGER;
509         flag.velocity = '0 0 0';
510         flag.angles = flag.mangle;
511         flag.ctf_status = FLAG_BASE;
512         flag.flags = FL_ITEM | FL_NOTARGET;
513         flag.owner = world;
514 }
515
516 void ctf_Reset()
517 {
518         if(self.owner)
519                 if(self.owner.classname == "player")
520                         ctf_Handle_Drop(self.owner);
521                         
522         ctf_RespawnFlag(self);
523         print("ctf reset\n");
524 }
525
526 void ctf_SetupFlag(float teamnumber, entity flag) // called when spawning a flag entity on the map as a spawnfunc 
527 {
528         // declarations
529         teamnumber = fabs(teamnumber - bound(0, g_ctf_reverse, 1)); // if we were originally 1, this will become 0. If we were originally 0, this will become 1. 
530         
531         // main setup
532         flag.ctf_worldflagnext = ctf_worldflaglist; // link flag into ctf_worldflaglist // todo: find out if this can be simplified
533         ctf_worldflaglist = flag;
534
535         setattachment(flag, world, ""); 
536
537         flag.netname = ((teamnumber) ? "^1RED^7 flag" : "^4BLUE^7 flag");
538         flag.team = ((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2); // COLOR_TEAM1: color 4 team (red) - COLOR_TEAM2: color 13 team (blue)
539         flag.items = ((teamnumber) ? IT_KEY2 : IT_KEY1); // IT_KEY2: gold key (redish enough) - IT_KEY1: silver key (bluish enough)
540         flag.classname = "item_flag_team";
541         flag.target = "###item###"; // wut?
542         flag.flags = FL_ITEM | FL_NOTARGET;
543         flag.solid = SOLID_TRIGGER;
544         flag.velocity = '0 0 0';
545         flag.ctf_status = FLAG_BASE;
546         flag.mangle = flag.angles;
547         flag.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
548         
549         // handle spawn origin and flag placement
550         flag.dropped_origin = (flag.origin + (FLAG_MAX * '0 0 1')); 
551         
552         if(flag.spawnflags & 1) // don't drop to floor, just stay at fixed location
553         {       
554                 flag.noalign = TRUE;
555                 // builtin_droptofloor();
556                 flag.movetype = MOVETYPE_NONE;
557                 print("^1|^3||||^1| This map was loaded with flags using MOVETYPE_NONE\n");
558         }
559         else // drop to floor, automatically find a platform and set that as spawn origin
560         { 
561                 flag.noalign = FALSE;
562                 builtin_droptofloor();
563                 flag.movetype = MOVETYPE_TOSS; 
564                 print("^1|^3||||^1| This map was loaded with flags using MOVETYPE_TOSS\n");
565         }       
566         
567         flag.ctf_spawnorigin = flag.dropped_origin; // set spawn origin to the "dropped" origin.
568         
569         flag.reset = ctf_Reset;
570         flag.touch = ctf_FlagTouch;
571
572         // appearence
573         if(!flag.model) { flag.model = ((teamnumber) ? autocvar_g_ctf_flag_red_model : autocvar_g_ctf_flag_blue_model); }
574         setmodel (flag, flag.model); // precision set below
575         setsize(flag, FLAG_MIN, FLAG_MAX);
576         setorigin(flag, flag.ctf_spawnorigin);
577         if(!flag.scale) { flag.scale = 0.6; }
578         
579         flag.skin = ((teamnumber) ? autocvar_g_ctf_flag_red_skin : autocvar_g_ctf_flag_blue_skin);
580         
581         if(autocvar_g_ctf_flag_glowtrails)
582         {
583                 flag.glow_color = ((teamnumber) ? 251 : 210); // 251: red - 210: blue
584                 flag.glow_size = 25;
585                 flag.glow_trail = 1;
586         }
587         
588         flag.effects |= EF_LOWPRECISION;
589         if(autocvar_g_ctf_fullbrightflags) { flag.effects |= EF_FULLBRIGHT; }
590         if(autocvar_g_ctf_dynamiclights)   { flag.effects |= ((teamnumber) ? EF_RED : EF_BLUE); }
591         
592         // sound 
593         if(!flag.noise)  { flag.noise  = ((teamnumber) ? "ctf/red_taken.wav" : "ctf/blue_taken.wav"); }
594         if(!flag.noise1) { flag.noise1 = ((teamnumber) ? "ctf/red_returned.wav" : "ctf/blue_returned.wav"); }
595         if(!flag.noise2) { flag.noise2 = ((teamnumber) ? "ctf/red_capture.wav" : "ctf/blue_capture.wav"); } // blue team scores by capturing the red flag
596         if(!flag.noise3) { flag.noise3 = "ctf/flag_respawn.wav"; } // if there is ever a team-based sound for this, update the code to match.
597         if(!flag.noise4) { flag.noise4 = ((teamnumber) ? "ctf/red_dropped.wav" : "ctf/blue_dropped.wav"); }
598         
599         // precache
600         precache_sound(flag.noise);
601         precache_sound(flag.noise1);
602         precache_sound(flag.noise2);
603         precache_sound(flag.noise3);
604         precache_sound(flag.noise4);
605         precache_model(flag.model);
606         precache_model("models/ctf/shield.md3");
607         precache_model("models/ctf/shockwavetransring.md3");
608
609         // bot waypoints
610         waypoint_spawnforitem_force(flag, flag.origin);
611         flag.nearestwaypointtimeout = 0; // activate waypointing again
612         flag.bot_basewaypoint = flag.nearestwaypoint;
613
614         // waypointsprites
615         WaypointSprite_SpawnFixed(((teamnumber) ? "redbase" : "bluebase"), flag.origin + '0 0 64', flag, wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
616         WaypointSprite_UpdateTeamRadar(flag.wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
617
618         // captureshield setup
619         ctf_CaptureShield_Spawn(flag);
620 }
621
622
623 // ==============
624 // Hook Functions
625 // ==============
626
627 // g_ctf_ignore_frags
628
629 MUTATOR_HOOKFUNCTION(ctf_RemovePlayer)
630 {
631         if(self.flagcarried) { ctf_Handle_Drop(self); }
632         return 0;
633 }
634
635 MUTATOR_HOOKFUNCTION(ctf_PlayerPreThink)
636 {
637         entity flag;
638         
639         // initially clear items so they can be set as necessary later.
640         self.items &~= (IT_RED_FLAG_CARRYING | IT_RED_FLAG_TAKEN | IT_RED_FLAG_LOST 
641                 | IT_BLUE_FLAG_CARRYING | IT_BLUE_FLAG_TAKEN | IT_BLUE_FLAG_LOST | IT_CTF_SHIELDED);
642
643         // item for stopping players from capturing the flag too often
644         if(self.ctf_captureshielded)
645                 self.items |= IT_CTF_SHIELDED;
646
647         // scan through all the flags and notify the client about them 
648         for (flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext)
649         {
650                 if(flag.ctf_status == FLAG_CARRY)
651                         if(flag.owner == self)
652                                 self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_CARRYING : IT_BLUE_FLAG_CARRYING); // carrying: self is currently carrying the flag
653                         else 
654                                 self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_TAKEN : IT_BLUE_FLAG_TAKEN); // taken: someone on self's team is carrying the flag
655                 else if(flag.ctf_status == FLAG_DROPPED) 
656                         self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_LOST : IT_BLUE_FLAG_LOST); // lost: the flag is dropped somewhere on the map
657         }
658         
659         return 0;
660 }
661
662 MUTATOR_HOOKFUNCTION(ctf_PlayerDamage) // for changing damage and force values that are applied to players in g_damage.qc
663 {       /*
664         if(frag_attacker.flagcarried) // if the attacker is a flagcarrier
665         {
666                 if(frag_target == frag_attacker) // damage done to yourself
667                 {
668                         frag_damage *= autocvar_g_ctf_flagcarrier_selfdamagefactor;
669                         frag_force *= autocvar_g_ctf_flagcarrier_selfforcefactor;
670                 }
671                 else // damage done to noncarriers
672                 {
673                         frag_damage *= autocvar_g_ctf_flagcarrier_damagefactor;
674                         frag_force *= autocvar_g_ctf_flagcarrier_forcefactor;
675                 }
676         }*/
677         return 0;
678 }
679
680 MUTATOR_HOOKFUNCTION(ctf_GiveFragsForKill)
681 {
682         frag_score = 0; // no frags counted in ctf
683         return (g_ctf_ignore_frags); // you deceptive little bugger ;3 This needs to be true in order for this function to even count. 
684 }
685
686 MUTATOR_HOOKFUNCTION(ctf_PlayerUseKey)
687 {
688         if(autocvar_g_ctf_allow_drop)
689                 ctf_Handle_Drop(self);
690                 
691         return 0;
692 }
693
694 // ==========
695 // Spawnfuncs
696 // ==========
697
698 /*QUAKED spawnfunc_info_player_team1 (1 0 0) (-16 -16 -24) (16 16 24)
699 CTF Starting point for a player in team one (Red).
700 Keys: "angle" viewing angle when spawning. */
701 void spawnfunc_info_player_team1()
702 {
703         if(g_assault) { remove(self); return; }
704         
705         self.team = COLOR_TEAM1; // red
706         spawnfunc_info_player_deathmatch();
707 }
708
709
710 /*QUAKED spawnfunc_info_player_team2 (1 0 0) (-16 -16 -24) (16 16 24)
711 CTF Starting point for a player in team two (Blue).
712 Keys: "angle" viewing angle when spawning. */
713 void spawnfunc_info_player_team2()
714 {
715         if(g_assault) { remove(self); return; }
716         
717         self.team = COLOR_TEAM2; // blue
718         spawnfunc_info_player_deathmatch();
719 }
720
721 /*QUAKED spawnfunc_info_player_team3 (1 0 0) (-16 -16 -24) (16 16 24)
722 CTF Starting point for a player in team three (Yellow).
723 Keys: "angle" viewing angle when spawning. */
724 void spawnfunc_info_player_team3()
725 {
726         if(g_assault) { remove(self); return; }
727         
728         self.team = COLOR_TEAM3; // yellow
729         spawnfunc_info_player_deathmatch();
730 }
731
732
733 /*QUAKED spawnfunc_info_player_team4 (1 0 0) (-16 -16 -24) (16 16 24)
734 CTF Starting point for a player in team four (Purple).
735 Keys: "angle" viewing angle when spawning. */
736 void spawnfunc_info_player_team4()
737 {
738         if(g_assault) { remove(self); return; }
739         
740         self.team = COLOR_TEAM4; // purple
741         spawnfunc_info_player_deathmatch();
742 }
743
744 /*QUAKED spawnfunc_item_flag_team1 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
745 CTF flag for team one (Red). Multiple flags are allowed.
746 Keys: 
747 "angle" Angle the flag will point (minus 90 degrees)... 
748 "model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
749 "noise" sound played when flag is picked up (default ctf/take.wav)...
750 "noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
751 "noise2" sound played when flag is captured (default ctf/redcapture.wav)...
752 "noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
753 void spawnfunc_item_flag_team1()
754 {
755         if(!g_ctf) { remove(self); return; }
756
757         ctf_SetupFlag(1, self); // 1 = red
758 }
759
760 /*QUAKED spawnfunc_item_flag_team2 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
761 CTF flag for team two (Blue). Multiple flags are allowed.
762 Keys: 
763 "angle" Angle the flag will point (minus 90 degrees)... 
764 "model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
765 "noise" sound played when flag is picked up (default ctf/take.wav)...
766 "noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
767 "noise2" sound played when flag is captured (default ctf/redcapture.wav)...
768 "noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
769 void spawnfunc_item_flag_team2()
770 {
771         if(!g_ctf) { remove(self); return; }
772
773         ctf_SetupFlag(0, self); // the 0 is misleading, but -- 0 = blue.
774 }
775
776 /*QUAKED spawnfunc_ctf_team (0 .5 .8) (-16 -16 -24) (16 16 32)
777 Team declaration for CTF gameplay, this allows you to decide what team names and control point models are used in your map.
778 Note: If you use spawnfunc_ctf_team entities you must define at least 2!  However, unlike domination, you don't need to make a blank one too.
779 Keys:
780 "netname" Name of the team (for example Red, Blue, Green, Yellow, Life, Death, Offense, Defense, etc)...
781 "cnt" Scoreboard color of the team (for example 4 is red and 13 is blue)... */
782 void spawnfunc_ctf_team()
783 {
784         if(!g_ctf) { remove(self); return; }
785         
786         self.classname = "ctf_team";
787         self.team = self.cnt + 1;
788 }
789
790
791 // ==============
792 // Initialization
793 // ==============
794
795 // code from here on is just to support maps that don't have flag and team entities
796 void ctf_SpawnTeam (string teamname, float teamcolor)
797 {
798         entity oldself;
799         oldself = self;
800         self = spawn();
801         self.classname = "ctf_team";
802         self.netname = teamname;
803         self.cnt = teamcolor;
804
805         spawnfunc_ctf_team();
806
807         self = oldself;
808 }
809
810 void ctf_DelayedInit() // Do this check with a delay so we can wait for teams to be set up.
811 {
812         // if no teams are found, spawn defaults
813         if(find(world, classname, "ctf_team") == world)
814         {
815                 print("NO TEAMS FOUND FOR CTF! creating them anyway.\n");
816                 ctf_SpawnTeam("Red", COLOR_TEAM1 - 1);
817                 ctf_SpawnTeam("Blue", COLOR_TEAM2 - 1);
818         }
819         
820         ScoreRules_ctf();
821 }
822
823 void ctf_Initialize()
824 {
825         ctf_captimerecord = stof(db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time")));
826
827         ctf_captureshield_min_negscore = autocvar_g_ctf_shield_min_negscore;
828         ctf_captureshield_max_ratio = autocvar_g_ctf_shield_max_ratio;
829         ctf_captureshield_force = autocvar_g_ctf_shield_force;
830
831         //g_ctf_win_mode = cvar("g_ctf_win_mode");
832         
833         InitializeEntity(world, ctf_DelayedInit, INITPRIO_GAMETYPE);
834 }
835
836
837 MUTATOR_DEFINITION(gamemode_ctf)
838 {
839         MUTATOR_HOOK(MakePlayerObserver, ctf_RemovePlayer, CBC_ORDER_ANY);
840         MUTATOR_HOOK(ClientDisconnect, ctf_RemovePlayer, CBC_ORDER_ANY);
841         MUTATOR_HOOK(PlayerDies, ctf_RemovePlayer, CBC_ORDER_ANY);
842         MUTATOR_HOOK(GiveFragsForKill, ctf_GiveFragsForKill, CBC_ORDER_ANY);
843         MUTATOR_HOOK(PlayerPreThink, ctf_PlayerPreThink, CBC_ORDER_ANY);
844         MUTATOR_HOOK(PlayerDamage_Calculate, ctf_PlayerDamage, CBC_ORDER_ANY);
845         MUTATOR_HOOK(PlayerUseKey, ctf_PlayerUseKey, CBC_ORDER_ANY);
846         //MUTATOR_HOOK(PlayerPowerups, ctf_PlayerPowerups, CBC_ORDER_ANY);
847
848         MUTATOR_ONADD
849         {
850                 if(time > 1) // game loads at time 1
851                         error("This is a game type and it cannot be added at runtime.");
852                 g_ctf = 1;
853                 ctf_Initialize();
854         }
855
856         MUTATOR_ONREMOVE
857         {
858                 g_ctf = 0;
859                 error("This is a game type and it cannot be removed at runtime.");
860         }
861
862         return 0;
863 }