]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/bots.qc
Added teamcount() function, will be used to improve the ctf ai
[divverent/nexuiz.git] / data / qcsrc / server / bots.qc
1 .float aistatus;
2 float AI_STATUS_ROAMING                         = 1;    // Bot is just crawling the map. No enemies at sight
3 float AI_STATUS_ATTACKING                       = 2;    // There are enemies at sight
4 float AI_STATUS_RUNNING                         = 4;    // Bot is bunny hopping
5 float AI_STATUS_DANGER_AHEAD                    = 8;    // There is lava/slime/trigger_hurt ahead
6 float AI_STATUS_OUT_JUMPPAD                     = 16;   // Trying to get out of a "vertical" jump pad
7 float AI_STATUS_OUT_WATER                       = 32;   // Trying to get out of water
8 float AI_STATUS_WAYPOINT_PERSONAL_GOING         = 64;   // Going to a personal waypoint
9 float AI_STATUS_WAYPOINT_PERSONAL_REACHED       = 128;  // Personal waypoint reached
10
11 // utilities for path debugging
12 #ifdef DEBUG_TRACEWALK
13
14 float DEBUG_NODE_SUCCESS        = 1;
15 float DEBUG_NODE_WARNING        = 2;
16 float DEBUG_NODE_FAIL           = 3;
17
18 vector debuglastnode;
19
20 void debugresetnodes()
21 {
22         debuglastnode = '0 0 0';
23 }
24
25 void debugnode(vector node)
26 {
27         if not(self.classname=="player")
28                 return;
29
30         if(debuglastnode=='0 0 0')
31         {
32                 debuglastnode = node;
33                 return;
34         }
35
36         te_lightning2(world, node, debuglastnode);
37         debuglastnode = node;
38 }
39
40 void debugnodestatus(vector position, float status)
41 {
42         vector color;
43
44         switch (status)
45         {
46                 case DEBUG_NODE_SUCCESS:
47                         color = '0 15 0';
48                         break;
49                 case DEBUG_NODE_WARNING:
50                         color = '15 15 0';
51                         break;
52                 case DEBUG_NODE_FAIL:
53                         color = '15 0 0';
54                         break;
55                 default:
56                         color = '15 15 15';
57         }
58
59         te_customflash(position, 40,  2, color);
60 }
61
62 #endif
63
64 // rough simulation of walking from one point to another to test if a path
65 // can be traveled, used for waypoint linking and havocbot
66
67 vector stepheightvec;
68 float navigation_testtracewalk;
69 float tracewalk(entity e, vector start, vector m1, vector m2, vector end, float movemode)
70 {
71         local vector org;
72         local vector move;
73         local vector dir;
74         local float dist;
75         local float totaldist;
76         local float stepdist;
77         local float yaw;
78         local float ignorehazards;
79         local float swimming;
80
81         #ifdef DEBUG_TRACEWALK
82                 debugresetnodes();
83                 debugnode(start);
84         #endif
85
86         move = end - start;
87         move_z = 0;
88         org = start;
89         dist = totaldist = vlen(move);
90         dir = normalize(move);
91         stepdist = 32;
92         ignorehazards = FALSE;
93
94         // Analyze starting point
95         traceline(start, start, MOVE_NORMAL, e);
96         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
97                 ignorehazards = TRUE;
98         else
99         {
100                 traceline( start, start + '0 0 -65536', MOVE_NORMAL, e);
101                 if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
102                 {
103                         ignorehazards = TRUE;
104                         swimming = TRUE;
105                 }
106         }
107         tracebox(start, m1, m2, start, MOVE_NOMONSTERS, e);
108         if (trace_startsolid)
109         {
110                 // Bad start
111                 #ifdef DEBUG_TRACEWALK
112                         debugnodestatus(start, DEBUG_NODE_FAIL);
113                 #endif
114                 return FALSE;
115         }
116
117         // Movement loop
118         yaw = vectoyaw(move);
119         move = end - org;
120         for (;;)
121         {
122                 if (boxesoverlap(end, end, org + m1 + '-1 -1 -1', org + m2 + '1 1 1'))
123                 {
124                         // Succeeded
125                         #ifdef DEBUG_TRACEWALK
126                                 debugnodestatus(org, DEBUG_NODE_SUCCESS);
127                         #endif
128                         return TRUE;
129                 }
130                 #ifdef DEBUG_TRACEWALK
131                         debugnode(org);
132                 #endif
133
134                 if (dist <= 0)
135                         break;
136                 if (stepdist > dist)
137                         stepdist = dist;
138                 dist = dist - stepdist;
139                 traceline(org, org, MOVE_NORMAL, e);
140                 if (!ignorehazards)
141                 {
142                         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
143                         {
144                                 // hazards blocking path
145                                 #ifdef DEBUG_TRACEWALK
146                                         debugnodestatus(org, DEBUG_NODE_FAIL);
147                                 #endif
148                                 return FALSE;
149                         }
150                 }
151                 if (trace_dpstartcontents & DPCONTENTS_LIQUIDSMASK)
152                 {
153                         move = normalize(end - org);
154                         tracebox(org, m1, m2, org + move * stepdist, movemode, e);
155
156                         #ifdef DEBUG_TRACEWALK
157                                 debugnode(trace_endpos);
158                         #endif
159
160                         if (trace_fraction < 1)
161                         {
162                                 swimming = TRUE;
163                                 org = trace_endpos - normalize(org - trace_endpos) * stepdist;
164                                 for(; org_z < end_z + self.maxs_z; org_z += stepdist)
165                                 {
166                                                 #ifdef DEBUG_TRACEWALK
167                                                         debugnode(org);
168                                                 #endif
169                                         if(pointcontents(org) == CONTENT_EMPTY)
170                                                         break;
171                                 }
172
173                                 if not (pointcontents(org + '0 0 1') == CONTENT_EMPTY)
174                                 {
175                                         #ifdef DEBUG_TRACEWALK
176                                                 debugnodestatus(org, DEBUG_NODE_FAIL);
177                                         #endif
178                                         return FALSE;
179                                 }
180                                 continue;
181
182                         }
183                         else
184                                 org = trace_endpos;
185                 }
186                 else
187                 {
188                         move = dir * stepdist + org;
189                         tracebox(org, m1, m2, move, movemode, e);
190
191                         #ifdef DEBUG_TRACEWALK
192                                 debugnode(trace_endpos);
193                         #endif
194
195                         // hit something
196                         if (trace_fraction < 1)
197                         {
198                                 // check if we can walk over this obstacle
199                                 tracebox(org + stepheightvec, m1, m2, move + stepheightvec, movemode, e);
200                                 if (trace_fraction < 1 || trace_startsolid)
201                                 {
202                                         #ifdef DEBUG_TRACEWALK
203                                                 debugnodestatus(trace_endpos, DEBUG_NODE_WARNING);
204                                         #endif
205
206                                         // check for doors
207                                         traceline( org, move, movemode, e);
208                                         if ( trace_ent.classname == "door_rotating" || trace_ent.classname == "door")
209                                         {
210                                                 local vector nextmove;
211                                                 move = trace_endpos;
212                                                 while(trace_ent.classname == "door_rotating" || trace_ent.classname == "door")
213                                                 {
214                                                         nextmove = move + (dir * stepdist);
215                                                         traceline( move, nextmove, movemode, e);
216                                                         move = nextmove;
217                                                 }
218                                         }
219                                         else
220                                         {
221                                                 // Check if we can jump over the obstacle
222                                                 local vector jumpheight;
223                                                 // this is an estimate, a proper calculation should involve the cvars sv_jumpvelocity and sv_gravity
224                                                 jumpheight = (PL_VIEW_OFS_z + PL_MIN_z) * '0 0 1';
225                                                 tracebox(org + jumpheight, m1, m2, move + jumpheight, movemode, e);
226
227                                                 if (trace_fraction < 1)
228                                                 {
229                                                         #ifdef DEBUG_TRACEWALK
230                                                                 debugnodestatus(trace_endpos, DEBUG_NODE_FAIL);
231                                                         #endif
232                                                         return FALSE; // failed
233                                                 }
234                                                 // Here we will avoid the trace down because we jumped
235                                                 org = trace_endpos;
236                                                 continue;
237                                         }
238                                 }
239                                 else
240                                         move = trace_endpos;
241                         }
242                         else
243                                 move = trace_endpos;
244
245                         // trace down from stepheight as far as possible and move there,
246                         // if this starts in solid we try again without the stepup, and
247                         // if that also fails we assume it is a wall
248                         // (this is the same logic as the Quake walkmove function used)
249                         tracebox(move, m1, m2, move + '0 0 -65536', movemode, e);
250
251                         // moved successfully
252                         if(swimming)
253                         {
254                                 local float c;
255                                 c = pointcontents(org + '0 0 1');
256                                 if not(c == CONTENT_WATER || c == CONTENT_LAVA || c == CONTENT_SLIME)
257                                         swimming = FALSE;
258                                 else
259                                         continue;
260                         }
261
262                         org = trace_endpos;
263                 }
264         }
265
266         // moved but didn't arrive at the intended destination
267         #ifdef DEBUG_TRACEWALK
268                 debugnodestatus(org, DEBUG_NODE_FAIL);
269         #endif
270
271         return FALSE;
272 };
273
274
275 // grenade tracing to decide the best pitch to fire at
276
277 entity tracetossent;
278 entity tracetossfaketarget;
279
280 // traces multiple trajectories to find one that will impact the target
281 // 'end' vector is the place it aims for,
282 // returns TRUE only if it hit targ (don't target non-solid entities)
283 vector findtrajectory_velocity;
284 float findtrajectorywithleading(vector org, vector m1, vector m2, entity targ, float shotspeed, float shotspeedupward, float maxtime, float shotdelay, entity ignore)
285 {
286         local float c, savesolid, shottime;
287         local vector dir, end, v;
288         if (shotspeed < 1)
289                 return FALSE; // could cause division by zero if calculated
290         if (targ.solid < SOLID_BBOX) // SOLID_NOT and SOLID_TRIGGER
291                 return FALSE; // could never hit it
292         if (!tracetossent)
293                 tracetossent = spawn();
294         tracetossent.owner = ignore;
295         setsize(tracetossent, m1, m2);
296         savesolid = targ.solid;
297         targ.solid = SOLID_NOT;
298         shottime = ((vlen(targ.origin - org) / shotspeed) + shotdelay);
299         v = targ.velocity * shottime + targ.origin;
300         tracebox(targ.origin, targ.mins, targ.maxs, v, FALSE, targ);
301         v = trace_endpos;
302         end = v + (targ.mins + targ.maxs) * 0.5;
303         if ((vlen(end - org) / shotspeed + 0.2) > maxtime)
304         {
305                 // out of range
306                 targ.solid = savesolid;
307                 return FALSE;
308         }
309
310         if (!tracetossfaketarget)
311                 tracetossfaketarget = spawn();
312         tracetossfaketarget.solid = savesolid;
313         tracetossfaketarget.movetype = targ.movetype;
314         setmodel(tracetossfaketarget, targ.model); // no low precision
315         tracetossfaketarget.model = targ.model;
316         tracetossfaketarget.modelindex = targ.modelindex;
317         setsize(tracetossfaketarget, targ.mins, targ.maxs);
318         setorigin(tracetossfaketarget, v);
319
320         c = 0;
321         dir = normalize(end - org);
322         while (c < 10) // 10 traces
323         {
324                 setorigin(tracetossent, org); // reset
325                 tracetossent.velocity = findtrajectory_velocity = normalize(dir) * shotspeed + shotspeedupward * '0 0 1';
326                 tracetoss(tracetossent, ignore); // love builtin functions...
327                 if (trace_ent == tracetossfaketarget) // done
328                 {
329                         targ.solid = savesolid;
330
331                         // make it disappear
332                         tracetossfaketarget.solid = SOLID_NOT;
333                         tracetossfaketarget.movetype = MOVETYPE_NONE;
334                         tracetossfaketarget.model = "";
335                         tracetossfaketarget.modelindex = 0;
336                         // relink to remove it from physics considerations
337                         setorigin(tracetossfaketarget, v);
338
339                         return TRUE;
340                 }
341                 dir_z = dir_z + 0.1; // aim up a little more
342                 c = c + 1;
343         }
344         targ.solid = savesolid;
345
346         // make it disappear
347         tracetossfaketarget.solid = SOLID_NOT;
348         tracetossfaketarget.movetype = MOVETYPE_NONE;
349         tracetossfaketarget.model = "";
350         tracetossfaketarget.modelindex = 0;
351         // relink to remove it from physics considerations
352         setorigin(tracetossfaketarget, v);
353
354         // leave a valid one even if it won't reach
355         findtrajectory_velocity = normalize(end - org) * shotspeed + shotspeedupward * '0 0 1';
356         return FALSE;
357 };
358
359
360
361 // lag simulation
362
363 .void(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4) lag_func;
364
365 // upto 5 queued messages
366 .float lag1_time;
367 .float lag1_float1;
368 .float lag1_float2;
369 .entity lag1_entity1;
370 .vector lag1_vec1;
371 .vector lag1_vec2;
372 .vector lag1_vec3;
373 .vector lag1_vec4;
374
375 .float lag2_time;
376 .float lag2_float1;
377 .float lag2_float2;
378 .entity lag2_entity1;
379 .vector lag2_vec1;
380 .vector lag2_vec2;
381 .vector lag2_vec3;
382 .vector lag2_vec4;
383
384 .float lag3_time;
385 .float lag3_float1;
386 .float lag3_float2;
387 .entity lag3_entity1;
388 .vector lag3_vec1;
389 .vector lag3_vec2;
390 .vector lag3_vec3;
391 .vector lag3_vec4;
392
393 .float lag4_time;
394 .float lag4_float1;
395 .float lag4_float2;
396 .entity lag4_entity1;
397 .vector lag4_vec1;
398 .vector lag4_vec2;
399 .vector lag4_vec3;
400 .vector lag4_vec4;
401
402 .float lag5_time;
403 .float lag5_float1;
404 .float lag5_float2;
405 .entity lag5_entity1;
406 .vector lag5_vec1;
407 .vector lag5_vec2;
408 .vector lag5_vec3;
409 .vector lag5_vec4;
410
411 void lag_update()
412 {
413         if (self.lag1_time) if (time > self.lag1_time) {self.lag_func(self.lag1_time, self.lag1_float1, self.lag1_float2, self.lag1_entity1, self.lag1_vec1, self.lag1_vec2, self.lag1_vec3, self.lag1_vec4);self.lag1_time = 0;}
414         if (self.lag2_time) if (time > self.lag2_time) {self.lag_func(self.lag2_time, self.lag2_float1, self.lag2_float2, self.lag2_entity1, self.lag2_vec1, self.lag2_vec2, self.lag2_vec3, self.lag2_vec4);self.lag2_time = 0;}
415         if (self.lag3_time) if (time > self.lag3_time) {self.lag_func(self.lag3_time, self.lag3_float1, self.lag3_float2, self.lag3_entity1, self.lag3_vec1, self.lag3_vec2, self.lag3_vec3, self.lag3_vec4);self.lag3_time = 0;}
416         if (self.lag4_time) if (time > self.lag4_time) {self.lag_func(self.lag4_time, self.lag4_float1, self.lag4_float2, self.lag4_entity1, self.lag4_vec1, self.lag4_vec2, self.lag4_vec3, self.lag4_vec4);self.lag4_time = 0;}
417         if (self.lag5_time) if (time > self.lag5_time) {self.lag_func(self.lag5_time, self.lag5_float1, self.lag5_float2, self.lag5_entity1, self.lag5_vec1, self.lag5_vec2, self.lag5_vec3, self.lag5_vec4);self.lag5_time = 0;}
418 };
419
420 float lag_additem(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
421 {
422         if (self.lag1_time == 0) {self.lag1_time = t;self.lag1_float1 = f1;self.lag1_float2 = f2;self.lag1_entity1 = e1;self.lag1_vec1 = v1;self.lag1_vec2 = v2;self.lag1_vec3 = v3;self.lag1_vec4 = v4;return TRUE;}
423         if (self.lag2_time == 0) {self.lag2_time = t;self.lag2_float1 = f1;self.lag2_float2 = f2;self.lag2_entity1 = e1;self.lag2_vec1 = v1;self.lag2_vec2 = v2;self.lag2_vec3 = v3;self.lag2_vec4 = v4;return TRUE;}
424         if (self.lag3_time == 0) {self.lag3_time = t;self.lag3_float1 = f1;self.lag3_float2 = f2;self.lag3_entity1 = e1;self.lag3_vec1 = v1;self.lag3_vec2 = v2;self.lag3_vec3 = v3;self.lag3_vec4 = v4;return TRUE;}
425         if (self.lag4_time == 0) {self.lag4_time = t;self.lag4_float1 = f1;self.lag4_float2 = f2;self.lag4_entity1 = e1;self.lag4_vec1 = v1;self.lag4_vec2 = v2;self.lag4_vec3 = v3;self.lag4_vec4 = v4;return TRUE;}
426         if (self.lag5_time == 0) {self.lag5_time = t;self.lag5_float1 = f1;self.lag5_float2 = f2;self.lag5_entity1 = e1;self.lag5_vec1 = v1;self.lag5_vec2 = v2;self.lag5_vec3 = v3;self.lag5_vec4 = v4;return TRUE;}
427         // no room for it (what is the best thing to do here??)
428         return FALSE;
429 };
430
431
432 // Random skill system
433 .float bot_thinkskill;
434 .float bot_mouseskill;
435 .float bot_predictionskill;
436 .float bot_offsetskill;
437
438
439 // spawnfunc_waypoint navigation system
440
441 // itemscore = (howmuchmoreIwant / howmuchIcanwant) / itemdistance
442 // waypointscore = 0.7 / waypointdistance
443
444 .entity wp00, wp01, wp02, wp03, wp04, wp05, wp06, wp07;
445 .entity wp08, wp09, wp10, wp11, wp12, wp13, wp14, wp15;
446 .entity wp16, wp17, wp18, wp19, wp20, wp21, wp22, wp23, wp24, wp25, wp26, wp27, wp28, wp29, wp30, wp31;
447 .float wp00mincost, wp01mincost, wp02mincost, wp03mincost, wp04mincost, wp05mincost, wp06mincost, wp07mincost;
448 .float wp08mincost, wp09mincost, wp10mincost, wp11mincost, wp12mincost, wp13mincost, wp14mincost, wp15mincost;
449 .float wp16mincost, wp17mincost, wp18mincost, wp19mincost, wp20mincost, wp21mincost, wp22mincost, wp23mincost, wp24mincost, wp25mincost, wp26mincost, wp27mincost, wp28mincost, wp29mincost, wp30mincost, wp31mincost;
450 .float wpfire, wpcost, wpconsidered;
451 .float wpisbox;
452 .float wpflags;
453 .vector wpnearestpoint;
454
455 // stack of current goals (the last one of which may be an item or other
456 // desirable object, the rest are typically waypoints to reach it)
457 .entity goalcurrent, goalstack01, goalstack02, goalstack03;
458 .entity goalstack04, goalstack05, goalstack06, goalstack07;
459 .entity goalstack08, goalstack09, goalstack10, goalstack11;
460 .entity goalstack12, goalstack13, goalstack14, goalstack15;
461 .entity goalstack16, goalstack17, goalstack18, goalstack19;
462 .entity goalstack20, goalstack21, goalstack22, goalstack23;
463 .entity goalstack24, goalstack25, goalstack26, goalstack27;
464 .entity goalstack28, goalstack29, goalstack30, goalstack31;
465
466 .entity nearestwaypoint;
467 .float nearestwaypointtimeout;
468
469 // used during navigation_goalrating_begin/end sessions
470 #define MAX_BESTGOALS 3
471 float bestgoalswindex;
472 float bestgoalsrindex;
473 float navigation_bestrating;
474 entity navigation_bestgoals[MAX_BESTGOALS];
475 .float navigation_hasgoals;
476
477 /////////////////////////////////////////////////////////////////////////////
478 // spawnfunc_waypoint management
479 /////////////////////////////////////////////////////////////////////////////
480
481 // waypoints with this flag are not saved, they are automatically generated
482 // waypoints like jump pads, teleporters, and items
483 float WAYPOINTFLAG_GENERATED = 8388608;
484 float WAYPOINTFLAG_ITEM = 4194304;
485 float WAYPOINTFLAG_TELEPORT = 2097152;
486 float WAYPOINTFLAG_NORELINK = 1048576;
487 float WAYPOINTFLAG_PERSONAL = 524288;
488
489 // add a new link to the spawnfunc_waypoint, replacing the furthest link it already has
490 void waypoint_addlink(entity from, entity to)
491 {
492         local float c;
493
494         if (from == to)
495                 return;
496         if (from.wpflags & WAYPOINTFLAG_NORELINK)
497                 return;
498
499         if (from.wp00 == to) return;if (from.wp01 == to) return;if (from.wp02 == to) return;if (from.wp03 == to) return;
500         if (from.wp04 == to) return;if (from.wp05 == to) return;if (from.wp06 == to) return;if (from.wp07 == to) return;
501         if (from.wp08 == to) return;if (from.wp09 == to) return;if (from.wp10 == to) return;if (from.wp11 == to) return;
502         if (from.wp12 == to) return;if (from.wp13 == to) return;if (from.wp14 == to) return;if (from.wp15 == to) return;
503         if (from.wp16 == to) return;if (from.wp17 == to) return;if (from.wp18 == to) return;if (from.wp19 == to) return;
504         if (from.wp20 == to) return;if (from.wp21 == to) return;if (from.wp22 == to) return;if (from.wp23 == to) return;
505         if (from.wp24 == to) return;if (from.wp25 == to) return;if (from.wp26 == to) return;if (from.wp27 == to) return;
506         if (from.wp28 == to) return;if (from.wp29 == to) return;if (from.wp30 == to) return;if (from.wp31 == to) return;
507
508         if (to.wpisbox || from.wpisbox)
509         {
510                 // if either is a box we have to find the nearest points on them to
511                 // calculate the distance properly
512                 local vector v1, v2, m1, m2;
513                 v1 = from.origin;
514                 m1 = to.absmin;
515                 m2 = to.absmax;
516                 v1_x = bound(m1_x, v1_x, m2_x);
517                 v1_y = bound(m1_y, v1_y, m2_y);
518                 v1_z = bound(m1_z, v1_z, m2_z);
519                 v2 = to.origin;
520                 m1 = from.absmin;
521                 m2 = from.absmax;
522                 v2_x = bound(m1_x, v2_x, m2_x);
523                 v2_y = bound(m1_y, v2_y, m2_y);
524                 v2_z = bound(m1_z, v2_z, m2_z);
525                 v2 = to.origin;
526                 c = vlen(v2 - v1);
527         }
528         else
529                 c = vlen(to.origin - from.origin);
530
531         if (from.wp31mincost < c) return;
532         if (from.wp30mincost < c) {from.wp31 = to;from.wp31mincost = c;return;} from.wp31 = from.wp30;from.wp31mincost = from.wp30mincost;
533         if (from.wp29mincost < c) {from.wp30 = to;from.wp30mincost = c;return;} from.wp30 = from.wp29;from.wp30mincost = from.wp29mincost;
534         if (from.wp28mincost < c) {from.wp29 = to;from.wp29mincost = c;return;} from.wp29 = from.wp28;from.wp29mincost = from.wp28mincost;
535         if (from.wp27mincost < c) {from.wp28 = to;from.wp28mincost = c;return;} from.wp28 = from.wp27;from.wp28mincost = from.wp27mincost;
536         if (from.wp26mincost < c) {from.wp27 = to;from.wp27mincost = c;return;} from.wp27 = from.wp26;from.wp27mincost = from.wp26mincost;
537         if (from.wp25mincost < c) {from.wp26 = to;from.wp26mincost = c;return;} from.wp26 = from.wp25;from.wp26mincost = from.wp25mincost;
538         if (from.wp24mincost < c) {from.wp25 = to;from.wp25mincost = c;return;} from.wp25 = from.wp24;from.wp25mincost = from.wp24mincost;
539         if (from.wp23mincost < c) {from.wp24 = to;from.wp24mincost = c;return;} from.wp24 = from.wp23;from.wp24mincost = from.wp23mincost;
540         if (from.wp22mincost < c) {from.wp23 = to;from.wp23mincost = c;return;} from.wp23 = from.wp22;from.wp23mincost = from.wp22mincost;
541         if (from.wp21mincost < c) {from.wp22 = to;from.wp22mincost = c;return;} from.wp22 = from.wp21;from.wp22mincost = from.wp21mincost;
542         if (from.wp20mincost < c) {from.wp21 = to;from.wp21mincost = c;return;} from.wp21 = from.wp20;from.wp21mincost = from.wp20mincost;
543         if (from.wp19mincost < c) {from.wp20 = to;from.wp20mincost = c;return;} from.wp20 = from.wp19;from.wp20mincost = from.wp19mincost;
544         if (from.wp18mincost < c) {from.wp19 = to;from.wp19mincost = c;return;} from.wp19 = from.wp18;from.wp19mincost = from.wp18mincost;
545         if (from.wp17mincost < c) {from.wp18 = to;from.wp18mincost = c;return;} from.wp18 = from.wp17;from.wp18mincost = from.wp17mincost;
546         if (from.wp16mincost < c) {from.wp17 = to;from.wp17mincost = c;return;} from.wp17 = from.wp16;from.wp17mincost = from.wp16mincost;
547         if (from.wp15mincost < c) {from.wp16 = to;from.wp16mincost = c;return;} from.wp16 = from.wp15;from.wp16mincost = from.wp15mincost;
548         if (from.wp14mincost < c) {from.wp15 = to;from.wp15mincost = c;return;} from.wp15 = from.wp14;from.wp15mincost = from.wp14mincost;
549         if (from.wp13mincost < c) {from.wp14 = to;from.wp14mincost = c;return;} from.wp14 = from.wp13;from.wp14mincost = from.wp13mincost;
550         if (from.wp12mincost < c) {from.wp13 = to;from.wp13mincost = c;return;} from.wp13 = from.wp12;from.wp13mincost = from.wp12mincost;
551         if (from.wp11mincost < c) {from.wp12 = to;from.wp12mincost = c;return;} from.wp12 = from.wp11;from.wp12mincost = from.wp11mincost;
552         if (from.wp10mincost < c) {from.wp11 = to;from.wp11mincost = c;return;} from.wp11 = from.wp10;from.wp11mincost = from.wp10mincost;
553         if (from.wp09mincost < c) {from.wp10 = to;from.wp10mincost = c;return;} from.wp10 = from.wp09;from.wp10mincost = from.wp09mincost;
554         if (from.wp08mincost < c) {from.wp09 = to;from.wp09mincost = c;return;} from.wp09 = from.wp08;from.wp09mincost = from.wp08mincost;
555         if (from.wp07mincost < c) {from.wp08 = to;from.wp08mincost = c;return;} from.wp08 = from.wp07;from.wp08mincost = from.wp07mincost;
556         if (from.wp06mincost < c) {from.wp07 = to;from.wp07mincost = c;return;} from.wp07 = from.wp06;from.wp07mincost = from.wp06mincost;
557         if (from.wp05mincost < c) {from.wp06 = to;from.wp06mincost = c;return;} from.wp06 = from.wp05;from.wp06mincost = from.wp05mincost;
558         if (from.wp04mincost < c) {from.wp05 = to;from.wp05mincost = c;return;} from.wp05 = from.wp04;from.wp05mincost = from.wp04mincost;
559         if (from.wp03mincost < c) {from.wp04 = to;from.wp04mincost = c;return;} from.wp04 = from.wp03;from.wp04mincost = from.wp03mincost;
560         if (from.wp02mincost < c) {from.wp03 = to;from.wp03mincost = c;return;} from.wp03 = from.wp02;from.wp03mincost = from.wp02mincost;
561         if (from.wp01mincost < c) {from.wp02 = to;from.wp02mincost = c;return;} from.wp02 = from.wp01;from.wp02mincost = from.wp01mincost;
562         if (from.wp00mincost < c) {from.wp01 = to;from.wp01mincost = c;return;} from.wp01 = from.wp00;from.wp01mincost = from.wp00mincost;
563         from.wp00 = to;from.wp00mincost = c;return;
564 };
565
566 // fields you can query using prvm_global server to get some statistics about waypoint linking culling
567 float relink_total, relink_walkculled, relink_pvsculled, relink_lengthculled;
568
569 // relink this spawnfunc_waypoint
570 // (precompile a list of all reachable waypoints from this spawnfunc_waypoint)
571 // (SLOW!)
572 void waypoint_think()
573 {
574         local entity e;
575         local vector sv, sm1, sm2, ev, em1, em2, dv;
576         //dprint("waypoint_think wpisbox = ", ftos(self.wpisbox), "\n");
577         sm1 = self.origin + self.mins;
578         sm2 = self.origin + self.maxs;
579         stepheightvec = cvar("sv_stepheight") * '0 0 1';
580         for(e = world; (e = find(e, classname, "waypoint")); )
581         {
582                 if (boxesoverlap(self.absmin, self.absmax, e.absmin, e.absmax))
583                 {
584                         waypoint_addlink(self, e);
585                         waypoint_addlink(e, self);
586                 }
587                 else
588                 {
589                         ++relink_total;
590                         if(!checkpvs(self.origin, e))
591                         {
592                                 ++relink_pvsculled;
593                                 continue;
594                         }
595                         sv = e.origin;
596                         sv_x = bound(sm1_x, sv_x, sm2_x);
597                         sv_y = bound(sm1_y, sv_y, sm2_y);
598                         sv_z = bound(sm1_z, sv_z, sm2_z);
599                         ev = self.origin;
600                         em1 = e.origin + e.mins;
601                         em2 = e.origin + e.maxs;
602                         ev_x = bound(em1_x, ev_x, em2_x);
603                         ev_y = bound(em1_y, ev_y, em2_y);
604                         ev_z = bound(em1_z, ev_z, em2_z);
605                         dv = ev - sv;
606                         dv_z = 0;
607                         if (vlen(dv) >= 1050) // max search distance in XY
608                         {
609                                 ++relink_lengthculled;
610                                 continue;
611                         }
612                         navigation_testtracewalk = 0;
613                         if (!self.wpisbox)
614                         {
615                                 tracebox(sv - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, sv, FALSE, self);
616                                 if (!trace_startsolid)
617                                 {
618                                         //dprint("sv deviation", vtos(trace_endpos - sv), "\n");
619                                         sv = trace_endpos + '0 0 1';
620                                 }
621                         }
622                         if (!e.wpisbox)
623                         {
624                                 tracebox(ev - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, ev, FALSE, e);
625                                 if (!trace_startsolid)
626                                 {
627                                         //dprint("ev deviation", vtos(trace_endpos - ev), "\n");
628                                         ev = trace_endpos + '0 0 1';
629                                 }
630                         }
631                         //traceline(self.origin, e.origin, FALSE, world);
632                         //if (trace_fraction == 1)
633                         if (!self.wpisbox && tracewalk(self, sv, PL_MIN, PL_MAX, ev, MOVE_NOMONSTERS))
634                                 waypoint_addlink(self, e);
635                         else
636                                 relink_walkculled += 0.5;
637                         if (!e.wpisbox && tracewalk(e, ev, PL_MIN, PL_MAX, sv, MOVE_NOMONSTERS))
638                                 waypoint_addlink(e, self);
639                         else
640                                 relink_walkculled += 0.5;
641                 }
642         }
643         navigation_testtracewalk = 0;
644 };
645
646 void waypoint_clearlinks(entity wp)
647 {
648         // clear links to other waypoints
649         local float f;
650         f = 10000000;
651         wp.wp00 = wp.wp01 = wp.wp02 = wp.wp03 = wp.wp04 = wp.wp05 = wp.wp06 = wp.wp07 = world;wp.wp00mincost = wp.wp01mincost = wp.wp02mincost = wp.wp03mincost = wp.wp04mincost = wp.wp05mincost = wp.wp06mincost = wp.wp07mincost = f;
652         wp.wp08 = wp.wp09 = wp.wp10 = wp.wp11 = wp.wp12 = wp.wp13 = wp.wp14 = wp.wp15 = world;wp.wp08mincost = wp.wp09mincost = wp.wp10mincost = wp.wp11mincost = wp.wp12mincost = wp.wp13mincost = wp.wp14mincost = wp.wp15mincost = f;
653         wp.wp16 = wp.wp17 = wp.wp18 = wp.wp19 = wp.wp20 = wp.wp21 = wp.wp22 = wp.wp23 = world;wp.wp16mincost = wp.wp17mincost = wp.wp18mincost = wp.wp19mincost = wp.wp20mincost = wp.wp21mincost = wp.wp22mincost = wp.wp23mincost = f;
654         wp.wp24 = wp.wp25 = wp.wp26 = wp.wp27 = wp.wp28 = wp.wp29 = wp.wp30 = wp.wp31 = world;wp.wp24mincost = wp.wp25mincost = wp.wp26mincost = wp.wp27mincost = wp.wp28mincost = wp.wp29mincost = wp.wp30mincost = wp.wp31mincost = f;
655 };
656
657 // tell a spawnfunc_waypoint to relink
658 void waypoint_schedulerelink(entity wp)
659 {
660         if (wp == world)
661                 return;
662         // TODO: add some sort of visible box in edit mode for box waypoints
663         if (cvar("g_waypointeditor"))
664         {
665                 local vector m1, m2;
666                 m1 = wp.mins;
667                 m2 = wp.maxs;
668                 setmodel(wp, "models/runematch/rune.mdl"); wp.effects = EF_LOWPRECISION;
669                 setsize(wp, m1, m2);
670                 if (wp.wpflags & WAYPOINTFLAG_ITEM)
671                         wp.colormod = '1 0 0';
672                 else if (wp.wpflags & WAYPOINTFLAG_GENERATED)
673                         wp.colormod = '1 1 0';
674                 else
675                         wp.colormod = '1 1 1';
676         }
677         else
678                 wp.model = "";
679         wp.wpisbox = vlen(wp.size) > 0;
680         wp.enemy = world;
681         wp.owner = world;
682         if (!(wp.wpflags & WAYPOINTFLAG_NORELINK))
683                 waypoint_clearlinks(wp);
684         // schedule an actual relink on next frame
685         wp.think = waypoint_think;
686         wp.nextthink = time;
687         wp.effects = EF_LOWPRECISION;
688 }
689
690 // create a new spawnfunc_waypoint and automatically link it to other waypoints, and link
691 // them back to it as well
692 // (suitable for spawnfunc_waypoint editor)
693 entity waypoint_spawn(vector m1, vector m2, float f)
694 {
695         local entity w;
696         local vector org;
697         w = find(world, classname, "waypoint");
698
699         if not(f & WAYPOINTFLAG_PERSONAL)
700         while (w)
701         {
702                 // if a matching spawnfunc_waypoint already exists, don't add a duplicate
703                 if (boxesoverlap(m1, m2, w.absmin, w.absmax))
704                         return w;
705                 w = find(w, classname, "waypoint");
706         }
707
708         w = spawn();
709         w.classname = "waypoint";
710         w.wpflags = f;
711         setorigin(w, (m1 + m2) * 0.5);
712         setsize(w, m1 - w.origin, m2 - w.origin);
713         if (vlen(w.size) > 0)
714                 w.wpisbox = TRUE;
715
716         if(!(f & WAYPOINTFLAG_GENERATED))
717         if(!w.wpisbox)
718         {
719                 traceline(w.origin + '0 0 1', w.origin + PL_MIN_z * '0 0 1' - '0 0 1', MOVE_NOMONSTERS, w);
720                 if (trace_fraction < 1)
721                         setorigin(w, trace_endpos - PL_MIN_z * '0 0 1');
722
723                 // check if the start position is stuck
724                 tracebox(w.origin, PL_MIN + '-1 -1 -1', PL_MAX + '1 1 1', w.origin, MOVE_NOMONSTERS, w);
725                 if (trace_startsolid)
726                 {
727                         org = w.origin + '0 0 26';
728                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
729                         if(trace_startsolid)
730                         {
731                                 org = w.origin + '2 2 2';
732                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
733                                 if(trace_startsolid)
734                                 {
735                                         org = w.origin + '-2 -2 2';
736                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
737                                         if(trace_startsolid)
738                                         {
739                                                 org = w.origin + '-2 2 2';
740                                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
741                                                 if(trace_startsolid)
742                                                 {
743                                                         org = w.origin + '2 -2 2';
744                                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
745                                                         if(trace_startsolid)
746                                                         {
747                                                                 // this WP is in solid, refuse it
748                                                                 dprint("Killed a waypoint that was stuck in solid at ", vtos(org), "\n");
749                                                                 remove(w);
750                                                                 return world;
751                                                         }
752                                                 }
753                                         }
754                                 }
755                         }
756                         setorigin(w, org * 0.05 + trace_endpos * 0.95); // don't trust the trace fully
757                 }
758
759                 tracebox(w.origin, PL_MIN, PL_MAX, w.origin - '0 0 128', MOVE_WORLDONLY, w);
760                 if(trace_startsolid)
761                 {
762                         dprint("Killed a waypoint that was stuck in solid ", vtos(w.origin), "\n");
763                         remove(w);
764                         return world;
765                 }
766                 if (!trace_inwater)
767                 {
768                         if(trace_fraction == 1)
769                         {
770                                 dprint("Killed a waypoint that was stuck in air at ", vtos(w.origin), "\n");
771                                 remove(w);
772                                 return world;
773                         }
774                         trace_endpos_z += 0.1; // don't trust the trace fully
775 //                      dprint("Moved waypoint at ", vtos(w.origin), " by ", ftos(vlen(w.origin - trace_endpos)));
776 //                      dprint(" direction: ", vtos((trace_endpos - w.origin)), "\n");
777                         setorigin(w, trace_endpos);
778                 }
779         }
780
781         waypoint_clearlinks(w);
782         //waypoint_schedulerelink(w);
783         return w;
784 };
785
786 // spawnfunc_waypoint map entity
787 void spawnfunc_waypoint()
788 {
789         setorigin(self, self.origin);
790         // schedule a relink after other waypoints have had a chance to spawn
791         waypoint_clearlinks(self);
792         //waypoint_schedulerelink(self);
793 };
794
795 // remove a spawnfunc_waypoint, and schedule all neighbors to relink
796 void waypoint_remove(entity e)
797 {
798         // tell all linked waypoints that they need to relink
799         waypoint_schedulerelink(e.wp00);
800         waypoint_schedulerelink(e.wp01);
801         waypoint_schedulerelink(e.wp02);
802         waypoint_schedulerelink(e.wp03);
803         waypoint_schedulerelink(e.wp04);
804         waypoint_schedulerelink(e.wp05);
805         waypoint_schedulerelink(e.wp06);
806         waypoint_schedulerelink(e.wp07);
807         waypoint_schedulerelink(e.wp08);
808         waypoint_schedulerelink(e.wp09);
809         waypoint_schedulerelink(e.wp10);
810         waypoint_schedulerelink(e.wp11);
811         waypoint_schedulerelink(e.wp12);
812         waypoint_schedulerelink(e.wp13);
813         waypoint_schedulerelink(e.wp14);
814         waypoint_schedulerelink(e.wp15);
815         waypoint_schedulerelink(e.wp16);
816         waypoint_schedulerelink(e.wp17);
817         waypoint_schedulerelink(e.wp18);
818         waypoint_schedulerelink(e.wp19);
819         waypoint_schedulerelink(e.wp20);
820         waypoint_schedulerelink(e.wp21);
821         waypoint_schedulerelink(e.wp22);
822         waypoint_schedulerelink(e.wp23);
823         waypoint_schedulerelink(e.wp24);
824         waypoint_schedulerelink(e.wp25);
825         waypoint_schedulerelink(e.wp26);
826         waypoint_schedulerelink(e.wp27);
827         waypoint_schedulerelink(e.wp28);
828         waypoint_schedulerelink(e.wp29);
829         waypoint_schedulerelink(e.wp30);
830         waypoint_schedulerelink(e.wp31);
831         // and now remove the spawnfunc_waypoint
832         remove(e);
833 };
834
835 // empties the map of waypoints
836 void waypoint_removeall()
837 {
838         local entity head, next;
839         head = findchain(classname, "waypoint");
840         while (head)
841         {
842                 next = head.chain;
843                 remove(head);
844                 head = next;
845         }
846 };
847
848 // tell all waypoints to relink
849 // (is this useful at all?)
850 void waypoint_schedulerelinkall()
851 {
852         local entity head;
853         relink_total = relink_walkculled = relink_pvsculled = relink_lengthculled = 0;
854         head = findchain(classname, "waypoint");
855         while (head)
856         {
857                 waypoint_schedulerelink(head);
858                 head = head.chain;
859         }
860 };
861
862 // Load waypoint links from file
863 float botframe_cachedwaypointlinks;
864 float waypoint_load_links()
865 {
866         local string filename, s;
867         local float file, tokens, c, found;
868         local entity wp_from, wp_to;
869         local vector wp_to_pos, wp_from_pos;
870         filename = strcat("maps/", mapname);
871         filename = strcat(filename, ".waypoints.cache");
872         file = fopen(filename, FILE_READ);
873
874         if (file < 0)
875         {
876                 dprint("waypoint links load from ");
877                 dprint(filename);
878                 dprint(" failed\n");
879                 return FALSE;
880         }
881
882         while (1)
883         {
884                 s = fgets(file);
885                 if (!s)
886                         break;
887
888                 tokens = tokenizebyseparator(s, "*");
889
890                 if (tokens!=2)
891                 {
892                         // bad file format
893                         fclose(file);
894                         return FALSE;
895                 }
896
897                 wp_from_pos     = stov(argv(0));
898                 wp_to_pos       = stov(argv(1));
899
900                 // Search "from" waypoint
901                 if(wp_from.origin!=wp_from_pos)
902                 {
903                         wp_from = findradius(wp_from_pos, 1);
904                         found = FALSE;
905                         while(wp_from)
906                         {
907                                 if(vlen(wp_from.origin-wp_from_pos)<1)
908                                 if(wp_from.classname == "waypoint")
909                                 {
910                                         found = TRUE;
911                                         break;
912                                 }
913                                 wp_from = wp_from.chain;
914                         }
915
916                         if(!found)
917                         {
918                                 // can't find that waypoint
919                                 fclose(file);
920                                 return FALSE;
921                         }
922                 }
923
924                 // Search "to" waypoint
925                 wp_to = findradius(wp_to_pos, 1);
926                 found = FALSE;
927                 while(wp_to)
928                 {
929                         if(vlen(wp_to.origin-wp_to_pos)<1)
930                         if(wp_to.classname == "waypoint")
931                         {
932                                 found = TRUE;
933                                 break;
934                         }
935                         wp_to = wp_to.chain;
936                 }
937
938                 if(!found)
939                 {
940                         // can't find that waypoint
941                         fclose(file);
942                         return FALSE;
943                 }
944
945                 ++c;
946                 waypoint_addlink(wp_from, wp_to);
947         }
948
949         fclose(file);
950
951         dprint("loaded ");
952         dprint(ftos(c));
953         dprint(" waypoint links from maps/");
954         dprint(mapname);
955         dprint(".waypoints.cache\n");
956
957         botframe_cachedwaypointlinks = TRUE;
958         return TRUE;
959 };
960
961 float botframe_loadedforcedlinks;
962 void waypoint_load_links_hardwired()
963 {
964         local string filename, s;
965         local float file, tokens, c, found;
966         local entity wp_from, wp_to;
967         local vector wp_to_pos, wp_from_pos;
968         filename = strcat("maps/", mapname);
969         filename = strcat(filename, ".waypoints.hardwired");
970         file = fopen(filename, FILE_READ);
971
972         botframe_loadedforcedlinks = TRUE;
973
974         if (file < 0)
975         {
976                 dprint("waypoint links load from ");
977                 dprint(filename);
978                 dprint(" failed\n");
979                 return;
980         }
981
982         for (;;)
983         {
984                 s = fgets(file);
985                 if (!s)
986                         break;
987
988                 if(substring(s, 0, 2)=="//")
989                         continue;
990
991                 if(substring(s, 0, 1)=="#")
992                         continue;
993
994                 tokens = tokenizebyseparator(s, "*");
995
996                 if (tokens!=2)
997                         continue;
998
999                 wp_from_pos     = stov(argv(0));
1000                 wp_to_pos       = stov(argv(1));
1001
1002                 // Search "from" waypoint
1003                 if(wp_from.origin!=wp_from_pos)
1004                 {
1005                         wp_from = findradius(wp_from_pos, 1);
1006                         found = FALSE;
1007                         while(wp_from)
1008                         {
1009                                 if(vlen(wp_from.origin-wp_from_pos)<1)
1010                                 if(wp_from.classname == "waypoint")
1011                                 {
1012                                         found = TRUE;
1013                                         break;
1014                                 }
1015                                 wp_from = wp_from.chain;
1016                         }
1017
1018                         if(!found)
1019                         {
1020                                 print(strcat("NOTICE: Can not find waypoint at ", vtos(wp_from_pos), ". Path skipped\n"));
1021                                 continue;
1022                         }
1023                 }
1024
1025                 // Search "to" waypoint
1026                 wp_to = findradius(wp_to_pos, 1);
1027                 found = FALSE;
1028                 while(wp_to)
1029                 {
1030                         if(vlen(wp_to.origin-wp_to_pos)<1)
1031                         if(wp_to.classname == "waypoint")
1032                         {
1033                                 found = TRUE;
1034                                 break;
1035                         }
1036                         wp_to = wp_to.chain;
1037                 }
1038
1039                 if(!found)
1040                 {
1041                         print(strcat("NOTICE: Can not find waypoint at ", vtos(wp_to_pos), ". Path skipped\n"));
1042                         continue;
1043                 }
1044
1045                 ++c;
1046                 waypoint_addlink(wp_from, wp_to);
1047         }
1048
1049         fclose(file);
1050
1051         dprint("loaded ");
1052         dprint(ftos(c));
1053         dprint(" waypoint links from maps/");
1054         dprint(mapname);
1055         dprint(".waypoints.hardwired\n");
1056 };
1057
1058
1059 // Save all waypoint links to a file
1060 void waypoint_save_links()
1061 {
1062         local string filename, s;
1063         local float file, c, i;
1064         local entity w, link;
1065         filename = strcat("maps/", mapname);
1066         filename = strcat(filename, ".waypoints.cache");
1067         file = fopen(filename, FILE_WRITE);
1068         if (file < 0)
1069         {
1070                 print("waypoint links save to ");
1071                 print(filename);
1072                 print(" failed\n");
1073         }
1074         c = 0;
1075         w = findchain(classname, "waypoint");
1076         while (w)
1077         {
1078                 for(i=0;i<32;++i)
1079                 {
1080                         // :S
1081                         switch(i)
1082                         {
1083                                 //      for i in $(seq -w 0 31); do echo "case $i:link = w.wp$i; break;"; done;
1084                                 case 00:link = w.wp00; break;
1085                                 case 01:link = w.wp01; break;
1086                                 case 02:link = w.wp02; break;
1087                                 case 03:link = w.wp03; break;
1088                                 case 04:link = w.wp04; break;
1089                                 case 05:link = w.wp05; break;
1090                                 case 06:link = w.wp06; break;
1091                                 case 07:link = w.wp07; break;
1092                                 case 08:link = w.wp08; break;
1093                                 case 09:link = w.wp09; break;
1094                                 case 10:link = w.wp10; break;
1095                                 case 11:link = w.wp11; break;
1096                                 case 12:link = w.wp12; break;
1097                                 case 13:link = w.wp13; break;
1098                                 case 14:link = w.wp14; break;
1099                                 case 15:link = w.wp15; break;
1100                                 case 16:link = w.wp16; break;
1101                                 case 17:link = w.wp17; break;
1102                                 case 18:link = w.wp18; break;
1103                                 case 19:link = w.wp19; break;
1104                                 case 20:link = w.wp20; break;
1105                                 case 21:link = w.wp21; break;
1106                                 case 22:link = w.wp22; break;
1107                                 case 23:link = w.wp23; break;
1108                                 case 24:link = w.wp24; break;
1109                                 case 25:link = w.wp25; break;
1110                                 case 26:link = w.wp26; break;
1111                                 case 27:link = w.wp27; break;
1112                                 case 28:link = w.wp28; break;
1113                                 case 29:link = w.wp29; break;
1114                                 case 30:link = w.wp30; break;
1115                                 case 31:link = w.wp31; break;
1116                         }
1117
1118                         if(link==world)
1119                                 continue;
1120
1121                         s = strcat(vtos(w.origin), "*", vtos(link.origin), "\n");
1122                         fputs(file, s);
1123                         ++c;
1124                 }
1125                 w = w.chain;
1126         }
1127         fclose(file);
1128         botframe_cachedwaypointlinks = TRUE;
1129
1130         print("saved ");
1131         print(ftos(c));
1132         print(" waypoints links to maps/");
1133         print(mapname);
1134         print(".waypoints.cache\n");
1135 };
1136
1137 // save waypoints to gamedir/data/maps/mapname.waypoints
1138 void waypoint_saveall()
1139 {
1140         local string filename, s;
1141         local float file, c;
1142         local entity w;
1143         filename = strcat("maps/", mapname);
1144         filename = strcat(filename, ".waypoints");
1145         file = fopen(filename, FILE_WRITE);
1146         if (file >= 0)
1147         {
1148                 c = 0;
1149                 w = findchain(classname, "waypoint");
1150                 while (w)
1151                 {
1152                         if (!(w.wpflags & WAYPOINTFLAG_GENERATED))
1153                         {
1154                                 s = strcat(vtos(w.origin + w.mins), "\n");
1155                                 s = strcat(s, vtos(w.origin + w.maxs));
1156                                 s = strcat(s, "\n");
1157                                 s = strcat(s, ftos(w.wpflags));
1158                                 s = strcat(s, "\n");
1159                                 fputs(file, s);
1160                                 c = c + 1;
1161                         }
1162                         w = w.chain;
1163                 }
1164                 fclose(file);
1165                 bprint("saved ");
1166                 bprint(ftos(c));
1167                 bprint(" waypoints to maps/");
1168                 bprint(mapname);
1169                 bprint(".waypoints\n");
1170         }
1171         else
1172         {
1173                 bprint("waypoint save to ");
1174                 bprint(filename);
1175                 bprint(" failed\n");
1176         }
1177         waypoint_save_links();
1178         botframe_loadedforcedlinks = FALSE;
1179 };
1180
1181 // load waypoints from file
1182 float waypoint_loadall()
1183 {
1184         local string filename, s;
1185         local float file, cwp, cwb, fl;
1186         local vector m1, m2;
1187         cwp = 0;
1188         cwb = 0;
1189         filename = strcat("maps/", mapname);
1190         filename = strcat(filename, ".waypoints");
1191         file = fopen(filename, FILE_READ);
1192         if (file >= 0)
1193         {
1194                 while (1)
1195                 {
1196                         s = fgets(file);
1197                         if (!s)
1198                                 break;
1199                         m1 = stov(s);
1200                         s = fgets(file);
1201                         if (!s)
1202                                 break;
1203                         m2 = stov(s);
1204                         s = fgets(file);
1205                         if (!s)
1206                                 break;
1207                         fl = stof(s);
1208                         waypoint_spawn(m1, m2, fl);
1209                         if (m1 == m2)
1210                                 cwp = cwp + 1;
1211                         else
1212                                 cwb = cwb + 1;
1213                 }
1214                 fclose(file);
1215                 dprint("loaded ");
1216                 dprint(ftos(cwp));
1217                 dprint(" waypoints and ");
1218                 dprint(ftos(cwb));
1219                 dprint(" wayboxes from maps/");
1220                 dprint(mapname);
1221                 dprint(".waypoints\n");
1222         }
1223         else
1224         {
1225                 dprint("waypoint load from ");
1226                 dprint(filename);
1227                 dprint(" failed\n");
1228         }
1229         return cwp + cwb;
1230 };
1231
1232 void waypoint_spawnforitem(entity e)
1233 {
1234         local entity w;
1235         local vector org;
1236
1237         if(!bot_waypoints_for_items)
1238                 return;
1239
1240         // Center of entity
1241         org = e.origin + (e.mins + e.maxs) * 0.5;
1242
1243         // Calculate the altitude where the waypoint will be placed
1244         traceline(e.origin, e.origin + '0 0 -65535', TRUE, e);
1245         if(e.origin_z + e.mins_z - trace_endpos_z < PL_MAX_z - PL_MIN_z + 10)
1246                 org_z = trace_endpos_z + PL_MAX_z - PL_MIN_z;
1247         else
1248                 org_z = e.origin_z;
1249
1250         e.nearestwaypointtimeout = time + 1000000000;
1251         // don't spawn an item spawnfunc_waypoint if it already exists
1252         w = findchain(classname, "waypoint");
1253         while (w)
1254         {
1255                 if (w.wpisbox)
1256                 {
1257                         if (boxesoverlap(org, org, w.absmin, w.absmax))
1258                         {
1259                                 e.nearestwaypoint = w;
1260                                 return;
1261                         }
1262                 }
1263                 else
1264                 {
1265                         if (vlen(w.origin - org) < 16)
1266                         {
1267                                 e.nearestwaypoint = w;
1268                                 return;
1269                         }
1270                 }
1271                 w = w.chain;
1272         }
1273         e.nearestwaypoint = waypoint_spawn(org, org, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_ITEM);
1274 };
1275
1276 void waypoint_spawnforteleporter(entity e, vector destination, float timetaken)
1277 {
1278         local entity w;
1279         local entity dw;
1280         w = waypoint_spawn(e.absmin, e.absmax, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_TELEPORT | WAYPOINTFLAG_NORELINK);
1281         dw = waypoint_spawn(destination, destination, WAYPOINTFLAG_GENERATED);
1282         // one way link to the destination
1283         w.wp00 = dw;
1284         w.wp00mincost = timetaken; // this is just for jump pads
1285         // the teleporter's nearest spawnfunc_waypoint is this one
1286         // (teleporters are not goals, so this is probably useless)
1287         e.nearestwaypoint = w;
1288         e.nearestwaypointtimeout = time + 1000000000;
1289 };
1290
1291 entity waypoint_spawnpersonal(vector position)
1292 {
1293         entity w;
1294
1295         w = waypoint_spawn(position, position, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_PERSONAL);
1296         w.nearestwaypoint = world;
1297         w.nearestwaypointtimeout = 0;
1298         w.owner = self;
1299
1300         return w;
1301 };
1302
1303 /////////////////////////////////////////////////////////////////////////////
1304 // goal stack
1305 /////////////////////////////////////////////////////////////////////////////
1306
1307 // completely empty the goal stack, used when deciding where to go
1308 void navigation_clearroute()
1309 {
1310         self.navigation_hasgoals = FALSE;
1311         self.goalcurrent = world;
1312         self.goalstack01 = world;
1313         self.goalstack02 = world;
1314         self.goalstack03 = world;
1315         self.goalstack04 = world;
1316         self.goalstack05 = world;
1317         self.goalstack06 = world;
1318         self.goalstack07 = world;
1319         self.goalstack08 = world;
1320         self.goalstack09 = world;
1321         self.goalstack10 = world;
1322         self.goalstack11 = world;
1323         self.goalstack12 = world;
1324         self.goalstack13 = world;
1325         self.goalstack14 = world;
1326         self.goalstack15 = world;
1327         self.goalstack16 = world;
1328         self.goalstack17 = world;
1329         self.goalstack18 = world;
1330         self.goalstack19 = world;
1331         self.goalstack20 = world;
1332         self.goalstack21 = world;
1333         self.goalstack22 = world;
1334         self.goalstack23 = world;
1335         self.goalstack24 = world;
1336         self.goalstack25 = world;
1337         self.goalstack26 = world;
1338         self.goalstack27 = world;
1339         self.goalstack28 = world;
1340         self.goalstack29 = world;
1341         self.goalstack30 = world;
1342         self.goalstack31 = world;
1343 };
1344
1345 // add a new goal at the beginning of the stack
1346 // (in other words: add a new prerequisite before going to the later goals)
1347 void navigation_pushroute(entity e)
1348 {
1349         self.goalstack31 = self.goalstack30;
1350         self.goalstack30 = self.goalstack29;
1351         self.goalstack29 = self.goalstack28;
1352         self.goalstack28 = self.goalstack27;
1353         self.goalstack27 = self.goalstack26;
1354         self.goalstack26 = self.goalstack25;
1355         self.goalstack25 = self.goalstack24;
1356         self.goalstack24 = self.goalstack23;
1357         self.goalstack23 = self.goalstack22;
1358         self.goalstack22 = self.goalstack21;
1359         self.goalstack21 = self.goalstack20;
1360         self.goalstack20 = self.goalstack19;
1361         self.goalstack19 = self.goalstack18;
1362         self.goalstack18 = self.goalstack17;
1363         self.goalstack17 = self.goalstack16;
1364         self.goalstack16 = self.goalstack15;
1365         self.goalstack15 = self.goalstack14;
1366         self.goalstack14 = self.goalstack13;
1367         self.goalstack13 = self.goalstack12;
1368         self.goalstack12 = self.goalstack11;
1369         self.goalstack11 = self.goalstack10;
1370         self.goalstack10 = self.goalstack09;
1371         self.goalstack09 = self.goalstack08;
1372         self.goalstack08 = self.goalstack07;
1373         self.goalstack07 = self.goalstack06;
1374         self.goalstack06 = self.goalstack05;
1375         self.goalstack05 = self.goalstack04;
1376         self.goalstack04 = self.goalstack03;
1377         self.goalstack03 = self.goalstack02;
1378         self.goalstack02 = self.goalstack01;
1379         self.goalstack01 = self.goalcurrent;
1380         self.goalcurrent = e;
1381 };
1382
1383 // remove first goal from stack
1384 // (in other words: remove a prerequisite for reaching the later goals)
1385 // (used when a spawnfunc_waypoint is reached)
1386 void navigation_poproute()
1387 {
1388         if(self.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL && self.goalcurrent.owner==self)
1389                 remove(self.goalcurrent);
1390
1391         self.goalcurrent = self.goalstack01;
1392         self.goalstack01 = self.goalstack02;
1393         self.goalstack02 = self.goalstack03;
1394         self.goalstack03 = self.goalstack04;
1395         self.goalstack04 = self.goalstack05;
1396         self.goalstack05 = self.goalstack06;
1397         self.goalstack06 = self.goalstack07;
1398         self.goalstack07 = self.goalstack08;
1399         self.goalstack08 = self.goalstack09;
1400         self.goalstack09 = self.goalstack10;
1401         self.goalstack10 = self.goalstack11;
1402         self.goalstack11 = self.goalstack12;
1403         self.goalstack12 = self.goalstack13;
1404         self.goalstack13 = self.goalstack14;
1405         self.goalstack14 = self.goalstack15;
1406         self.goalstack15 = self.goalstack16;
1407         self.goalstack16 = self.goalstack17;
1408         self.goalstack17 = self.goalstack18;
1409         self.goalstack18 = self.goalstack19;
1410         self.goalstack19 = self.goalstack20;
1411         self.goalstack20 = self.goalstack21;
1412         self.goalstack21 = self.goalstack22;
1413         self.goalstack22 = self.goalstack23;
1414         self.goalstack23 = self.goalstack24;
1415         self.goalstack24 = self.goalstack25;
1416         self.goalstack25 = self.goalstack26;
1417         self.goalstack26 = self.goalstack27;
1418         self.goalstack27 = self.goalstack28;
1419         self.goalstack28 = self.goalstack29;
1420         self.goalstack29 = self.goalstack30;
1421         self.goalstack30 = self.goalstack31;
1422         self.goalstack31 = world;
1423 };
1424
1425 // find the spawnfunc_waypoint near a dynamic goal such as a dropped weapon
1426 entity navigation_findnearestwaypoint(entity player, float walkfromwp)
1427 {
1428         local entity waylist, w, best;
1429         local float dist, bestdist;
1430         local vector v, org, pm1, pm2;
1431         pm1 = player.origin + PL_MIN;
1432         pm2 = player.origin + PL_MAX;
1433         waylist = findchain(classname, "waypoint");
1434         // do two scans, because box test is cheaper
1435         w = waylist;
1436         while (w)
1437         {
1438                 // if object is touching spawnfunc_waypoint
1439                 if (boxesoverlap(pm1, pm2, w.absmin, w.absmax))
1440                         return w;
1441                 w = w.chain;
1442         }
1443
1444         org = player.origin + (player.mins_z - PL_MIN_z) * '0 0 1';
1445         if(player.tag_entity)
1446                 org = org + player.tag_entity.origin;
1447         if (navigation_testtracewalk)
1448                 te_plasmaburn(org);
1449         best = world;
1450         bestdist = 1050;
1451
1452         // box check failed, try walk
1453         w = waylist;
1454         while (w)
1455         {
1456                 // if object can walk from spawnfunc_waypoint
1457                 if (w.wpisbox)
1458                 {
1459                         local vector wm1, wm2;
1460                         wm1 = w.origin + w.mins;
1461                         wm2 = w.origin + w.maxs;
1462                         v_x = bound(wm1_x, org_x, wm2_x);
1463                         v_y = bound(wm1_y, org_y, wm2_y);
1464                         v_z = bound(wm1_z, org_z, wm2_z);
1465                 }
1466                 else
1467                         v = w.origin;
1468                 dist = vlen(v - org);
1469                 if (bestdist > dist)
1470                 {
1471                         if (walkfromwp)
1472                         {
1473                                 traceline(v, org, TRUE, player);
1474                                 if (trace_fraction == 1)
1475                                 if (tracewalk(player, v, PL_MIN, PL_MAX, org, MOVE_NORMAL))
1476                                 {
1477                                         bestdist = dist;
1478                                         best = w;
1479                                 }
1480                         }
1481                         else
1482                         {
1483                                 traceline(v, org, TRUE, player);
1484                                 if (trace_fraction == 1)
1485                                 if (tracewalk(player, org, PL_MIN, PL_MAX, v, MOVE_NORMAL))
1486                                 {
1487                                         bestdist = dist;
1488                                         best = w;
1489                                 }
1490                         }
1491                 }
1492                 w = w.chain;
1493         }
1494         return best;
1495 }
1496
1497 // finds the waypoints near the bot initiating a navigation query
1498 float navigation_markroutes_nearestwaypoints(entity waylist, float maxdist)
1499 {
1500         local entity head;
1501         local vector v, m1, m2, diff;
1502         local float c;
1503 //      navigation_testtracewalk = TRUE;
1504         c = 0;
1505         head = waylist;
1506         while (head)
1507         {
1508                 if (!head.wpconsidered)
1509                 {
1510                         if (head.wpisbox)
1511                         {
1512                                 m1 = head.origin + head.mins;
1513                                 m2 = head.origin + head.maxs;
1514                                 v = self.origin;
1515                                 v_x = bound(m1_x, v_x, m2_x);
1516                                 v_y = bound(m1_y, v_y, m2_y);
1517                                 v_z = bound(m1_z, v_z, m2_z);
1518                         }
1519                         else
1520                                 v = head.origin;
1521                         diff = v - self.origin;
1522                         diff_z = max(0, diff_z);
1523                         if (vlen(diff) < maxdist)
1524                         {
1525                                 head.wpconsidered = TRUE;
1526                                 if (tracewalk(self, self.origin, self.mins, self.maxs, v, MOVE_NORMAL))
1527                                 {
1528                                         head.wpnearestpoint = v;
1529                                         head.wpcost = vlen(v - self.origin) + head.dmg;
1530                                         head.wpfire = 1;
1531                                         head.enemy = world;
1532                                         c = c + 1;
1533                                 }
1534                         }
1535                 }
1536                 head = head.chain;
1537         }
1538         //navigation_testtracewalk = FALSE;
1539         return c;
1540 }
1541
1542 // updates a path link if a spawnfunc_waypoint link is better than the current one
1543 void navigation_markroutes_checkwaypoint(entity w, entity wp, float cost2, vector p)
1544 {
1545         local vector m1;
1546         local vector m2;
1547         local vector v;
1548         if (wp.wpisbox)
1549         {
1550                 m1 = wp.absmin;
1551                 m2 = wp.absmax;
1552                 v_x = bound(m1_x, p_x, m2_x);
1553                 v_y = bound(m1_y, p_y, m2_y);
1554                 v_z = bound(m1_z, p_z, m2_z);
1555         }
1556         else
1557                 v = wp.origin;
1558         cost2 = cost2 + vlen(v);
1559         if (wp.wpcost > cost2)
1560         {
1561                 wp.wpcost = cost2;
1562                 wp.enemy = w;
1563                 wp.wpfire = 1;
1564                 wp.wpnearestpoint = v;
1565         }
1566 };
1567
1568 // queries the entire spawnfunc_waypoint network for pathes leading away from the bot
1569 void navigation_markroutes()
1570 {
1571         local entity w, wp, waylist;
1572         local float searching, cost, cost2;
1573         local vector p;
1574         w = waylist = findchain(classname, "waypoint");
1575         while (w)
1576         {
1577                 w.wpconsidered = FALSE;
1578                 w.wpnearestpoint = '0 0 0';
1579                 w.wpcost = 10000000;
1580                 w.wpfire = 0;
1581                 w.enemy = world;
1582                 w = w.chain;
1583         }
1584
1585         // try a short range search for the nearest waypoints, and expand the search repeatedly if none are found
1586         // as this search is expensive we will use lower values if the bot is on the air
1587         local float i, increment, maxdistance;
1588         if(self.flags & FL_ONGROUND)
1589         {
1590                 increment = 750;
1591                 maxdistance = 50000;
1592         }
1593         else
1594         {
1595                 increment = 500;
1596                 maxdistance = 1500;
1597         }
1598
1599         for(i=increment;!navigation_markroutes_nearestwaypoints(waylist, i)&&i<maxdistance;i+=increment);
1600
1601         searching = TRUE;
1602         while (searching)
1603         {
1604                 searching = FALSE;
1605                 w = waylist;
1606                 while (w)
1607                 {
1608                         if (w.wpfire)
1609                         {
1610                                 searching = TRUE;
1611                                 w.wpfire = 0;
1612                                 cost = w.wpcost;
1613                                 p = w.wpnearestpoint;
1614                                 wp = w.wp00;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp00mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1615                                 wp = w.wp01;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp01mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1616                                 wp = w.wp02;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp02mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1617                                 wp = w.wp03;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp03mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1618                                 wp = w.wp04;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp04mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1619                                 wp = w.wp05;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp05mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1620                                 wp = w.wp06;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp06mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1621                                 wp = w.wp07;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp07mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1622                                 wp = w.wp08;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp08mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1623                                 wp = w.wp09;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp09mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1624                                 wp = w.wp10;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp10mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1625                                 wp = w.wp11;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp11mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1626                                 wp = w.wp12;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp12mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1627                                 wp = w.wp13;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp13mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1628                                 wp = w.wp14;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp14mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1629                                 wp = w.wp15;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp15mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1630                                 wp = w.wp16;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp16mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1631                                 wp = w.wp17;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp17mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1632                                 wp = w.wp18;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp18mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1633                                 wp = w.wp19;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp19mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1634                                 wp = w.wp20;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp20mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1635                                 wp = w.wp21;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp21mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1636                                 wp = w.wp22;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp22mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1637                                 wp = w.wp23;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp23mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1638                                 wp = w.wp24;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp24mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1639                                 wp = w.wp25;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp25mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1640                                 wp = w.wp26;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp26mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1641                                 wp = w.wp27;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp27mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1642                                 wp = w.wp28;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp28mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1643                                 wp = w.wp29;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp29mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1644                                 wp = w.wp30;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp30mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1645                                 wp = w.wp31;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp31mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1646                                 }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
1647                         }
1648                         w = w.chain;
1649                 }
1650         }
1651 };
1652
1653 void navigation_bestgoals_reset()
1654 {
1655         local float i;
1656
1657         bestgoalswindex = 0;
1658         bestgoalsrindex = 0;
1659
1660         for(i=0;i>MAX_BESTGOALS-1;++i)
1661         {
1662                 navigation_bestgoals[i] = world;
1663         }
1664 }
1665
1666 void navigation_add_bestgoal(entity goal)
1667 {
1668         if(bestgoalsrindex>0)
1669         {
1670                 ++bestgoalsrindex;
1671
1672                 if(bestgoalsrindex==MAX_BESTGOALS)
1673                         bestgoalsrindex = 0;
1674         }
1675
1676         if(bestgoalswindex==MAX_BESTGOALS)
1677         {
1678                 bestgoalswindex=0;
1679                 if(bestgoalsrindex==0)
1680                         bestgoalsrindex=1;
1681         }
1682
1683         navigation_bestgoals[bestgoalswindex] = goal;
1684
1685         ++bestgoalswindex;
1686 }
1687
1688 entity navigation_get_bestgoal()
1689 {
1690         local entity ent;
1691
1692         ent = navigation_bestgoals[bestgoalsrindex];
1693         navigation_bestgoals[bestgoalsrindex] = world;
1694
1695         ++bestgoalsrindex;
1696
1697         if(bestgoalsrindex==MAX_BESTGOALS)
1698                 bestgoalsrindex = 0;
1699
1700         return ent;
1701 }
1702
1703 // updates the best goal according to a weighted calculation of travel cost and item value of a new proposed item
1704 .void() havocbot_role;
1705 void() havocbot_role_ctf_offense;
1706 void navigation_routerating(entity e, float f, float rangebias)
1707 {
1708         if (!e)
1709                 return;
1710         //te_wizspike(e.origin);
1711         //bprint(etos(e));
1712         //bprint("\n");
1713         // update the cached spawnfunc_waypoint link on a dynamic item entity
1714         if (time > e.nearestwaypointtimeout)
1715         {
1716                 e.nearestwaypoint = navigation_findnearestwaypoint(e, TRUE);
1717                 e.nearestwaypointtimeout = time + random() * 3 + 5;
1718         }
1719         //dprint(e.classname, " ", ftos(f));
1720         //dprint("-- checking ", e.classname, " (with cost ", ftos(e.nearestwaypoint.wpcost), ")\n");
1721         if (e.nearestwaypoint)
1722         if (e.nearestwaypoint.wpcost < 10000000)
1723         {
1724                 //te_wizspike(e.nearestwaypoint.wpnearestpoint);
1725                 //dprint(e.classname, " ", ftos(f), "/(1+", ftos((e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint))), "/", ftos(rangebias), ") = ");
1726                 f = f * rangebias / (rangebias + (e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint)));
1727                 //if (self.havocbot_role == havocbot_role_ctf_offense)
1728                 //      dprint("-- considering ", e.classname, " (with rating ", ftos(f), ")\n");
1729                 //dprint(ftos(f));
1730                 if (navigation_bestrating < f)
1731                 {
1732                         navigation_bestrating = f;
1733                         navigation_add_bestgoal(e);
1734                 }
1735         }
1736         //dprint("\n");
1737 };
1738
1739 // adds an item to the the goal stack with the path to a given item
1740 float navigation_routetogoal(entity e, vector startposition)
1741 {
1742         self.goalentity = e;
1743
1744         // if there is no goal, just exit
1745         if (!e)
1746                 return FALSE;
1747
1748         self.navigation_hasgoals = TRUE;
1749
1750         // put the entity on the goal stack
1751         navigation_pushroute(e);
1752
1753         // if it can reach the goal there is nothing more to do
1754         if (tracewalk(self, startposition, PL_MIN, PL_MAX, e.origin, MOVE_NORMAL))
1755                 return TRUE;
1756
1757         // see if there are waypoints describing a path to the item
1758         e = e.nearestwaypoint;
1759         if(e == world)
1760                 return FALSE;
1761
1762         for (;;)
1763         {
1764                 // add the spawnfunc_waypoint to the path
1765                 navigation_pushroute(e);
1766                 e = e.enemy;
1767
1768                 if(e==world)
1769                         break;
1770         }
1771
1772         return FALSE;
1773 };
1774
1775 void navigation_routetogoals()
1776 {
1777         entity g1, g2;
1778
1779         navigation_clearroute();
1780
1781         g1 = navigation_get_bestgoal();
1782         for(;;)
1783         {
1784                 if(g2==world)
1785                         g2 = navigation_get_bestgoal();
1786
1787                 if(g2==world)
1788                 {
1789                         navigation_routetogoal(g1, self.origin);
1790                         return;
1791                 }
1792
1793                 if(navigation_routetogoal(g1, g2.origin))
1794                 {
1795                         g1 = g2;
1796                         g2 = world;
1797                         continue;
1798                 }
1799
1800                 navigation_clearroute();
1801                 g1 = g2;
1802                 g2 = world;
1803         }
1804 }
1805
1806 // removes any currently touching waypoints from the goal stack
1807 // (this is how bots detect if they have reached a goal)
1808 .float lastteleporttime;
1809
1810 void navigation_poptouchedgoals()
1811 {
1812         local vector org, m1, m2;
1813         org = self.origin;
1814         m1 = org + self.mins;
1815         m2 = org + self.maxs;
1816
1817         if(self.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
1818         {
1819                 if(self.lastteleporttime>0)
1820                 if(time-self.lastteleporttime<0.2)
1821                 {
1822                         navigation_poproute();
1823                         return;
1824                 }
1825         }
1826
1827         // Loose goal touching check when running
1828         if(self.aistatus & AI_STATUS_RUNNING)
1829         if(self.goalcurrent.classname=="waypoint")
1830         {
1831                 if(vlen(self.origin - self.goalcurrent.origin)<150)
1832                 {
1833                         traceline(self.origin + self.view_ofs , self.goalcurrent.origin, TRUE, world);
1834                         if(trace_fraction==1)
1835                         {
1836                                 // Detect personal waypoints
1837                                 if(self.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
1838                                 if(self.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL && self.goalcurrent.owner==self)
1839                                 {
1840                                         self.aistatus &~= AI_STATUS_WAYPOINT_PERSONAL_GOING;
1841                                         self.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_REACHED;
1842                                 }
1843
1844                                 navigation_poproute();
1845                         }
1846                 }
1847         }
1848
1849         while (self.goalcurrent && boxesoverlap(m1, m2, self.goalcurrent.absmin, self.goalcurrent.absmax))
1850         {
1851                 // Detect personal waypoints
1852                 if(self.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
1853                 if(self.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL && self.goalcurrent.owner==self)
1854                 {
1855                         self.aistatus &~= AI_STATUS_WAYPOINT_PERSONAL_GOING;
1856                         self.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_REACHED;
1857                 }
1858
1859                 navigation_poproute();
1860         }
1861 }
1862
1863 // begin a goal selection session (queries spawnfunc_waypoint network)
1864 void navigation_goalrating_start()
1865 {
1866         navigation_bestrating = -1;
1867         self.navigation_hasgoals = FALSE;
1868         navigation_bestgoals_reset();
1869         navigation_markroutes();
1870 };
1871
1872 // ends a goal selection session (updates goal stack to the best goal)
1873 void navigation_goalrating_end()
1874 {
1875         navigation_routetogoals();
1876 };
1877
1878
1879 //////////////////////////////////////////////////////////////////////////////
1880 // general bot functions
1881 //////////////////////////////////////////////////////////////////////////////
1882
1883 .float isbot; // true if this client is actually a bot
1884
1885 float skill;
1886 entity bot_list;
1887 .entity nextbot;
1888 .string netname_freeme;
1889 .string playermodel_freeme;
1890 .string playerskin_freeme;
1891
1892 float sv_maxspeed;
1893 .float createdtime;
1894
1895 .float bot_preferredcolors;
1896
1897 .float bot_attack;
1898 .float bot_dodge;
1899 .float bot_dodgerating;
1900
1901 //.float bot_painintensity;
1902 .float bot_firetimer;
1903 //.float bot_oldhealth;
1904 .void() bot_ai;
1905
1906 .entity bot_aimtarg;
1907 .float bot_aimlatency;
1908 .vector bot_aimselforigin;
1909 .vector bot_aimselfvelocity;
1910 .vector bot_aimtargorigin;
1911 .vector bot_aimtargvelocity;
1912
1913 .float bot_pickup;
1914 .float(entity player, entity item) bot_pickupevalfunc;
1915 .float bot_pickupbasevalue;
1916 .float bot_canfire;
1917 .float bot_strategytime;
1918
1919 // used for aiming currently
1920 // FIXME: make the weapon code use these and then replace the calculations here with a call to the weapon code
1921 vector shotorg;
1922 vector shotdir;
1923
1924 .float bot_forced_team;
1925 .float bot_config_loaded;
1926
1927 void bot_setnameandstuff()
1928 {
1929         local string readfile, s;
1930         local float file, tokens;
1931
1932         local string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
1933         local string name, prefix, suffix;
1934
1935         file = fopen(cvar_string("bot_config_file"), FILE_READ);
1936
1937         if(file < 0)
1938                 print(strcat("Error: Can not open the bot configuration file '",cvar_string("bot_config_file"),"'\n"));
1939         else
1940         {
1941                 RandomSelection_Init();
1942                 for(;;)
1943                 {
1944                         s = fgets(file);
1945                         if(!s)
1946                                 break;
1947                         if(substring(s, 0, 2) == "//")
1948                                 continue;
1949                         if(substring(s, 0, 1) == "#")
1950                                 continue;
1951                         RandomSelection_Add(world, 0, s, 1, 0);
1952                         readfile = RandomSelection_chosen_string;
1953                 }
1954                 fclose(file);
1955         }
1956
1957         tokens = tokenizebyseparator(readfile, "\t");
1958         if(argv(0) != "") bot_name = argv(0);
1959         else bot_name = "Bot";
1960
1961         if(argv(1) != "") bot_model = argv(1);
1962         else bot_model = "marine";
1963
1964         if(argv(2) != "") bot_skin = argv(2);
1965         else bot_skin = "0";
1966
1967         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
1968         else bot_shirt = ftos(floor(random() * 15));
1969
1970         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
1971         else bot_pants = ftos(floor(random() * 15));
1972
1973         self.bot_forced_team = stof(argv(5));
1974         self.bot_config_loaded = TRUE;
1975         prefix = cvar_string("bot_prefix");
1976         suffix = cvar_string("bot_suffix");
1977
1978         // this is really only a default, JoinBestTeam is called later
1979         setcolor(self, stof(bot_shirt) * 16 + stof(bot_pants));
1980         self.bot_preferredcolors = self.clientcolors;
1981
1982         // pick the name
1983         if (cvar("bot_usemodelnames"))
1984                 name = bot_model;
1985         else
1986                 name = bot_name;
1987
1988         // pick the model and skin
1989         self.playermodel = self.playermodel_freeme = strzone(strcat("models/player/", bot_model, ".zym"));
1990         self.playerskin = self.playerskin_freeme = strzone(bot_skin);
1991
1992         if(!cvar("g_campaign"))
1993                 self.netname = self.netname_freeme = strzone(strcat(prefix, name, suffix));
1994         else
1995                 self.netname = self.netname_freeme = strzone(name);
1996 };
1997
1998 float bot_custom_weapon;
1999 float bot_distance_far;
2000 float bot_distance_close;
2001
2002 float bot_weapons_far[WEP_LAST];
2003 float bot_weapons_mid[WEP_LAST];
2004 float bot_weapons_close[WEP_LAST];
2005
2006 void bot_custom_weapon_priority_setup()
2007 {
2008         local float tokens, i, c, w;
2009
2010         bot_custom_weapon = FALSE;
2011
2012         if(     cvar_string("bot_ai_custom_weapon_priority_far") == "" ||
2013                 cvar_string("bot_ai_custom_weapon_priority_mid") == "" ||
2014                 cvar_string("bot_ai_custom_weapon_priority_close") == "" ||
2015                 cvar_string("bot_ai_custom_weapon_priority_distances") == ""
2016         )
2017                 return;
2018
2019         // Parse distances
2020         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_distances")," ");
2021
2022         if (tokens!=2)
2023                 return;
2024
2025         bot_distance_far = stof(argv(0));
2026         bot_distance_close = stof(argv(1));
2027
2028         if(bot_distance_far < bot_distance_close){
2029                 bot_distance_far = stof(argv(1));
2030                 bot_distance_close = stof(argv(0));
2031         }
2032
2033         // Initialize list of weapons
2034         bot_weapons_far[0] = -1;
2035         bot_weapons_mid[0] = -1;
2036         bot_weapons_close[0] = -1;
2037
2038         // Parse far distance weapon priorities
2039         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_far")," ");
2040
2041         c = 0;
2042         for(i=0; i < tokens && c < WEP_COUNT; ++i){
2043                 w = stof(argv(i));
2044                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2045                         bot_weapons_far[c] = w;
2046                         ++c;
2047                 }
2048         }
2049         if(c < WEP_COUNT)
2050                 bot_weapons_far[c] = -1;
2051
2052         // Parse mid distance weapon priorities
2053         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_mid")," ");
2054
2055         c = 0;
2056         for(i=0; i < tokens && c < WEP_COUNT; ++i){
2057                 w = stof(argv(i));
2058                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2059                         bot_weapons_mid[c] = w;
2060                         ++c;
2061                 }
2062         }
2063         if(c < WEP_COUNT)
2064                 bot_weapons_mid[c] = -1;
2065
2066         // Parse close distance weapon priorities
2067         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_close")," ");
2068
2069         c = 0;
2070         for(i=0; i < tokens && i < WEP_COUNT; ++i){
2071                 w = stof(argv(i));
2072                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2073                         bot_weapons_close[c] = w;
2074                         ++c;
2075                 }
2076         }
2077         if(c < WEP_COUNT)
2078                 bot_weapons_close[c] = -1;
2079
2080         bot_custom_weapon = TRUE;
2081 };
2082
2083
2084 void bot_endgame()
2085 {
2086         local entity e;
2087         //dprint("bot_endgame\n");
2088         e = bot_list;
2089         while (e)
2090         {
2091                 setcolor(e, e.bot_preferredcolors);
2092                 e = e.nextbot;
2093         }
2094         // if dynamic waypoints are ever implemented, save them here
2095 };
2096
2097 float bot_ignore_bots; // let bots not attack other bots (only works in non-teamplay)
2098 float bot_shouldattack(entity e)
2099 {
2100         if (e.team == self.team)
2101         {
2102                 if (e == self)
2103                         return FALSE;
2104                 if (teams_matter)
2105                 if (e.team != 0)
2106                         return FALSE;
2107         }
2108         if(!teams_matter)
2109                 if(bot_ignore_bots)
2110                         if(clienttype(e) == CLIENTTYPE_BOT)
2111                                 return FALSE;
2112         if (!e.takedamage)
2113                 return FALSE;
2114         if (e.deadflag)
2115                 return FALSE;
2116         if (e.BUTTON_CHAT)
2117                 return FALSE;
2118         if(g_minstagib)
2119         if(e.items & IT_STRENGTH)
2120                 return FALSE;
2121         if(e.flags & FL_NOTARGET)
2122                 return FALSE;
2123         return TRUE;
2124 };
2125
2126 void bot_lagfunc(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
2127 {
2128         if(self.flags & FL_INWATER)
2129         {
2130                 self.bot_aimtarg = world;
2131                 return;
2132         }
2133         self.bot_aimtarg = e1;
2134         self.bot_aimlatency = self.ping; // FIXME?  Shouldn't this be in the lag item?
2135         self.bot_aimselforigin = v1;
2136         self.bot_aimselfvelocity = v2;
2137         self.bot_aimtargorigin = v3;
2138         self.bot_aimtargvelocity = v4;
2139         if(skill <= 0)
2140                 self.bot_canfire = (random() < 0.8);
2141         else if(skill <= 1)
2142                 self.bot_canfire = (random() < 0.9);
2143         else if(skill <= 2)
2144                 self.bot_canfire = (random() < 0.95);
2145         else
2146                 self.bot_canfire = 1;
2147 };
2148
2149 .float bot_nextthink;
2150 .float bot_badaimtime;
2151 .float bot_aimthinktime;
2152 .float bot_prevaimtime;
2153 .vector bot_mouseaim;
2154 .vector bot_badaimoffset;
2155 .vector bot_1st_order_aimfilter;
2156 .vector bot_2nd_order_aimfilter;
2157 .vector bot_3th_order_aimfilter;
2158 .vector bot_4th_order_aimfilter;
2159 .vector bot_5th_order_aimfilter;
2160 .vector bot_olddesiredang;
2161 float bot_aimdir(vector v, float maxfiredeviation)
2162 {
2163         local float dist, delta_t, blend;
2164         local vector desiredang, diffang;
2165
2166         //dprint("aim ", self.netname, ": old:", vtos(self.v_angle));
2167         // make sure v_angle is sane first
2168         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
2169         self.v_angle_z = 0;
2170
2171         // get the desired angles to aim at
2172         //dprint(" at:", vtos(v));
2173         v = normalize(v);
2174         //te_lightning2(world, self.origin + self.view_ofs, self.origin + self.view_ofs + v * 200);
2175         if (time >= self.bot_badaimtime)
2176         {
2177                 self.bot_badaimtime = max(self.bot_badaimtime + 0.3, time);
2178                 self.bot_badaimoffset = randomvec() * bound(0, 5 - 0.5 * (skill+self.bot_offsetskill), 5) * cvar("bot_ai_aimskill_offset");
2179         }
2180         desiredang = vectoangles(v) + self.bot_badaimoffset;
2181         //dprint(" desired:", vtos(desiredang));
2182         if (desiredang_x >= 180)
2183                 desiredang_x = desiredang_x - 360;
2184         desiredang_x = bound(-90, 0 - desiredang_x, 90);
2185         desiredang_z = self.v_angle_z;
2186         //dprint(" / ", vtos(desiredang));
2187
2188         //// pain throws off aim
2189         //if (self.bot_painintensity)
2190         //{
2191         //      // shake from pain
2192         //      desiredang = desiredang + randomvec() * self.bot_painintensity * 0.2;
2193         //}
2194
2195         // calculate turn angles
2196         diffang = (desiredang - self.bot_olddesiredang);
2197         // wrap yaw turn
2198         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2199         if (diffang_y >= 180)
2200                 diffang_y = diffang_y - 360;
2201         self.bot_olddesiredang = desiredang;
2202         //dprint(" diff:", vtos(diffang));
2203
2204         delta_t = time-self.bot_prevaimtime;
2205         self.bot_prevaimtime = time;
2206         // Here we will try to anticipate the comming aiming direction
2207         self.bot_1st_order_aimfilter= self.bot_1st_order_aimfilter
2208                 + (diffang * (1 / delta_t)    - self.bot_1st_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_1st"),1);
2209         self.bot_2nd_order_aimfilter= self.bot_2nd_order_aimfilter
2210                 + (self.bot_1st_order_aimfilter - self.bot_2nd_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_2nd"),1);
2211         self.bot_3th_order_aimfilter= self.bot_3th_order_aimfilter
2212                 + (self.bot_2nd_order_aimfilter - self.bot_3th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_3th"),1);
2213         self.bot_4th_order_aimfilter= self.bot_4th_order_aimfilter
2214                 + (self.bot_3th_order_aimfilter - self.bot_4th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_4th"),1);
2215         self.bot_5th_order_aimfilter= self.bot_5th_order_aimfilter
2216                 + (self.bot_4th_order_aimfilter - self.bot_5th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_5th"),1);
2217
2218         //blend = (bound(0,skill,10)*0.1)*pow(1-bound(0,skill,10)*0.05,2.5)*5.656854249; //Plot formule before changing !
2219         blend = bound(0,skill,10)*0.1;
2220         desiredang = desiredang + blend *
2221         (
2222                   self.bot_1st_order_aimfilter * cvar("bot_ai_aimskill_order_mix_1st")
2223                 + self.bot_2nd_order_aimfilter * cvar("bot_ai_aimskill_order_mix_2nd")
2224                 + self.bot_3th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_3th")
2225                 + self.bot_4th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_4th")
2226                 + self.bot_5th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_5th")
2227         );
2228
2229         // calculate turn angles
2230         diffang = desiredang - self.bot_mouseaim;
2231         // wrap yaw turn
2232         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2233         if (diffang_y >= 180)
2234                 diffang_y = diffang_y - 360;
2235         //dprint(" diff:", vtos(diffang));
2236
2237         if (time >= self.bot_aimthinktime)
2238         {
2239                 self.bot_aimthinktime = max(self.bot_aimthinktime + 0.5 - 0.05*(skill+self.bot_thinkskill), time);
2240                 self.bot_mouseaim = self.bot_mouseaim + diffang * (1-random()*0.1*bound(1,10-skill,10));
2241         }
2242
2243         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
2244
2245         diffang = self.bot_mouseaim - desiredang;
2246         // wrap yaw turn
2247         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2248         if (diffang_y >= 180)
2249                 diffang_y = diffang_y - 360;
2250         desiredang = desiredang + diffang * bound(0,cvar("bot_ai_aimskill_think"),1);
2251
2252         // calculate turn angles
2253         diffang = desiredang - self.v_angle;
2254         // wrap yaw turn
2255         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2256         if (diffang_y >= 180)
2257                 diffang_y = diffang_y - 360;
2258         //dprint(" diff:", vtos(diffang));
2259
2260         // jitter tracking
2261         dist = vlen(diffang);
2262         //diffang = diffang + randomvec() * (dist * 0.05 * (3.5 - bound(0, skill, 3)));
2263
2264         // turn
2265         local float r, fixedrate, blendrate;
2266         fixedrate = cvar("bot_ai_aimskill_fixedrate") / bound(1,dist,1000);
2267         blendrate = cvar("bot_ai_aimskill_blendrate");
2268         r = max(fixedrate, blendrate);
2269         //self.v_angle = self.v_angle + diffang * bound(frametime, r * frametime * (2+skill*skill*0.05-random()*0.05*(10-skill)), 1);
2270         self.v_angle = self.v_angle + diffang * bound(delta_t, r * delta_t * (2+pow(skill+self.bot_mouseskill,3)*0.005-random()), 1);
2271         self.v_angle = self.v_angle * bound(0,cvar("bot_ai_aimskill_mouse"),1) + desiredang * bound(0,(1-cvar("bot_ai_aimskill_mouse")),1);
2272         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
2273         //self.v_angle = self.v_angle + diffang * (1/ blendrate);
2274         self.v_angle_z = 0;
2275         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
2276         //dprint(" turn:", vtos(self.v_angle));
2277
2278         makevectors(self.v_angle);
2279         shotorg = self.origin + self.view_ofs;
2280         shotdir = v_forward;
2281
2282         //dprint(" dir:", vtos(v_forward));
2283         //te_lightning2(world, shotorg, shotorg + shotdir * 100);
2284
2285         // calculate turn angles again
2286         //diffang = desiredang - self.v_angle;
2287         //diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2288         //if (diffang_y >= 180)
2289         //      diffang_y = diffang_y - 360;
2290
2291         //dprint("e ", vtos(diffang), " < ", ftos(maxfiredeviation), "\n");
2292
2293         // decide whether to fire this time
2294         // note the maxfiredeviation is in degrees so this has to convert to radians first
2295         //if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
2296         if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
2297         if (vlen(trace_endpos-shotorg) < 500+500*bound(0, skill, 10) || random()*random()>bound(0,skill*0.05,1))
2298                 self.bot_firetimer = time + bound(0.1, 0.5-skill*0.05, 0.5);
2299         //traceline(shotorg,shotorg+shotdir*1000,FALSE,world);
2300         //dprint(ftos(maxfiredeviation),"\n");
2301         //dprint(" diff:", vtos(diffang), "\n");
2302
2303         return self.bot_canfire && (time < self.bot_firetimer);
2304 };
2305
2306 vector bot_shotlead(vector targorigin, vector targvelocity, float shotspeed, float shotdelay)
2307 {
2308         // Try to add code here that predicts gravity effect here, no clue HOW to though ... well not yet atleast...
2309         return targorigin + targvelocity * (shotdelay + vlen(targorigin - shotorg) / shotspeed);
2310 };
2311
2312 float bot_aim(float shotspeed, float shotspeedupward, float maxshottime, float applygravity)
2313 {
2314         local float f, r;
2315         local vector v;
2316         /*
2317         eprint(self);
2318         dprint("bot_aim(", ftos(shotspeed));
2319         dprint(", ", ftos(shotspeedupward));
2320         dprint(", ", ftos(maxshottime));
2321         dprint(", ", ftos(applygravity));
2322         dprint(");\n");
2323         */
2324         if (!shotspeed)
2325         {
2326                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " shotspeed is zero!\n");
2327                 shotspeed = 1000000;
2328         }
2329         if (!maxshottime)
2330         {
2331                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " maxshottime is zero!\n");
2332                 maxshottime = 1;
2333         }
2334         makevectors(self.v_angle);
2335         shotorg = self.origin + self.view_ofs;
2336         shotdir = v_forward;
2337         v = bot_shotlead(self.bot_aimtargorigin, self.bot_aimtargvelocity, shotspeed, self.bot_aimlatency);
2338         local float distanceratio;
2339         distanceratio =sqrt(bound(0,skill,10000))*0.3*(vlen(v-shotorg)-100)/cvar("bot_ai_aimskill_firetolerance_distdegrees");
2340         distanceratio = bound(0,distanceratio,1);
2341         r =  (cvar("bot_ai_aimskill_firetolerance_maxdegrees")-cvar("bot_ai_aimskill_firetolerance_mindegrees"))
2342                 * (1-distanceratio) + cvar("bot_ai_aimskill_firetolerance_mindegrees");
2343         if (applygravity && self.bot_aimtarg)
2344         {
2345                 if (!findtrajectorywithleading(shotorg, '0 0 0', '0 0 0', self.bot_aimtarg, shotspeed, shotspeedupward, maxshottime, 0, self))
2346                         return FALSE;
2347                 f = bot_aimdir(findtrajectory_velocity - shotspeedupward * '0 0 1', r);
2348         }
2349         else
2350         {
2351                 f = bot_aimdir(v - shotorg, r);
2352                 //dprint("AIM: ");dprint(vtos(self.bot_aimtargorigin));dprint(" + ");dprint(vtos(self.bot_aimtargvelocity));dprint(" * ");dprint(ftos(self.bot_aimlatency + vlen(self.bot_aimtargorigin - shotorg) / shotspeed));dprint(" = ");dprint(vtos(v));dprint(" : aimdir = ");dprint(vtos(normalize(v - shotorg)));dprint(" : ");dprint(vtos(shotdir));dprint("\n");
2353                 traceline(shotorg, shotorg + shotdir * 10000, FALSE, self);
2354                 if (trace_ent.takedamage)
2355                 if (trace_fraction < 1)
2356                 if (!bot_shouldattack(trace_ent))
2357                         return FALSE;
2358                 traceline(shotorg, self.bot_aimtargorigin, FALSE, self);
2359                 if (trace_fraction < 1)
2360                 if (trace_ent != self.enemy)
2361                 if (!bot_shouldattack(trace_ent))
2362                         return FALSE;
2363         }
2364         if (r > maxshottime * shotspeed)
2365                 return FALSE;
2366         return f;
2367 };
2368
2369 // TODO: move this painintensity code to the player damage code
2370 void bot_think()
2371 {
2372         if (self.bot_nextthink > time)
2373                 return;
2374         self.bot_nextthink = self.bot_nextthink + cvar("bot_ai_thinkinterval");
2375         //if (self.bot_painintensity > 0)
2376         //      self.bot_painintensity = self.bot_painintensity - (skill + 1) * 40 * frametime;
2377
2378         //self.bot_painintensity = self.bot_painintensity + self.bot_oldhealth - self.health;
2379         //self.bot_painintensity = bound(0, self.bot_painintensity, 100);
2380
2381         if(time < game_starttime || ((cvar("g_campaign") && !campaign_bots_may_start)))
2382         {
2383                 self.nextthink = time + 0.5;
2384                 return;
2385         }
2386
2387         if (self.fixangle)
2388         {
2389                 self.v_angle = self.angles;
2390                 self.v_angle_z = 0;
2391                 self.fixangle = FALSE;
2392         }
2393
2394         self.dmg_take = 0;
2395         self.dmg_save = 0;
2396         self.dmg_inflictor = world;
2397
2398         // calculate an aiming latency based on the skill setting
2399         // (simulated network latency + naturally delayed reflexes)
2400         //self.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
2401         // minimum ping 20+10 random
2402         self.ping = bound(0,0.07 - bound(0, skill * 0.005,0.05)+random()*0.01,0.65); // Now holds real lag to server, and higer skill players take a less laggy server
2403         // skill 10 = ping 0.2 (adrenaline)
2404         // skill 0 = ping 0.7 (slightly drunk)
2405
2406         // clear buttons
2407         self.BUTTON_ATCK = 0;
2408         self.button1 = 0;
2409         self.BUTTON_JUMP = 0;
2410         self.BUTTON_ATCK2 = 0;
2411         self.BUTTON_ZOOM = 0;
2412         self.BUTTON_CROUCH = 0;
2413         self.BUTTON_HOOK = 0;
2414         self.BUTTON_INFO = 0;
2415         self.button8 = 0;
2416         self.BUTTON_CHAT = 0;
2417         self.BUTTON_USE = 0;
2418
2419         // if dead, just wait until we can respawn
2420         if (self.deadflag)
2421         {
2422                 if (self.deadflag == DEAD_DEAD)
2423                 {
2424                         self.BUTTON_JUMP = 1; // press jump to respawn
2425                         self.bot_strategytime = 0;
2426                 }
2427                 return;
2428         }
2429
2430         // now call the current bot AI (havocbot for example)
2431         self.bot_ai();
2432 };
2433
2434 entity bot_strategytoken;
2435 float bot_strategytoken_taken;
2436 entity player_list;
2437 .entity nextplayer;
2438 void bot_relinkplayerlist()
2439 {
2440         local entity e;
2441         local entity prevbot;
2442         player_count = 0;
2443         currentbots = 0;
2444         player_list = e = findchainflags(flags, FL_CLIENT);
2445         bot_list = world;
2446         prevbot = world;
2447         while (e)
2448         {
2449                 player_count = player_count + 1;
2450                 e.nextplayer = e.chain;
2451                 if (clienttype(e) == CLIENTTYPE_BOT)
2452                 {
2453                         if (prevbot)
2454                                 prevbot.nextbot = e;
2455                         else
2456                                 bot_list = e;
2457                         prevbot = e;
2458                         currentbots = currentbots + 1;
2459                 }
2460                 e = e.chain;
2461         }
2462         dprint(strcat("relink: ", ftos(currentbots), " bots seen.\n"));
2463         bot_strategytoken = bot_list;
2464         bot_strategytoken_taken = TRUE;
2465 };
2466
2467 void() havocbot_setupbot;
2468 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam);
2469
2470 void bot_clientdisconnect()
2471 {
2472         if (clienttype(self) != CLIENTTYPE_BOT)
2473                 return;
2474         if(self.netname_freeme)
2475                 strunzone(self.netname_freeme);
2476         if(self.playermodel_freeme)
2477                 strunzone(self.playermodel_freeme);
2478         if(self.playerskin_freeme)
2479                 strunzone(self.playerskin_freeme);
2480         self.netname_freeme = string_null;
2481         self.playermodel_freeme = string_null;
2482         self.playerskin_freeme = string_null;
2483 }
2484
2485 void bot_clientconnect()
2486 {
2487         if (clienttype(self) != CLIENTTYPE_BOT)
2488                 return;
2489         self.bot_preferredcolors = self.clientcolors;
2490         self.bot_nextthink = time - random();
2491         self.lag_func = bot_lagfunc;
2492         self.isbot = TRUE;
2493         self.createdtime = self.nextthink;
2494
2495         if(!self.bot_config_loaded) // This is needed so team overrider doesn't break between matches
2496                 bot_setnameandstuff();
2497
2498         if(self.bot_forced_team==1)
2499                 self.team = COLOR_TEAM1;
2500         else if(self.bot_forced_team==2)
2501                 self.team = COLOR_TEAM2;
2502         else if(self.bot_forced_team==3)
2503                 self.team = COLOR_TEAM3;
2504         else if(self.bot_forced_team==4)
2505                 self.team = COLOR_TEAM4;
2506         else
2507                 JoinBestTeam(self, FALSE, TRUE);
2508
2509         havocbot_setupbot();
2510         self.bot_mouseskill=random()-0.5;
2511         self.bot_thinkskill=random()-0.5;
2512         self.bot_predictionskill=random()-0.5;
2513         self.bot_offsetskill=random()-0.5;
2514 };
2515
2516 entity bot_spawn()
2517 {
2518         local entity oldself, bot;
2519         bot = spawnclient();
2520         if (bot)
2521         {
2522                 currentbots = currentbots + 1;
2523                 oldself = self;
2524                 self = bot;
2525                 bot_setnameandstuff();
2526                 ClientConnect();
2527                 PutClientInServer();
2528                 self = oldself;
2529         }
2530         return bot;
2531 };
2532
2533 void CheckAllowedTeams(entity for_whom); void GetTeamCounts(entity other); float c1, c2, c3, c4;
2534 void bot_removefromlargestteam()
2535 {
2536         local float besttime, bestcount, thiscount;
2537         local entity best, head;
2538         CheckAllowedTeams(world);
2539         GetTeamCounts(world);
2540         head = findchainfloat(isbot, TRUE);
2541         if (!head)
2542                 return;
2543         best = head;
2544         besttime = head.createdtime;
2545         bestcount = 0;
2546         while (head)
2547         {
2548                 if(head.team == COLOR_TEAM1)
2549                         thiscount = c1;
2550                 else if(head.team == COLOR_TEAM2)
2551                         thiscount = c2;
2552                 else if(head.team == COLOR_TEAM3)
2553                         thiscount = c3;
2554                 else if(head.team == COLOR_TEAM4)
2555                         thiscount = c4;
2556                 else
2557                         thiscount = 0;
2558                 if (thiscount > bestcount)
2559                 {
2560                         bestcount = thiscount;
2561                         besttime = head.createdtime;
2562                         best = head;
2563                 }
2564                 else if (thiscount == bestcount && besttime < head.createdtime)
2565                 {
2566                         besttime = head.createdtime;
2567                         best = head;
2568                 }
2569                 head = head.chain;
2570         }
2571         currentbots = currentbots - 1;
2572         dropclient(best);
2573 };
2574
2575 void bot_removenewest()
2576 {
2577         local float besttime;
2578         local entity best, head;
2579
2580         if(teams_matter)
2581         {
2582                 bot_removefromlargestteam();
2583                 return;
2584         }
2585
2586         head = findchainfloat(isbot, TRUE);
2587         if (!head)
2588                 return;
2589         best = head;
2590         besttime = head.createdtime;
2591         while (head)
2592         {
2593                 if (besttime < head.createdtime)
2594                 {
2595                         besttime = head.createdtime;
2596                         best = head;
2597                 }
2598                 head = head.chain;
2599         }
2600         currentbots = currentbots - 1;
2601         dropclient(best);
2602 };
2603
2604 float botframe_waypointeditorlightningtime;
2605 void botframe_showwaypointlinks()
2606 {
2607         local entity player, head, w;
2608         if (time < botframe_waypointeditorlightningtime)
2609                 return;
2610         botframe_waypointeditorlightningtime = time + 0.5;
2611         player = find(world, classname, "player");
2612         while (player)
2613         {
2614                 if (!player.isbot)
2615                 if (player.flags & FL_ONGROUND || player.waterlevel > WATERLEVEL_NONE)
2616                 {
2617                         //navigation_testtracewalk = TRUE;
2618                         head = navigation_findnearestwaypoint(player, FALSE);
2619                         //navigation_testtracewalk = FALSE;
2620                         if (head)
2621                         {
2622                                 w = head     ;if (w) te_lightning2(world, w.origin, player.origin);
2623                                 w = head.wp00;if (w) te_lightning2(world, w.origin, head.origin);
2624                                 w = head.wp01;if (w) te_lightning2(world, w.origin, head.origin);
2625                                 w = head.wp02;if (w) te_lightning2(world, w.origin, head.origin);
2626                                 w = head.wp03;if (w) te_lightning2(world, w.origin, head.origin);
2627                                 w = head.wp04;if (w) te_lightning2(world, w.origin, head.origin);
2628                                 w = head.wp05;if (w) te_lightning2(world, w.origin, head.origin);
2629                                 w = head.wp06;if (w) te_lightning2(world, w.origin, head.origin);
2630                                 w = head.wp07;if (w) te_lightning2(world, w.origin, head.origin);
2631                                 w = head.wp08;if (w) te_lightning2(world, w.origin, head.origin);
2632                                 w = head.wp09;if (w) te_lightning2(world, w.origin, head.origin);
2633                                 w = head.wp10;if (w) te_lightning2(world, w.origin, head.origin);
2634                                 w = head.wp11;if (w) te_lightning2(world, w.origin, head.origin);
2635                                 w = head.wp12;if (w) te_lightning2(world, w.origin, head.origin);
2636                                 w = head.wp13;if (w) te_lightning2(world, w.origin, head.origin);
2637                                 w = head.wp14;if (w) te_lightning2(world, w.origin, head.origin);
2638                                 w = head.wp15;if (w) te_lightning2(world, w.origin, head.origin);
2639                                 w = head.wp16;if (w) te_lightning2(world, w.origin, head.origin);
2640                                 w = head.wp17;if (w) te_lightning2(world, w.origin, head.origin);
2641                                 w = head.wp18;if (w) te_lightning2(world, w.origin, head.origin);
2642                                 w = head.wp19;if (w) te_lightning2(world, w.origin, head.origin);
2643                                 w = head.wp20;if (w) te_lightning2(world, w.origin, head.origin);
2644                                 w = head.wp21;if (w) te_lightning2(world, w.origin, head.origin);
2645                                 w = head.wp22;if (w) te_lightning2(world, w.origin, head.origin);
2646                                 w = head.wp23;if (w) te_lightning2(world, w.origin, head.origin);
2647                                 w = head.wp24;if (w) te_lightning2(world, w.origin, head.origin);
2648                                 w = head.wp25;if (w) te_lightning2(world, w.origin, head.origin);
2649                                 w = head.wp26;if (w) te_lightning2(world, w.origin, head.origin);
2650                                 w = head.wp27;if (w) te_lightning2(world, w.origin, head.origin);
2651                                 w = head.wp28;if (w) te_lightning2(world, w.origin, head.origin);
2652                                 w = head.wp29;if (w) te_lightning2(world, w.origin, head.origin);
2653                                 w = head.wp30;if (w) te_lightning2(world, w.origin, head.origin);
2654                                 w = head.wp31;if (w) te_lightning2(world, w.origin, head.origin);
2655                         }
2656                 }
2657                 player = find(player, classname, "player");
2658         }
2659 };
2660
2661 entity botframe_dangerwaypoint;
2662 void botframe_updatedangerousobjects(float maxupdate)
2663 {
2664         local entity head, bot_dodgelist;
2665         local vector m1, m2, v;
2666         local float c, d, danger;
2667         c = 0;
2668         bot_dodgelist = findchainfloat(bot_dodge, TRUE);
2669         botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2670         while (botframe_dangerwaypoint != world)
2671         {
2672                 danger = 0;
2673                 m1 = botframe_dangerwaypoint.mins;
2674                 m2 = botframe_dangerwaypoint.maxs;
2675                 head = bot_dodgelist;
2676                 while (head)
2677                 {
2678                         v = head.origin;
2679                         v_x = bound(m1_x, v_x, m2_x);
2680                         v_y = bound(m1_y, v_y, m2_y);
2681                         v_z = bound(m1_z, v_z, m2_z);
2682                         d = head.bot_dodgerating - vlen(head.origin - v);
2683                         if (d > 0)
2684                         {
2685                                 traceline(head.origin, v, TRUE, world);
2686                                 if (trace_fraction == 1)
2687                                         danger = danger + d;
2688                         }
2689                         head = head.chain;
2690                 }
2691                 botframe_dangerwaypoint.dmg = danger;
2692                 c = c + 1;
2693                 if (c >= maxupdate)
2694                         break;
2695                 botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2696         }
2697 };
2698
2699
2700 float botframe_spawnedwaypoints;
2701 float botframe_nextthink;
2702 float botframe_nextdangertime;
2703
2704 float autoskill_nextthink;
2705 .float totalfrags_lastcheck;
2706 void autoskill(float factor)
2707 {
2708         float bestbot;
2709         float bestplayer;
2710         entity head;
2711
2712         bestbot = -1;
2713         bestplayer = -1;
2714         FOR_EACH_PLAYER(head)
2715         {
2716                 if(clienttype(head) == CLIENTTYPE_REAL)
2717                         bestplayer = max(bestplayer, head.totalfrags - head.totalfrags_lastcheck);
2718                 else
2719                         bestbot = max(bestbot, head.totalfrags - head.totalfrags_lastcheck);
2720         }
2721
2722         dprint("autoskill: best player got ", ftos(bestplayer), ", ");
2723         dprint("best bot got ", ftos(bestbot), "; ");
2724         if(bestbot < 0 || bestplayer < 0)
2725         {
2726                 dprint("not doing anything\n");
2727                 // don't return, let it reset all counters below
2728         }
2729         else if(bestbot <= bestplayer * factor - 2)
2730         {
2731                 if(cvar("skill") < 17)
2732                 {
2733                         dprint("2 frags difference, increasing skill\n");
2734                         cvar_set("skill", ftos(cvar("skill") + 1));
2735                         bprint("^2SKILL UP!^7 Now at level ", ftos(cvar("skill")), "\n");
2736                 }
2737         }
2738         else if(bestbot >= bestplayer * factor + 2)
2739         {
2740                 if(cvar("skill") > 0)
2741                 {
2742                         dprint("2 frags difference, decreasing skill\n");
2743                         cvar_set("skill", ftos(cvar("skill") - 1));
2744                         bprint("^1SKILL DOWN!^7 Now at level ", ftos(cvar("skill")), "\n");
2745                 }
2746         }
2747         else
2748         {
2749                 dprint("not doing anything\n");
2750                 return;
2751                 // don't reset counters, wait for them to accumulate
2752         }
2753
2754         FOR_EACH_PLAYER(head)
2755                 head.totalfrags_lastcheck = head.totalfrags;
2756 }
2757
2758 float bot_cvar_nextthink;
2759 void bot_serverframe()
2760 {
2761         float realplayers, bots, activerealplayers;
2762         entity head;
2763
2764         if (intermission_running)
2765                 return;
2766
2767         if (time < 2)
2768                 return;
2769
2770         if(time > autoskill_nextthink)
2771         {
2772                 float a;
2773                 a = cvar("skill_auto");
2774                 if(a)
2775                         autoskill(a);
2776                 autoskill_nextthink = time + 5;
2777         }
2778
2779         activerealplayers = 0;
2780         realplayers = 0;
2781
2782         FOR_EACH_REALCLIENT(head)
2783         {
2784                 if(head.classname == "player" || g_lms || g_arena)
2785                         ++activerealplayers;
2786                 ++realplayers;
2787         }
2788
2789         // add/remove bots if needed to make sure there are at least
2790         // minplayers+bot_number, or remove all bots if no one is playing
2791         // But don't remove bots immediately on level change, as the real players
2792         // usually haven't rejoined yet
2793         bots_would_leave = FALSE;
2794         if (realplayers || cvar("bot_join_empty") || (currentbots > 0 && time < 5))
2795         {
2796                 float realminplayers, minplayers;
2797                 realminplayers = cvar("minplayers");
2798                 minplayers = max(0, floor(realminplayers));
2799
2800                 float realminbots, minbots;
2801                 if(cvar("bot_vs_human"))
2802                         realminbots = ceil(fabs(cvar("bot_vs_human")) * activerealplayers);
2803                 else
2804                         realminbots = cvar("bot_number");
2805                 minbots = max(0, floor(realminbots));
2806
2807                 bots = min(max(minbots, minplayers - activerealplayers), maxclients - realplayers);
2808                 if(bots > minbots)
2809                         bots_would_leave = TRUE;
2810         }
2811         else
2812         {
2813                 // if there are no players, remove bots
2814                 bots = 0;
2815         }
2816
2817         bot_ignore_bots = cvar("bot_ignore_bots");
2818
2819         // only add one bot per frame to avoid utter chaos
2820         if(time > botframe_nextthink)
2821         {
2822                 //dprint(ftos(bots), " ? ", ftos(currentbots), "\n");
2823                 while (currentbots < bots)
2824                 {
2825                         if (bot_spawn() == world)
2826                         {
2827                                 bprint("Can not add bot, server full.\n");
2828                                 botframe_nextthink = time + 10;
2829                                 break;
2830                         }
2831                 }
2832                 while (currentbots > bots)
2833                         bot_removenewest();
2834         }
2835
2836         if(botframe_spawnedwaypoints)
2837         {
2838                 if(cvar("waypoint_benchmark"))
2839                         localcmd("quit\n");
2840         }
2841
2842         if (currentbots > 0 || cvar("g_waypointeditor"))
2843         if (botframe_spawnedwaypoints)
2844         {
2845                 if(botframe_cachedwaypointlinks)
2846                 {
2847                         if(!botframe_loadedforcedlinks)
2848                                 waypoint_load_links_hardwired();
2849                 }
2850                 else
2851                 {
2852                         // TODO: Make this check cleaner
2853                         local entity wp = findchain(classname, "waypoint");
2854                         if(time - wp.nextthink > 10)
2855                                 waypoint_save_links();
2856                 }
2857         }
2858         else
2859         {
2860                 botframe_spawnedwaypoints = TRUE;
2861                 waypoint_loadall();
2862                 if(!waypoint_load_links())
2863                         waypoint_schedulerelinkall();
2864         }
2865
2866         if (bot_list)
2867         {
2868                 // cycle the goal token from one bot to the next each frame
2869                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
2870                 //  frame, which causes choppy framerates)
2871                 if (bot_strategytoken_taken)
2872                 {
2873                         bot_strategytoken_taken = FALSE;
2874                         if (bot_strategytoken)
2875                                 bot_strategytoken = bot_strategytoken.nextbot;
2876                         if (!bot_strategytoken)
2877                                 bot_strategytoken = bot_list;
2878                 }
2879
2880                 if (botframe_nextdangertime < time)
2881                 {
2882                         local float interval;
2883                         interval = cvar("bot_ai_dangerdetectioninterval");
2884                         if (botframe_nextdangertime < time - interval * 1.5)
2885                                 botframe_nextdangertime = time;
2886                         botframe_nextdangertime = botframe_nextdangertime + interval;
2887                         botframe_updatedangerousobjects(cvar("bot_ai_dangerdetectionupdates"));
2888                 }
2889         }
2890
2891         if (cvar("g_waypointeditor"))
2892                 botframe_showwaypointlinks();
2893
2894         if(time > bot_cvar_nextthink)
2895         {
2896                 if(currentbots>1)
2897                         bot_custom_weapon_priority_setup();
2898                 bot_cvar_nextthink = time + 5;
2899         }
2900 };