Merge branch 'Mario/teams_bitflag' into 'master'
[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(int 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         set_movetype(key, 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         set_movetype(key, 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                         int missing_teams_mask = 0;
963                         if(kh_teams & BIT(0))
964                                 missing_teams_mask += boolean(p1) * 1;
965                         if(kh_teams & BIT(1))
966                                 missing_teams_mask += boolean(p2) * 2;
967                         if(kh_teams & BIT(2))
968                                 missing_teams_mask += boolean(p3) * 4;
969                         if(kh_teams & BIT(3))
970                                 missing_teams_mask += boolean(p4) * 8;
971                         if(prev_missing_teams_mask != missing_teams_mask)
972                         {
973                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask);
974                                 prev_missing_teams_mask = missing_teams_mask;
975                         }
976                 }
977                 kh_Controller_SetThink(1, kh_WaitForPlayers);
978         }
979 }
980
981 void kh_EnableTrackingDevice()  // runs after each round
982 {
983         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT);
984         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER);
985
986         kh_tracking_enabled = true;
987 }
988
989 void kh_StartRound()  // runs at the start of each round
990 {
991         float i, players, teem;
992
993         if(time < game_starttime)
994         {
995                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
996                 return;
997         }
998
999         float p1 = kh_CheckPlayers(0), p2 = kh_CheckPlayers(1), p3 = kh_CheckPlayers(2), p4 = kh_CheckPlayers(3);
1000         if(!KH_READY_TEAMS_OK())
1001         {
1002                 kh_Controller_SetThink(1, kh_WaitForPlayers);
1003                 return;
1004         }
1005
1006         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT);
1007         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER);
1008
1009         for(i = 0; i < kh_teams; ++i)
1010         {
1011                 teem = kh_Team_ByID(i);
1012                 players = 0;
1013                 entity my_player = NULL;
1014                 FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1015                         if(!IS_DEAD(it) && !PHYS_INPUT_BUTTON_CHAT(it) && it.team == teem)
1016                         {
1017                                 ++players;
1018                                 if(random() * players <= 1)
1019                                         my_player = it;
1020                         }
1021                 ));
1022                 kh_Key_Spawn(my_player, 360 * i / kh_teams, i);
1023         }
1024
1025         kh_tracking_enabled = false;
1026         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_SCAN, autocvar_g_balance_keyhunt_delay_tracking);
1027         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_tracking, kh_EnableTrackingDevice);
1028 }
1029
1030 float kh_HandleFrags(entity attacker, entity targ, float f)  // adds to the player score
1031 {
1032         if(attacker == targ)
1033                 return f;
1034
1035         if(targ.kh_next)
1036         {
1037                 if(attacker.team == targ.team)
1038                 {
1039                         entity k;
1040                         float nk;
1041                         nk = 0;
1042                         for(k = targ.kh_next; k != NULL; k = k.kh_next)
1043                                 ++nk;
1044                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", -nk * autocvar_g_balance_keyhunt_score_collect, 0);
1045                 }
1046                 else
1047                 {
1048                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", autocvar_g_balance_keyhunt_score_carrierfrag-1, 0);
1049                         PlayerScore_Add(attacker, SP_KH_KCKILLS, 1);
1050                         // the frag gets added later
1051                 }
1052         }
1053
1054         return f;
1055 }
1056
1057 void kh_Initialize()  // sets up th KH environment
1058 {
1059         // setup variables
1060         kh_teams = autocvar_g_keyhunt_teams_override;
1061         if(kh_teams < 2)
1062                 kh_teams = autocvar_g_keyhunt_teams;
1063         kh_teams = bound(2, kh_teams, 4);
1064
1065         int teams = 0;
1066         if(kh_teams >= 1) teams |= BIT(0);
1067         if(kh_teams >= 2) teams |= BIT(1);
1068         if(kh_teams >= 3) teams |= BIT(2);
1069         if(kh_teams >= 4) teams |= BIT(3);
1070
1071         kh_teams = teams; // now set it?
1072
1073         // make a KH entity for controlling the game
1074         kh_controller = spawn();
1075         setthink(kh_controller, kh_Controller_Think);
1076         kh_Controller_SetThink(0, kh_WaitForPlayers);
1077
1078         setmodel(kh_controller, MDL_KH_KEY);
1079         kh_key_dropped = kh_controller.modelindex;
1080         /*
1081         dprint(vtos(kh_controller.mins));
1082         dprint(vtos(kh_controller.maxs));
1083         dprint("\n");
1084         */
1085 #ifdef KH_PLAYER_USE_CARRIEDMODEL
1086         setmodel(kh_controller, MDL_KH_KEY_CARRIED);
1087         kh_key_carried = kh_controller.modelindex;
1088 #else
1089         kh_key_carried = kh_key_dropped;
1090 #endif
1091
1092         kh_controller.model = "";
1093         kh_controller.modelindex = 0;
1094
1095         kh_ScoreRules(kh_teams);
1096 }
1097
1098 void kh_finalize()
1099 {
1100         // to be called before intermission
1101         kh_FinishRound();
1102         remove(kh_controller);
1103         kh_controller = NULL;
1104 }
1105
1106 // legacy bot role
1107
1108 void(entity this) havocbot_role_kh_carrier;
1109 void(entity this) havocbot_role_kh_defense;
1110 void(entity this) havocbot_role_kh_offense;
1111 void(entity this) havocbot_role_kh_freelancer;
1112
1113
1114 void havocbot_goalrating_kh(entity this, float ratingscale_team, float ratingscale_dropped, float ratingscale_enemy)
1115 {
1116         entity head;
1117         for (head = kh_worldkeylist; head; head = head.kh_worldkeynext)
1118         {
1119                 if(head.owner == this)
1120                         continue;
1121                 if(!kh_tracking_enabled)
1122                 {
1123                         // if it's carried by our team we know about it
1124                         // otherwise we have to see it to know about it
1125                         if(!head.owner || head.team != this.team)
1126                         {
1127                                 traceline(this.origin + this.view_ofs, head.origin, MOVE_NOMONSTERS, this);
1128                                 if (trace_fraction < 1 && trace_ent != head)
1129                                         continue; // skip what I can't see
1130                         }
1131                 }
1132                 if(!head.owner)
1133                         navigation_routerating(this, head, ratingscale_dropped * BOT_PICKUP_RATING_HIGH, 100000);
1134                 else if(head.team == this.team)
1135                         navigation_routerating(this, head.owner, ratingscale_team * BOT_PICKUP_RATING_HIGH, 100000);
1136                 else
1137                         navigation_routerating(this, head.owner, ratingscale_enemy * BOT_PICKUP_RATING_HIGH, 100000);
1138         }
1139
1140         havocbot_goalrating_items(this, 1, this.origin, 10000);
1141 }
1142
1143 void havocbot_role_kh_carrier(entity this)
1144 {
1145         if(IS_DEAD(this))
1146                 return;
1147
1148         if (!(this.kh_next))
1149         {
1150                 LOG_TRACE("changing role to freelancer\n");
1151                 this.havocbot_role = havocbot_role_kh_freelancer;
1152                 this.havocbot_role_timeout = 0;
1153                 return;
1154         }
1155
1156         if (this.bot_strategytime < time)
1157         {
1158                 this.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1159                 navigation_goalrating_start(this);
1160
1161                 if(kh_Key_AllOwnedByWhichTeam() == this.team)
1162                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // bring home
1163                 else
1164                         havocbot_goalrating_kh(this, 4, 4, 1); // play defensively
1165
1166                 navigation_goalrating_end(this);
1167         }
1168 }
1169
1170 void havocbot_role_kh_defense(entity this)
1171 {
1172         if(IS_DEAD(this))
1173                 return;
1174
1175         if (this.kh_next)
1176         {
1177                 LOG_TRACE("changing role to carrier\n");
1178                 this.havocbot_role = havocbot_role_kh_carrier;
1179                 this.havocbot_role_timeout = 0;
1180                 return;
1181         }
1182
1183         if (!this.havocbot_role_timeout)
1184                 this.havocbot_role_timeout = time + random() * 10 + 20;
1185         if (time > this.havocbot_role_timeout)
1186         {
1187                 LOG_TRACE("changing role to freelancer\n");
1188                 this.havocbot_role = havocbot_role_kh_freelancer;
1189                 this.havocbot_role_timeout = 0;
1190                 return;
1191         }
1192
1193         if (this.bot_strategytime < time)
1194         {
1195                 float key_owner_team;
1196                 this.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1197                 navigation_goalrating_start(this);
1198
1199                 key_owner_team = kh_Key_AllOwnedByWhichTeam();
1200                 if(key_owner_team == this.team)
1201                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend key carriers
1202                 else if(key_owner_team == -1)
1203                         havocbot_goalrating_kh(this, 4, 1, 0.1); // play defensively
1204                 else
1205                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY
1206
1207                 navigation_goalrating_end(this);
1208         }
1209 }
1210
1211 void havocbot_role_kh_offense(entity this)
1212 {
1213         if(IS_DEAD(this))
1214                 return;
1215
1216         if (this.kh_next)
1217         {
1218                 LOG_TRACE("changing role to carrier\n");
1219                 this.havocbot_role = havocbot_role_kh_carrier;
1220                 this.havocbot_role_timeout = 0;
1221                 return;
1222         }
1223
1224         if (!this.havocbot_role_timeout)
1225                 this.havocbot_role_timeout = time + random() * 10 + 20;
1226         if (time > this.havocbot_role_timeout)
1227         {
1228                 LOG_TRACE("changing role to freelancer\n");
1229                 this.havocbot_role = havocbot_role_kh_freelancer;
1230                 this.havocbot_role_timeout = 0;
1231                 return;
1232         }
1233
1234         if (this.bot_strategytime < time)
1235         {
1236                 float key_owner_team;
1237
1238                 this.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1239                 navigation_goalrating_start(this);
1240
1241                 key_owner_team = kh_Key_AllOwnedByWhichTeam();
1242                 if(key_owner_team == this.team)
1243                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway
1244                 else if(key_owner_team == -1)
1245                         havocbot_goalrating_kh(this, 0.1, 1, 4); // play offensively
1246                 else
1247                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK! EMERGENCY!
1248
1249                 navigation_goalrating_end(this);
1250         }
1251 }
1252
1253 void havocbot_role_kh_freelancer(entity this)
1254 {
1255         if(IS_DEAD(this))
1256                 return;
1257
1258         if (this.kh_next)
1259         {
1260                 LOG_TRACE("changing role to carrier\n");
1261                 this.havocbot_role = havocbot_role_kh_carrier;
1262                 this.havocbot_role_timeout = 0;
1263                 return;
1264         }
1265
1266         if (!this.havocbot_role_timeout)
1267                 this.havocbot_role_timeout = time + random() * 10 + 10;
1268         if (time > this.havocbot_role_timeout)
1269         {
1270                 if (random() < 0.5)
1271                 {
1272                         LOG_TRACE("changing role to offense\n");
1273                         this.havocbot_role = havocbot_role_kh_offense;
1274                 }
1275                 else
1276                 {
1277                         LOG_TRACE("changing role to defense\n");
1278                         this.havocbot_role = havocbot_role_kh_defense;
1279                 }
1280                 this.havocbot_role_timeout = 0;
1281                 return;
1282         }
1283
1284         if (this.bot_strategytime < time)
1285         {
1286                 float key_owner_team;
1287
1288                 this.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1289                 navigation_goalrating_start(this);
1290
1291                 key_owner_team = kh_Key_AllOwnedByWhichTeam();
1292                 if(key_owner_team == this.team)
1293                         havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway
1294                 else if(key_owner_team == -1)
1295                         havocbot_goalrating_kh(this, 1, 10, 4); // prefer dropped keys
1296                 else
1297                         havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY
1298
1299                 navigation_goalrating_end(this);
1300         }
1301 }
1302
1303
1304 // register this as a mutator
1305
1306 MUTATOR_HOOKFUNCTION(kh, ClientDisconnect)
1307 {
1308         entity player = M_ARGV(0, entity);
1309
1310         kh_Key_DropAll(player, true);
1311 }
1312
1313 MUTATOR_HOOKFUNCTION(kh, MakePlayerObserver)
1314 {
1315         entity player = M_ARGV(0, entity);
1316
1317         kh_Key_DropAll(player, true);
1318 }
1319
1320 MUTATOR_HOOKFUNCTION(kh, PlayerDies)
1321 {
1322         entity frag_attacker = M_ARGV(1, entity);
1323         entity frag_target = M_ARGV(2, entity);
1324
1325         if(frag_target == frag_attacker)
1326                 kh_Key_DropAll(frag_target, true);
1327         else if(IS_PLAYER(frag_attacker))
1328                 kh_Key_DropAll(frag_target, false);
1329         else
1330                 kh_Key_DropAll(frag_target, true);
1331 }
1332
1333 MUTATOR_HOOKFUNCTION(kh, GiveFragsForKill, CBC_ORDER_FIRST)
1334 {
1335         entity frag_attacker = M_ARGV(0, entity);
1336         entity frag_target = M_ARGV(1, entity);
1337         float frag_score = M_ARGV(2, float);
1338         M_ARGV(2, float) = kh_HandleFrags(frag_attacker, frag_target, frag_score);
1339 }
1340
1341 MUTATOR_HOOKFUNCTION(kh, MatchEnd)
1342 {
1343         kh_finalize();
1344 }
1345
1346 MUTATOR_HOOKFUNCTION(kh, GetTeamCount, CBC_ORDER_EXCLUSIVE)
1347 {
1348         M_ARGV(0, float) = kh_teams;
1349 }
1350
1351 MUTATOR_HOOKFUNCTION(kh, SpectateCopy)
1352 {
1353         entity spectatee = M_ARGV(0, entity);
1354         entity client = M_ARGV(1, entity);
1355
1356         client.kh_state = spectatee.kh_state;
1357 }
1358
1359 MUTATOR_HOOKFUNCTION(kh, PlayerUseKey)
1360 {
1361         entity player = M_ARGV(0, entity);
1362
1363         if(MUTATOR_RETURNVALUE == 0)
1364         {
1365                 entity k = player.kh_next;
1366                 if(k)
1367                 {
1368                         kh_Key_DropOne(k);
1369                         return true;
1370                 }
1371         }
1372 }
1373
1374 MUTATOR_HOOKFUNCTION(kh, HavocBot_ChooseRole)
1375 {
1376     entity bot = M_ARGV(0, entity);
1377
1378         if(IS_DEAD(bot))
1379                 return true;
1380
1381         float r = random() * 3;
1382         if (r < 1)
1383                 bot.havocbot_role = havocbot_role_kh_offense;
1384         else if (r < 2)
1385                 bot.havocbot_role = havocbot_role_kh_defense;
1386         else
1387                 bot.havocbot_role = havocbot_role_kh_freelancer;
1388
1389         return true;
1390 }
1391
1392 MUTATOR_HOOKFUNCTION(kh, DropSpecialItems)
1393 {
1394         entity frag_target = M_ARGV(0, entity);
1395         
1396         kh_Key_DropAll(frag_target, false);
1397 }
1398
1399 MUTATOR_HOOKFUNCTION(kh, reset_map_global)
1400 {
1401         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round + (game_starttime - time), kh_StartRound);
1402 }
1403
1404 #endif