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