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