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