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