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