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