6523612e2336220dadb86f03342aa8fc605980fc
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / gamemodes / gamemode / keyhunt / keyhunt.qc
1 #include "keyhunt.qh"
2
3 // TODO: sv_keyhunt
4 #ifdef SVQC
5 float autocvar_g_balance_keyhunt_damageforcescale;
6 float autocvar_g_balance_keyhunt_delay_collect;
7 float autocvar_g_balance_keyhunt_delay_damage_return;
8 float autocvar_g_balance_keyhunt_delay_return;
9 float autocvar_g_balance_keyhunt_delay_round;
10 float autocvar_g_balance_keyhunt_delay_tracking;
11 float autocvar_g_balance_keyhunt_return_when_unreachable;
12 float autocvar_g_balance_keyhunt_dropvelocity;
13 float autocvar_g_balance_keyhunt_maxdist;
14 float autocvar_g_balance_keyhunt_protecttime;
15
16 int autocvar_g_balance_keyhunt_score_capture;
17 int autocvar_g_balance_keyhunt_score_carrierfrag;
18 int autocvar_g_balance_keyhunt_score_collect;
19 int autocvar_g_balance_keyhunt_score_destroyed;
20 int autocvar_g_balance_keyhunt_score_destroyed_ownfactor;
21 int autocvar_g_balance_keyhunt_score_push;
22 float autocvar_g_balance_keyhunt_throwvelocity;
23
24 //int autocvar_g_keyhunt_teams;
25 int autocvar_g_keyhunt_teams_override;
26
27 // #define KH_PLAYER_USE_ATTACHMENT
28 // #define KH_PLAYER_USE_CARRIEDMODEL
29
30 #ifdef KH_PLAYER_USE_ATTACHMENT
31 const vector KH_PLAYER_ATTACHMENT_DIST_ROTATED = '0 -4 0';
32 const vector KH_PLAYER_ATTACHMENT_DIST = '4 0 0';
33 const vector KH_PLAYER_ATTACHMENT = '0 0 0';
34 const vector KH_PLAYER_ATTACHMENT_ANGLES = '0 0 0';
35 const string KH_PLAYER_ATTACHMENT_BONE = "";
36 #else
37 const float KH_KEY_ZSHIFT = 22;
38 const float KH_KEY_XYDIST = 24;
39 const float KH_KEY_XYSPEED = 45;
40 #endif
41 const float KH_KEY_WP_ZSHIFT = 20;
42
43 const vector KH_KEY_MIN = '-10 -10 -46';
44 const vector KH_KEY_MAX = '10 10 3';
45 const float KH_KEY_BRIGHTNESS = 2;
46
47 bool kh_no_radar_circles;
48
49 // kh_state
50 //     bits  0- 4: team of key 1, or 0 for no such key, or 30 for dropped, or 31 for self
51 //     bits  5- 9: team of key 2, or 0 for no such key, or 30 for dropped, or 31 for self
52 //     bits 10-14: team of key 3, or 0 for no such key, or 30 for dropped, or 31 for self
53 //     bits 15-19: team of key 4, or 0 for no such key, or 30 for dropped, or 31 for self
54 .float siren_time;  //  time delay the siren
55 //.float stuff_time;  //  time delay to stuffcmd a cvar
56
57 int kh_keystatus[17];
58 //kh_keystatus[0] = status of dropped keys, kh_keystatus[1 - 16] = player #
59 //replace 17 with cvar("maxplayers") or similar !!!!!!!!!
60 //for(i = 0; i < maxplayers; ++i)
61 //      kh_keystatus[i] = "0";
62
63 int kh_Team_ByID(int t)
64 {
65         if(t == 0) return NUM_TEAM_1;
66         if(t == 1) return NUM_TEAM_2;
67         if(t == 2) return NUM_TEAM_3;
68         if(t == 3) return NUM_TEAM_4;
69         return 0;
70 }
71
72 //entity kh_worldkeylist;
73 .entity kh_worldkeynext;
74 entity kh_controller;
75 //bool kh_tracking_enabled;
76 int kh_teams;
77 int kh_interferemsg_team;
78 float kh_interferemsg_time;
79 .entity kh_next, kh_prev; // linked list
80 .float kh_droptime;
81 .int kh_dropperteam;
82 .entity kh_previous_owner;
83 .int kh_previous_owner_playerid;
84
85 int kh_key_dropped, kh_key_carried;
86
87 int kh_Key_AllOwnedByWhichTeam();
88
89 const int ST_KH_CAPS = 1;
90 void kh_ScoreRules(int teams)
91 {
92         GameRules_scoring(teams, SFL_SORT_PRIO_PRIMARY, SFL_SORT_PRIO_PRIMARY, {
93         field_team(ST_KH_CAPS, "caps", SFL_SORT_PRIO_SECONDARY);
94         field(SP_KH_CAPS, "caps", SFL_SORT_PRIO_SECONDARY);
95         field(SP_KH_PUSHES, "pushes", 0);
96         field(SP_KH_DESTROYS, "destroyed", SFL_LOWER_IS_BETTER);
97         field(SP_KH_PICKUPS, "pickups", 0);
98         field(SP_KH_KCKILLS, "kckills", 0);
99         field(SP_KH_LOSSES, "losses", SFL_LOWER_IS_BETTER);
100         });
101 }
102
103 bool kh_KeyCarrier_waypointsprite_visible_for_player(entity this, entity player, entity view)  // runs all the time
104 {
105         if(!IS_PLAYER(view) || DIFF_TEAM(this, view))
106                 if(!kh_tracking_enabled)
107                         return false;
108
109         return true;
110 }
111
112 bool kh_Key_waypointsprite_visible_for_player(entity this, entity player, entity view)
113 {
114         if(!kh_tracking_enabled)
115                 return false;
116         if(!this.owner)
117                 return true;
118         if(!this.owner.owner)
119                 return true;
120         return false;  // draw only when key is not owned
121 }
122
123 void kh_update_state()
124 {
125         entity key;
126         int f;
127         int s = 0;
128         FOR_EACH_KH_KEY(key)
129         {
130                 if(key.owner)
131                         f = key.team;
132                 else
133                         f = 30;
134                 s |= (32 ** key.count) * f;
135         }
136
137         FOREACH_CLIENT(true, { STAT(KH_KEYS, it) = s; });
138
139         FOR_EACH_KH_KEY(key)
140         {
141                 if(key.owner)
142                         STAT(KH_KEYS, key.owner) |= (32 ** key.count) * 31;
143         }
144         //print(ftos((nextent(NULL)).kh_state), "\n");
145 }
146
147
148
149
150 var kh_Think_t kh_Controller_Thinkfunc;
151 void kh_Controller_SetThink(float t, kh_Think_t func)  // runs occasionaly
152 {
153         kh_Controller_Thinkfunc = func;
154         kh_controller.cnt = ceil(t);
155         if(t == 0)
156                 kh_controller.nextthink = time; // force
157 }
158 void kh_WaitForPlayers();
159 void kh_Controller_Think(entity this)  // called a lot
160 {
161         if(game_stopped)
162                 return;
163         if(this.cnt > 0)
164         {
165                 if(getthink(this) != kh_WaitForPlayers)
166                         this.cnt -= 1;
167         }
168         else if(this.cnt == 0)
169         {
170                 this.cnt -= 1;
171                 kh_Controller_Thinkfunc();
172         }
173         this.nextthink = time + 1;
174 }
175
176 // frags f: take from cvar * f
177 // frags 0: no frags
178 void kh_Scores_Event(entity player, entity key, string what, float frags_player, float frags_owner)  // update the score when a key is captured
179 {
180         string s;
181         if(game_stopped)
182                 return;
183
184         if(frags_player)
185                 UpdateFrags(player, frags_player);
186
187         if(key && key.owner && frags_owner)
188                 UpdateFrags(key.owner, frags_owner);
189
190         if(!autocvar_sv_eventlog)  //output extra info to the console or text file
191                 return;
192
193         s = strcat(":keyhunt:", what, ":", ftos(player.playerid), ":", ftos(frags_player));
194
195         if(key && key.owner)
196                 s = strcat(s, ":", ftos(key.owner.playerid));
197         else
198                 s = strcat(s, ":0");
199
200         s = strcat(s, ":", ftos(frags_owner), ":");
201
202         if(key)
203                 s = strcat(s, key.netname);
204
205         GameLogEcho(s);
206 }
207
208 vector kh_AttachedOrigin(entity e)  // runs when a team captures the flag, it can run 2 or 3 times.
209 {
210         if(e.tag_entity)
211         {
212                 makevectors(e.tag_entity.angles);
213                 return e.tag_entity.origin + e.origin.x * v_forward - e.origin.y * v_right + e.origin.z * v_up;
214         }
215         else
216                 return e.origin;
217 }
218
219 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
220 {
221 #ifdef KH_PLAYER_USE_ATTACHMENT
222         entity first = key.owner.kh_next;
223         if(key == first)
224         {
225                 setattachment(key, key.owner, KH_PLAYER_ATTACHMENT_BONE);
226                 if(key.kh_next)
227                 {
228                         setattachment(key.kh_next, key, "");
229                         setorigin(key, key.kh_next.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
230                         setorigin(key.kh_next, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
231                         key.kh_next.angles = '0 0 0';
232                 }
233                 else
234                         setorigin(key, KH_PLAYER_ATTACHMENT);
235                 key.angles = KH_PLAYER_ATTACHMENT_ANGLES;
236         }
237         else
238         {
239                 setattachment(key, key.kh_prev, "");
240                 if(key.kh_next)
241                         setattachment(key.kh_next, key, "");
242                 setorigin(key, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
243                 setorigin(first, first.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
244                 key.angles = '0 0 0';
245         }
246 #else
247         setattachment(key, key.owner, "");
248         setorigin(key, '0 0 1' * KH_KEY_ZSHIFT);  // fixing x, y in think
249         key.angles_y -= key.owner.angles.y;
250 #endif
251         key.flags = 0;
252         if(IL_CONTAINS(g_items, key))
253                 IL_REMOVE(g_items, key);
254         key.solid = SOLID_NOT;
255         set_movetype(key, MOVETYPE_NONE);
256         key.team = key.owner.team;
257         key.nextthink = time;
258         key.damageforcescale = 0;
259         key.takedamage = DAMAGE_NO;
260         key.modelindex = kh_key_carried;
261         navigation_dynamicgoal_unset(key);
262 }
263
264 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
265 {
266 #ifdef KH_PLAYER_USE_ATTACHMENT
267         entity first = key.owner.kh_next;
268         if(key == first)
269         {
270                 if(key.kh_next)
271                 {
272                         setattachment(key.kh_next, key.owner, KH_PLAYER_ATTACHMENT_BONE);
273                         setorigin(key.kh_next, key.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
274                         key.kh_next.angles = KH_PLAYER_ATTACHMENT_ANGLES;
275                 }
276         }
277         else
278         {
279                 if(key.kh_next)
280                         setattachment(key.kh_next, key.kh_prev, "");
281                 setorigin(first, first.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
282         }
283         // in any case:
284         setattachment(key, NULL, "");
285         setorigin(key, key.owner.origin + '0 0 1' * (STAT(PL_MIN, key.owner).z - KH_KEY_MIN_z));
286         key.angles = key.owner.angles;
287 #else
288         setorigin(key, key.owner.origin + key.origin.z * '0 0 1');
289         setattachment(key, NULL, "");
290         key.angles_y += key.owner.angles.y;
291 #endif
292         key.flags = FL_ITEM;
293         if(!IL_CONTAINS(g_items, key))
294                 IL_PUSH(g_items, key);
295         key.solid = SOLID_TRIGGER;
296         set_movetype(key, MOVETYPE_TOSS);
297         key.pain_finished = time + autocvar_g_balance_keyhunt_delay_return;
298         key.damageforcescale = autocvar_g_balance_keyhunt_damageforcescale;
299         key.takedamage = DAMAGE_YES;
300         // let key.team stay
301         key.modelindex = kh_key_dropped;
302         navigation_dynamicgoal_set(key);
303         key.kh_previous_owner = key.owner;
304         key.kh_previous_owner_playerid = key.owner.playerid;
305 }
306
307 void kh_Key_AssignTo(entity key, entity player)  // runs every time a key is picked up or assigned. Runs prior to kh_key_attach
308 {
309         if(key.owner == player)
310                 return;
311
312         int ownerteam0 = kh_Key_AllOwnedByWhichTeam();
313
314         if(key.owner)
315         {
316                 kh_Key_Detach(key);
317
318                 // remove from linked list
319                 if(key.kh_next)
320                         key.kh_next.kh_prev = key.kh_prev;
321                 key.kh_prev.kh_next = key.kh_next;
322                 key.kh_next = NULL;
323                 key.kh_prev = NULL;
324
325                 if(key.owner.kh_next == NULL)
326                 {
327                         // No longer a key carrier
328                         if(!kh_no_radar_circles)
329                                 WaypointSprite_Ping(key.owner.waypointsprite_attachedforcarrier);
330                         WaypointSprite_DetachCarrier(key.owner);
331                 }
332         }
333
334         key.owner = player;
335
336         if(player)
337         {
338                 // insert into linked list
339                 key.kh_next = player.kh_next;
340                 key.kh_prev = player;
341                 player.kh_next = key;
342                 if(key.kh_next)
343                         key.kh_next.kh_prev = key;
344
345                 float i;
346                 i = kh_keystatus[key.owner.playerid];
347                         if(key.netname == "^1red key")
348                                 i += 1;
349                         if(key.netname == "^4blue key")
350                                 i += 2;
351                         if(key.netname == "^3yellow key")
352                                 i += 4;
353                         if(key.netname == "^6pink key")
354                                 i += 8;
355                 kh_keystatus[key.owner.playerid] = i;
356
357                 kh_Key_Attach(key);
358
359                 if(key.kh_next == NULL)
360                 {
361                         // player is now a key carrier
362                         entity wp = WaypointSprite_AttachCarrier(WP_Null, player, RADARICON_FLAGCARRIER);
363                         wp.colormod = colormapPaletteColor(player.team - 1, 0);
364                         player.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_KeyCarrier_waypointsprite_visible_for_player;
365                         WaypointSprite_UpdateRule(player.waypointsprite_attachedforcarrier, player.team, SPRITERULE_TEAMPLAY);
366                         if(player.team == NUM_TEAM_1)
367                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierRed, WP_KeyCarrierFriend, WP_KeyCarrierRed);
368                         else if(player.team == NUM_TEAM_2)
369                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierBlue, WP_KeyCarrierFriend, WP_KeyCarrierBlue);
370                         else if(player.team == NUM_TEAM_3)
371                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierYellow, WP_KeyCarrierFriend, WP_KeyCarrierYellow);
372                         else if(player.team == NUM_TEAM_4)
373                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierPink, WP_KeyCarrierFriend, WP_KeyCarrierPink);
374                         if(!kh_no_radar_circles)
375                                 WaypointSprite_Ping(player.waypointsprite_attachedforcarrier);
376                 }
377         }
378
379         // moved that here, also update if there's no player
380         kh_update_state();
381
382         key.pusher = NULL;
383
384         int ownerteam = kh_Key_AllOwnedByWhichTeam();
385         if(ownerteam != ownerteam0)
386         {
387                 entity k;
388                 if(ownerteam != -1)
389                 {
390                         kh_interferemsg_time = time + 0.2;
391                         kh_interferemsg_team = player.team;
392
393                         // audit all key carrier sprites, update them to "Run here"
394                         FOR_EACH_KH_KEY(k)
395                         {
396                                 if (!k.owner) continue;
397                                 entity first = WP_Null;
398                                 FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, { first = it; break; });
399                                 entity third = WP_Null;
400                                 FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, { third = it; break; });
401                                 WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFinish, third);
402                         }
403                 }
404                 else
405                 {
406                         kh_interferemsg_time = 0;
407
408                         // audit all key carrier sprites, update them to "Key Carrier"
409                         FOR_EACH_KH_KEY(k)
410                         {
411                                 if (!k.owner) continue;
412                                 entity first = WP_Null;
413                                 FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, { first = it; break; });
414                                 entity third = WP_Null;
415                                 FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, { third = it; break; });
416                                 WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFriend, third);
417                         }
418                 }
419         }
420 }
421
422 void kh_Key_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
423 {
424         if(this.owner)
425                 return;
426         if(ITEM_DAMAGE_NEEDKILL(deathtype))
427         {
428                 this.pain_finished = bound(time, time + autocvar_g_balance_keyhunt_delay_damage_return, this.pain_finished);
429                 return;
430         }
431         if(force == '0 0 0')
432                 return;
433         if(time > this.pushltime)
434                 if(IS_PLAYER(attacker))
435                         this.team = attacker.team;
436 }
437
438 void kh_Key_Collect(entity key, entity player)  //a player picks up a dropped key
439 {
440         sound(player, CH_TRIGGER, SND_KH_COLLECT, VOL_BASE, ATTEN_NORM);
441
442         if(key.kh_dropperteam != player.team)
443         {
444                 kh_Scores_Event(player, key, "collect", autocvar_g_balance_keyhunt_score_collect, 0);
445                 GameRules_scoring_add(player, KH_PICKUPS, 1);
446         }
447         key.kh_dropperteam = 0;
448         int realteam = kh_Team_ByID(key.count);
449         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_PICKUP), player.netname);
450
451         kh_Key_AssignTo(key, player); // this also updates .kh_state
452 }
453
454 void kh_Key_Touch(entity this, entity toucher)  // runs many, many times when a key has been dropped and can be picked up
455 {
456         if(game_stopped)
457                 return;
458
459         if(this.owner) // already carried
460                 return;
461
462         if(ITEM_TOUCH_NEEDKILL())
463         {
464                 this.pain_finished = bound(time, time + autocvar_g_balance_keyhunt_delay_damage_return, this.pain_finished);
465                 return;
466         }
467
468         if (!IS_PLAYER(toucher))
469                 return;
470         if(IS_DEAD(toucher))
471                 return;
472         if(toucher == this.enemy)
473                 if(time < this.kh_droptime + autocvar_g_balance_keyhunt_delay_collect)
474                         return;  // you just dropped it!
475         kh_Key_Collect(this, toucher);
476 }
477
478 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
479 {
480         entity o = key.owner;
481         kh_Key_AssignTo(key, NULL);
482         if(o) // it was attached
483                 WaypointSprite_Kill(key.waypointsprite_attachedforcarrier);
484         else // it was dropped
485                 WaypointSprite_DetachCarrier(key);
486
487         // remove key from key list
488         if (kh_worldkeylist == key)
489                 kh_worldkeylist = kh_worldkeylist.kh_worldkeynext;
490         else
491         {
492                 o = kh_worldkeylist;
493                 while (o)
494                 {
495                         if (o.kh_worldkeynext == key)
496                         {
497                                 o.kh_worldkeynext = o.kh_worldkeynext.kh_worldkeynext;
498                                 break;
499                         }
500                         o = o.kh_worldkeynext;
501                 }
502         }
503
504         delete(key);
505
506         kh_update_state();
507 }
508
509 void kh_FinishRound()  // runs when a team captures the keys
510 {
511         // prepare next round
512         kh_interferemsg_time = 0;
513         entity key;
514
515         kh_no_radar_circles = true;
516         FOR_EACH_KH_KEY(key)
517                 kh_Key_Remove(key);
518         kh_no_radar_circles = false;
519
520         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
521         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
522 }
523
524 void nades_GiveBonus(entity player, float score);
525
526 void kh_WinnerTeam(int winner_team)  // runs when a team wins
527 {
528         // all key carriers get some points
529         entity key;
530         float score = (NumTeams(kh_teams) - 1) * autocvar_g_balance_keyhunt_score_capture;
531         DistributeEvenly_Init(score, NumTeams(kh_teams));
532         // twice the score for 3 team games, three times the score for 4 team games!
533         // note: for a win by destroying the key, this should NOT be applied
534         FOR_EACH_KH_KEY(key)
535         {
536                 float f = DistributeEvenly_Get(1);
537                 kh_Scores_Event(key.owner, key, "capture", f, 0);
538                 GameRules_scoring_add_team(key.owner, KH_CAPS, 1);
539                 nades_GiveBonus(key.owner, autocvar_g_nades_bonus_score_high);
540         }
541
542         bool first = true;
543         string keyowner = "";
544         FOR_EACH_KH_KEY(key)
545                 if(key.owner.kh_next == key)
546                 {
547                         if(!first)
548                                 keyowner = strcat(keyowner, ", ");
549                         keyowner = key.owner.netname;
550                         first = false;
551                 }
552
553         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN));
554         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_KEYHUNT_CAPTURE), keyowner);
555
556         first = true;
557         vector firstorigin = '0 0 0', lastorigin = '0 0 0', midpoint = '0 0 0';
558         FOR_EACH_KH_KEY(key)
559         {
560                 vector thisorigin = kh_AttachedOrigin(key);
561                 //dprint("Key origin: ", vtos(thisorigin), "\n");
562                 midpoint += thisorigin;
563
564                 if(!first)
565                         te_lightning2(NULL, lastorigin, thisorigin);
566                 lastorigin = thisorigin;
567                 if(first)
568                         firstorigin = thisorigin;
569                 first = false;
570         }
571         if(NumTeams(kh_teams) > 2)
572         {
573                 te_lightning2(NULL, lastorigin, firstorigin);
574         }
575         midpoint = midpoint * (1 / NumTeams(kh_teams));
576         te_customflash(midpoint, 1000, 1, Team_ColorRGB(winner_team) * 0.5 + '0.5 0.5 0.5');  // make the color >=0.5 in each component
577
578         play2all(SND(KH_CAPTURE));
579         kh_FinishRound();
580 }
581
582 void kh_LoserTeam(int loser_team, entity lostkey)  // runs when a player pushes a flag carrier off the map
583 {
584         float f;
585         entity attacker = NULL;
586         if(lostkey.pusher)
587                 if(lostkey.pusher.team != loser_team)
588                         if(IS_PLAYER(lostkey.pusher))
589                                 attacker = lostkey.pusher;
590
591         if(attacker)
592         {
593                 if(lostkey.kh_previous_owner)
594                         kh_Scores_Event(lostkey.kh_previous_owner, NULL, "pushed", 0, -autocvar_g_balance_keyhunt_score_push);
595                         // don't actually GIVE him the -nn points, just log
596                 kh_Scores_Event(attacker, NULL, "push", autocvar_g_balance_keyhunt_score_push, 0);
597                 GameRules_scoring_add(attacker, KH_PUSHES, 1);
598                 //centerprint(attacker, "Your push is the best!"); // does this really need to exist?
599         }
600         else
601         {
602                 int players = 0;
603                 float of = autocvar_g_balance_keyhunt_score_destroyed_ownfactor;
604
605                 FOREACH_CLIENT(IS_PLAYER(it) && it.team != loser_team, { ++players; });
606
607                 entity key;
608                 int keys = 0;
609                 FOR_EACH_KH_KEY(key)
610                         if(key.owner && key.team != loser_team)
611                                 ++keys;
612
613                 if(lostkey.kh_previous_owner)
614                         kh_Scores_Event(lostkey.kh_previous_owner, NULL, "destroyed", 0, -autocvar_g_balance_keyhunt_score_destroyed);
615                         // don't actually GIVE him the -nn points, just log
616
617                 if(lostkey.kh_previous_owner.playerid == lostkey.kh_previous_owner_playerid)
618                         GameRules_scoring_add(lostkey.kh_previous_owner, KH_DESTROYS, 1);
619
620                 DistributeEvenly_Init(autocvar_g_balance_keyhunt_score_destroyed, keys * of + players);
621
622                 FOR_EACH_KH_KEY(key)
623                         if(key.owner && key.team != loser_team)
624                         {
625                                 f = DistributeEvenly_Get(of);
626                                 kh_Scores_Event(key.owner, NULL, "destroyed_holdingkey", f, 0);
627                         }
628
629                 int fragsleft = DistributeEvenly_Get(players);
630
631                 // Now distribute these among all other teams...
632                 int j = NumTeams(kh_teams) - 1;
633                 for(int i = 0; i < NumTeams(kh_teams); ++i)
634                 {
635                         int thisteam = kh_Team_ByID(i);
636                         if(thisteam == loser_team) // bad boy, no cookie - this WILL happen
637                                 continue;
638
639                         players = 0;
640                         FOREACH_CLIENT(IS_PLAYER(it) && it.team == thisteam, { ++players; });
641
642                         DistributeEvenly_Init(fragsleft, j);
643                         fragsleft = DistributeEvenly_Get(j - 1);
644                         DistributeEvenly_Init(DistributeEvenly_Get(1), players);
645
646                         FOREACH_CLIENT(IS_PLAYER(it) && it.team == thisteam, {
647                                 f = DistributeEvenly_Get(1);
648                                 kh_Scores_Event(it, NULL, "destroyed", f, 0);
649                         });
650
651                         --j;
652                 }
653         }
654
655         int realteam = kh_Team_ByID(lostkey.count);
656         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(loser_team, CENTER_ROUND_TEAM_LOSS));
657         if(attacker)
658                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_PUSHED), attacker.netname, lostkey.kh_previous_owner.netname);
659         else
660                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_DESTROYED), lostkey.kh_previous_owner.netname);
661
662         play2all(SND(KH_DESTROY));
663         te_tarexplosion(lostkey.origin);
664
665         kh_FinishRound();
666 }
667
668 void kh_Key_Think(entity this)  // runs all the time
669 {
670         if(game_stopped)
671                 return;
672
673         if(this.owner)
674         {
675 #ifndef KH_PLAYER_USE_ATTACHMENT
676                 makevectors('0 1 0' * (this.cnt + (time % 360) * KH_KEY_XYSPEED));
677                 setorigin(this, v_forward * KH_KEY_XYDIST + '0 0 1' * this.origin.z);
678 #endif
679         }
680
681         // if in nodrop or time over, end the round
682         if(!this.owner)
683                 if(time > this.pain_finished)
684                         kh_LoserTeam(this.team, this);
685
686         if(this.owner)
687         if(kh_Key_AllOwnedByWhichTeam() != -1)
688         {
689                 if(this.siren_time < time)
690                 {
691                         sound(this.owner, CH_TRIGGER, SND_KH_ALARM, VOL_BASE, ATTEN_NORM);  // play a simple alarm
692                         this.siren_time = time + 2.5;  // repeat every 2.5 seconds
693                 }
694
695                 entity key;
696                 vector p = this.owner.origin;
697                 FOR_EACH_KH_KEY(key)
698                         if(vdist(key.owner.origin - p, >, autocvar_g_balance_keyhunt_maxdist))
699                                 goto not_winning;
700                 kh_WinnerTeam(this.team);
701 LABEL(not_winning)
702         }
703
704         if(kh_interferemsg_time && time > kh_interferemsg_time)
705         {
706                 kh_interferemsg_time = 0;
707                 FOREACH_CLIENT(IS_PLAYER(it), {
708                         if(it.team == kh_interferemsg_team)
709                                 if(it.kh_next)
710                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_KEYHUNT_MEET);
711                                 else
712                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_KEYHUNT_HELP);
713                         else
714                                 Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_TEAM_NUM(kh_interferemsg_team, CENTER_KEYHUNT_INTERFERE));
715                 });
716         }
717
718         this.nextthink = time + 0.05;
719 }
720
721 void key_reset(entity this)
722 {
723         kh_Key_AssignTo(this, NULL);
724         kh_Key_Remove(this);
725 }
726
727 const string STR_ITEM_KH_KEY = "item_kh_key";
728 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
729 {
730         entity key = spawn();
731         key.count = i;
732         key.classname = STR_ITEM_KH_KEY;
733         settouch(key, kh_Key_Touch);
734         setthink(key, kh_Key_Think);
735         key.nextthink = time;
736         key.items = IT_KEY1 | IT_KEY2;
737         key.cnt = _angle;
738         key.angles = '0 360 0' * random();
739         key.event_damage = kh_Key_Damage;
740         key.takedamage = DAMAGE_YES;
741         key.damagedbytriggers = autocvar_g_balance_keyhunt_return_when_unreachable;
742         key.damagedbycontents = autocvar_g_balance_keyhunt_return_when_unreachable;
743         key.modelindex = kh_key_dropped;
744         key.model = "key";
745         key.kh_dropperteam = 0;
746         key.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
747         setsize(key, KH_KEY_MIN, KH_KEY_MAX);
748         key.colormod = Team_ColorRGB(initial_owner.team) * KH_KEY_BRIGHTNESS;
749         key.reset = key_reset;
750         navigation_dynamicgoal_init(key, false);
751
752         switch(initial_owner.team)
753         {
754                 case NUM_TEAM_1:
755                         key.netname = "^1red key";
756                         break;
757                 case NUM_TEAM_2:
758                         key.netname = "^4blue key";
759                         break;
760                 case NUM_TEAM_3:
761                         key.netname = "^3yellow key";
762                         break;
763                 case NUM_TEAM_4:
764                         key.netname = "^6pink key";
765                         break;
766                 default:
767                         key.netname = "NETGIER key";
768                         break;
769         }
770
771         // link into key list
772         key.kh_worldkeynext = kh_worldkeylist;
773         kh_worldkeylist = key;
774
775         Send_Notification(NOTIF_ONE, initial_owner, MSG_CENTER, APP_TEAM_NUM(initial_owner.team, CENTER_KEYHUNT_START));
776
777         WaypointSprite_Spawn(WP_KeyDropped, 0, 0, key, '0 0 1' * KH_KEY_WP_ZSHIFT, NULL, key.team, key, waypointsprite_attachedforcarrier, false, RADARICON_FLAG);
778         key.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_Key_waypointsprite_visible_for_player;
779
780         kh_Key_AssignTo(key, initial_owner);
781 }
782
783 // -1 when no team completely owns all keys yet
784 int kh_Key_AllOwnedByWhichTeam()  // constantly called. check to see if all the keys are owned by the same team
785 {
786         entity key;
787         int teem = -1;
788         int keys = NumTeams(kh_teams);
789         FOR_EACH_KH_KEY(key)
790         {
791                 if(!key.owner)
792                         return -1;
793                 if(teem == -1)
794                         teem = key.team;
795                 else if(teem != key.team)
796                         return -1;
797                 --keys;
798         }
799         if(keys != 0)
800                 return -1;
801         return teem;
802 }
803
804 void kh_Key_DropOne(entity key)
805 {
806         // prevent collecting this one for some time
807         entity player = key.owner;
808
809         key.kh_droptime = time;
810         key.enemy = player;
811
812         kh_Scores_Event(player, key, "dropkey", 0, 0);
813         GameRules_scoring_add(player, KH_LOSSES, 1);
814         int realteam = kh_Team_ByID(key.count);
815         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_DROP), player.netname);
816
817         kh_Key_AssignTo(key, NULL);
818         makevectors(player.v_angle);
819         key.velocity = W_CalculateProjectileVelocity(player, player.velocity, autocvar_g_balance_keyhunt_throwvelocity * v_forward, false);
820         key.pusher = NULL;
821         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
822         key.kh_dropperteam = key.team;
823
824         sound(player, CH_TRIGGER, SND_KH_DROP, VOL_BASE, ATTEN_NORM);
825 }
826
827 void kh_Key_DropAll(entity player, float suicide) // runs whenever a player dies
828 {
829         if(player.kh_next)
830         {
831                 entity mypusher = NULL;
832                 if(player.pusher)
833                         if(time < player.pushltime)
834                                 mypusher = player.pusher;
835
836                 entity key;
837                 while((key = player.kh_next))
838                 {
839                         kh_Scores_Event(player, key, "losekey", 0, 0);
840                         GameRules_scoring_add(player, KH_LOSSES, 1);
841                         int realteam = kh_Team_ByID(key.count);
842                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_LOST), player.netname);
843                         kh_Key_AssignTo(key, NULL);
844                         makevectors('-1 0 0' * (45 + 45 * random()) + '0 360 0' * random());
845                         key.velocity = W_CalculateProjectileVelocity(player, player.velocity, autocvar_g_balance_keyhunt_dropvelocity * v_forward, false);
846                         key.pusher = mypusher;
847                         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
848                         if(suicide)
849                                 key.kh_dropperteam = player.team;
850                 }
851                 sound(player, CH_TRIGGER, SND_KH_DROP, VOL_BASE, ATTEN_NORM);
852         }
853 }
854
855 int kh_GetMissingTeams()
856 {
857         int missing_teams = 0;
858         for(int i = 0; i < NumTeams(kh_teams); ++i)
859         {
860                 int teem = kh_Team_ByID(i);
861                 int players = 0;
862                 FOREACH_CLIENT(IS_PLAYER(it), {
863                         if(!IS_DEAD(it) && !PHYS_INPUT_BUTTON_CHAT(it) && it.team == teem)
864                                 ++players;
865                 });
866                 if (!players)
867                         missing_teams |= (2 ** i);
868         }
869         return missing_teams;
870 }
871
872 void kh_WaitForPlayers()  // delay start of the round until enough players are present
873 {
874         static int prev_missing_teams_mask;
875         if(time < game_starttime)
876         {
877                 if (prev_missing_teams_mask > 0)
878                         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS);
879                 prev_missing_teams_mask = -1;
880                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
881                 return;
882         }
883
884         int missing_teams_mask = kh_GetMissingTeams();
885         if(!missing_teams_mask)
886         {
887                 if(prev_missing_teams_mask > 0)
888                         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS);
889                 prev_missing_teams_mask = -1;
890                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
891                 kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
892         }
893         else
894         {
895                 if(player_count == 0)
896                 {
897                         if(prev_missing_teams_mask > 0)
898                                 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS);
899                         prev_missing_teams_mask = -1;
900                 }
901                 else
902                 {
903                         if(prev_missing_teams_mask != missing_teams_mask)
904                         {
905                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask);
906                                 prev_missing_teams_mask = missing_teams_mask;
907                         }
908                 }
909                 kh_Controller_SetThink(1, kh_WaitForPlayers);
910         }
911 }
912
913 void kh_EnableTrackingDevice()  // runs after each round
914 {
915         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT);
916         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER);
917
918         kh_tracking_enabled = true;
919 }
920
921 void kh_StartRound()  // runs at the start of each round
922 {
923         if(time < game_starttime)
924         {
925                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
926                 return;
927         }
928
929         if(kh_GetMissingTeams())
930         {
931                 kh_Controller_SetThink(1, kh_WaitForPlayers);
932                 return;
933         }
934
935         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT);
936         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER);
937
938         for(int i = 0; i < NumTeams(kh_teams); ++i)
939         {
940                 int teem = kh_Team_ByID(i);
941                 int players = 0;
942                 entity my_player = NULL;
943                 FOREACH_CLIENT(IS_PLAYER(it), {
944                         if(!IS_DEAD(it) && !PHYS_INPUT_BUTTON_CHAT(it) && it.team == teem)
945                         {
946                                 ++players;
947                                 if(random() * players <= 1)
948                                         my_player = it;
949                         }
950                 });
951                 kh_Key_Spawn(my_player, 360 * i / NumTeams(kh_teams), i);
952         }
953
954         kh_tracking_enabled = false;
955         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_SCAN, autocvar_g_balance_keyhunt_delay_tracking);
956         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_tracking, kh_EnableTrackingDevice);
957 }
958
959 float kh_HandleFrags(entity attacker, entity targ, float f)  // adds to the player score
960 {
961         if(attacker == targ)
962                 return f;
963
964         if(targ.kh_next)
965         {
966                 if(attacker.team == targ.team)
967                 {
968                         int nk = 0;
969                         for(entity k = targ.kh_next; k != NULL; k = k.kh_next)
970                                 ++nk;
971                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", -nk * autocvar_g_balance_keyhunt_score_collect, 0);
972                 }
973                 else
974                 {
975                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", autocvar_g_balance_keyhunt_score_carrierfrag-1, 0);
976                         GameRules_scoring_add(attacker, KH_KCKILLS, 1);
977                         // the frag gets added later
978                 }
979         }
980
981         return f;
982 }
983
984 void kh_Initialize()  // sets up th KH environment
985 {
986         // setup variables
987         kh_teams = autocvar_g_keyhunt_teams_override;
988         if(kh_teams < 2)
989                 kh_teams = cvar("g_keyhunt_teams"); // read the cvar directly as it gets written earlier in the same frame
990         kh_teams = BITS(bound(2, kh_teams, 4));
991
992         // make a KH entity for controlling the game
993         kh_controller = spawn();
994         setthink(kh_controller, kh_Controller_Think);
995         kh_Controller_SetThink(0, kh_WaitForPlayers);
996
997         setmodel(kh_controller, MDL_KH_KEY);
998         kh_key_dropped = kh_controller.modelindex;
999         /*
1000         dprint(vtos(kh_controller.mins));
1001         dprint(vtos(kh_controller.maxs));
1002         dprint("\n");
1003         */
1004 #ifdef KH_PLAYER_USE_CARRIEDMODEL
1005         setmodel(kh_controller, MDL_KH_KEY_CARRIED);
1006         kh_key_carried = kh_controller.modelindex;
1007 #else
1008         kh_key_carried = kh_key_dropped;
1009 #endif
1010
1011         kh_controller.model = "";
1012         kh_controller.modelindex = 0;
1013
1014         kh_ScoreRules(kh_teams);
1015 }
1016
1017 void kh_finalize()
1018 {
1019         // to be called before intermission
1020         kh_FinishRound();
1021         delete(kh_controller);
1022         kh_controller = NULL;
1023 }
1024
1025 // legacy bot role
1026
1027 void(entity this) havocbot_role_kh_carrier;
1028 void(entity this) havocbot_role_kh_defense;
1029 void(entity this) havocbot_role_kh_offense;
1030 void(entity this) havocbot_role_kh_freelancer;
1031
1032
1033 void havocbot_goalrating_kh(entity this, float ratingscale_team, float ratingscale_dropped, float ratingscale_enemy)
1034 {
1035         entity head;
1036         for (head = kh_worldkeylist; head; head = head.kh_worldkeynext)
1037         {
1038                 if(head.owner == this)
1039                         continue;
1040                 if(!kh_tracking_enabled)
1041                 {
1042                         // if it's carried by our team we know about it
1043                         // otherwise we have to see it to know about it
1044                         if(!head.owner || head.team != this.team)
1045                         {
1046                                 traceline(this.origin + this.view_ofs, head.origin, MOVE_NOMONSTERS, this);
1047                                 if (trace_fraction < 1 && trace_ent != head)
1048                                         continue; // skip what I can't see
1049                         }
1050                 }
1051                 if(!head.owner)
1052                         navigation_routerating(this, head, ratingscale_dropped * 10000, 100000);
1053                 else if(head.team == this.team)
1054                         navigation_routerating(this, head.owner, ratingscale_team * 10000, 100000);
1055                 else
1056                         navigation_routerating(this, head.owner, ratingscale_enemy * 10000, 100000);
1057         }
1058
1059         havocbot_goalrating_items(this, 1, this.origin, 10000);
1060 }
1061
1062 void havocbot_role_kh_carrier(entity this)
1063 {
1064         if(IS_DEAD(this))
1065                 return;
1066
1067         if (!(this.kh_next))
1068         {
1069                 LOG_TRACE("changing role to freelancer");
1070                 this.havocbot_role = havocbot_role_kh_freelancer;
1071                 this.havocbot_role_timeout = 0;
1072                 return;
1073         }
1074
1075         if (navigation_goalrating_timeout(this))
1076         {
1077                 navigation_goalrating_start(this);
1078
1079                 if(kh_Key_AllOwnedByWhichTeam() == this.team)
1080                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // bring home
1081                 else
1082                         havocbot_goalrating_kh(this, 4, 4, 1); // play defensively
1083
1084                 navigation_goalrating_end(this);
1085
1086                 navigation_goalrating_timeout_set(this);
1087         }
1088 }
1089
1090 void havocbot_role_kh_defense(entity this)
1091 {
1092         if(IS_DEAD(this))
1093                 return;
1094
1095         if (this.kh_next)
1096         {
1097                 LOG_TRACE("changing role to carrier");
1098                 this.havocbot_role = havocbot_role_kh_carrier;
1099                 this.havocbot_role_timeout = 0;
1100                 return;
1101         }
1102
1103         if (!this.havocbot_role_timeout)
1104                 this.havocbot_role_timeout = time + random() * 10 + 20;
1105         if (time > this.havocbot_role_timeout)
1106         {
1107                 LOG_TRACE("changing role to freelancer");
1108                 this.havocbot_role = havocbot_role_kh_freelancer;
1109                 this.havocbot_role_timeout = 0;
1110                 return;
1111         }
1112
1113         if (navigation_goalrating_timeout(this))
1114         {
1115                 float key_owner_team;
1116                 navigation_goalrating_start(this);
1117
1118                 key_owner_team = kh_Key_AllOwnedByWhichTeam();
1119                 if(key_owner_team == this.team)
1120                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend key carriers
1121                 else if(key_owner_team == -1)
1122                         havocbot_goalrating_kh(this, 4, 1, 0.1); // play defensively
1123                 else
1124                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY
1125
1126                 navigation_goalrating_end(this);
1127
1128                 navigation_goalrating_timeout_set(this);
1129         }
1130 }
1131
1132 void havocbot_role_kh_offense(entity this)
1133 {
1134         if(IS_DEAD(this))
1135                 return;
1136
1137         if (this.kh_next)
1138         {
1139                 LOG_TRACE("changing role to carrier");
1140                 this.havocbot_role = havocbot_role_kh_carrier;
1141                 this.havocbot_role_timeout = 0;
1142                 return;
1143         }
1144
1145         if (!this.havocbot_role_timeout)
1146                 this.havocbot_role_timeout = time + random() * 10 + 20;
1147         if (time > this.havocbot_role_timeout)
1148         {
1149                 LOG_TRACE("changing role to freelancer");
1150                 this.havocbot_role = havocbot_role_kh_freelancer;
1151                 this.havocbot_role_timeout = 0;
1152                 return;
1153         }
1154
1155         if (navigation_goalrating_timeout(this))
1156         {
1157                 float key_owner_team;
1158
1159                 navigation_goalrating_start(this);
1160
1161                 key_owner_team = kh_Key_AllOwnedByWhichTeam();
1162                 if(key_owner_team == this.team)
1163                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway
1164                 else if(key_owner_team == -1)
1165                         havocbot_goalrating_kh(this, 0.1, 1, 4); // play offensively
1166                 else
1167                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK! EMERGENCY!
1168
1169                 navigation_goalrating_end(this);
1170
1171                 navigation_goalrating_timeout_set(this);
1172         }
1173 }
1174
1175 void havocbot_role_kh_freelancer(entity this)
1176 {
1177         if(IS_DEAD(this))
1178                 return;
1179
1180         if (this.kh_next)
1181         {
1182                 LOG_TRACE("changing role to carrier");
1183                 this.havocbot_role = havocbot_role_kh_carrier;
1184                 this.havocbot_role_timeout = 0;
1185                 return;
1186         }
1187
1188         if (!this.havocbot_role_timeout)
1189                 this.havocbot_role_timeout = time + random() * 10 + 10;
1190         if (time > this.havocbot_role_timeout)
1191         {
1192                 if (random() < 0.5)
1193                 {
1194                         LOG_TRACE("changing role to offense");
1195                         this.havocbot_role = havocbot_role_kh_offense;
1196                 }
1197                 else
1198                 {
1199                         LOG_TRACE("changing role to defense");
1200                         this.havocbot_role = havocbot_role_kh_defense;
1201                 }
1202                 this.havocbot_role_timeout = 0;
1203                 return;
1204         }
1205
1206         if (navigation_goalrating_timeout(this))
1207         {
1208                 navigation_goalrating_start(this);
1209
1210                 int key_owner_team = kh_Key_AllOwnedByWhichTeam();
1211                 if(key_owner_team == this.team)
1212                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway
1213                 else if(key_owner_team == -1)
1214                         havocbot_goalrating_kh(this, 1, 10, 4); // prefer dropped keys
1215                 else
1216                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY
1217
1218                 navigation_goalrating_end(this);
1219
1220                 navigation_goalrating_timeout_set(this);
1221         }
1222 }
1223
1224
1225 // register this as a mutator
1226
1227 MUTATOR_HOOKFUNCTION(kh, ClientDisconnect)
1228 {
1229         entity player = M_ARGV(0, entity);
1230
1231         kh_Key_DropAll(player, true);
1232 }
1233
1234 MUTATOR_HOOKFUNCTION(kh, MakePlayerObserver)
1235 {
1236         entity player = M_ARGV(0, entity);
1237
1238         kh_Key_DropAll(player, true);
1239 }
1240
1241 MUTATOR_HOOKFUNCTION(kh, PlayerDies)
1242 {
1243         entity frag_attacker = M_ARGV(1, entity);
1244         entity frag_target = M_ARGV(2, entity);
1245
1246         if(frag_target == frag_attacker)
1247                 kh_Key_DropAll(frag_target, true);
1248         else if(IS_PLAYER(frag_attacker))
1249                 kh_Key_DropAll(frag_target, false);
1250         else
1251                 kh_Key_DropAll(frag_target, true);
1252 }
1253
1254 MUTATOR_HOOKFUNCTION(kh, GiveFragsForKill, CBC_ORDER_FIRST)
1255 {
1256         entity frag_attacker = M_ARGV(0, entity);
1257         entity frag_target = M_ARGV(1, entity);
1258         float frag_score = M_ARGV(2, float);
1259         M_ARGV(2, float) = kh_HandleFrags(frag_attacker, frag_target, frag_score);
1260 }
1261
1262 MUTATOR_HOOKFUNCTION(kh, MatchEnd)
1263 {
1264         kh_finalize();
1265 }
1266
1267 MUTATOR_HOOKFUNCTION(kh, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE)
1268 {
1269         M_ARGV(0, float) = kh_teams;
1270 }
1271
1272 MUTATOR_HOOKFUNCTION(kh, SpectateCopy)
1273 {
1274         entity spectatee = M_ARGV(0, entity);
1275         entity client = M_ARGV(1, entity);
1276
1277         STAT(KH_KEYS, client) = STAT(KH_KEYS, spectatee);
1278 }
1279
1280 MUTATOR_HOOKFUNCTION(kh, PlayerUseKey)
1281 {
1282         entity player = M_ARGV(0, entity);
1283
1284         if(MUTATOR_RETURNVALUE == 0)
1285         {
1286                 entity k = player.kh_next;
1287                 if(k)
1288                 {
1289                         kh_Key_DropOne(k);
1290                         return true;
1291                 }
1292         }
1293 }
1294
1295 MUTATOR_HOOKFUNCTION(kh, HavocBot_ChooseRole)
1296 {
1297     entity bot = M_ARGV(0, entity);
1298
1299         if(IS_DEAD(bot))
1300                 return true;
1301
1302         float r = random() * 3;
1303         if (r < 1)
1304                 bot.havocbot_role = havocbot_role_kh_offense;
1305         else if (r < 2)
1306                 bot.havocbot_role = havocbot_role_kh_defense;
1307         else
1308                 bot.havocbot_role = havocbot_role_kh_freelancer;
1309
1310         return true;
1311 }
1312
1313 MUTATOR_HOOKFUNCTION(kh, DropSpecialItems)
1314 {
1315         entity frag_target = M_ARGV(0, entity);
1316
1317         kh_Key_DropAll(frag_target, false);
1318 }
1319
1320 MUTATOR_HOOKFUNCTION(kh, reset_map_global)
1321 {
1322         kh_WaitForPlayers(); // takes care of killing the "missing teams" message
1323 }
1324 #endif