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