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