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