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