Merge remote branch 'origin/master' into samual/mutator_ctf
authorSamual <samual@xonotic.org>
Tue, 27 Mar 2012 22:28:37 +0000 (18:28 -0400)
committerSamual <samual@xonotic.org>
Tue, 27 Mar 2012 22:28:37 +0000 (18:28 -0400)
Conflicts:
qcsrc/server/arena.qc
qcsrc/server/cl_client.qc
qcsrc/server/defs.qh
qcsrc/server/mutators/mutators.qh
qcsrc/server/progs.src

12 files changed:
1  2 
qcsrc/server/attic/nexball.qc
qcsrc/server/autocvars.qh
qcsrc/server/cl_client.qc
qcsrc/server/cl_player.qc
qcsrc/server/defs.qh
qcsrc/server/g_damage.qc
qcsrc/server/mutators/gamemode_ctf.qc
qcsrc/server/mutators/gamemode_ctf.qh
qcsrc/server/mutators/gamemode_nexball.qc
qcsrc/server/mutators/mutators.qh
qcsrc/server/progs.src
qcsrc/server/teamplay.qc

index 0000000,a068a33..d3f4b55
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,738 +1,741 @@@
 -      ball.dropperid = plyr.playerid;
+ //EF_BRIGHTFIELD|EF_BRIGHTLIGHT|EF_DIMLIGHT|EF_BLUE|EF_RED|EF_FLAME
+ #define BALL_EFFECTMASK 1229
+ #define BALL_MINS '-16 -16 -16'  // The model is 24*24*24
+ #define BALL_MAXS '16 16 16'
+ #define BALL_ATTACHORG '3 0 16'
+ #define BALL_SPRITECOLOR '.91 .85 .62'
+ #define BALL_FOOT   1
+ #define BALL_BASKET 2
+ //spawnflags
+ #define GOAL_TOUCHPLAYER 1
+ //goal types
+ #define GOAL_FAULT -1
+ #define GOAL_OUT -2
+ #define CVTOV(s) s = cvar( #s )
+ float g_nexball_football_boost_forward;
+ float g_nexball_football_boost_up;
+ float g_nexball_football_physics;
+ float g_nexball_delay_idle;
+ float g_nexball_basketball_delay_hold;
+ float g_nexball_basketball_delay_hold_forteam;
+ float g_nexball_basketball_effects_default;
+ float g_nexball_basketball_teamsteal;
+ float balls;
+ float ball_scale;
+ float nb_teams;
+ .float teamtime;
++.float nb_dropperid;
++.float nb_droptime;
++
+ void nb_delayedinit();
+ void nb_init() // Called early (worldspawn stage)
+ {
+       CVTOV(g_nexball_meter_period); //sent with the client init entity
+       if (g_nexball_meter_period <= 0)
+               g_nexball_meter_period = 2; // avoid division by zero etc. due to silly users
+       g_nexball_meter_period = rint(g_nexball_meter_period * 32) / 32; //Round to 1/32ths to send as a byte multiplied by 32
+       addstat(STAT_NB_METERSTART, AS_FLOAT, metertime);
+       // General settings
+       CVTOV(g_nexball_football_boost_forward);   //100
+       CVTOV(g_nexball_football_boost_up);        //200
+       CVTOV(g_nexball_delay_idle);               //10
+       CVTOV(g_nexball_football_physics);         //0
+       radar_showennemies = autocvar_g_nexball_radar_showallplayers;
+       InitializeEntity(world, nb_delayedinit, INITPRIO_GAMETYPE);
+ }
+ float OtherTeam(float t)  //works only if there are two teams on the map!
+ {
+       entity e;
+       e = find(world, classname, "nexball_team");
+       if (e.team == t)
+               e = find(e, classname, "nexball_team");
+       return e.team;
+ }
+ void ResetBall();
+ void LogNB(string mode, entity actor)
+ {
+       string s;
+       if(!autocvar_sv_eventlog)
+               return;
+       s = strcat(":nexball:", mode);
+       if(actor != world)
+               s = strcat(s, ":", ftos(actor.playerid));
+       GameLogEcho(s);
+ }
+ void ball_restart (void)
+ {
+       if(self.owner)
+               DropBall(self, self.owner.origin, '0 0 0');
+       ResetBall();
+ }
+ void nexball_setstatus (void)
+ {
+       entity oldself;
+       self.items &~= IT_KEY1;
+       if (self.ballcarried)
+       {
+               if (self.ballcarried.teamtime && (self.ballcarried.teamtime < time))
+               {
+                       bprint("The ", ColoredTeamName(self.team), " held the ball for too long.\n");
+                       oldself = self;
+                       self = self.ballcarried;
+                       DropBall(self, self.owner.origin, '0 0 0');
+                       ResetBall();
+                       self = oldself;
+               } else
+                       self.items |= IT_KEY1;
+       }
+ }
+ void relocate_nexball (void)
+ {
+       tracebox(self.origin, BALL_MINS, BALL_MAXS, self.origin, TRUE, self);
+       if (trace_startsolid)
+       {
+               vector o;
+               o = self.origin;
+               if(!move_out_of_solid(self))
+                       objerror("could not get out of solid at all!");
+               print("^1NOTE: this map needs FIXING. ", self.classname, " at ", vtos(o - '0 0 1'));
+               print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
+               print(" ", ftos(self.origin_y - o_y));
+               print(" ", ftos(self.origin_z - o_z), "'\n");
+               self.origin = o;
+       }
+ }
+ void basketball_touch();
+ void football_touch();
+ void DropOwner (void)
+ {
+       entity ownr;
+       ownr = self.owner;
+       DropBall(self, ownr.origin, ownr.velocity);
+       makevectors(ownr.v_angle_y * '0 1 0');
+       ownr.velocity += ('0 0 0.75' - v_forward) * 1000;
+       ownr.flags &~= FL_ONGROUND;
+ }
+ void GiveBall (entity plyr, entity ball)
+ {
+       entity ownr;
+       if ((ownr = ball.owner))
+       {
+               ownr.effects &~= g_nexball_basketball_effects_default;
+               ownr.ballcarried = world;
+               if (ownr.metertime)
+               {
+                       ownr.metertime = 0;
+                       ownr.weaponentity.state = WS_READY;
+               }
+               WaypointSprite_Kill(ownr.waypointsprite_attachedforcarrier);
+       }
+       else
+       {
+               WaypointSprite_Kill(ball.waypointsprite_attachedforcarrier);
+       }
+       setattachment(ball, plyr, "");
+       setorigin(ball, BALL_ATTACHORG);
+       if (ball.team != plyr.team)
+               ball.teamtime = time + g_nexball_basketball_delay_hold_forteam;
+       ball.owner = ball.pusher = plyr; //"owner" is set to the player carrying, "pusher" to the last player who touched it
+       ball.team = plyr.team;
+       plyr.ballcarried = ball;
 -      ball.ctf_droptime = time;
++      ball.nb_dropperid = plyr.playerid;
+       plyr.effects |= g_nexball_basketball_effects_default;
+       ball.effects &~= g_nexball_basketball_effects_default;
+       ball.velocity = '0 0 0';
+       ball.movetype = MOVETYPE_NONE;
+       ball.touch = SUB_Null;
+       ball.effects |= EF_NOSHADOW;
+       ball.scale = 1; // scale down.
+       WaypointSprite_AttachCarrier("nb-ball", plyr, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR);
+       WaypointSprite_UpdateRule(plyr.waypointsprite_attachedforcarrier, 0, SPRITERULE_DEFAULT);
+       if (g_nexball_basketball_delay_hold)
+       {
+               ball.think = DropOwner;
+               ball.nextthink = time + g_nexball_basketball_delay_hold;
+       }
+ }
+ void DropBall (entity ball, vector org, vector vel)
+ {
+       ball.effects |= g_nexball_basketball_effects_default;
+       ball.effects &~= EF_NOSHADOW;
+       ball.owner.effects &~= g_nexball_basketball_effects_default;
+       setattachment(ball, world, "");
+       setorigin (ball, org);
+       ball.movetype = MOVETYPE_BOUNCE;
+       ball.flags &~= FL_ONGROUND;
+       ball.scale = ball_scale;
+       ball.velocity = vel;
 -      if (!self.cnt && other.classname == "player" && (other.playerid != self.dropperid || time > self.ctf_droptime + autocvar_g_nexball_delay_collect)) {
++      ball.nb_droptime = time;
+       ball.touch = basketball_touch;
+       ball.think = ResetBall;
+       ball.nextthink = min(time + g_nexball_delay_idle, ball.teamtime);
+       if (ball.owner.metertime)
+       {
+               ball.owner.metertime = 0;
+               ball.owner.weaponentity.state = WS_READY;
+       }
+       WaypointSprite_Kill(ball.owner.waypointsprite_attachedforcarrier);
+       WaypointSprite_Spawn("nb-ball", 0, 0, ball, '0 0 64', world, ball.team, ball, waypointsprite_attachedforcarrier, FALSE, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR); // no health bar please
+       WaypointSprite_UpdateRule(ball.waypointsprite_attachedforcarrier, 0, SPRITERULE_DEFAULT);
+       ball.owner.ballcarried = world;
+       ball.owner = world;
+ }
+ void InitBall (void)
+ {
+       if (gameover) return;
+       self.flags &~= FL_ONGROUND;
+       self.movetype = MOVETYPE_BOUNCE;
+       if (self.classname == "nexball_basketball")
+               self.touch = basketball_touch;
+       else if (self.classname == "nexball_football")
+               self.touch = football_touch;
+       self.cnt = 0;
+       self.think = ResetBall;
+       self.nextthink = time + g_nexball_delay_idle + 3;
+       self.teamtime = 0;
+       self.pusher = world;
+       self.team = FALSE;
+       sound (self, CH_TRIGGER, self.noise1, VOL_BASE, ATTN_NORM);
+       WaypointSprite_Ping(self.waypointsprite_attachedforcarrier);
+       LogNB("init", world);
+ }
+ void ResetBall (void)
+ {
+       if (self.cnt < 2) { // step 1
+               if (time == self.teamtime)
+                       bprint("The ", ColoredTeamName(self.team), " held the ball for too long.\n");
+               self.touch = SUB_Null;
+               self.movetype = MOVETYPE_NOCLIP;
+               self.velocity = '0 0 0'; // just in case?
+               if(!self.cnt)
+                       LogNB("resetidle", world);
+               self.cnt = 2;
+               self.nextthink = time;
+       } else if (self.cnt < 4) { // step 2 and 3
+ //            dprint("Step ", ftos(self.cnt), ": Calculated velocity: ", vtos(self.spawnorigin - self.origin), ", time: ", ftos(time), "\n");
+               self.velocity = (self.spawnorigin - self.origin) * (self.cnt - 1); // 1 or 0.5 second movement
+               self.nextthink = time + 0.5;
+               self.cnt += 1;
+       } else { // step 4
+ //            dprint("Step 4: time: ", ftos(time), "\n");
+               if (vlen(self.origin - self.spawnorigin) > 10) // should not happen anymore
+                       dprint("The ball moved too far away from its spawn origin.\nOffset: ",
+                              vtos(self.origin - self.spawnorigin), " Velocity: ", vtos(self.velocity), "\n");
+               self.velocity = '0 0 0';
+               setorigin(self, self.spawnorigin); // make sure it's positioned correctly anyway
+               self.movetype = MOVETYPE_NONE;
+               self.think = InitBall;
+               self.nextthink = max(time, game_starttime) + autocvar_g_nexball_delay_start;
+       }
+ }
+ void football_touch (void)
+ {
+       if (other.solid == SOLID_BSP) {
+               if (time > self.lastground + 0.1)
+               {
+                       sound (self, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NORM);
+                       self.lastground = time;
+               }
+               if (vlen(self.velocity) && !self.cnt)
+                       self.nextthink = time + g_nexball_delay_idle;
+               return;
+       }
+       if (other.classname != "player")
+               return;
+       if (other.health < 1)
+               return;
+       if (!self.cnt)
+               self.nextthink = time + g_nexball_delay_idle;
+       self.pusher = other;
+       self.team = other.team;
+       if (g_nexball_football_physics == -1) { // MrBougo try 1, before decompiling Rev's original
+               if (vlen(other.velocity))
+                       self.velocity = other.velocity * 1.5 + '0 0 1' * g_nexball_football_boost_up;
+       } else if (g_nexball_football_physics == 1) { // MrBougo's modded Rev style: partially independant of the height of the aiming point
+               makevectors(other.v_angle);
+               self.velocity = other.velocity + v_forward * g_nexball_football_boost_forward + '0 0 1' * g_nexball_football_boost_up;
+       } else if (g_nexball_football_physics == 2) { // 2nd mod try: totally independant. Really playable!
+               makevectors(other.v_angle_y * '0 1 0');
+               self.velocity = other.velocity + v_forward * g_nexball_football_boost_forward + v_up * g_nexball_football_boost_up;
+       } else { // Revenant's original style (from the original mod's disassembly, acknowledged by Revenant)
+               makevectors(other.v_angle);
+               self.velocity = other.velocity + v_forward * g_nexball_football_boost_forward + v_up * g_nexball_football_boost_up;
+       }
+       self.avelocity = -250 * v_forward;  // maybe there is a way to make it look better?
+ }
+ void basketball_touch (void)
+ {
+       if (other.ballcarried)
+       {
+               football_touch();
+               return;
+       }
++      if (!self.cnt && other.classname == "player" && (other.playerid != self.nb_dropperid || time > self.nb_droptime + autocvar_g_nexball_delay_collect)) {
+               if (other.health <= 0)
+                       return;
+               LogNB("caught", other);
+               GiveBall(other, self);
+       } else if (other.solid == SOLID_BSP) {
+               sound (self, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NORM);
+               if (vlen(self.velocity) && !self.cnt)
+                       self.nextthink = min(time + g_nexball_delay_idle, self.teamtime);
+       }
+ }
+ void GoalTouch (void)
+ {
+       entity ball;
+       float isclient, pscore, otherteam;
+       string pname;
+       if (gameover) return;
+       if ((self.spawnflags & GOAL_TOUCHPLAYER) && other.ballcarried)
+               ball = other.ballcarried;
+       else
+               ball = other;
+       if (ball.classname != "nexball_basketball")
+       if (ball.classname != "nexball_football")
+               return;
+       if ((!ball.pusher && self.team != GOAL_OUT) || ball.cnt)
+               return;
+       EXACTTRIGGER_TOUCH;
+       if(nb_teams == 2)
+               otherteam = OtherTeam(ball.team);
+       if((isclient = ball.pusher.flags & FL_CLIENT))
+               pname = ball.pusher.netname;
+       else
+               pname = "Someone (?)";
+       if        (ball.team == self.team) //owngoal (regular goals)
+       {
+               LogNB("owngoal", ball.pusher);
+               bprint("Boo! ", pname, "^7 scored a goal against their own team!\n");
+               pscore = -1;
+       } else if (self.team == GOAL_FAULT) {
+               LogNB("fault", ball.pusher);
+               if (nb_teams == 2)
+                       bprint(ColoredTeamName(otherteam), " gets a point due to ", pname, "^7's silliness.\n");
+               else
+                       bprint(ColoredTeamName(ball.team), " loses a point due to ", pname, "^7's silliness.\n");
+               pscore = -1;
+       } else if (self.team == GOAL_OUT) {
+               LogNB("out", ball.pusher);
+               if ((self.spawnflags & GOAL_TOUCHPLAYER) && ball.owner)
+                       bprint(pname, "^7 went out of bounds.\n");
+               else
+                       bprint("The ball was returned.\n");
+               pscore = 0;
+       } else {                           //score
+               LogNB(strcat("goal:", ftos(self.team)), ball.pusher);
+               bprint("Goaaaaal! ", pname, "^7 scored a point for the ", ColoredTeamName(ball.team), ".\n");
+               pscore = 1;
+       }
+       sound (ball, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NONE);
+       if(ball.team && pscore)
+       {
+               if (nb_teams == 2 && pscore < 0)
+                       TeamScore_AddToTeam(otherteam, ST_NEXBALL_GOALS, -pscore);
+               else
+                       TeamScore_AddToTeam(ball.team, ST_NEXBALL_GOALS, pscore);
+       }
+       if (isclient)
+       {
+               if (pscore > 0)
+                       PlayerScore_Add(ball.pusher, SP_NEXBALL_GOALS, pscore);
+               else if (pscore < 0)
+                       PlayerScore_Add(ball.pusher, SP_NEXBALL_FAULTS, -pscore);
+       }
+       if (ball.owner) // Happens on spawnflag GOAL_TOUCHPLAYER
+               DropBall(ball, ball.owner.origin, ball.owner.velocity);
+       WaypointSprite_Ping(ball.waypointsprite_attachedforcarrier);
+       ball.cnt = 1;
+       ball.think = ResetBall;
+       if (ball.classname == "nexball_basketball")
+               ball.touch = football_touch; // better than SUB_Null: football control until the ball gets reset
+       ball.nextthink = time + autocvar_g_nexball_delay_goal * (self.team != GOAL_OUT);
+ }
+ //=======================//
+ //       team ents       //
+ //=======================//
+ void spawnfunc_nexball_team (void)
+ {
+       if(!g_nexball) { remove(self); return; }
+       self.team = self.cnt + 1;
+ }
+ void nb_spawnteam (string teamname, float teamcolor)
+ {
+       dprint("^2spawned team ", teamname, "\n");
+       entity e;
+       e = spawn();
+       e.classname = "nexball_team";
+       e.netname = teamname;
+       e.cnt = teamcolor;
+       e.team = e.cnt + 1;
+       nb_teams += 1;
+ }
+ void nb_spawnteams (void)
+ {
+       float t_r, t_b, t_y, t_p;
+       entity e;
+       for(e = world; (e = find(e, classname, "nexball_goal")); )
+       {
+               switch(e.team)
+               {
+                       case COLOR_TEAM1: if(!t_r) { nb_spawnteam ("Red", e.team-1)   ; t_r = 1; } break;
+                       case COLOR_TEAM2: if(!t_b) { nb_spawnteam ("Blue", e.team-1)  ; t_b = 1; } break;
+                       case COLOR_TEAM3: if(!t_y) { nb_spawnteam ("Yellow", e.team-1); t_y = 1; } break;
+                       case COLOR_TEAM4: if(!t_p) { nb_spawnteam ("Pink", e.team-1)  ; t_p = 1; } break;
+               }
+       }
+ }
+ void nb_delayedinit (void)
+ {
+       if (find(world, classname, "nexball_team") == world)
+               nb_spawnteams();
+       ScoreRules_nexball(nb_teams);
+ }
+ //=======================//
+ //      spawnfuncs       //
+ //=======================//
+ void SpawnBall (void)
+ {
+       if(!g_nexball) { remove(self); return; }
+ //    balls += 4; // using the remaining bits to count balls will leave more than the max edict count, so it's fine
+       if (!self.model) {
+               self.model = "models/nexball/ball.md3";
+               self.scale = 1.3;
+       }
+       precache_model (self.model);
+       setmodel (self, self.model);
+       setsize (self, BALL_MINS, BALL_MAXS);
+       ball_scale = self.scale;
+       relocate_nexball();
+       self.spawnorigin = self.origin;
+       self.effects = self.effects | EF_LOWPRECISION;
+       if (cvar(strcat("g_", self.classname, "_trail"))) //nexball_basketball :p
+       {
+               self.glow_color = autocvar_g_nexball_trail_color;
+               self.glow_trail = TRUE;
+       }
+       self.movetype = MOVETYPE_FLY;
+       if (!autocvar_g_nexball_sound_bounce)
+               self.noise = "";
+       else if (!self.noise)
+               self.noise = "sound/nexball/bounce.wav";
+               //bounce sound placeholder (FIXME)
+       if (!self.noise1)
+               self.noise1 = "sound/nexball/drop.wav";
+               //ball drop sound placeholder (FIXME)
+       if (!self.noise2)
+               self.noise2 = "sound/nexball/steal.wav";
+               //stealing sound placeholder (FIXME)
+       if (self.noise) precache_sound (self.noise);
+       precache_sound (self.noise1);
+       precache_sound (self.noise2);
+       WaypointSprite_AttachCarrier("nb-ball", self, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR); // the ball's team is not set yet, no rule update needed
+       self.reset = ball_restart;
+       self.think = InitBall;
+       self.nextthink = game_starttime + autocvar_g_nexball_delay_start;
+ }
+ void spawnfunc_nexball_basketball (void)
+ {
+       self.classname = "nexball_basketball";
+       if not(balls & BALL_BASKET)
+       {
+               CVTOV(g_nexball_basketball_effects_default);
+               CVTOV(g_nexball_basketball_delay_hold);
+               CVTOV(g_nexball_basketball_delay_hold_forteam);
+               CVTOV(g_nexball_basketball_teamsteal);
+               g_nexball_basketball_effects_default = g_nexball_basketball_effects_default & BALL_EFFECTMASK;
+       }
+       if (!self.effects)
+               self.effects = g_nexball_basketball_effects_default;
+       self.solid = SOLID_TRIGGER;
+       balls |= BALL_BASKET;
+       self.bouncefactor = autocvar_g_nexball_basketball_bouncefactor;
+       self.bouncestop = autocvar_g_nexball_basketball_bouncestop;
+       SpawnBall();
+ }
+ void spawnfunc_nexball_football (void)
+ {
+       self.classname = "nexball_football";
+       self.solid = SOLID_TRIGGER;
+       balls |= BALL_FOOT;
+       self.bouncefactor = autocvar_g_nexball_football_bouncefactor;
+       self.bouncestop = autocvar_g_nexball_football_bouncestop;
+       SpawnBall();
+ }
+ void SpawnGoal (void)
+ {
+       if(!g_nexball) { remove(self); return; }
+       EXACTTRIGGER_INIT;
+       self.classname = "nexball_goal";
+       if (!self.noise)
+               self.noise = "ctf/respawn.wav";
+       precache_sound(self.noise);
+       self.touch = GoalTouch;
+ }
+ void spawnfunc_nexball_redgoal (void)
+ {
+       self.team = COLOR_TEAM1;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_bluegoal (void)
+ {
+       self.team = COLOR_TEAM2;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_yellowgoal (void)
+ {
+       self.team = COLOR_TEAM3;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_pinkgoal (void)
+ {
+       self.team = COLOR_TEAM4;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_fault (void)
+ {
+       self.team = GOAL_FAULT;
+       if (!self.noise)
+               self.noise = "misc/typehit.wav";
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_out (void)
+ {
+       self.team = GOAL_OUT;
+       if (!self.noise)
+               self.noise = "misc/typehit.wav";
+       SpawnGoal();
+ }
+ //
+ //Spawnfuncs preserved for compatibility
+ //
+ void spawnfunc_ball            (void) { spawnfunc_nexball_football(); }
+ void spawnfunc_ball_football   (void) { spawnfunc_nexball_football(); }
+ void spawnfunc_ball_basketball (void) { spawnfunc_nexball_basketball(); }
+ // The "red goal" is defended by blue team. A ball in there counts as a point for red.
+ void spawnfunc_ball_redgoal    (void) { spawnfunc_nexball_bluegoal(); } // I blame Revenant
+ void spawnfunc_ball_bluegoal   (void) { spawnfunc_nexball_redgoal(); }  // but he didn't mean to cause trouble :p
+ void spawnfunc_ball_fault      (void) { spawnfunc_nexball_fault(); }
+ void spawnfunc_ball_bound      (void) { spawnfunc_nexball_out(); }
+ //=======================//
+ //      Weapon code      //
+ //=======================//
+ void W_Nexball_Touch (void)
+ {
+       entity ball, attacker;
+       attacker = self.owner;
+       PROJECTILE_TOUCH;
+       if(attacker.team != other.team || g_nexball_basketball_teamsteal)
+       if((ball = other.ballcarried) && (attacker.classname == "player"))
+       {
+               other.velocity = other.velocity + normalize(self.velocity) * other.damageforcescale * autocvar_g_balance_nexball_secondary_force;
+               other.flags &~= FL_ONGROUND;
+               if(!attacker.ballcarried)
+               {
+                       LogNB("stole", attacker);
+                       sound (other, CH_TRIGGER, ball.noise2, VOL_BASE, ATTN_NORM);
+                       if(attacker.team == other.team && time > attacker.teamkill_complain)
+                       {
+                               attacker.teamkill_complain = time + 5;
+                               attacker.teamkill_soundtime = time + 0.4;
+                               attacker.teamkill_soundsource = other;
+                       }
+                       GiveBall(attacker, other.ballcarried);
+               }
+       }
+       remove(self);
+ }
+ void W_Nexball_Attack (float t)
+ {
+       entity ball;
+       float mul, mi, ma;
+       if (!(ball = self.ballcarried))
+               return;
+       W_SetupShot (self, FALSE, 4, "nexball/shoot1.wav", CH_WEAPON_A, 0);
+       tracebox(w_shotorg, BALL_MINS, BALL_MAXS, w_shotorg, MOVE_WORLDONLY, world);
+       if(trace_startsolid)
+       {
+               if(self.metertime)
+                       self.metertime = 0; // Shot failed, hide the power meter
+               return;
+       }
+       //Calculate multiplier
+       if (t < 0)
+               mul = 1;
+       else
+       {
+               mi = autocvar_g_nexball_basketball_meter_minpower;
+               ma = max(mi, autocvar_g_nexball_basketball_meter_maxpower); // avoid confusion
+               //One triangle wave period with 1 as max
+               mul = 2 * mod(t, g_nexball_meter_period) / g_nexball_meter_period;
+               if (mul > 1)
+                       mul = 2 - mul;
+               mul = mi + (ma - mi) * mul; // range from the minimal power to the maximal power
+       }
+       DropBall (ball, w_shotorg, W_CalculateProjectileVelocity(self.velocity, w_shotdir * autocvar_g_balance_nexball_primary_speed * mul, FALSE));
+       //TODO: use the speed_up cvar too ??
+ }
+ void W_Nexball_Attack2 (void)
+ {
+       entity missile;
+       if (!(balls & BALL_BASKET))
+               return;
+       W_SetupShot (self, FALSE, 2, "nexball/shoot2.wav", CH_WEAPON_A, 0);
+ //    pointparticles(particleeffectnum("grenadelauncher_muzzleflash"), w_shotorg, w_shotdir * 1000, 1);
+       missile = spawn ();
+       missile.owner = self;
+       missile.classname = "ballstealer";
+       missile.movetype = MOVETYPE_FLY;
+       PROJECTILE_MAKETRIGGER(missile);
+       setmodel (missile, "models/elaser.mdl"); // precision set below
+       setsize (missile, '0 0 0', '0 0 0');
+       setorigin (missile, w_shotorg);
+       W_SetupProjectileVelocity(missile, autocvar_g_balance_nexball_secondary_speed, 0);
+       missile.angles = vectoangles (missile.velocity);
+       missile.touch = W_Nexball_Touch;
+       missile.think = SUB_Remove;
+       missile.nextthink = time + autocvar_g_balance_nexball_secondary_lifetime; //FIXME: use a distance instead?
+       missile.effects = EF_BRIGHTFIELD | EF_LOWPRECISION;
+       missile.flags = FL_PROJECTILE;
+ }
+ float w_nexball_weapon(float req)
+ {
+       if (req == WR_THINK)
+       {
+               if (self.BUTTON_ATCK)
+               if (weapon_prepareattack(0, autocvar_g_balance_nexball_primary_refire))
+               if (autocvar_g_nexball_basketball_meter)
+               {
+                       if (self.ballcarried && !self.metertime)
+                               self.metertime = time;
+                       else
+                               weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+               }
+               else
+               {
+                       W_Nexball_Attack(-1);
+                       weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+               }
+               if (self.BUTTON_ATCK2)
+               if (weapon_prepareattack(1, autocvar_g_balance_nexball_secondary_refire))
+               {
+                       W_Nexball_Attack2();
+                       weapon_thinkf(WFRAME_FIRE2, autocvar_g_balance_nexball_secondary_animtime, w_ready);
+               }
+               if (!self.BUTTON_ATCK && self.metertime && self.ballcarried)
+               {
+                       W_Nexball_Attack(time - self.metertime);
+                       // DropBall or stealing will set metertime back to 0
+                       weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+               }
+       }
+       else if (req == WR_PRECACHE)
+       {
+               precache_model ("models/weapons/g_porto.md3");
+               precache_model ("models/weapons/v_porto.md3");
+               precache_model ("models/weapons/h_porto.iqm");
+               precache_model ("models/elaser.mdl");
+               precache_sound ("nexball/shoot1.wav");
+               precache_sound ("nexball/shoot2.wav");
+               precache_sound ("misc/typehit.wav");
+       }
+       else if (req == WR_SETUP)
+               weapon_setup(WEP_PORTO);
+       else if (req == WR_SUICIDEMESSAGE)
+       {
+               w_deathtypestring = "is a weirdo";
+       }
+       else if (req == WR_KILLMESSAGE)
+       {
+               w_deathtypestring = "got killed by #'s black magic";
+       }
+       // No need to check WR_CHECKAMMO* or WR_AIM, it should always return TRUE
+       return TRUE;
+ }
Simple merge
@@@ -419,11 -418,8 +418,8 @@@ void PutObserverInServer (void
            vehicles_exit(VHEF_RELESE);
  
        if(self.flagcarried)
 -              DropFlag(self.flagcarried, world, world);
 +              ctf_Handle_Drop(self); // FIXCTF
  
-       if(self.ballcarried && g_nexball)
-               DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
        WaypointSprite_PlayerDead();
  
        if not(g_ca)  // don't reset teams when moving a ca player to the spectators
@@@ -1652,9 -1653,7 +1653,7 @@@ void ClientDisconnect (void
  
        RemoveGrapplingHook(self);
        if(self.flagcarried)
 -              DropFlag(self.flagcarried, world, world);
 +              ctf_Handle_Drop(self); // FIXCTF
-       if(self.ballcarried && g_nexball)
-               DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
  
        // Here, everything has been done that requires this player to be a client.
  
@@@ -697,16 -695,13 +695,14 @@@ void PlayerDamage (entity inflictor, en
  
                if(self.flagcarried)
                {
 +                      // FIXCTF
                        if(attacker.classname != "player")
 -                              DropFlag(self.flagcarried, self, attacker); // penalty for flag loss by suicide
 +                              ctf_Handle_Drop(self); // penalty for flag loss by suicide
                        else if(attacker.team == self.team)
 -                              DropFlag(self.flagcarried, attacker, attacker); // penalty for flag loss by suicide/teamkill
 +                              ctf_Handle_Drop(self); // penalty for flag loss by suicide/teamkill
                        else
 -                              DropFlag(self.flagcarried, world, attacker);
 +                              ctf_Handle_Drop(self);
                }
-               if(self.ballcarried && g_nexball)
-                       DropBall(self.ballcarried, self.origin, self.velocity);
                Portal_ClearAllLater(self);
  
                if(clienttype(self) == CLIENTTYPE_REAL)
@@@ -341,8 -341,7 +341,7 @@@ string gamemode_name
  
  float startitem_failed;
  
 -void DropFlag(entity flag, entity penalty_receiver, entity attacker);
 +void ctf_Handle_Drop(entity player); // FIXCTF
- void DropBall(entity ball, vector org, vector vel);
  void DropAllRunes(entity pl);
  
  
Simple merge
index 44f7601,0000000..3cfff88
mode 100644,000000..100644
--- /dev/null
@@@ -1,881 -1,0 +1,844 @@@
- //  Last updated: February 8th, 2012
 +// ================================================================
 +//  Official capture the flag game mode coding, reworked by Samual
- // Flag constants 
- #define FLAG_MIN (PL_MIN + '0 0 -13')
- #define FLAG_MAX (PL_MAX + '0 0 -13')
- #define FLAG_CARRY_POS '-15 0 7'
- .entity bot_basewaypoint; // flag waypointsprite
- .entity wps_flagbase; 
- .entity wps_flagcarrier;
- .entity wps_flagdropped;
- entity ctf_worldflaglist; // CTF flags in the map
- .entity ctf_worldflagnext;
- .vector ctf_spawnorigin; // stored vector for where the flag is placed on the map itself. 
- float ctf_captimerecord; // record time for capturing the flag
- .float ctf_pickuptime;
- .float ctf_pickupid;
- .float ctf_dropperid; // don't allow spam of dropping the flag
- .float ctf_droptime;
- .float ctf_status; // status of the flag (FLAG_BASE, FLAG_DROPPED, FLAG_CARRY declared globally)
- .float next_take_time; // Delay between when the person can pick up a flag // is this obsolete from the stuff above?
- // CaptureShield: If the player is too bad to be allowed to capture, shield them from taking the flag.
- .float ctf_captureshielded; // set to 1 if the player is too bad to be allowed to capture
- float ctf_captureshield_min_negscore; // punish at -20 points
- float ctf_captureshield_max_ratio; // punish at most 30% of each team
- float ctf_captureshield_force; // push force of the shield
- // after game mode is finished, these will be changed to use #define with other entities so as to not create many more.
- // ==================
- // Misc CTF functions
- // ==================
++//  Last updated: March 27th, 2012
 +// ================================================================
 +
 +float ctf_ReadScore(string parameter) // make this obsolete
 +{
 +      //if(g_ctf_win_mode != 2)
 +              return cvar(strcat("g_ctf_personal", parameter));
 +      //else
 +      //      return cvar(strcat("g_ctf_flag", parameter));
 +}
 +
 +void ctf_FakeTimeLimit(entity e, float t)
 +{
 +      msg_entity = e;
 +      WriteByte(MSG_ONE, 3); // svc_updatestat
 +      WriteByte(MSG_ONE, 236); // STAT_TIMELIMIT
 +      if(t < 0)
 +              WriteCoord(MSG_ONE, autocvar_timelimit);
 +      else
 +              WriteCoord(MSG_ONE, (t + 1) / 60);
 +}
 +
 +void ctf_EventLog(string mode, float flagteam, entity actor) // use an alias for easy changing and quick editing later
 +{
 +      if(autocvar_sv_eventlog)
 +              GameLogEcho(strcat(":ctf:", mode, ":", ftos(flagteam), ((actor != world) ? (strcat(":", ftos(actor.playerid))) : "")));
 +}
 +
 +
 +// =======================
 +// CaptureShield Functions 
 +// =======================
 +
 +float ctf_CaptureShield_CheckStatus(entity p) 
 +{
 +      float s, se;
 +      entity e;
 +      float players_worseeq, players_total;
 +
 +      if(ctf_captureshield_max_ratio <= 0)
 +              return FALSE;
 +
 +      s = PlayerScore_Add(p, SP_SCORE, 0);
 +      if(s >= -ctf_captureshield_min_negscore)
 +              return FALSE;
 +
 +      players_total = players_worseeq = 0;
 +      FOR_EACH_PLAYER(e)
 +      {
 +              if(e.team != p.team)
 +                      continue;
 +              se = PlayerScore_Add(e, SP_SCORE, 0);
 +              if(se <= s)
 +                      ++players_worseeq;
 +              ++players_total;
 +      }
 +
 +      // player is in the worse half, if >= half the players are better than him, or consequently, if < half of the players are worse
 +      // use this rule here
 +      
 +      if(players_worseeq >= players_total * ctf_captureshield_max_ratio)
 +              return FALSE;
 +
 +      return TRUE;
 +}
 +
 +void ctf_CaptureShield_Update(entity player, float wanted_status)
 +{
 +      float updated_status = ctf_CaptureShield_CheckStatus(player);
 +      if((wanted_status == player.ctf_captureshielded) && (updated_status != wanted_status)) // 0: shield only, 1: unshield only
 +      {
 +              if(updated_status) // TODO csqc notifier for this // Samual: How?
 +                      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);
 +              else
 +                      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);
 +                      
 +              player.ctf_captureshielded = updated_status;
 +      }
 +}
 +
 +float ctf_CaptureShield_Customize()
 +{
 +      if not(other.ctf_captureshielded)
 +              return FALSE;
 +      if(self.team == other.team)
 +              return FALSE;
 +      return TRUE;
 +}
 +
 +void ctf_CaptureShield_Touch()
 +{
 +      if not(other.ctf_captureshielded)
 +              return;
 +      if(self.team == other.team)
 +              return;
 +      vector mymid;
 +      vector othermid;
 +      mymid = (self.absmin + self.absmax) * 0.5;
 +      othermid = (other.absmin + other.absmax) * 0.5;
 +      Damage(other, self, self, 0, DEATH_HURTTRIGGER, mymid, normalize(othermid - mymid) * ctf_captureshield_force);
 +      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);
 +}
 +
 +void ctf_CaptureShield_Spawn(entity flag)
 +{
 +      entity e;
 +      e = spawn();
 +      e.enemy = self;
 +      e.team = self.team;
 +      e.touch = ctf_CaptureShield_Touch;
 +      e.customizeentityforclient = ctf_CaptureShield_Customize;
 +      e.classname = "ctf_captureshield";
 +      e.effects = EF_ADDITIVE;
 +      e.movetype = MOVETYPE_NOCLIP;
 +      e.solid = SOLID_TRIGGER;
 +      e.avelocity = '7 0 11';
 +      setorigin(e, self.origin);
 +      setmodel(e, "models/ctf/shield.md3");
 +      e.scale = 0.5;
 +      setsize(e, e.scale * e.mins, e.scale * e.maxs);
 +}
 +
 +
 +// ==============
 +// Event Handlers
 +// ==============
 +
 +void ctf_Handle_Drop(entity player)
 +{
 +      entity flag = player.flagcarried;
 +
 +      if(!flag) { return; }
 +      if(flag.speedrunning) { ctf_RespawnFlag(flag); return; }
 +      
 +      // reset the flag
 +      setattachment(flag, world, "");
 +      setorigin(flag, player.origin - '0 0 24' + '0 0 37');
 +      flag.owner.flagcarried = world;
 +      flag.owner = world;
 +      flag.movetype = MOVETYPE_TOSS;
 +      flag.solid = SOLID_TRIGGER;
 +      flag.takedamage = DAMAGE_YES;
 +      flag.velocity = ('0 0 200' + ('0 100 0' * crandom()) + ('100 0 0' * crandom()));
 +      flag.pain_finished = time + autocvar_g_ctf_flag_returntime; // replace this later
 +      
 +      flag.ctf_droptime = time;
 +      flag.ctf_dropperid = player.playerid;
 +      flag.ctf_status = FLAG_DROPPED;
 +
 +      // messages and sounds
 +      Send_KillNotification(player.netname, flag.netname, "", INFO_LOSTFLAG, MSG_INFO);
 +      sound(flag, CH_TRIGGER, flag.noise4, VOL_BASE, ATTN_NONE);
 +      ctf_EventLog("dropped", player.team, player);
 +      
 +      // scoring
 +      PlayerTeamScore_AddScore(player, -ctf_ReadScore("penalty_drop"));       
 +      PlayerScore_Add(player, SP_CTF_DROPS, 1);
 +
 +      // waypoints
 +      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)
 +      WaypointSprite_Ping(player.wps_flagcarrier);
 +      WaypointSprite_Kill(player.wps_flagcarrier);
 +
 +      // captureshield
 +      ctf_CaptureShield_Update(player, 0); // shield only
 +
 +      // check if the flag will fall off the map
 +      trace_startsolid = FALSE;
 +      tracebox(flag.origin, flag.mins, flag.maxs, flag.origin, TRUE, flag);
 +      if(trace_startsolid)
 +              dprint("FLAG FALLTHROUGH will happen SOON\n");
 +}
 +
 +void ctf_Handle_Capture(entity flag, entity player)
 +{
 +      // declarations
 +      float cap_time, cap_record, success;
 +      string cap_message, refername;
 +
 +      // records
 +      if((autocvar_g_ctf_captimerecord_always) || (player_count - currentbots)) {
 +              cap_record = ctf_captimerecord;
 +              cap_time = (time - player.flagcarried.ctf_pickuptime);
 +
 +              refername = db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"));
 +              refername = ((refername == player.netname) ? "their" : strcat(refername, "^7's"));
 +
 +              if(!ctf_captimerecord) 
 +                      { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds"); success = TRUE; }
 +              else if(cap_time < cap_record) 
 +                      { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, breaking ", refername, " previous record of ", ftos_decimals(cap_record, 2), " seconds"); success = TRUE; }
 +              else
 +                      { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, failing to break ", refername, " record of ", ftos_decimals(cap_record, 2), " seconds"); success = FALSE; }
 +
 +              if(success) {
 +                      ctf_captimerecord = cap_time;
 +                      db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time"), ftos(cap_time));
 +                      db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"), player.netname);
 +                      write_recordmarker(player, (time - cap_time), cap_time); } }
 +      
 +      // messages and sounds
 +      Send_KillNotification(player.netname, player.flagcarried.netname, cap_message, INFO_CAPTUREFLAG, MSG_INFO);
 +      sound(player, CH_TRIGGER, flag.noise2, VOL_BASE, ATTN_NONE); // "ctf/*_capture.wav"
 +      ctf_EventLog("capture", player.flagcarried.team, player);
 +      
 +      // scoring
 +      PlayerTeamScore_AddScore(player, ctf_ReadScore("score_capture"));
 +      PlayerTeamScore_Add(player, SP_CTF_CAPS, ST_CTF_CAPS, 1);
 +
 +      // effects
 +      if (autocvar_g_ctf_flag_capture_effects) 
 +      {
 +              pointparticles(particleeffectnum((player.team == COLOR_TEAM1) ? "red_ground_quake" : "blue_ground_quake"), flag.origin, '0 0 0', 1);
 +              //shockwave_spawn("models/ctf/shockwavetransring.md3", flag.origin - '0 0 15', -0.8, 0, 1);
 +      }
 +
 +      // waypointsprites
 +      WaypointSprite_Kill(player.wps_flagcarrier);
 +
 +      // reset the flag
 +      if(flag.speedrunning) { ctf_FakeTimeLimit(player, -1); }
 +      
 +      ctf_RespawnFlag(player.flagcarried);
 +}
 +
 +void ctf_Handle_Return(entity flag, entity player)
 +{
 +      // messages and sounds
 +      Send_KillNotification (player.netname, flag.netname, "", INFO_RETURNFLAG, MSG_INFO);
 +      sound(player, CH_TRIGGER, flag.noise1, VOL_BASE, ATTN_NONE);
 +      ctf_EventLog("return", flag.team, player);
 +
 +      // scoring
 +      PlayerTeamScore_AddScore(player, ctf_ReadScore(strcat("score_return", ((player.playerid == flag.playerid) ? "_by_killer" : "")))); // reward for return
 +      PlayerScore_Add(player, SP_CTF_RETURNS, 1); // add to count of returns
 +
 +      TeamScore_AddToTeam(((flag.team == COLOR_TEAM1) ? COLOR_TEAM2 : COLOR_TEAM1), ST_SCORE, -ctf_ReadScore("penalty_returned")); // punish the team who was last carrying it
 +      FOR_EACH_PLAYER(player) if(player.playerid == flag.ctf_dropperid) // punish the player who dropped the flag
 +      {
 +              PlayerScore_Add(player, SP_SCORE, -ctf_ReadScore("penalty_returned"));
 +              ctf_CaptureShield_Update(player, 0); // shield only
 +      }
 +
 +      // waypointsprites 
 +      WaypointSprite_Kill(flag.wps_flagdropped);
 +      
 +      // reset the flag
 +      ctf_RespawnFlag(flag);
 +}
 +
 +void ctf_Handle_Pickup_Base(entity flag, entity player)
 +{
 +      entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
 +      string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
 +
 +      // attach the flag to the player
 +      flag.owner = player;
 +      player.flagcarried = flag;
 +      setattachment(flag, player, "");
 +      setorigin(flag, FLAG_CARRY_POS);
 +      
 +      // set up the flag
 +      flag.movetype = MOVETYPE_NONE;
 +      flag.takedamage = DAMAGE_NO;
 +      flag.solid = SOLID_NOT;
 +      flag.angles = '0 0 0';
 +      flag.ctf_pickuptime = time; // used for timing runs
 +      flag.ctf_pickupid = player.playerid;
 +      flag.ctf_status = FLAG_CARRY;
 +      
 +      // messages and sounds
 +      Send_KillNotification (player.netname, flag.netname, "", INFO_GOTFLAG, MSG_INFO);
 +      sound(player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
 +      ctf_EventLog("steal", flag.team, player);
 +      verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : ""); // replace TRUE with an autocvar for it.
 +      FOR_EACH_PLAYER(tmp_player)
 +              if(tmp_player.team == flag.team)
 +                      centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
 +              else if((tmp_player.team == player.team) && (tmp_player != player))
 +                      centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
 +      
 +      // scoring
 +      PlayerTeamScore_AddScore(player, ctf_ReadScore("score_pickup_base"));
 +      PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
 +      
 +      // speedrunning
 +      flag.speedrunning = player.speedrunning; // if speedrunning, flag will flag-return and teleport the owner back after the record
 +      if((player.speedrunning) && (ctf_captimerecord))
 +              ctf_FakeTimeLimit(player, time + ctf_captimerecord);
 +              
 +      // effects
 +      if (autocvar_g_ctf_flag_pickup_effects)
 +      {
 +              pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1);
 +      }
 +      
 +      // waypoints 
 +      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)
 +      WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
 +      WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
 +      WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
 +      WaypointSprite_Ping(player.wps_flagcarrier);
 +}
 + 
 +void ctf_Handle_Pickup_Dropped(entity flag, entity player) // make sure this works
 +{
 +      // declarations
 +      float returnscore = bound(0, (flag.pain_finished - time) / autocvar_g_ctf_flag_returntime, 1); // can this be division by zero?
 +      entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
 +      string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
 +
 +      // attach the flag to the player
 +      flag.owner = player;
 +      player.flagcarried = flag;
 +      setattachment(flag, player, "");
 +      setorigin(flag, FLAG_CARRY_POS);
 +      
 +      // set up the flag
 +      flag.movetype = MOVETYPE_NONE;
 +      flag.takedamage = DAMAGE_NO;
 +      flag.solid = SOLID_NOT;
 +      flag.angles = '0 0 0';
 +      //flag.ctf_pickuptime = time; // don't update pickuptime since this isn't a real steal. 
 +      flag.ctf_pickupid = player.playerid;
 +      flag.ctf_status = FLAG_CARRY;
 +
 +      // messages and sounds
 +      Send_KillNotification (player.netname, flag.netname, "", INFO_PICKUPFLAG, MSG_INFO);
 +      sound (player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
 +      ctf_EventLog("pickup", flag.team, player);
 +      verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : "");
 +      FOR_EACH_PLAYER(tmp_player)
 +              if(tmp_player.team == flag.team)
 +                      centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
 +              else if((tmp_player.team == player.team) && (tmp_player != player))
 +                      centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
 +
 +      // scoring
 +      returnscore = floor((ctf_ReadScore("score_pickup_dropped_late") * (1-returnscore) + ctf_ReadScore("score_pickup_dropped_early") * returnscore) + 0.5);
 +      print("score is ", ftos(returnscore), "\n");
 +      PlayerTeamScore_AddScore(player, returnscore);
 +      PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
 +
 +      // effects
 +      if (autocvar_g_ctf_flag_pickup_effects) // field pickup effect
 +      {
 +              pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1); 
 +      }
 +
 +      // waypoints
 +      WaypointSprite_Kill(flag.wps_flagdropped);
 +      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)
 +      WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
 +      WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
 +      WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
 +      WaypointSprite_Ping(player.wps_flagcarrier);
 +}
 +
 +
 +// ===================
 +// Main Flag Functions
 +// ===================
 +
 +void ctf_FlagThink()
 +{
 +      // declarations
 +      entity tmp_entity;
 +
 +      self.nextthink = time + 0.1; // only 10 fps, more is unnecessary.
 +
 +      // captureshield
 +      if(self == ctf_worldflaglist) // only for the first flag
 +              FOR_EACH_CLIENT(tmp_entity)
 +                      ctf_CaptureShield_Update(tmp_entity, 1); // release shield only
 +
 +      // sanity checks
 +      if(self.mins != FLAG_MIN || self.maxs != FLAG_MAX) { // reset the flag boundaries in case it got squished
 +              dprint("wtf the flag got squished?\n");
 +              tracebox(self.origin, FLAG_MIN, FLAG_MAX, self.origin, MOVE_NOMONSTERS, self);
 +              if(!trace_startsolid) // can we resize it without getting stuck?
 +                      setsize(self, FLAG_MIN, FLAG_MAX); }
 +
 +      if(self.owner.classname != "player" || (self.owner.deadflag) || (self.owner.flagcarried != self)) {
 +              dprint("CANNOT HAPPEN - player dead and STILL had a flag!\n");
 +              ctf_Handle_Drop(self.owner);
 +              return; }
 +
 +      // main think method
 +      switch(self.ctf_status) 
 +      {       
 +              case FLAG_BASE: // nothing to do here
 +                      return;
 +              
 +              case FLAG_DROPPED:
 +                      // flag fallthrough? FIXME remove this if bug is really fixed now
 +                      if(self.origin_z < -131072)
 +                      {
 +                              dprint("FLAG FALLTHROUGH just happened\n");
 +                              self.pain_finished = 0;
 +                      }
 +                      setattachment(self, world, "");
 +                      if(time > self.pain_finished)
 +                      {
 +                              bprint("The ", self.netname, " has returned to base\n");
 +                              sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
 +                              ctf_EventLog("returned", self.team, world);
 +                              ctf_RespawnFlag(self);
 +                      }
 +                      return;
 +                              
 +              case FLAG_CARRY:
 +                      if((self.owner) && (self.speedrunning) && (ctf_captimerecord) && (time >= self.ctf_pickuptime + ctf_captimerecord)) 
 +                      {
 +                              bprint("The ", self.netname, " became impatient after ", ftos_decimals(ctf_captimerecord, 2), " seconds and returned itself\n");
 +                              sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
 +
 +                              self.owner.impulse = 141; // returning!
 +
 +                              tmp_entity = self;
 +                              self = self.owner;
 +                              ctf_RespawnFlag(tmp_entity);
 +                              ImpulseCommands();
 +                              self = tmp_entity;
 +                      }
 +                      return;
 +
 +              default: // this should never happen
 +                      dprint("Think: Flag exists with no status?\n");
 +                      return;
 +      }
 +}
 +
 +void ctf_FlagTouch()
 +{
 +      if(gameover) { return; }
 +      if(!self) { return; }
 +      if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
 +      { // The flag fell off the map, respawn it since players can't get to it
 +              ctf_RespawnFlag(self);
 +              return;
 +      }
 +      if(other.deadflag != DEAD_NO) { return; }
 +      if(other.classname != "player") 
 +      {  // The flag just touched an object, most likely the world
 +              pointparticles(particleeffectnum("kaball_sparks"), self.origin, '0 0 0', 1);
 +              sound(self, CH_TRIGGER, "keepaway/touch.wav", VOL_BASE, ATTN_NORM);
 +              return; 
 +      }
 +      else if(self.wait > time) { return; }
 +
 +      switch(self.ctf_status) 
 +      {       
 +              case FLAG_BASE:
 +                      if((other.team == self.team) && (other.flagcarried) && (other.flagcarried.team != self.team))
 +                              ctf_Handle_Capture(self, other); // other just captured the enemies flag to his base
 +                      else if((other.team != self.team) && (!other.flagcarried) && (!other.ctf_captureshielded))
 +                              ctf_Handle_Pickup_Base(self, other); // other just stole the enemies flag
 +                      break;
 +              
 +              case FLAG_DROPPED:
 +                      if(other.team == self.team)
 +                              ctf_Handle_Return(self, other); // other just returned his own flag
 +                      else if((!other.flagcarried) && ((other.playerid != self.ctf_dropperid) || (time > self.ctf_droptime + autocvar_g_balance_ctf_delay_collect)))
 +                              ctf_Handle_Pickup_Dropped(self, other); // other just picked up a dropped enemy flag
 +                      break;
 +                              
 +              case FLAG_CARRY:
 +                      dprint("Someone touched a flag even though it was being carried?\n");
 +                      break;
 +
 +              default: // this should never happen
 +                      dprint("Touch: Flag exists with no status?\n");
 +                      break;
 +      }
 +}
 +
 +void ctf_RespawnFlag(entity flag)
 +{
 +      // reset the player (if there is one)
 +      if((flag.owner) && (flag.owner.flagcarried == flag))
 +      {
 +              WaypointSprite_Kill(flag.wps_flagcarrier);
 +              flag.owner.flagcarried = world;
 +
 +              if(flag.speedrunning)
 +                      ctf_FakeTimeLimit(flag.owner, -1);
 +      }
 +
 +      // reset the flag
 +      setattachment(flag, world, "");
 +      setorigin(flag, flag.ctf_spawnorigin); // replace with flag.ctf_spawnorigin
 +      flag.movetype = ((flag.noalign) ? MOVETYPE_NONE : MOVETYPE_TOSS);
 +      flag.takedamage = DAMAGE_NO;
 +      flag.solid = SOLID_TRIGGER;
 +      flag.velocity = '0 0 0';
 +      flag.angles = flag.mangle;
 +      flag.ctf_status = FLAG_BASE;
 +      flag.flags = FL_ITEM | FL_NOTARGET;
 +      flag.owner = world;
 +}
 +
 +void ctf_Reset()
 +{
 +      if(self.owner)
 +              if(self.owner.classname == "player")
 +                      ctf_Handle_Drop(self.owner);
 +                      
 +      ctf_RespawnFlag(self);
 +}
 +
 +void ctf_SetupFlag(float teamnumber, entity flag) // called when spawning a flag entity on the map as a spawnfunc 
 +{
 +      // declarations
 +      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. 
 +      
 +      // main setup
 +      flag.ctf_worldflagnext = ctf_worldflaglist; // link flag into ctf_worldflaglist // todo: find out if this can be simplified
 +      ctf_worldflaglist = flag;
 +
 +      setattachment(flag, world, ""); 
 +
 +      flag.netname = ((teamnumber) ? "^1RED^7 flag" : "^4BLUE^7 flag");
 +      flag.team = ((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2); // COLOR_TEAM1: color 4 team (red) - COLOR_TEAM2: color 13 team (blue)
 +      flag.items = ((teamnumber) ? IT_KEY2 : IT_KEY1); // IT_KEY2: gold key (redish enough) - IT_KEY1: silver key (bluish enough)
 +      flag.classname = "item_flag_team";
 +      flag.target = "###item###"; // wut?
 +      flag.flags = FL_ITEM | FL_NOTARGET;
 +      flag.solid = SOLID_TRIGGER;
 +      flag.velocity = '0 0 0';
 +      flag.ctf_status = FLAG_BASE;
 +      flag.ctf_spawnorigin = flag.origin; 
 +      flag.mangle = flag.angles;
 +      flag.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
 +      
 +      if(flag.spawnflags & 1) // I don't understand what all this is about.
 +      {       
 +              flag.noalign = TRUE;
 +              flag.movetype = MOVETYPE_NONE;
 +              print("This map was loaded with flags using MOVETYPE_NONE\n");
 +      }
 +      else 
 +      { 
 +              flag.noalign = FALSE;
 +              flag.movetype = MOVETYPE_TOSS; 
 +              print("This map was loaded with flags using MOVETYPE_TOSS\n");
 +      }       
 +      
 +      flag.reset = ctf_Reset;
 +      flag.touch = ctf_FlagTouch;
 +
 +      // appearence
 +      if(!flag.model) { flag.model = ((teamnumber) ? autocvar_g_ctf_flag_red_model : autocvar_g_ctf_flag_blue_model); }
 +      setmodel (flag, flag.model); // precision set below
 +      setsize(flag, FLAG_MIN, FLAG_MAX);
 +      setorigin(flag, flag.origin);
 +      if(!flag.scale) { flag.scale = 0.6; }
 +      
 +      flag.skin = ((teamnumber) ? autocvar_g_ctf_flag_red_skin : autocvar_g_ctf_flag_blue_skin);
 +      
 +      if(autocvar_g_ctf_flag_glowtrails)
 +      {
 +              flag.glow_color = ((teamnumber) ? 251 : 210); // 251: red - 210: blue
 +              flag.glow_size = 25;
 +              flag.glow_trail = 1;
 +      }
 +      
 +      flag.effects |= EF_LOWPRECISION;
 +      if(autocvar_g_ctf_fullbrightflags) { flag.effects |= EF_FULLBRIGHT; }
 +      if(autocvar_g_ctf_dynamiclights)   { flag.effects |= ((teamnumber) ? EF_RED : EF_BLUE); }
 +      
 +      // sound 
 +      if(!flag.noise)  { flag.noise  = ((teamnumber) ? "ctf/red_taken.wav" : "ctf/blue_taken.wav"); }
 +      if(!flag.noise1) { flag.noise1 = ((teamnumber) ? "ctf/red_returned.wav" : "ctf/blue_returned.wav"); }
 +      if(!flag.noise2) { flag.noise2 = ((teamnumber) ? "ctf/red_capture.wav" : "ctf/blue_capture.wav"); } // blue team scores by capturing the red flag
 +      if(!flag.noise3) { flag.noise3 = "ctf/flag_respawn.wav"; } // if there is ever a team-based sound for this, update the code to match.
 +      if(!flag.noise4) { flag.noise4 = ((teamnumber) ? "ctf/red_dropped.wav" : "ctf/blue_dropped.wav"); }
 +      
 +      // precache
 +      precache_sound(flag.noise);
 +      precache_sound(flag.noise1);
 +      precache_sound(flag.noise2);
 +      precache_sound(flag.noise3);
 +      precache_sound(flag.noise4);
 +      precache_model(flag.model);
 +      precache_model("models/ctf/shield.md3");
 +      precache_model("models/ctf/shockwavetransring.md3");
 +
 +      // bot waypoints
 +      waypoint_spawnforitem_force(flag, flag.origin);
 +      flag.nearestwaypointtimeout = 0; // activate waypointing again
 +      flag.bot_basewaypoint = flag.nearestwaypoint;
 +
 +      // waypointsprites
 +      WaypointSprite_SpawnFixed(((teamnumber) ? "redbase" : "bluebase"), flag.origin + '0 0 64', flag, wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
 +      WaypointSprite_UpdateTeamRadar(flag.wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
 +
 +      // captureshield setup
 +      ctf_CaptureShield_Spawn(flag);
 +}
 +
 +
 +// ==============
 +// Hook Functions
 +// ==============
 +
 +// g_ctf_ignore_frags
 +
 +MUTATOR_HOOKFUNCTION(ctf_RemovePlayer)
 +{
 +      if(self.flagcarried) { ctf_Handle_Drop(self); }
 +      return 0;
 +}
 +
 +MUTATOR_HOOKFUNCTION(ctf_PlayerPreThink)
 +{
 +      entity flag;
 +      
 +      // initially clear items so they can be set as necessary later.
 +      self.items &~= (IT_RED_FLAG_CARRYING | IT_RED_FLAG_TAKEN | IT_RED_FLAG_LOST 
 +              | IT_BLUE_FLAG_CARRYING | IT_BLUE_FLAG_TAKEN | IT_BLUE_FLAG_LOST | IT_CTF_SHIELDED);
 +
 +      // item for stopping players from capturing the flag too often
 +      if(self.ctf_captureshielded)
 +              self.items |= IT_CTF_SHIELDED;
 +
 +      // scan through all the flags and notify the client about them 
 +      for (flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext)
 +      {
 +              if(flag.ctf_status == FLAG_CARRY)
 +                      if(flag.owner == self)
 +                              self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_CARRYING : IT_BLUE_FLAG_CARRYING); // carrying: self is currently carrying the flag
 +                      else 
 +                              self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_TAKEN : IT_BLUE_FLAG_TAKEN); // taken: someone on self's team is carrying the flag
 +              else if(flag.ctf_status == FLAG_DROPPED) 
 +                      self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_LOST : IT_BLUE_FLAG_LOST); // lost: the flag is dropped somewhere on the map
 +      }
 +      
 +      return 0;
 +}
 +
 +MUTATOR_HOOKFUNCTION(ctf_PlayerDamage) // for changing damage and force values that are applied to players in g_damage.qc
 +{     /*
 +      if(frag_attacker.flagcarried) // if the attacker is a flagcarrier
 +      {
 +              if(frag_target == frag_attacker) // damage done to yourself
 +              {
 +                      frag_damage *= autocvar_g_ctf_flagcarrier_selfdamagefactor;
 +                      frag_force *= autocvar_g_ctf_flagcarrier_selfforcefactor;
 +              }
 +              else // damage done to noncarriers
 +              {
 +                      frag_damage *= autocvar_g_ctf_flagcarrier_damagefactor;
 +                      frag_force *= autocvar_g_ctf_flagcarrier_forcefactor;
 +              }
 +      }*/
 +      return 0;
 +}
 +
 +MUTATOR_HOOKFUNCTION(ctf_GiveFragsForKill)
 +{
 +      frag_score = 0; // no frags counted in ctf
 +      return (g_ctf_ignore_frags); // you deceptive little bugger ;3 This needs to be true in order for this function to even count. 
 +}
 +
 +MUTATOR_HOOKFUNCTION(ctf_PlayerUseKey)
 +{
 +      if(autocvar_g_ctf_allow_drop)
 +              ctf_Handle_Drop(self);
 +              
 +      return 0;
 +}
 +
 +// ==========
 +// Spawnfuncs
 +// ==========
 +
 +/*QUAKED spawnfunc_info_player_team1 (1 0 0) (-16 -16 -24) (16 16 24)
 +CTF Starting point for a player in team one (Red).
 +Keys: "angle" viewing angle when spawning. */
 +void spawnfunc_info_player_team1()
 +{
 +      if(g_assault) { remove(self); return; }
 +      
 +      self.team = COLOR_TEAM1; // red
 +      spawnfunc_info_player_deathmatch();
 +}
 +
 +
 +/*QUAKED spawnfunc_info_player_team2 (1 0 0) (-16 -16 -24) (16 16 24)
 +CTF Starting point for a player in team two (Blue).
 +Keys: "angle" viewing angle when spawning. */
 +void spawnfunc_info_player_team2()
 +{
 +      if(g_assault) { remove(self); return; }
 +      
 +      self.team = COLOR_TEAM2; // blue
 +      spawnfunc_info_player_deathmatch();
 +}
 +
 +/*QUAKED spawnfunc_info_player_team3 (1 0 0) (-16 -16 -24) (16 16 24)
 +CTF Starting point for a player in team three (Yellow).
 +Keys: "angle" viewing angle when spawning. */
 +void spawnfunc_info_player_team3()
 +{
 +      if(g_assault) { remove(self); return; }
 +      
 +      self.team = COLOR_TEAM3; // yellow
 +      spawnfunc_info_player_deathmatch();
 +}
 +
 +
 +/*QUAKED spawnfunc_info_player_team4 (1 0 0) (-16 -16 -24) (16 16 24)
 +CTF Starting point for a player in team four (Purple).
 +Keys: "angle" viewing angle when spawning. */
 +void spawnfunc_info_player_team4()
 +{
 +      if(g_assault) { remove(self); return; }
 +      
 +      self.team = COLOR_TEAM4; // purple
 +      spawnfunc_info_player_deathmatch();
 +}
 +
 +/*QUAKED spawnfunc_item_flag_team1 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
 +CTF flag for team one (Red). Multiple flags are allowed.
 +Keys: 
 +"angle" Angle the flag will point (minus 90 degrees)... 
 +"model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
 +"noise" sound played when flag is picked up (default ctf/take.wav)...
 +"noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
 +"noise2" sound played when flag is captured (default ctf/redcapture.wav)...
 +"noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
 +void spawnfunc_item_flag_team1()
 +{
 +      if(!g_ctf) { remove(self); return; }
 +
 +      ctf_SetupFlag(1, self); // 1 = red
 +}
 +
 +/*QUAKED spawnfunc_item_flag_team2 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
 +CTF flag for team two (Blue). Multiple flags are allowed.
 +Keys: 
 +"angle" Angle the flag will point (minus 90 degrees)... 
 +"model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
 +"noise" sound played when flag is picked up (default ctf/take.wav)...
 +"noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
 +"noise2" sound played when flag is captured (default ctf/redcapture.wav)...
 +"noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
 +void spawnfunc_item_flag_team2()
 +{
 +      if(!g_ctf) { remove(self); return; }
 +
 +      ctf_SetupFlag(0, self); // the 0 is misleading, but -- 0 = blue.
 +}
 +
 +/*QUAKED spawnfunc_ctf_team (0 .5 .8) (-16 -16 -24) (16 16 32)
 +Team declaration for CTF gameplay, this allows you to decide what team names and control point models are used in your map.
 +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.
 +Keys:
 +"netname" Name of the team (for example Red, Blue, Green, Yellow, Life, Death, Offense, Defense, etc)...
 +"cnt" Scoreboard color of the team (for example 4 is red and 13 is blue)... */
 +void spawnfunc_ctf_team()
 +{
 +      if(!g_ctf) { remove(self); return; }
 +      
 +      self.classname = "ctf_team";
 +      self.team = self.cnt + 1;
 +}
 +
 +
 +// ==============
 +// Initialization
 +// ==============
 +
 +// code from here on is just to support maps that don't have flag and team entities
 +void ctf_SpawnTeam (string teamname, float teamcolor)
 +{
 +      entity oldself;
 +      oldself = self;
 +      self = spawn();
 +      self.classname = "ctf_team";
 +      self.netname = teamname;
 +      self.cnt = teamcolor;
 +
 +      spawnfunc_ctf_team();
 +
 +      self = oldself;
 +}
 +
 +void ctf_DelayedInit() // Do this check with a delay so we can wait for teams to be set up.
 +{
 +      // if no teams are found, spawn defaults
 +      if(find(world, classname, "ctf_team") == world)
 +      {
 +              print("NO TEAMS FOUND FOR CTF! creating them anyway.\n");
 +              ctf_SpawnTeam("Red", COLOR_TEAM1 - 1);
 +              ctf_SpawnTeam("Blue", COLOR_TEAM2 - 1);
 +      }
 +      
 +      ScoreRules_ctf();
 +}
 +
 +void ctf_Initialize()
 +{
 +      ctf_captimerecord = stof(db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time")));
 +
 +      ctf_captureshield_min_negscore = autocvar_g_ctf_shield_min_negscore;
 +      ctf_captureshield_max_ratio = autocvar_g_ctf_shield_max_ratio;
 +      ctf_captureshield_force = autocvar_g_ctf_shield_force;
 +
 +      //g_ctf_win_mode = cvar("g_ctf_win_mode");
 +      
 +      InitializeEntity(world, ctf_DelayedInit, INITPRIO_GAMETYPE);
 +}
 +
 +
 +MUTATOR_DEFINITION(gamemode_ctf)
 +{
 +      MUTATOR_HOOK(MakePlayerObserver, ctf_RemovePlayer, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(ClientDisconnect, ctf_RemovePlayer, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(PlayerDies, ctf_RemovePlayer, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(GiveFragsForKill, ctf_GiveFragsForKill, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(PlayerPreThink, ctf_PlayerPreThink, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(PlayerDamage_Calculate, ctf_PlayerDamage, CBC_ORDER_ANY);
 +      MUTATOR_HOOK(PlayerUseKey, ctf_PlayerUseKey, CBC_ORDER_ANY);
 +      //MUTATOR_HOOK(PlayerPowerups, ctf_PlayerPowerups, CBC_ORDER_ANY);
 +
 +      MUTATOR_ONADD
 +      {
 +              if(time > 1) // game loads at time 1
 +                      error("This is a game type and it cannot be added at runtime.");
 +              g_ctf = 1;
 +              ctf_Initialize();
 +      }
 +
 +      MUTATOR_ONREMOVE
 +      {
 +              g_ctf = 0;
 +              error("This is a game type and it cannot be removed at runtime.");
 +      }
 +
 +      return 0;
 +}
index 8e80674,0000000..748cc0a
mode 100644,000000..100644
--- /dev/null
@@@ -1,10 -1,0 +1,44 @@@
 +// these are needed since mutators are compiled last
 +
++// used in cheats.qc
++void ctf_RespawnFlag(entity flag)
++
 +// used in t_quake3.qc
 +void spawnfunc_info_player_team1();
 +void spawnfunc_info_player_team2();
 +void spawnfunc_info_player_team3();
 +void spawnfunc_info_player_team4();
 +void spawnfunc_item_flag_team1();
 +void spawnfunc_item_flag_team2();
 +void spawnfunc_ctf_team();
++
++// flag constants 
++#define FLAG_MIN (PL_MIN + '0 0 -13')
++#define FLAG_MAX (PL_MAX + '0 0 -13')
++#define FLAG_CARRY_POS '-15 0 7'
++
++.entity bot_basewaypoint; // flag waypointsprite
++.entity wps_flagbase; 
++.entity wps_flagcarrier;
++.entity wps_flagdropped;
++
++entity ctf_worldflaglist; // CTF flags in the map
++.entity ctf_worldflagnext;
++
++.vector ctf_spawnorigin; // stored vector for where the flag is placed on the map itself. 
++
++float ctf_captimerecord; // record time for capturing the flag
++.float ctf_pickuptime;
++.float ctf_pickupid;
++.float ctf_dropperid; // don't allow spam of dropping the flag
++.float ctf_droptime;
++.float ctf_status; // status of the flag (FLAG_BASE, FLAG_DROPPED, FLAG_CARRY declared globally)
++
++
++.float next_take_time; // Delay between when the person can pick up a flag // is this obsolete from the stuff above?
++
++// CaptureShield: If the player is too bad to be allowed to capture, shield them from taking the flag.
++.float ctf_captureshielded; // set to 1 if the player is too bad to be allowed to capture
++float ctf_captureshield_min_negscore; // punish at -20 points
++float ctf_captureshield_max_ratio; // punish at most 30% of each team
++float ctf_captureshield_force; // push force of the shield
index 0000000,8554a12..da3fd75
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,983 +1,983 @@@
 -      ball.dropperid = plyr.playerid;
+ float autocvar_g_nexball_safepass_turnrate;
+ float autocvar_g_nexball_safepass_maxdist;
+ float autocvar_g_nexball_safepass_holdtime;
+ float autocvar_g_nexball_viewmodel_scale;
+ float autocvar_g_nexball_tackling;
+ vector autocvar_g_nexball_viewmodel_offset;
+ void basketball_touch();
+ void football_touch();
+ void ResetBall();
+ #define NBM_NONE 0
+ #define NBM_FOOTBALL 2
+ #define NBM_BASKETBALL 4
+ float nexball_mode;
+ float OtherTeam(float t)  //works only if there are two teams on the map!
+ {
+       entity e;
+       e = find(world, classname, "nexball_team");
+       if(e.team == t)
+               e = find(e, classname, "nexball_team");
+       return e.team;
+ }
+ void LogNB(string mode, entity actor)
+ {
+       string s;
+       if(!autocvar_sv_eventlog)
+               return;
+       s = strcat(":nexball:", mode);
+       if(actor != world)
+               s = strcat(s, ":", ftos(actor.playerid));
+       GameLogEcho(s);
+ }
+ void ball_restart(void)
+ {
+       if(self.owner)
+               DropBall(self, self.owner.origin, '0 0 0');
+       ResetBall();
+ }
+ void nexball_setstatus(void)
+ {
+       entity oldself;
+       self.items &~= IT_KEY1;
+       if(self.ballcarried)
+       {
+               if(self.ballcarried.teamtime && (self.ballcarried.teamtime < time))
+               {
+                       bprint("The ", ColoredTeamName(self.team), " held the ball for too long.\n");
+                       oldself = self;
+                       self = self.ballcarried;
+                       DropBall(self, self.owner.origin, '0 0 0');
+                       ResetBall();
+                       self = oldself;
+               }
+               else
+                       self.items |= IT_KEY1;
+       }
+ }
+ void relocate_nexball(void)
+ {
+       tracebox(self.origin, BALL_MINS, BALL_MAXS, self.origin, TRUE, self);
+       if(trace_startsolid)
+       {
+               vector o;
+               o = self.origin;
+               if(!move_out_of_solid(self))
+                       objerror("could not get out of solid at all!");
+               print("^1NOTE: this map needs FIXING. ", self.classname, " at ", vtos(o - '0 0 1'));
+               print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
+               print(" ", ftos(self.origin_y - o_y));
+               print(" ", ftos(self.origin_z - o_z), "'\n");
+               self.origin = o;
+       }
+ }
+ void DropOwner(void)
+ {
+       entity ownr;
+       ownr = self.owner;
+       DropBall(self, ownr.origin, ownr.velocity);
+       makevectors(ownr.v_angle_y * '0 1 0');
+       ownr.velocity += ('0 0 0.75' - v_forward) * 1000;
+       ownr.flags &~= FL_ONGROUND;
+ }
+ void GiveBall(entity plyr, entity ball)
+ {
+       entity ownr;
+       if((ownr = ball.owner))
+       {
+               ownr.effects &~= autocvar_g_nexball_basketball_effects_default;
+               ownr.ballcarried = world;
+               if(ownr.metertime)
+               {
+                       ownr.metertime = 0;
+                       ownr.weaponentity.state = WS_READY;
+               }
+               WaypointSprite_Kill(ownr.waypointsprite_attachedforcarrier);
+       }
+       else
+       {
+               WaypointSprite_Kill(ball.waypointsprite_attachedforcarrier);
+       }
+       
+       //setattachment(ball, plyr, "");
+       setorigin(ball, plyr.origin + plyr.view_ofs);
+       if(ball.team != plyr.team)
+               ball.teamtime = time + autocvar_g_nexball_basketball_delay_hold_forteam;
+       ball.owner = ball.pusher = plyr; //"owner" is set to the player carrying, "pusher" to the last player who touched it
+       ball.team = plyr.team;
+       plyr.ballcarried = ball;
 -      if(!self.cnt && other.classname == "player" && (other.playerid != self.dropperid || time > self.ctf_droptime + autocvar_g_nexball_delay_collect))
++      ball.ctf_dropperid = plyr.playerid;
+       plyr.effects |= autocvar_g_nexball_basketball_effects_default;
+       ball.effects &~= autocvar_g_nexball_basketball_effects_default;
+       ball.velocity = '0 0 0';
+       ball.movetype = MOVETYPE_NONE;
+       ball.touch = SUB_Null;
+       ball.effects |= EF_NOSHADOW;
+       ball.scale = 1; // scale down.
+       WaypointSprite_AttachCarrier("nb-ball", plyr, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR);
+       WaypointSprite_UpdateRule(plyr.waypointsprite_attachedforcarrier, 0, SPRITERULE_DEFAULT);
+       if(autocvar_g_nexball_basketball_delay_hold)
+       {
+               ball.think = DropOwner;
+               ball.nextthink = time + autocvar_g_nexball_basketball_delay_hold;
+       }
+       
+     ownr = self;
+     self = plyr;    
+     self.weaponentity.weapons = self.weapons;
+     self.weaponentity.switchweapon = self.weapon;
+     self.weapons = W_WeaponBit(WEP_PORTO);      
+     weapon_action(WEP_PORTO, WR_RESETPLAYER);
+     self.switchweapon = WEP_PORTO;
+     W_SwitchWeapon(WEP_PORTO);
+     self = ownr;
+ }
+ void DropBall(entity ball, vector org, vector vel)
+ {
+       ball.effects |= autocvar_g_nexball_basketball_effects_default;
+       ball.effects &~= EF_NOSHADOW;
+       ball.owner.effects &~= autocvar_g_nexball_basketball_effects_default;
+       setattachment(ball, world, "");
+       setorigin(ball, org);
+       ball.movetype = MOVETYPE_BOUNCE;
+       ball.flags &~= FL_ONGROUND;
+       ball.scale = ball_scale;
+       ball.velocity = vel;
+       ball.ctf_droptime = time;
+       ball.touch = basketball_touch;
+       ball.think = ResetBall;
+       ball.nextthink = min(time + autocvar_g_nexball_delay_idle, ball.teamtime);
+       if(ball.owner.metertime)
+       {
+               ball.owner.metertime = 0;
+               ball.owner.weaponentity.state = WS_READY;
+       }
+       WaypointSprite_Kill(ball.owner.waypointsprite_attachedforcarrier);
+       WaypointSprite_Spawn("nb-ball", 0, 0, ball, '0 0 64', world, ball.team, ball, waypointsprite_attachedforcarrier, FALSE, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR); // no health bar please
+       WaypointSprite_UpdateRule(ball.waypointsprite_attachedforcarrier, 0, SPRITERULE_DEFAULT);
+       ball.owner.ballcarried = world;
+       ball.owner = world;
+ }
+ void InitBall(void)
+ {
+       if(gameover) return;
+       self.flags &~= FL_ONGROUND;
+       self.movetype = MOVETYPE_BOUNCE;
+       if(self.classname == "nexball_basketball")
+               self.touch = basketball_touch;
+       else if(self.classname == "nexball_football")
+               self.touch = football_touch;
+       self.cnt = 0;
+       self.think = ResetBall;
+       self.nextthink = time + autocvar_g_nexball_delay_idle + 3;
+       self.teamtime = 0;
+       self.pusher = world;
+       self.team = FALSE;
+       sound(self, CH_TRIGGER, self.noise1, VOL_BASE, ATTN_NORM);
+       WaypointSprite_Ping(self.waypointsprite_attachedforcarrier);
+       LogNB("init", world);
+ }
+ void ResetBall(void)
+ {
+       if(self.cnt < 2)    // step 1
+       {
+               if(time == self.teamtime)
+                       bprint("The ", ColoredTeamName(self.team), " held the ball for too long.\n");
+               self.touch = SUB_Null;
+               self.movetype = MOVETYPE_NOCLIP;
+               self.velocity = '0 0 0'; // just in case?
+               if(!self.cnt)
+                       LogNB("resetidle", world);
+               self.cnt = 2;
+               self.nextthink = time;
+       }
+       else if(self.cnt < 4)      // step 2 and 3
+       {
+ //            dprint("Step ", ftos(self.cnt), ": Calculated velocity: ", vtos(self.spawnorigin - self.origin), ", time: ", ftos(time), "\n");
+               self.velocity = (self.spawnorigin - self.origin) * (self.cnt - 1); // 1 or 0.5 second movement
+               self.nextthink = time + 0.5;
+               self.cnt += 1;
+       }
+       else     // step 4
+       {
+ //            dprint("Step 4: time: ", ftos(time), "\n");
+               if(vlen(self.origin - self.spawnorigin) > 10)  // should not happen anymore
+                       dprint("The ball moved too far away from its spawn origin.\nOffset: ",
+                                  vtos(self.origin - self.spawnorigin), " Velocity: ", vtos(self.velocity), "\n");
+               self.velocity = '0 0 0';
+               setorigin(self, self.spawnorigin); // make sure it's positioned correctly anyway
+               self.movetype = MOVETYPE_NONE;
+               self.think = InitBall;
+               self.nextthink = max(time, game_starttime) + autocvar_g_nexball_delay_start;
+       }
+ }
+ void football_touch(void)
+ {
+       if(other.solid == SOLID_BSP)
+       {
+               if(time > self.lastground + 0.1)
+               {
+                       sound(self, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NORM);
+                       self.lastground = time;
+               }
+               if(vlen(self.velocity) && !self.cnt)
+                       self.nextthink = time + autocvar_g_nexball_delay_idle;
+               return;
+       }
+       if(other.classname != "player")
+               return;
+       if(other.health < 1)
+               return;
+       if(!self.cnt)
+               self.nextthink = time + autocvar_g_nexball_delay_idle;
+       self.pusher = other;
+       self.team = other.team;
+       if(autocvar_g_nexball_football_physics == -1)    // MrBougo try 1, before decompiling Rev's original
+       {
+               if(vlen(other.velocity))
+                       self.velocity = other.velocity * 1.5 + '0 0 1' * autocvar_g_nexball_football_boost_up;
+       }
+       else if(autocvar_g_nexball_football_physics == 1)      // MrBougo's modded Rev style: partially independant of the height of the aiming point
+       {
+               makevectors(other.v_angle);
+               self.velocity = other.velocity + v_forward * autocvar_g_nexball_football_boost_forward + '0 0 1' * autocvar_g_nexball_football_boost_up;
+       }
+       else if(autocvar_g_nexball_football_physics == 2)      // 2nd mod try: totally independant. Really playable!
+       {
+               makevectors(other.v_angle_y * '0 1 0');
+               self.velocity = other.velocity + v_forward * autocvar_g_nexball_football_boost_forward + v_up * autocvar_g_nexball_football_boost_up;
+       }
+       else     // Revenant's original style (from the original mod's disassembly, acknowledged by Revenant)
+       {
+               makevectors(other.v_angle);
+               self.velocity = other.velocity + v_forward * autocvar_g_nexball_football_boost_forward + v_up * autocvar_g_nexball_football_boost_up;
+       }
+       self.avelocity = -250 * v_forward;  // maybe there is a way to make it look better?
+ }
+ void basketball_touch(void)
+ {
+       if(other.ballcarried)
+       {
+               football_touch();
+               return;
+       }
++      if(!self.cnt && other.classname == "player" && (other.playerid != self.ctf_dropperid || time > self.ctf_droptime + autocvar_g_nexball_delay_collect))
+       {
+               if(other.health <= 0)
+                       return;
+               LogNB("caught", other);
+               GiveBall(other, self);
+       }
+       else if(other.solid == SOLID_BSP)
+       {
+               sound(self, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NORM);
+               if(vlen(self.velocity) && !self.cnt)
+                       self.nextthink = min(time + autocvar_g_nexball_delay_idle, self.teamtime);
+       }
+ }
+ void GoalTouch(void)
+ {
+       entity ball;
+       float isclient, pscore, otherteam;
+       string pname;
+       if(gameover) return;
+       if((self.spawnflags & GOAL_TOUCHPLAYER) && other.ballcarried)
+               ball = other.ballcarried;
+       else
+               ball = other;
+       if(ball.classname != "nexball_basketball")
+               if(ball.classname != "nexball_football")
+                       return;
+       if((!ball.pusher && self.team != GOAL_OUT) || ball.cnt)
+               return;
+       EXACTTRIGGER_TOUCH;
+       if(nb_teams == 2)
+               otherteam = OtherTeam(ball.team);
+       if((isclient = ball.pusher.flags & FL_CLIENT))
+               pname = ball.pusher.netname;
+       else
+               pname = "Someone (?)";
+       if(ball.team == self.team)         //owngoal (regular goals)
+       {
+               LogNB("owngoal", ball.pusher);
+               bprint("Boo! ", pname, "^7 scored a goal against their own team!\n");
+               pscore = -1;
+       }
+       else if(self.team == GOAL_FAULT)
+       {
+               LogNB("fault", ball.pusher);
+               if(nb_teams == 2)
+                       bprint(ColoredTeamName(otherteam), " gets a point due to ", pname, "^7's silliness.\n");
+               else
+                       bprint(ColoredTeamName(ball.team), " loses a point due to ", pname, "^7's silliness.\n");
+               pscore = -1;
+       }
+       else if(self.team == GOAL_OUT)
+       {
+               LogNB("out", ball.pusher);
+               if((self.spawnflags & GOAL_TOUCHPLAYER) && ball.owner)
+                       bprint(pname, "^7 went out of bounds.\n");
+               else
+                       bprint("The ball was returned.\n");
+               pscore = 0;
+       }
+       else                               //score
+       {
+               LogNB(strcat("goal:", ftos(self.team)), ball.pusher);
+               bprint("Goaaaaal! ", pname, "^7 scored a point for the ", ColoredTeamName(ball.team), ".\n");
+               pscore = 1;
+       }
+       sound(ball, CH_TRIGGER, self.noise, VOL_BASE, ATTN_NONE);
+       if(ball.team && pscore)
+       {
+               if(nb_teams == 2 && pscore < 0)
+                       TeamScore_AddToTeam(otherteam, ST_NEXBALL_GOALS, -pscore);
+               else
+                       TeamScore_AddToTeam(ball.team, ST_NEXBALL_GOALS, pscore);
+       }
+       if(isclient)
+       {
+               if(pscore > 0)
+                       PlayerScore_Add(ball.pusher, SP_NEXBALL_GOALS, pscore);
+               else if(pscore < 0)
+                       PlayerScore_Add(ball.pusher, SP_NEXBALL_FAULTS, -pscore);
+       }
+       if(ball.owner)  // Happens on spawnflag GOAL_TOUCHPLAYER
+               DropBall(ball, ball.owner.origin, ball.owner.velocity);
+       WaypointSprite_Ping(ball.waypointsprite_attachedforcarrier);
+       ball.cnt = 1;
+       ball.think = ResetBall;
+       if(ball.classname == "nexball_basketball")
+               ball.touch = football_touch; // better than SUB_Null: football control until the ball gets reset
+       ball.nextthink = time + autocvar_g_nexball_delay_goal * (self.team != GOAL_OUT);
+ }
+ //=======================//
+ //       team ents       //
+ //=======================//
+ void spawnfunc_nexball_team(void)
+ {
+       if(!g_nexball)
+       {
+               remove(self);
+               return;
+       }
+       self.team = self.cnt + 1;
+ }
+ void nb_spawnteam(string teamname, float teamcolor)
+ {
+       dprint("^2spawned team ", teamname, "\n");
+       entity e;
+       e = spawn();
+       e.classname = "nexball_team";
+       e.netname = teamname;
+       e.cnt = teamcolor;
+       e.team = e.cnt + 1;
+       nb_teams += 1;
+ }
+ void nb_spawnteams(void)
+ {
+       float t_r, t_b, t_y, t_p;
+       entity e;
+       for(e = world; (e = find(e, classname, "nexball_goal"));)
+       {
+               switch(e.team)
+               {
+               case COLOR_TEAM1:
+                       if(!t_r)
+                       {
+                               nb_spawnteam("Red", e.team-1)   ;
+                               t_r = 1;
+                       }
+                       break;
+               case COLOR_TEAM2:
+                       if(!t_b)
+                       {
+                               nb_spawnteam("Blue", e.team-1)  ;
+                               t_b = 1;
+                       }
+                       break;
+               case COLOR_TEAM3:
+                       if(!t_y)
+                       {
+                               nb_spawnteam("Yellow", e.team-1);
+                               t_y = 1;
+                       }
+                       break;
+               case COLOR_TEAM4:
+                       if(!t_p)
+                       {
+                               nb_spawnteam("Pink", e.team-1)  ;
+                               t_p = 1;
+                       }
+                       break;
+               }
+       }
+ }
+ void nb_delayedinit(void)
+ {
+       if(find(world, classname, "nexball_team") == world)
+               nb_spawnteams();
+       ScoreRules_nexball(nb_teams);
+ }
+ //=======================//
+ //      spawnfuncs       //
+ //=======================//
+ void SpawnBall(void)
+ {
+       if(!g_nexball)
+       {
+               remove(self);
+               return;
+       }
+ //    balls += 4; // using the remaining bits to count balls will leave more than the max edict count, so it's fine
+       if(!self.model)
+       {
+               self.model = "models/nexball/ball.md3";
+               self.scale = 1.3;
+       }
+       precache_model(self.model);
+       setmodel(self, self.model);
+       setsize(self, BALL_MINS, BALL_MAXS);
+       ball_scale = self.scale;
+       relocate_nexball();
+       self.spawnorigin = self.origin;
+       self.effects = self.effects | EF_LOWPRECISION;
+       if(cvar(strcat("g_", self.classname, "_trail")))  //nexball_basketball :p
+       {
+               self.glow_color = autocvar_g_nexball_trail_color;
+               self.glow_trail = TRUE;
+       }
+       self.movetype = MOVETYPE_FLY;
+       if(!autocvar_g_nexball_sound_bounce)
+               self.noise = "";
+       else if(!self.noise)
+               self.noise = "sound/nexball/bounce.wav";
+       //bounce sound placeholder (FIXME)
+       if(!self.noise1)
+               self.noise1 = "sound/nexball/drop.wav";
+       //ball drop sound placeholder (FIXME)
+       if(!self.noise2)
+               self.noise2 = "sound/nexball/steal.wav";
+       //stealing sound placeholder (FIXME)
+       if(self.noise) precache_sound(self.noise);
+       precache_sound(self.noise1);
+       precache_sound(self.noise2);
+       WaypointSprite_AttachCarrier("nb-ball", self, RADARICON_FLAGCARRIER, BALL_SPRITECOLOR); // the ball's team is not set yet, no rule update needed
+       self.reset = ball_restart;
+       self.think = InitBall;
+       self.nextthink = game_starttime + autocvar_g_nexball_delay_start;
+ }
+ void spawnfunc_nexball_basketball(void)
+ {
+     nexball_mode |= NBM_BASKETBALL;
+       self.classname = "nexball_basketball";
+       if not(balls & BALL_BASKET)
+       {
+               /*
+               CVTOV(g_nexball_basketball_effects_default);
+               CVTOV(g_nexball_basketball_delay_hold);
+               CVTOV(g_nexball_basketball_delay_hold_forteam);
+               CVTOV(g_nexball_basketball_teamsteal);
+               */
+               autocvar_g_nexball_basketball_effects_default = autocvar_g_nexball_basketball_effects_default & BALL_EFFECTMASK;
+       }
+       if(!self.effects)
+               self.effects = autocvar_g_nexball_basketball_effects_default;
+       self.solid = SOLID_TRIGGER;
+       balls |= BALL_BASKET;
+       self.bouncefactor = autocvar_g_nexball_basketball_bouncefactor;
+       self.bouncestop = autocvar_g_nexball_basketball_bouncestop;
+       SpawnBall();
+ }
+ void spawnfunc_nexball_football(void)
+ {
+     nexball_mode |= NBM_FOOTBALL;
+       self.classname = "nexball_football";
+       self.solid = SOLID_TRIGGER;
+       balls |= BALL_FOOT;
+       self.bouncefactor = autocvar_g_nexball_football_bouncefactor;
+       self.bouncestop = autocvar_g_nexball_football_bouncestop;
+       SpawnBall();
+ }
+ void SpawnGoal(void)
+ {
+       if(!g_nexball)
+       {
+               remove(self);
+               return;
+       }
+       EXACTTRIGGER_INIT;
+       self.classname = "nexball_goal";
+       if(!self.noise)
+               self.noise = "ctf/respawn.wav";
+       precache_sound(self.noise);
+       self.touch = GoalTouch;
+ }
+ void spawnfunc_nexball_redgoal(void)
+ {
+       self.team = COLOR_TEAM1;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_bluegoal(void)
+ {
+       self.team = COLOR_TEAM2;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_yellowgoal(void)
+ {
+       self.team = COLOR_TEAM3;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_pinkgoal(void)
+ {
+       self.team = COLOR_TEAM4;
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_fault(void)
+ {
+       self.team = GOAL_FAULT;
+       if(!self.noise)
+               self.noise = "misc/typehit.wav";
+       SpawnGoal();
+ }
+ void spawnfunc_nexball_out(void)
+ {
+       self.team = GOAL_OUT;
+       if(!self.noise)
+               self.noise = "misc/typehit.wav";
+       SpawnGoal();
+ }
+ //
+ //Spawnfuncs preserved for compatibility
+ //
+ void spawnfunc_ball(void)
+ {
+       spawnfunc_nexball_football();
+ }
+ void spawnfunc_ball_football(void)
+ {
+       spawnfunc_nexball_football();
+ }
+ void spawnfunc_ball_basketball(void)
+ {
+       spawnfunc_nexball_basketball();
+ }
+ // The "red goal" is defended by blue team. A ball in there counts as a point for red.
+ void spawnfunc_ball_redgoal(void)
+ {
+       spawnfunc_nexball_bluegoal();    // I blame Revenant
+ }
+ void spawnfunc_ball_bluegoal(void)
+ {
+       spawnfunc_nexball_redgoal();    // but he didn't mean to cause trouble :p
+ }
+ void spawnfunc_ball_fault(void)
+ {
+       spawnfunc_nexball_fault();
+ }
+ void spawnfunc_ball_bound(void)
+ {
+       spawnfunc_nexball_out();
+ }
+ //=======================//
+ //      Weapon code      //
+ //=======================//
+ void W_Nexball_Think()
+ {
+     //dprint("W_Nexball_Think\n");
+     //vector new_dir = steerlib_arrive(self.enemy.origin, 2500);
+     vector new_dir = normalize(self.enemy.origin - self.origin);
+     vector old_dir = normalize(self.velocity);     
+     float _speed = vlen(self.velocity);    
+     vector new_vel = normalize(old_dir + (new_dir * autocvar_g_nexball_safepass_turnrate)) * _speed;
+     //vector new_vel = (new_dir * autocvar_g_nexball_safepass_turnrate
+     
+     self.velocity = new_vel;
+     
+     self.nextthink = time;
+ }
+ void W_Nexball_Touch(void)
+ {
+       entity ball, attacker;
+       attacker = self.owner;
+     //self.think = SUB_Null;
+     //self.enemy = world;
+     
+       PROJECTILE_TOUCH;
+       if(attacker.team != other.team || autocvar_g_nexball_basketball_teamsteal)
+               if((ball = other.ballcarried) && (attacker.classname == "player"))
+               {
+                       other.velocity = other.velocity + normalize(self.velocity) * other.damageforcescale * autocvar_g_balance_nexball_secondary_force;
+                       other.flags &~= FL_ONGROUND;
+                       if(!attacker.ballcarried)
+                       {
+                               LogNB("stole", attacker);
+                               sound(other, CH_TRIGGER, ball.noise2, VOL_BASE, ATTN_NORM);
+                               if(attacker.team == other.team && time > attacker.teamkill_complain)
+                               {
+                                       attacker.teamkill_complain = time + 5;
+                                       attacker.teamkill_soundtime = time + 0.4;
+                                       attacker.teamkill_soundsource = other;
+                               }
+                               GiveBall(attacker, other.ballcarried);
+                       }
+               }
+       remove(self);
+ }
+ void W_Nexball_Attack(float t)
+ {
+       entity ball;
+       float mul, mi, ma;
+       if(!(ball = self.ballcarried))
+               return;
+       W_SetupShot(self, FALSE, 4, "nexball/shoot1.wav", CH_WEAPON_A, 0);
+       tracebox(w_shotorg, BALL_MINS, BALL_MAXS, w_shotorg, MOVE_WORLDONLY, world);
+       if(trace_startsolid)
+       {
+               if(self.metertime)
+                       self.metertime = 0; // Shot failed, hide the power meter
+               return;
+       }
+       //Calculate multiplier
+       if(t < 0)
+               mul = 1;
+       else
+       {
+               mi = autocvar_g_nexball_basketball_meter_minpower;
+               ma = max(mi, autocvar_g_nexball_basketball_meter_maxpower); // avoid confusion
+               //One triangle wave period with 1 as max
+               mul = 2 * mod(t, g_nexball_meter_period) / g_nexball_meter_period;
+               if(mul > 1)
+                       mul = 2 - mul;
+               mul = mi + (ma - mi) * mul; // range from the minimal power to the maximal power
+       }
+       
+     DropBall(ball, w_shotorg, W_CalculateProjectileVelocity(self.velocity, w_shotdir * autocvar_g_balance_nexball_primary_speed * mul, FALSE));
+       
+       //TODO: use the speed_up cvar too ??
+ }
+ void W_Nexball_Attack2(void)
+ {
+       if(self.ballcarried.enemy)
+       {
+           entity _ball = self.ballcarried;
+         W_SetupShot(self, FALSE, 4, "nexball/shoot1.wav", CH_WEAPON_A, 0);
+           DropBall(_ball, w_shotorg, trigger_push_calculatevelocity(_ball.origin, _ball.enemy, 32));
+         _ball.think = W_Nexball_Think;
+         _ball.nextthink = time;
+           return;
+       }
+     
+     if(!autocvar_g_nexball_tackling)
+         return;
+       
+       entity missile;
+       if(!(balls & BALL_BASKET))
+               return;
+       W_SetupShot(self, FALSE, 2, "nexball/shoot2.wav", CH_WEAPON_A, 0);
+ //    pointparticles(particleeffectnum("grenadelauncher_muzzleflash"), w_shotorg, w_shotdir * 1000, 1);
+       missile = spawn();
+       missile.owner = self;
+       missile.classname = "ballstealer";
+       missile.movetype = MOVETYPE_FLY;
+       PROJECTILE_MAKETRIGGER(missile);
+       setmodel(missile, "models/elaser.mdl");  // precision set below
+       setsize(missile, '0 0 0', '0 0 0');
+       setorigin(missile, w_shotorg);
+       W_SetupProjectileVelocity(missile, autocvar_g_balance_nexball_secondary_speed, 0);
+       missile.angles = vectoangles(missile.velocity);
+       missile.touch = W_Nexball_Touch;
+       missile.think = SUB_Remove;
+       missile.nextthink = time + autocvar_g_balance_nexball_secondary_lifetime; //FIXME: use a distance instead?
+       missile.effects = EF_BRIGHTFIELD | EF_LOWPRECISION;
+       missile.flags = FL_PROJECTILE;
+ }
+ var const float() nullfunc;
+ float ball_customize()
+ {
+     if(!self.owner)
+     {
+         self.effects &~= EF_FLAME;
+         self.scale = 1;
+         self.customizeentityforclient = nullfunc;
+         return TRUE;
+     }        
+     
+     if(other == self.owner)
+     {
+         self.scale = autocvar_g_nexball_viewmodel_scale;
+         if(self.enemy)
+             self.effects |= EF_FLAME;
+         else
+             self.effects &~= EF_FLAME;
+     }    
+     else
+     {
+         self.effects &~= EF_FLAME;
+         self.scale = 1;
+     }
+         
+     return TRUE;
+ }
+ float w_nexball_weapon(float req)
+ {
+       if(req == WR_THINK)
+       {
+               if(self.BUTTON_ATCK)
+                       if(weapon_prepareattack(0, autocvar_g_balance_nexball_primary_refire))
+                               if(autocvar_g_nexball_basketball_meter)
+                               {
+                                       if(self.ballcarried && !self.metertime)
+                                               self.metertime = time;
+                                       else
+                                               weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+                               }
+                               else
+                               {
+                                       W_Nexball_Attack(-1);
+                                       weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+                               }
+               if(self.BUTTON_ATCK2)
+                       if(weapon_prepareattack(1, autocvar_g_balance_nexball_secondary_refire))
+                       {
+                               W_Nexball_Attack2();
+                               weapon_thinkf(WFRAME_FIRE2, autocvar_g_balance_nexball_secondary_animtime, w_ready);
+                       }
+               if(!self.BUTTON_ATCK && self.metertime && self.ballcarried)
+               {
+                       W_Nexball_Attack(time - self.metertime);
+                       // DropBall or stealing will set metertime back to 0
+                       weapon_thinkf(WFRAME_FIRE1, autocvar_g_balance_nexball_primary_animtime, w_ready);
+               }
+       }
+       else if(req == WR_PRECACHE)
+       {
+               precache_model("models/weapons/g_porto.md3");
+               precache_model("models/weapons/v_porto.md3");
+               precache_model("models/weapons/h_porto.iqm");
+               precache_model("models/elaser.mdl");
+               precache_sound("nexball/shoot1.wav");
+               precache_sound("nexball/shoot2.wav");
+               precache_sound("misc/typehit.wav");
+       }
+       else if(req == WR_SETUP)
+               weapon_setup(WEP_PORTO);
+       else if(req == WR_SUICIDEMESSAGE)
+       {
+               w_deathtypestring = "is a weirdo";
+       }
+       else if(req == WR_KILLMESSAGE)
+       {
+               w_deathtypestring = "got killed by #'s black magic";
+       }
+       // No need to check WR_CHECKAMMO* or WR_AIM, it should always return TRUE
+       return TRUE;
+ }
+ MUTATOR_HOOKFUNCTION(nexball_BallDrop)
+ {
+       if(self.ballcarried && g_nexball)
+               DropBall(self.ballcarried, self.origin, self.velocity);
+       return 0;
+ }
+ MUTATOR_HOOKFUNCTION(nexball_BuildMutatorsString)
+ {
+       ret_string = strcat(ret_string, ":NB");
+       return 0;
+ }
+ MUTATOR_HOOKFUNCTION(nexball_BuildMutatorsPrettyString)
+ {
+       ret_string = strcat(ret_string, ", NexBall");
+       return 0;
+ }
+ MUTATOR_HOOKFUNCTION(nexball_PlayerPreThink)
+ {
+     makevectors(self.v_angle);
+     if(nexball_mode & NBM_BASKETBALL)
+     {        
+         if(self.ballcarried)
+         {
+             // 'view ball'
+             self.ballcarried.velocity = self.velocity;            
+             self.ballcarried.customizeentityforclient = ball_customize;
+             
+             setorigin(self.ballcarried, self.origin + self.view_ofs + 
+                       v_forward * autocvar_g_nexball_viewmodel_offset_x + 
+                       v_right * autocvar_g_nexball_viewmodel_offset_y + 
+                       v_up * autocvar_g_nexball_viewmodel_offset_z);    
+                       
+             // 'safe passing'
+             if(autocvar_g_nexball_safepass_maxdist)
+             {
+                 if(self.ballcarried.wait < time && self.ballcarried.enemy)
+                 {
+                     //centerprint(self, sprintf("Lost lock on %s", self.ballcarried.enemy.netname));
+                     self.ballcarried.enemy = world;
+                 }
+                     
+                 
+                 //tracebox(self.origin + self.view_ofs, '-2 -2 -2', '2 2 2', self.origin + self.view_ofs + v_forward * autocvar_g_nexball_safepass_maxdist);
+                 crosshair_trace(self);
+                 if( trace_ent && 
+                     trace_ent.flags & FL_CLIENT &&
+                     trace_ent.deadflag == DEAD_NO &&
+                     trace_ent.team == self.team &&
+                     vlen(trace_ent.origin - self.origin) <= autocvar_g_nexball_safepass_maxdist )
+                 {
+                     
+                     //if(self.ballcarried.enemy != trace_ent)
+                     //    centerprint(self, sprintf("Locked to %s", trace_ent.netname));
+                     self.ballcarried.enemy = trace_ent;
+                     self.ballcarried.wait = time + autocvar_g_nexball_safepass_holdtime;
+                     
+                     
+                 }
+             }
+         }
+         else
+         {            
+             if(self.weaponentity.weapons)
+             {
+                 self.weapons = self.weaponentity.weapons;        
+                 weapon_action(WEP_PORTO, WR_RESETPLAYER);
+                 self.switchweapon = self.weaponentity.switchweapon;
+                 W_SwitchWeapon(self.switchweapon);
+                 
+                 self.weaponentity.weapons = 0;
+             }
+         }
+         
+     }
+     return FALSE;
+ }
+ MUTATOR_HOOKFUNCTION(nexball_PlayerSpawn)
+ {    
+     self.weaponentity.weapons = 0;
+     
+     if(nexball_mode & NBM_BASKETBALL)
+         self.weapons |= W_WeaponBit(WEP_PORTO);
+     else
+         self.weapons = 0; //    W_WeaponBit(WEP_PORTO);
+     return FALSE;
+ }
+ MUTATOR_DEFINITION(gamemode_nexball)
+ {
+       MUTATOR_HOOK(PlayerDies, nexball_BallDrop, CBC_ORDER_ANY);
+       MUTATOR_HOOK(MakePlayerObserver, nexball_BallDrop, CBC_ORDER_ANY);
+       MUTATOR_HOOK(ClientDisconnect, nexball_BallDrop, CBC_ORDER_ANY);
+       MUTATOR_HOOK(BuildMutatorsPrettyString, nexball_BuildMutatorsPrettyString, CBC_ORDER_ANY);
+       MUTATOR_HOOK(BuildMutatorsString, nexball_BuildMutatorsString, CBC_ORDER_ANY);
+       MUTATOR_HOOK(PlayerSpawn, nexball_PlayerSpawn, CBC_ORDER_ANY);
+       MUTATOR_HOOK(PlayerPreThink, nexball_PlayerPreThink, CBC_ORDER_ANY);
+       MUTATOR_ONADD
+       {
+           g_nexball = 1;
+               g_nexball_meter_period = autocvar_g_nexball_meter_period;
+               if(g_nexball_meter_period <= 0)
+                       g_nexball_meter_period = 2; // avoid division by zero etc. due to silly users
+               g_nexball_meter_period = rint(g_nexball_meter_period * 32) / 32; //Round to 1/32ths to send as a byte multiplied by 32
+               addstat(STAT_NB_METERSTART, AS_FLOAT, metertime);
+               // General settings
+               /*
+               CVTOV(g_nexball_football_boost_forward);   //100
+               CVTOV(g_nexball_football_boost_up);        //200
+               CVTOV(g_nexball_delay_idle);               //10
+               CVTOV(g_nexball_football_physics);         //0
+               */
+               radar_showennemies = autocvar_g_nexball_radar_showallplayers;
+               InitializeEntity(world, nb_delayedinit, INITPRIO_GAMETYPE);
+       }
+       return 0;
+ }
@@@ -1,7 -1,7 +1,8 @@@
  MUTATOR_DECLARATION(gamemode_keyhunt);
  MUTATOR_DECLARATION(gamemode_freezetag);
  MUTATOR_DECLARATION(gamemode_keepaway);
 +MUTATOR_DECLARATION(gamemode_ctf);
+ MUTATOR_DECLARATION(gamemode_nexball);
  
  MUTATOR_DECLARATION(mutator_invincibleprojectiles);
  MUTATOR_DECLARATION(mutator_nix);
@@@ -28,8 -29,8 +29,9 @@@ defs.qh               // Should rename this, it has 
  
  mutators/base.qh
  mutators/mutators.qh
- mutators/gamemode_ctf.qh // for spawnfuncs
++mutators/gamemode_ctf.qh
  mutators/gamemode_keyhunt.qh // TODO fix this
+ mutators/gamemode_nexball.qh 
  mutators/mutator_dodging.qh
  
  //// tZork Turrets ////
@@@ -137,10 -138,10 +139,10 @@@ cl_client.q
  t_plats.qc
  antilag.qc
  
 -ctf.qc
 +//ctf.qc
  domination.qc
  mode_onslaught.qc
- nexball.qc
//nexball.qc
  g_hook.qc
  
  t_swamp.qc
@@@ -202,10 -205,10 +206,11 @@@ playerstats.q
  ../common/explosion_equation.qc
  
  mutators/base.qc
 -mutators/gamemode_nexball.qc
 -mutators/gamemode_keyhunt.qc
 +mutators/gamemode_ctf.qc
- mutators/gamemode_keyhunt.qc
  mutators/gamemode_freezetag.qc
++mutators/gamemode_keyhunt.qc
  mutators/gamemode_keepaway.qc
++mutators/gamemode_nexball.qc
  mutators/mutator_invincibleproj.qc
  mutators/mutator_nix.qc
  mutators/mutator_dodging.qc
@@@ -68,10 -68,9 +68,9 @@@ string TeamNoName(float t
  }
  
  void dom_init();
 -void ctf_init();
 +//void ctf_init();
  void runematch_init();
  void tdm_init();
- void nb_init();
  void entcs_init();
  
  void LogTeamchange(float player_id, float team_number, float type)