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