Merge branch 'master' into terencehill/music_player
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / mutators / gamemode_keyhunt.qc
1 #define FOR_EACH_KH_KEY(v) for(v = kh_worldkeylist; v; v = v.kh_worldkeynext )
2
3 // #define KH_PLAYER_USE_ATTACHMENT
4 // #define KH_PLAYER_USE_CARRIEDMODEL
5
6 #ifdef KH_PLAYER_USE_ATTACHMENT
7 const vector KH_PLAYER_ATTACHMENT_DIST_ROTATED = '0 -4 0';
8 const vector KH_PLAYER_ATTACHMENT_DIST = '4 0 0';
9 const vector KH_PLAYER_ATTACHMENT = '0 0 0';
10 const vector KH_PLAYER_ATTACHMENT_ANGLES = '0 0 0';
11 const string KH_PLAYER_ATTACHMENT_BONE = "";
12 #else
13 const float KH_KEY_ZSHIFT = 22;
14 const float KH_KEY_XYDIST = 24;
15 const float KH_KEY_XYSPEED = 45;
16 #endif
17 const float KH_KEY_WP_ZSHIFT = 20;
18
19 const vector KH_KEY_MIN = '-10 -10 -46';
20 const vector KH_KEY_MAX = '10 10 3';
21 const float KH_KEY_BRIGHTNESS = 2;
22
23 float kh_no_radar_circles;
24
25 // kh_state
26 //     bits  0- 4: team of key 1, or 0 for no such key, or 30 for dropped, or 31 for self
27 //     bits  5- 9: team of key 2, or 0 for no such key, or 30 for dropped, or 31 for self
28 //     bits 10-14: team of key 3, or 0 for no such key, or 30 for dropped, or 31 for self
29 //     bits 15-19: team of key 4, or 0 for no such key, or 30 for dropped, or 31 for self
30 .float kh_state;
31 .float siren_time;  //  time delay the siren
32 //.float stuff_time;  //  time delay to stuffcmd a cvar
33
34 float kh_keystatus[17];
35 //kh_keystatus[0] = status of dropped keys, kh_keystatus[1 - 16] = player #
36 //replace 17 with cvar("maxplayers") or similar !!!!!!!!!
37 //for(i = 0; i < maxplayers; ++i)
38 //      kh_keystatus[i] = "0";
39
40 float kh_Team_ByID(float t)
41 {
42         if(t == 0) return NUM_TEAM_1;
43         if(t == 1) return NUM_TEAM_2;
44         if(t == 2) return NUM_TEAM_3;
45         if(t == 3) return NUM_TEAM_4;
46         return 0;
47 }
48
49 entity kh_worldkeylist;
50 .entity kh_worldkeynext;
51 entity kh_controller;
52 float kh_tracking_enabled;
53 float kh_teams;
54 float kh_interferemsg_time, kh_interferemsg_team;
55 .entity kh_next, kh_prev; // linked list
56 .float kh_droptime;
57 .float kh_dropperteam;
58 .entity kh_previous_owner;
59 .float kh_previous_owner_playerid;
60 .float kh_cp_duration;
61
62 string kh_sound_capture = "kh/capture.wav";
63 string kh_sound_destroy = "kh/destroy.wav";
64 string kh_sound_drop = "kh/drop.wav";
65 string kh_sound_collect = "kh/collect.wav";
66 string kh_sound_alarm = "kh/alarm.wav";  // the new siren/alarm
67
68 float kh_key_dropped, kh_key_carried;
69
70 #define ST_KH_CAPS 1
71 #define SP_KH_CAPS 4
72 #define SP_KH_PUSHES 5
73 #define SP_KH_DESTROYS 6
74 #define SP_KH_PICKUPS 7
75 #define SP_KH_KCKILLS 8
76 #define SP_KH_LOSSES 9
77 void kh_ScoreRules(float teams)
78 {
79         ScoreRules_basics(teams, SFL_SORT_PRIO_PRIMARY, SFL_SORT_PRIO_PRIMARY, TRUE);
80         ScoreInfo_SetLabel_TeamScore(  ST_KH_CAPS,      "caps",      SFL_SORT_PRIO_SECONDARY);
81         ScoreInfo_SetLabel_PlayerScore(SP_KH_CAPS,      "caps",      SFL_SORT_PRIO_SECONDARY);
82         ScoreInfo_SetLabel_PlayerScore(SP_KH_PUSHES,    "pushes",    0);
83         ScoreInfo_SetLabel_PlayerScore(SP_KH_DESTROYS,  "destroyed", SFL_LOWER_IS_BETTER);
84         ScoreInfo_SetLabel_PlayerScore(SP_KH_PICKUPS,   "pickups",   0);
85         ScoreInfo_SetLabel_PlayerScore(SP_KH_KCKILLS,   "kckills",   0);
86         ScoreInfo_SetLabel_PlayerScore(SP_KH_LOSSES,    "losses",    SFL_LOWER_IS_BETTER);
87         ScoreRules_basics_end();
88 }
89
90 float kh_KeyCarrier_waypointsprite_visible_for_player(entity e)  // runs all the time
91 {
92         if(!IS_PLAYER(e) || self.team != e.team)
93                 if(!kh_tracking_enabled)
94                         return FALSE;
95
96         return TRUE;
97 }
98
99 float kh_Key_waypointsprite_visible_for_player(entity e) // ??
100 {
101         if(!kh_tracking_enabled)
102                 return FALSE;
103         if(!self.owner)
104                 return TRUE;
105         if(!self.owner.owner)
106                 return TRUE;
107         return FALSE;  // draw only when key is not owned
108 }
109
110 void kh_update_state()
111 {
112         entity player;
113         entity key;
114         float s;
115         float f;
116
117         s = 0;
118         FOR_EACH_KH_KEY(key)
119         {
120                 if(key.owner)
121                         f = key.team;
122                 else
123                         f = 30;
124                 s |= pow(32, key.count) * f;
125         }
126
127         FOR_EACH_CLIENT(player)
128         {
129                 player.kh_state = s;
130         }
131
132         FOR_EACH_KH_KEY(key)
133         {
134                 if(key.owner)
135                         key.owner.kh_state |= pow(32, key.count) * 31;
136         }
137         //print(ftos((nextent(world)).kh_state), "\n");
138 }
139
140
141
142
143 var kh_Think_t kh_Controller_Thinkfunc;
144 void kh_Controller_SetThink(float t, kh_Think_t func)  // runs occasionaly
145 {
146         kh_Controller_Thinkfunc = func;
147         kh_controller.cnt = ceil(t);
148         if(t == 0)
149                 kh_controller.nextthink = time; // force
150 }
151 void kh_WaitForPlayers();
152 void kh_Controller_Think()  // called a lot
153 {
154         if(intermission_running)
155                 return;
156         if(self.cnt > 0)
157         { if(self.think != kh_WaitForPlayers) { self.cnt -= 1; } }
158         else if(self.cnt == 0)
159         {
160                 self.cnt -= 1;
161                 kh_Controller_Thinkfunc();
162         }
163         self.nextthink = time + 1;
164 }
165
166 // frags f: take from cvar * f
167 // frags 0: no frags
168 void kh_Scores_Event(entity player, entity key, string what, float frags_player, float frags_owner)  // update the score when a key is captured
169 {
170         string s;
171         if(intermission_running)
172                 return;
173
174         if(frags_player)
175                 UpdateFrags(player, frags_player);
176
177         if(key && key.owner && frags_owner)
178                 UpdateFrags(key.owner, frags_owner);
179
180         if(!autocvar_sv_eventlog)  //output extra info to the console or text file
181                 return;
182
183         s = strcat(":keyhunt:", what, ":", ftos(player.playerid), ":", ftos(frags_player));
184
185         if(key && key.owner)
186                 s = strcat(s, ":", ftos(key.owner.playerid));
187         else
188                 s = strcat(s, ":0");
189
190         s = strcat(s, ":", ftos(frags_owner), ":");
191
192         if(key)
193                 s = strcat(s, key.netname);
194
195         GameLogEcho(s);
196 }
197
198 vector kh_AttachedOrigin(entity e)  // runs when a team captures the flag, it can run 2 or 3 times.
199 {
200         if(e.tag_entity)
201         {
202                 makevectors(e.tag_entity.angles);
203                 return e.tag_entity.origin + e.origin_x * v_forward - e.origin_y * v_right + e.origin_z * v_up;
204         }
205         else
206                 return e.origin;
207 }
208
209 void kh_Key_Attach(entity key)  // runs when a player picks up a key and several times when a key is assigned to a player at the start of a round
210 {
211 #ifdef KH_PLAYER_USE_ATTACHMENT
212         entity first;
213         first = key.owner.kh_next;
214         if(key == first)
215         {
216                 setattachment(key, key.owner, KH_PLAYER_ATTACHMENT_BONE);
217                 if(key.kh_next)
218                 {
219                         setattachment(key.kh_next, key, "");
220                         setorigin(key, key.kh_next.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
221                         setorigin(key.kh_next, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
222                         key.kh_next.angles = '0 0 0';
223                 }
224                 else
225                         setorigin(key, KH_PLAYER_ATTACHMENT);
226                 key.angles = KH_PLAYER_ATTACHMENT_ANGLES;
227         }
228         else
229         {
230                 setattachment(key, key.kh_prev, "");
231                 if(key.kh_next)
232                         setattachment(key.kh_next, key, "");
233                 setorigin(key, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
234                 setorigin(first, first.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
235                 key.angles = '0 0 0';
236         }
237 #else
238         setattachment(key, key.owner, "");
239         setorigin(key, '0 0 1' * KH_KEY_ZSHIFT);  // fixing x, y in think
240         key.angles_y -= key.owner.angles_y;
241 #endif
242         key.flags = 0;
243         key.solid = SOLID_NOT;
244         key.movetype = MOVETYPE_NONE;
245         key.team = key.owner.team;
246         key.nextthink = time;
247         key.damageforcescale = 0;
248         key.takedamage = DAMAGE_NO;
249         key.modelindex = kh_key_carried;
250 }
251
252 void kh_Key_Detach(entity key) // runs every time a key is dropped or lost. Runs several times times when all the keys are captured
253 {
254 #ifdef KH_PLAYER_USE_ATTACHMENT
255         entity first;
256         first = key.owner.kh_next;
257         if(key == first)
258         {
259                 if(key.kh_next)
260                 {
261                         setattachment(key.kh_next, key.owner, KH_PLAYER_ATTACHMENT_BONE);
262                         setorigin(key.kh_next, key.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
263                         key.kh_next.angles = KH_PLAYER_ATTACHMENT_ANGLES;
264                 }
265         }
266         else
267         {
268                 if(key.kh_next)
269                         setattachment(key.kh_next, key.kh_prev, "");
270                 setorigin(first, first.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
271         }
272         // in any case:
273         setattachment(key, world, "");
274         setorigin(key, key.owner.origin + '0 0 1' * (PL_MIN_z - KH_KEY_MIN_z));
275         key.angles = key.owner.angles;
276 #else
277         setorigin(key, key.owner.origin + key.origin_z * '0 0 1');
278         setattachment(key, world, "");
279         key.angles_y += key.owner.angles_y;
280 #endif
281         key.flags = FL_ITEM;
282         key.solid = SOLID_TRIGGER;
283         key.movetype = MOVETYPE_TOSS;
284         key.pain_finished = time + autocvar_g_balance_keyhunt_delay_return;
285         key.damageforcescale = autocvar_g_balance_keyhunt_damageforcescale;
286         key.takedamage = DAMAGE_YES;
287         // let key.team stay
288         key.modelindex = kh_key_dropped;
289         key.kh_previous_owner = key.owner;
290         key.kh_previous_owner_playerid = key.owner.playerid;
291 }
292
293 void kh_Key_AssignTo(entity key, entity player)  // runs every time a key is picked up or assigned. Runs prior to kh_key_attach
294 {
295         entity k;
296         float ownerteam0, ownerteam;
297         if(key.owner == player)
298                 return;
299
300         ownerteam0 = kh_Key_AllOwnedByWhichTeam();
301
302         if(key.owner)
303         {
304                 kh_Key_Detach(key);
305
306                 // remove from linked list
307                 if(key.kh_next)
308                         key.kh_next.kh_prev = key.kh_prev;
309                 key.kh_prev.kh_next = key.kh_next;
310                 key.kh_next = world;
311                 key.kh_prev = world;
312
313                 if(key.owner.kh_next == world)
314                 {
315                         // No longer a key carrier
316                         if(!kh_no_radar_circles)
317                                 WaypointSprite_Ping(key.owner.waypointsprite_attachedforcarrier);
318                         WaypointSprite_DetachCarrier(key.owner);
319                 }
320         }
321
322         key.owner = player;
323
324         if(player)
325         {
326                 // insert into linked list
327                 key.kh_next = player.kh_next;
328                 key.kh_prev = player;
329                 player.kh_next = key;
330                 if(key.kh_next)
331                         key.kh_next.kh_prev = key;
332
333                 float i;
334                 i = kh_keystatus[key.owner.playerid];
335                         if(key.netname == "^1red key")
336                                 i += 1;
337                         if(key.netname == "^4blue key")
338                                 i += 2;
339                         if(key.netname == "^3yellow key")
340                                 i += 4;
341                         if(key.netname == "^6pink key")
342                                 i += 8;
343                 kh_keystatus[key.owner.playerid] = i;
344
345                 kh_Key_Attach(key);
346
347                 if(key.kh_next == world)
348                 {
349                         // player is now a key carrier
350                         WaypointSprite_AttachCarrier("", player, RADARICON_FLAGCARRIER, colormapPaletteColor(player.team - 1, 0));
351                         player.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_KeyCarrier_waypointsprite_visible_for_player;
352                         WaypointSprite_UpdateRule(player.waypointsprite_attachedforcarrier, player.team, SPRITERULE_TEAMPLAY);
353                         if(player.team == NUM_TEAM_1)
354                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, "keycarrier-red", "keycarrier-friend", "keycarrier-red");
355                         else if(player.team == NUM_TEAM_2)
356                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, "keycarrier-blue", "keycarrier-friend", "keycarrier-blue");
357                         else if(player.team == NUM_TEAM_3)
358                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, "keycarrier-yellow", "keycarrier-friend", "keycarrier-yellow");
359                         else if(player.team == NUM_TEAM_4)
360                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, "keycarrier-pink", "keycarrier-friend", "keycarrier-pink");
361                         if(!kh_no_radar_circles)
362                                 WaypointSprite_Ping(player.waypointsprite_attachedforcarrier);
363                 }
364         }
365
366         // moved that here, also update if there's no player
367         kh_update_state();
368
369         key.pusher = world;
370
371         ownerteam = kh_Key_AllOwnedByWhichTeam();
372         if(ownerteam != ownerteam0)
373         {
374                 if(ownerteam != -1)
375                 {
376                         kh_interferemsg_time = time + 0.2;
377                         kh_interferemsg_team = player.team;
378
379                         // audit all key carrier sprites, update them to RUN HERE
380                         FOR_EACH_KH_KEY(k)
381                         {
382                                 if(k.owner)
383                                         WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, k.owner.waypointsprite_attachedforcarrier.model1, "keycarrier-finish", k.owner.waypointsprite_attachedforcarrier.model3);
384                         }
385                 }
386                 else
387                 {
388                         kh_interferemsg_time = 0;
389
390                         // audit all key carrier sprites, update them to RUN HERE
391                         FOR_EACH_KH_KEY(k)
392                         {
393                                 if(k.owner)
394                                         WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, k.owner.waypointsprite_attachedforcarrier.model1, "keycarrier-friend", k.owner.waypointsprite_attachedforcarrier.model3);
395                         }
396                 }
397         }
398 }
399
400 void kh_Key_Damage(entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
401 {
402         if(self.owner)
403                 return;
404         if(ITEM_DAMAGE_NEEDKILL(deathtype))
405         {
406                 // touching lava, or hurt trigger
407                 // what shall we do?
408                 // immediately return is bad
409                 // maybe start a shorter countdown?
410         }
411         if(vlen(force) <= 0)
412                 return;
413         if(time > self.pushltime)
414                 if(IS_PLAYER(attacker))
415                         self.team = attacker.team;
416 }
417
418 void kh_Key_Collect(entity key, entity player)  //a player picks up a dropped key
419 {
420         sound(player, CH_TRIGGER, kh_sound_collect, VOL_BASE, ATTEN_NORM);
421
422         if(key.kh_dropperteam != player.team)
423         {
424                 kh_Scores_Event(player, key, "collect", autocvar_g_balance_keyhunt_score_collect, 0);
425                 PlayerScore_Add(player, SP_KH_PICKUPS, 1);
426         }
427         key.kh_dropperteam = 0;
428         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_PICKUP_), player.netname);
429
430         kh_Key_AssignTo(key, player); // this also updates .kh_state
431 }
432
433 void kh_Key_Touch()  // runs many, many times when a key has been dropped and can be picked up
434 {
435         if(intermission_running)
436                 return;
437
438         if(self.owner) // already carried
439                 return;
440
441         if(ITEM_TOUCH_NEEDKILL())
442         {
443                 // touching sky, or nodrop
444                 // what shall we do?
445                 // immediately return is bad
446                 // maybe start a shorter countdown?
447         }
448
449         if (!IS_PLAYER(other))
450                 return;
451         if(other.deadflag != DEAD_NO)
452                 return;
453         if(other == self.enemy)
454                 if(time < self.kh_droptime + autocvar_g_balance_keyhunt_delay_collect)
455                         return;  // you just dropped it!
456         kh_Key_Collect(self, other);
457 }
458
459 void kh_Key_Remove(entity key)  // runs after when all the keys have been collected or when a key has been dropped for more than X seconds
460 {
461         entity o;
462         o = key.owner;
463         kh_Key_AssignTo(key, world);
464         if(o) // it was attached
465                 WaypointSprite_Kill(key.waypointsprite_attachedforcarrier);
466         else // it was dropped
467                 WaypointSprite_DetachCarrier(key);
468
469         // remove key from key list
470         if (kh_worldkeylist == key)
471                 kh_worldkeylist = kh_worldkeylist.kh_worldkeynext;
472         else
473         {
474                 o = kh_worldkeylist;
475                 while (o)
476                 {
477                         if (o.kh_worldkeynext == key)
478                         {
479                                 o.kh_worldkeynext = o.kh_worldkeynext.kh_worldkeynext;
480                                 break;
481                         }
482                         o = o.kh_worldkeynext;
483                 }
484         }
485
486         remove(key);
487
488         kh_update_state();
489 }
490
491 void kh_FinishRound()  // runs when a team captures the keys
492 {
493         // prepare next round
494         kh_interferemsg_time = 0;
495         entity key;
496
497         kh_no_radar_circles = TRUE;
498         FOR_EACH_KH_KEY(key)
499                 kh_Key_Remove(key);
500         kh_no_radar_circles = FALSE;
501
502         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
503         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
504 }
505
506 void kh_WinnerTeam(float teem)  // runs when a team wins // Samual: Teem?.... TEEM?!?! what the fuck is wrong with you people
507 {
508         // all key carriers get some points
509         vector firstorigin, lastorigin, midpoint;
510         float first;
511         entity key;
512         float score;
513         score = (kh_teams - 1) * autocvar_g_balance_keyhunt_score_capture;
514         DistributeEvenly_Init(score, kh_teams);
515         // twice the score for 3 team games, three times the score for 4 team games!
516         // note: for a win by destroying the key, this should NOT be applied
517         FOR_EACH_KH_KEY(key)
518         {
519                 float f;
520                 f = DistributeEvenly_Get(1);
521                 kh_Scores_Event(key.owner, key, "capture", f, 0);
522                 PlayerTeamScore_Add(key.owner, SP_KH_CAPS, ST_KH_CAPS, 1);
523                 nades_GiveBonus(key.owner, autocvar_g_nades_bonus_score_high);
524         }
525
526         first = TRUE;
527         string keyowner = "";
528         FOR_EACH_KH_KEY(key)
529                 if(key.owner.kh_next == key)
530                 {
531                         if(!first)
532                                 keyowner = strcat(keyowner, ", ");
533                         keyowner = key.owner.netname;
534                         first = FALSE;
535                 }
536
537         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(teem, INFO_KEYHUNT_CAPTURE_), keyowner);
538
539         first = TRUE;
540         midpoint = '0 0 0';
541         firstorigin = '0 0 0';
542         lastorigin = '0 0 0';
543         FOR_EACH_KH_KEY(key)
544         {
545                 vector thisorigin;
546
547                 thisorigin = kh_AttachedOrigin(key);
548                 //dprint("Key origin: ", vtos(thisorigin), "\n");
549                 midpoint += thisorigin;
550
551                 if(!first)
552                         te_lightning2(world, lastorigin, thisorigin);
553                 lastorigin = thisorigin;
554                 if(first)
555                         firstorigin = thisorigin;
556                 first = FALSE;
557         }
558         if(kh_teams > 2)
559         {
560                 te_lightning2(world, lastorigin, firstorigin);
561         }
562         midpoint = midpoint * (1 / kh_teams);
563         te_customflash(midpoint, 1000, 1, Team_ColorRGB(teem) * 0.5 + '0.5 0.5 0.5');  // make the color >=0.5 in each component
564
565         play2all(kh_sound_capture);
566         kh_FinishRound();
567 }
568
569 void kh_LoserTeam(float teem, entity lostkey)  // runs when a player pushes a flag carrier off the map
570 {
571         entity player, key, attacker;
572         float players;
573         float keys;
574         float f;
575
576         attacker = world;
577         if(lostkey.pusher)
578                 if(lostkey.pusher.team != teem)
579                         if(IS_PLAYER(lostkey.pusher))
580                                 attacker = lostkey.pusher;
581
582         players = keys = 0;
583
584         if(attacker)
585         {
586                 if(lostkey.kh_previous_owner)
587                         kh_Scores_Event(lostkey.kh_previous_owner, world, "pushed", 0, -autocvar_g_balance_keyhunt_score_push);
588                         // don't actually GIVE him the -nn points, just log
589                 kh_Scores_Event(attacker, world, "push", autocvar_g_balance_keyhunt_score_push, 0);
590                 PlayerScore_Add(attacker, SP_KH_PUSHES, 1);
591                 //centerprint(attacker, "Your push is the best!"); // does this really need to exist?
592         }
593         else
594         {
595                 float of, fragsleft, i, j, thisteam;
596                 of = autocvar_g_balance_keyhunt_score_destroyed_ownfactor;
597
598                 FOR_EACH_PLAYER(player)
599                         if(player.team != teem)
600                                 ++players;
601
602                 FOR_EACH_KH_KEY(key)
603                         if(key.owner && key.team != teem)
604                                 ++keys;
605
606                 if(lostkey.kh_previous_owner)
607                         kh_Scores_Event(lostkey.kh_previous_owner, world, "destroyed", 0, -autocvar_g_balance_keyhunt_score_destroyed);
608                         // don't actually GIVE him the -nn points, just log
609
610                 if(lostkey.kh_previous_owner.playerid == lostkey.kh_previous_owner_playerid)
611                         PlayerScore_Add(lostkey.kh_previous_owner, SP_KH_DESTROYS, 1);
612
613                 DistributeEvenly_Init(autocvar_g_balance_keyhunt_score_destroyed, keys * of + players);
614
615                 FOR_EACH_KH_KEY(key)
616                         if(key.owner && key.team != teem)
617                         {
618                                 f = DistributeEvenly_Get(of);
619                                 kh_Scores_Event(key.owner, world, "destroyed_holdingkey", f, 0);
620                         }
621
622                 fragsleft = DistributeEvenly_Get(players);
623
624                 // Now distribute these among all other teams...
625                 j = kh_teams - 1;
626                 for(i = 0; i < kh_teams; ++i)
627                 {
628                         thisteam = kh_Team_ByID(i);
629                         if(thisteam == teem) // bad boy, no cookie - this WILL happen
630                                 continue;
631
632                         players = 0;
633                         FOR_EACH_PLAYER(player)
634                                 if(player.team == thisteam)
635                                         ++players;
636
637                         DistributeEvenly_Init(fragsleft, j);
638                         fragsleft = DistributeEvenly_Get(j - 1);
639                         DistributeEvenly_Init(DistributeEvenly_Get(1), players);
640
641                         FOR_EACH_PLAYER(player)
642                                 if(player.team == thisteam)
643                                 {
644                                         f = DistributeEvenly_Get(1);
645                                         kh_Scores_Event(player, world, "destroyed", f, 0);
646                                 }
647
648                         --j;
649                 }
650         }
651
652         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(lostkey, INFO_KEYHUNT_LOST_), lostkey.kh_previous_owner.netname);
653
654         play2all(kh_sound_destroy);
655         te_tarexplosion(lostkey.origin);
656
657         kh_FinishRound();
658 }
659
660 void kh_Key_Think()  // runs all the time
661 {
662         entity head;
663         //entity player;  // needed by FOR_EACH_PLAYER
664
665         if(intermission_running)
666                 return;
667
668         if(self.owner)
669         {
670 #ifndef KH_PLAYER_USE_ATTACHMENT
671                 makevectors('0 1 0' * (self.cnt + mod(time, 360) * KH_KEY_XYSPEED));
672                 setorigin(self, v_forward * KH_KEY_XYDIST + '0 0 1' * self.origin_z);
673 #endif
674         }
675
676         // if in nodrop or time over, end the round
677         if(!self.owner)
678                 if(time > self.pain_finished)
679                         kh_LoserTeam(self.team, self);
680
681         if(self.owner)
682         if(kh_Key_AllOwnedByWhichTeam() != -1)
683         {
684                 if(self.siren_time < time)
685                 {
686                         sound(self.owner, CH_TRIGGER, kh_sound_alarm, VOL_BASE, ATTEN_NORM);  // play a simple alarm
687                         self.siren_time = time + 2.5;  // repeat every 2.5 seconds
688                 }
689
690                 entity key;
691                 vector p;
692                 p = self.owner.origin;
693                 FOR_EACH_KH_KEY(key)
694                         if(vlen(key.owner.origin - p) > autocvar_g_balance_keyhunt_maxdist)
695                                 goto not_winning;
696                 kh_WinnerTeam(self.team);
697 :not_winning
698         }
699
700         if(kh_interferemsg_time && time > kh_interferemsg_time)
701         {
702                 kh_interferemsg_time = 0;
703                 FOR_EACH_PLAYER(head)
704                 {
705                         if(head.team == kh_interferemsg_team)
706                                 if(head.kh_next)
707                                         Send_Notification(NOTIF_ONE, head, MSG_CENTER, CENTER_KEYHUNT_MEET);
708                                 else
709                                         Send_Notification(NOTIF_ONE, head, MSG_CENTER, CENTER_KEYHUNT_HELP);
710                         else
711                                 Send_Notification(NOTIF_ONE, head, MSG_CENTER, APP_TEAM_NUM_4(kh_interferemsg_team, CENTER_KEYHUNT_INTERFERE_));
712                 }
713         }
714
715         self.nextthink = time + 0.05;
716 }
717
718 void key_reset()
719 {
720         kh_Key_AssignTo(self, world);
721         kh_Key_Remove(self);
722 }
723
724 const string STR_ITEM_KH_KEY = "item_kh_key";
725 void kh_Key_Spawn(entity initial_owner, float angle, float i)  // runs every time a new flag is created, ie after all the keys have been collected
726 {
727         entity key;
728         key = spawn();
729         key.count = i;
730         key.classname = STR_ITEM_KH_KEY;
731         key.touch = kh_Key_Touch;
732         key.think = kh_Key_Think;
733         key.nextthink = time;
734         key.items = IT_KEY1 | IT_KEY2;
735         key.cnt = angle;
736         key.angles = '0 360 0' * random();
737         key.event_damage = kh_Key_Damage;
738         key.takedamage = DAMAGE_YES;
739         key.modelindex = kh_key_dropped;
740         key.model = "key";
741         key.kh_dropperteam = 0;
742         key.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
743         setsize(key, KH_KEY_MIN, KH_KEY_MAX);
744         key.colormod = Team_ColorRGB(initial_owner.team) * KH_KEY_BRIGHTNESS;
745         key.reset = key_reset;
746
747         switch(initial_owner.team)
748         {
749                 case NUM_TEAM_1:
750                         key.netname = "^1red key";
751                         break;
752                 case NUM_TEAM_2:
753                         key.netname = "^4blue key";
754                         break;
755                 case NUM_TEAM_3:
756                         key.netname = "^3yellow key";
757                         break;
758                 case NUM_TEAM_4:
759                         key.netname = "^6pink key";
760                         break;
761                 default:
762                         key.netname = "NETGIER key";
763                         break;
764         }
765
766         // link into key list
767         key.kh_worldkeynext = kh_worldkeylist;
768         kh_worldkeylist = key;
769
770         Send_Notification(NOTIF_ONE, initial_owner, MSG_CENTER, APP_TEAM_NUM_4(initial_owner.team, CENTER_KEYHUNT_START_));
771
772         WaypointSprite_Spawn("key-dropped", 0, 0, key, '0 0 1' * KH_KEY_WP_ZSHIFT, world, key.team, key, waypointsprite_attachedforcarrier, FALSE, RADARICON_FLAG, '0 1 1');
773         key.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_Key_waypointsprite_visible_for_player;
774
775         kh_Key_AssignTo(key, initial_owner);
776 }
777
778 // -1 when no team completely owns all keys yet
779 float kh_Key_AllOwnedByWhichTeam()  // constantly called. check to see if all the keys are owned by the same team
780 {
781         entity key;
782         float teem;
783         float keys;
784
785         teem = -1;
786         keys = kh_teams;
787         FOR_EACH_KH_KEY(key)
788         {
789                 if(!key.owner)
790                         return -1;
791                 if(teem == -1)
792                         teem = key.team;
793                 else if(teem != key.team)
794                         return -1;
795                 --keys;
796         }
797         if(keys != 0)
798                 return -1;
799         return teem;
800 }
801
802 void kh_Key_DropOne(entity key)
803 {
804         // prevent collecting this one for some time
805         entity player;
806         player = key.owner;
807
808         key.kh_droptime = time;
809         key.enemy = player;
810
811         kh_Scores_Event(player, key, "dropkey", 0, 0);
812         PlayerScore_Add(player, SP_KH_LOSSES, 1);
813         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_DROP_), player.netname);
814
815         kh_Key_AssignTo(key, world);
816         makevectors(player.v_angle);
817         key.velocity = W_CalculateProjectileVelocity(player.velocity, autocvar_g_balance_keyhunt_throwvelocity * v_forward, FALSE);
818         key.pusher = world;
819         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
820         key.kh_dropperteam = key.team;
821
822         sound(player, CH_TRIGGER, kh_sound_drop, VOL_BASE, ATTEN_NORM);
823 }
824
825 void kh_Key_DropAll(entity player, float suicide) // runs whenever a player dies
826 {
827         entity key;
828         entity mypusher;
829         if(player.kh_next)
830         {
831                 mypusher = world;
832                 if(player.pusher)
833                         if(time < player.pushltime)
834                                 mypusher = player.pusher;
835                 while((key = player.kh_next))
836                 {
837                         kh_Scores_Event(player, key, "losekey", 0, 0);
838                         PlayerScore_Add(player, SP_KH_LOSSES, 1);
839                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_LOST_), player.netname);
840                         kh_Key_AssignTo(key, world);
841                         makevectors('-1 0 0' * (45 + 45 * random()) + '0 360 0' * random());
842                         key.velocity = W_CalculateProjectileVelocity(player.velocity, autocvar_g_balance_keyhunt_dropvelocity * v_forward, FALSE);
843                         key.pusher = mypusher;
844                         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
845                         if(suicide)
846                                 key.kh_dropperteam = player.team;
847                 }
848                 sound(player, CH_TRIGGER, kh_sound_drop, VOL_BASE, ATTEN_NORM);
849         }
850 }
851
852 float kh_CheckPlayers(float num)
853 {
854         if(num < kh_teams)
855         {
856                 float t_team = kh_Team_ByID(num);
857                 float players = 0;
858                 entity tmp_player;
859                 FOR_EACH_PLAYER(tmp_player)
860                         if(tmp_player.deadflag == DEAD_NO)
861                                 if(!tmp_player.BUTTON_CHAT)
862                                         if(tmp_player.team == t_team)
863                                                 ++players;
864
865                 if (!players) { return t_team; }
866         }
867         return 0;
868 }
869
870 void kh_WaitForPlayers()  // delay start of the round until enough players are present
871 {
872         if(time < game_starttime)
873         {
874                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
875                 return;
876         }
877
878         float p1 = kh_CheckPlayers(0), p2 = kh_CheckPlayers(1), p3 = kh_CheckPlayers(2), p4 = kh_CheckPlayers(3);
879         if (!(p1 || p2 || p3 || p4))
880         {
881                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
882                 kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
883         }
884         else
885         {
886                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_WAIT, p1, p2, p3, p4);
887                 kh_Controller_SetThink(1, kh_WaitForPlayers);
888         }
889 }
890
891 void kh_EnableTrackingDevice()  // runs after each round
892 {
893         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT);
894         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT_OTHER);
895
896         kh_tracking_enabled = TRUE;
897 }
898
899 void kh_StartRound()  // runs at the start of each round
900 {
901         float i, players, teem;
902         entity player;
903
904         if(time < game_starttime)
905         {
906                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
907                 return;
908         }
909
910         float p1 = kh_CheckPlayers(0), p2 = kh_CheckPlayers(1), p3 = kh_CheckPlayers(2), p4 = kh_CheckPlayers(3);
911         if(p1 || p2 || p3 || p4)
912         {
913                 kh_Controller_SetThink(1, kh_WaitForPlayers);
914                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_WAIT, p1, p2, p3, p4);
915                 return;
916         }
917
918         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT);
919         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT_OTHER);
920
921         for(i = 0; i < kh_teams; ++i)
922         {
923                 teem = kh_Team_ByID(i);
924                 players = 0;
925                 entity my_player = world;
926                 FOR_EACH_PLAYER(player)
927                         if(player.deadflag == DEAD_NO)
928                                 if(!player.BUTTON_CHAT)
929                                         if(player.team == teem)
930                                         {
931                                                 ++players;
932                                                 if(random() * players <= 1)
933                                                         my_player = player;
934                                         }
935                 kh_Key_Spawn(my_player, 360 * i / kh_teams, i);
936         }
937
938         kh_tracking_enabled = FALSE;
939         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_SCAN, autocvar_g_balance_keyhunt_delay_tracking);
940         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_tracking, kh_EnableTrackingDevice);
941 }
942
943 float kh_HandleFrags(entity attacker, entity targ, float f)  // adds to the player score
944 {
945         if(attacker == targ)
946                 return f;
947
948         if(targ.kh_next)
949         {
950                 if(attacker.team == targ.team)
951                 {
952                         entity k;
953                         float nk;
954                         nk = 0;
955                         for(k = targ.kh_next; k != world; k = k.kh_next)
956                                 ++nk;
957                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", -nk * autocvar_g_balance_keyhunt_score_collect, 0);
958                 }
959                 else
960                 {
961                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", autocvar_g_balance_keyhunt_score_carrierfrag-1, 0);
962                         PlayerScore_Add(attacker, SP_KH_KCKILLS, 1);
963                         // the frag gets added later
964                 }
965         }
966
967         return f;
968 }
969
970 void kh_Initialize()  // sets up th KH environment
971 {
972         precache_sound(kh_sound_capture);
973         precache_sound(kh_sound_destroy);
974         precache_sound(kh_sound_drop);
975         precache_sound(kh_sound_collect);
976         precache_sound(kh_sound_alarm);  // the new siren
977
978 #ifdef KH_PLAYER_USE_CARRIEDMODEL
979         precache_model("models/keyhunt/key-carried.md3");
980 #endif
981         precache_model("models/keyhunt/key.md3");
982
983         // setup variables
984         kh_teams = autocvar_g_keyhunt_teams_override;
985         if(kh_teams < 2)
986                 kh_teams = autocvar_g_keyhunt_teams;
987         kh_teams = bound(2, kh_teams, 4);
988
989         // make a KH entity for controlling the game
990         kh_controller = spawn();
991         kh_controller.think = kh_Controller_Think;
992         kh_Controller_SetThink(0, kh_WaitForPlayers);
993
994         setmodel(kh_controller, "models/keyhunt/key.md3");
995         kh_key_dropped = kh_controller.modelindex;
996         /*
997         dprint(vtos(kh_controller.mins));
998         dprint(vtos(kh_controller.maxs));
999         dprint("\n");
1000         */
1001 #ifdef KH_PLAYER_USE_CARRIEDMODEL
1002         setmodel(kh_controller, "models/keyhunt/key-carried.md3");
1003         kh_key_carried = kh_controller.modelindex;
1004 #else
1005         kh_key_carried = kh_key_dropped;
1006 #endif
1007
1008         kh_controller.model = "";
1009         kh_controller.modelindex = 0;
1010
1011         addstat(STAT_KH_KEYS, AS_INT, kh_state);
1012
1013         kh_ScoreRules(kh_teams);
1014 }
1015
1016 void kh_finalize()
1017 {
1018         // to be called before intermission
1019         kh_FinishRound();
1020         remove(kh_controller);
1021         kh_controller = world;
1022 }
1023
1024 // register this as a mutator
1025
1026 MUTATOR_HOOKFUNCTION(kh_Key_DropAll)
1027 {
1028         kh_Key_DropAll(self, TRUE);
1029         return 0;
1030 }
1031
1032 MUTATOR_HOOKFUNCTION(kh_PlayerDies)
1033 {
1034         if(self == other)
1035                 kh_Key_DropAll(self, TRUE);
1036         else if(IS_PLAYER(other))
1037                 kh_Key_DropAll(self, FALSE);
1038         else
1039                 kh_Key_DropAll(self, TRUE);
1040         return 0;
1041 }
1042
1043 MUTATOR_HOOKFUNCTION(kh_GiveFragsForKill)
1044 {
1045         frag_score = kh_HandleFrags(frag_attacker, frag_target, frag_score);
1046         return 0;
1047 }
1048
1049 MUTATOR_HOOKFUNCTION(kh_finalize)
1050 {
1051         kh_finalize();
1052         return 0;
1053 }
1054
1055 MUTATOR_HOOKFUNCTION(kh_GetTeamCount)
1056 {
1057         ret_float = kh_teams;
1058         return 0;
1059 }
1060
1061 MUTATOR_HOOKFUNCTION(kh_SpectateCopy)
1062 {
1063         self.kh_state = other.kh_state;
1064         return 0;
1065 }
1066
1067 MUTATOR_HOOKFUNCTION(kh_PlayerUseKey)
1068 {
1069         if(MUTATOR_RETURNVALUE == 0)
1070         {
1071                 entity k;
1072                 k = self.kh_next;
1073                 if(k)
1074                 {
1075                         kh_Key_DropOne(k);
1076                         return 1;
1077                 }
1078         }
1079         return 0;
1080 }
1081
1082 MUTATOR_DEFINITION(gamemode_keyhunt)
1083 {
1084         MUTATOR_HOOK(MakePlayerObserver, kh_Key_DropAll, CBC_ORDER_ANY);
1085         MUTATOR_HOOK(ClientDisconnect, kh_Key_DropAll, CBC_ORDER_ANY);
1086         MUTATOR_HOOK(PlayerDies, kh_PlayerDies, CBC_ORDER_ANY);
1087         MUTATOR_HOOK(GiveFragsForKill, kh_GiveFragsForKill, CBC_ORDER_FIRST);
1088         MUTATOR_HOOK(MatchEnd, kh_finalize, CBC_ORDER_ANY);
1089         MUTATOR_HOOK(GetTeamCount, kh_GetTeamCount, CBC_ORDER_EXCLUSIVE);
1090         MUTATOR_HOOK(SpectateCopy, kh_SpectateCopy, CBC_ORDER_ANY);
1091         MUTATOR_HOOK(PlayerUseKey, kh_PlayerUseKey, CBC_ORDER_ANY);
1092
1093         MUTATOR_ONADD
1094         {
1095                 if(time > 1) // game loads at time 1
1096                         error("This is a game type and it cannot be added at runtime.");
1097                 kh_Initialize();
1098         }
1099
1100         MUTATOR_ONROLLBACK_OR_REMOVE
1101         {
1102                 // we actually cannot roll back kh_Initialize here
1103                 // BUT: we don't need to! If this gets called, adding always
1104                 // succeeds.
1105         }
1106
1107         MUTATOR_ONREMOVE
1108         {
1109                 print("This is a game type and it cannot be removed at runtime.");
1110                 return -1;
1111         }
1112
1113         return 0;
1114 }