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