Merge branch 'Lyberta/TeamplayOverhaul' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / default / havocbot / havocbot.qc
1 #include "havocbot.qh"
2
3 #include <server/defs.qh>
4 #include <server/miscfunctions.qh>
5 #include "../cvars.qh"
6
7 #include "../aim.qh"
8 #include "../bot.qh"
9 #include "../navigation.qh"
10 #include "../scripting.qh"
11 #include "../waypoints.qh"
12
13 #include <common/constants.qh>
14 #include <common/impulses/all.qh>
15 #include <common/net_linked.qh>
16 #include <common/physics/player.qh>
17 #include <common/state.qh>
18 #include <common/items/_mod.qh>
19 #include <common/wepent.qh>
20
21 #include <common/mapobjects/teleporters.qh>
22 #include <common/mapobjects/trigger/jumppads.qh>
23
24 #include <lib/warpzone/common.qh>
25
26 .float speed;
27
28 void havocbot_ai(entity this)
29 {
30         if(this.draggedby)
31                 return;
32
33         if(bot_execute_commands(this))
34                 return;
35
36         if (bot_strategytoken == this && !bot_strategytoken_taken)
37         {
38                 if(this.havocbot_blockhead)
39                 {
40                         this.havocbot_blockhead = false;
41                 }
42                 else
43                 {
44                         if (!this.jumppadcount && !STAT(FROZEN, this))
45                                 this.havocbot_role(this); // little too far down the rabbit hole
46                 }
47
48                 // if we don't have a goal and we're under water look for a waypoint near the "shore" and push it
49                 if(!(IS_DEAD(this) || STAT(FROZEN, this)))
50                 if(!this.goalcurrent)
51                 if(this.waterlevel == WATERLEVEL_SWIMMING || (this.aistatus & AI_STATUS_OUT_WATER))
52                 {
53                         // Look for the closest waypoint out of water
54                         entity newgoal = NULL;
55                         IL_EACH(g_waypoints, vdist(it.origin - this.origin, <=, 10000),
56                         {
57                                 if(it.origin.z < this.origin.z)
58                                         continue;
59
60                                 if(it.origin.z - this.origin.z - this.view_ofs.z > 100)
61                                         continue;
62
63                                 if (pointcontents(it.origin + it.maxs + '0 0 1') != CONTENT_EMPTY)
64                                         continue;
65
66                                 traceline(this.origin + this.view_ofs, ((it.absmin + it.absmax) * 0.5), true, this);
67
68                                 if(trace_fraction < 1)
69                                         continue;
70
71                                 if(!newgoal || vlen2(it.origin - this.origin) < vlen2(newgoal.origin - this.origin))
72                                         newgoal = it;
73                         });
74
75                         if(newgoal)
76                         {
77                         //      te_wizspike(newgoal.origin);
78                                 navigation_pushroute(this, newgoal);
79                         }
80                 }
81
82                 // token has been used this frame
83                 bot_strategytoken_taken = true;
84         }
85
86         if(IS_DEAD(this) || STAT(FROZEN, this))
87         {
88                 if (this.goalcurrent)
89                         navigation_clearroute(this);
90                 return;
91         }
92
93         havocbot_chooseenemy(this);
94
95         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
96         {
97                 .entity weaponentity = weaponentities[slot];
98                 if(this.(weaponentity).m_weapon != WEP_Null || slot == 0)
99                 if(this.(weaponentity).bot_chooseweapontime < time)
100                 {
101                         this.(weaponentity).bot_chooseweapontime = time + autocvar_bot_ai_chooseweaponinterval;
102                         havocbot_chooseweapon(this, weaponentity);
103                 }
104         }
105         havocbot_aim(this);
106         lag_update(this);
107         if (this.bot_aimtarg)
108         {
109                 this.aistatus |= AI_STATUS_ATTACKING;
110                 this.aistatus &= ~AI_STATUS_ROAMING;
111
112                 if(STAT(WEAPONS, this))
113                 {
114                         if (autocvar_bot_nofire || IS_INDEPENDENT_PLAYER(this))
115                         {
116                                 PHYS_INPUT_BUTTON_ATCK(this) = false;
117                                 PHYS_INPUT_BUTTON_ATCK2(this) = false;
118                         }
119                         else
120                         {
121                                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
122                                 {
123                                         .entity weaponentity = weaponentities[slot];
124                                         Weapon w = this.(weaponentity).m_weapon;
125                                         if(w == WEP_Null && slot != 0)
126                                                 continue;
127                                         w.wr_aim(w, this, weaponentity);
128                                         if(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_ATCK2(this)) // TODO: what if we didn't fire this weapon, but the previous?
129                                                 this.(weaponentity).lastfiredweapon = this.(weaponentity).m_weapon.m_id;
130                                 }
131                         }
132                 }
133                 else
134                 {
135                         if(IS_PLAYER(this.bot_aimtarg))
136                                 bot_aimdir(this, this.bot_aimtarg.origin + this.bot_aimtarg.view_ofs - this.origin - this.view_ofs , -1);
137                 }
138         }
139         else if (this.goalcurrent)
140         {
141                 this.aistatus |= AI_STATUS_ROAMING;
142                 this.aistatus &= ~AI_STATUS_ATTACKING;
143
144                 vector now, next;
145                 float aimdistance,skillblend,distanceblend,blend;
146
147                 vector v = get_closer_dest(this.goalcurrent, this.origin);
148                 if(this.goalcurrent.wpisbox)
149                 {
150                         // avoid a glitch when bot is teleported but teleport waypoint isn't removed yet
151                         if(this.goalstack02 && this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT
152                         && this.lastteleporttime > 0 && time - this.lastteleporttime < 0.15)
153                                 v = (this.goalstack02.absmin + this.goalstack02.absmax) * 0.5;
154                         // aim to teleport origin if bot is inside teleport waypoint but hasn't touched the real teleport yet
155                         else if(boxesoverlap(this.goalcurrent.absmin, this.goalcurrent.absmax, this.origin, this.origin))
156                                 v = this.goalcurrent.origin;
157                 }
158                 next = now = v - (this.origin + this.view_ofs);
159                 aimdistance = vlen(now);
160
161                 //dprint(this.goalstack01.classname,etos(this.goalstack01),"\n");
162                 if(
163                         this.goalstack01 != this && this.goalstack01 && !wasfreed(this.goalstack01) && ((this.aistatus & AI_STATUS_RUNNING) == 0) &&
164                         !(this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
165                 )
166                         next = ((this.goalstack01.absmin + this.goalstack01.absmax) * 0.5) - (this.origin + this.view_ofs);
167
168                 skillblend=bound(0,(skill+this.bot_moveskill-2.5)*0.5,1); //lower skill player can't preturn
169                 distanceblend=bound(0,aimdistance/autocvar_bot_ai_keyboard_distance,1);
170                 blend = skillblend * (1-distanceblend);
171                 //v = (now * (distanceblend) + next * (1-distanceblend)) * (skillblend) + now * (1-skillblend);
172                 //v = now * (distanceblend) * (skillblend) + next * (1-distanceblend) * (skillblend) + now * (1-skillblend);
173                 //v = now * ((1-skillblend) + (distanceblend) * (skillblend)) + next * (1-distanceblend) * (skillblend);
174                 v = now + blend * (next - now);
175                 //dprint(etos(this), " ");
176                 //dprint(vtos(now), ":", vtos(next), "=", vtos(v), " (blend ", ftos(blend), ")\n");
177                 //v = now * (distanceblend) + next * (1-distanceblend);
178                 if (this.waterlevel < WATERLEVEL_SWIMMING)
179                         v.z = 0;
180                 //dprint("walk at:", vtos(v), "\n");
181                 //te_lightning2(NULL, this.origin, this.goalcurrent.origin);
182                 bot_aimdir(this, v, -1);
183         }
184         havocbot_movetogoal(this);
185
186         // if the bot is not attacking, consider reloading weapons
187         if (!(this.aistatus & AI_STATUS_ATTACKING))
188         {
189                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
190                 {
191                         .entity weaponentity = weaponentities[slot];
192
193                         if(this.(weaponentity).m_weapon == WEP_Null && slot != 0)
194                                 continue;
195
196                         // we are currently holding a weapon that's not fully loaded, reload it
197                         if(skill >= 2) // bots can only reload the held weapon on purpose past this skill
198                         if(this.(weaponentity).clip_load < this.(weaponentity).clip_size)
199                                 CS(this).impulse = IMP_weapon_reload.impulse; // not sure if this is done right
200
201                         // if we're not reloading a weapon, switch to any weapon in our invnetory that's not fully loaded to reload it next
202                         // the code above executes next frame, starting the reloading then
203                         if(skill >= 5) // bots can only look for unloaded weapons past this skill
204                         if(this.(weaponentity).clip_load >= 0) // only if we're not reloading a weapon already
205                         {
206                                 FOREACH(Weapons, it != WEP_Null, {
207                                         if((STAT(WEAPONS, this) & (it.m_wepset)) && (it.spawnflags & WEP_FLAG_RELOADABLE) && (this.(weaponentity).weapon_load[it.m_id] < it.reloading_ammo))
208                                         {
209                                                 this.(weaponentity).m_switchweapon = it;
210                                                 break;
211                                         }
212                                 });
213                         }
214                 }
215         }
216 }
217
218 void havocbot_keyboard_movement(entity this, vector destorg)
219 {
220         vector keyboard;
221
222         if (time > this.havocbot_keyboardtime)
223         {
224                 float sk = skill + this.bot_moveskill;
225                 this.havocbot_keyboardtime =
226                         max(
227                                 this.havocbot_keyboardtime
228                                         + 0.05 / max(1, sk + this.havocbot_keyboardskill)
229                                         + random() * 0.025 / max(0.00025, skill + this.havocbot_keyboardskill)
230                         , time);
231                 keyboard = CS(this).movement / autocvar_sv_maxspeed;
232
233                 float trigger = autocvar_bot_ai_keyboard_threshold;
234                 float trigger1 = -trigger;
235
236                 // categorize forward movement
237                 // at skill < 1.5 only forward
238                 // at skill < 2.5 only individual directions
239                 // at skill < 4.5 only individual directions, and forward diagonals
240                 // at skill >= 4.5, all cases allowed
241                 if (keyboard.x > trigger)
242                 {
243                         keyboard.x = 1;
244                         if (sk < 2.5)
245                                 keyboard.y = 0;
246                 }
247                 else if (keyboard.x < trigger1 && sk > 1.5)
248                 {
249                         keyboard.x = -1;
250                         if (sk < 4.5)
251                                 keyboard.y = 0;
252                 }
253                 else
254                 {
255                         keyboard.x = 0;
256                         if (sk < 1.5)
257                                 keyboard.y = 0;
258                 }
259                 if (sk < 4.5)
260                         keyboard.z = 0;
261
262                 if (keyboard.y > trigger)
263                         keyboard.y = 1;
264                 else if (keyboard.y < trigger1)
265                         keyboard.y = -1;
266                 else
267                         keyboard.y = 0;
268
269                 if (keyboard.z > trigger)
270                         keyboard.z = 1;
271                 else if (keyboard.z < trigger1)
272                         keyboard.z = -1;
273                 else
274                         keyboard.z = 0;
275
276                 this.havocbot_keyboard = keyboard * autocvar_sv_maxspeed;
277                 if (this.havocbot_ducktime > time)
278                         PHYS_INPUT_BUTTON_CROUCH(this) = true;
279         }
280
281         keyboard = this.havocbot_keyboard;
282         float blend = bound(0, vlen(destorg - this.origin) / autocvar_bot_ai_keyboard_distance, 1); // When getting close move with 360 degree
283         //dprint("movement ", vtos(CS(this).movement), " keyboard ", vtos(keyboard), " blend ", ftos(blend), "\n");
284         CS(this).movement = CS(this).movement + (keyboard - CS(this).movement) * blend;
285 }
286
287 void havocbot_bunnyhop(entity this, vector dir)
288 {
289         float bunnyhopdistance;
290         vector deviation;
291         float maxspeed;
292
293         // Don't jump when attacking
294         if(this.aistatus & AI_STATUS_ATTACKING)
295                 return;
296
297         if(IS_PLAYER(this.goalcurrent))
298                 return;
299
300         maxspeed = autocvar_sv_maxspeed;
301
302         if(this.aistatus & AI_STATUS_RUNNING && vdist(this.velocity, <, autocvar_sv_maxspeed * 0.75)
303                 || this.aistatus & AI_STATUS_DANGER_AHEAD)
304         {
305                 this.aistatus &= ~AI_STATUS_RUNNING;
306                 PHYS_INPUT_BUTTON_JUMP(this) = false;
307                 this.bot_canruntogoal = 0;
308                 this.bot_timelastseengoal = 0;
309                 return;
310         }
311
312         if(this.waterlevel > WATERLEVEL_WETFEET)
313         {
314                 this.aistatus &= ~AI_STATUS_RUNNING;
315                 return;
316         }
317
318         if(this.bot_lastseengoal != this.goalcurrent && !(this.aistatus & AI_STATUS_RUNNING))
319         {
320                 this.bot_canruntogoal = 0;
321                 this.bot_timelastseengoal = 0;
322         }
323
324         vector gco = get_closer_dest(this.goalcurrent, this.origin);
325         bunnyhopdistance = vlen(this.origin - gco);
326
327         // Run only to visible goals
328         if(IS_ONGROUND(this))
329         if(vdist(vec2(this.velocity), >=, autocvar_sv_maxspeed)) // if -really- running
330         if(checkpvs(this.origin + this.view_ofs, this.goalcurrent))
331         {
332                         this.bot_lastseengoal = this.goalcurrent;
333
334                         // seen it before
335                         if(this.bot_timelastseengoal)
336                         {
337                                 // for a period of time
338                                 if(time - this.bot_timelastseengoal > autocvar_bot_ai_bunnyhop_firstjumpdelay)
339                                 {
340                                         float checkdistance;
341                                         checkdistance = true;
342
343                                         // don't run if it is too close
344                                         if(this.bot_canruntogoal==0)
345                                         {
346                                                 if(bunnyhopdistance > autocvar_bot_ai_bunnyhop_startdistance)
347                                                         this.bot_canruntogoal = 1;
348                                                 else
349                                                         this.bot_canruntogoal = -1;
350                                         }
351
352                                         if(this.bot_canruntogoal != 1)
353                                                 return;
354
355                                         if(this.aistatus & AI_STATUS_ROAMING)
356                                         if(this.goalcurrent.classname=="waypoint")
357                                         if (!(this.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL))
358                                         if(fabs(gco.z - this.origin.z) < this.maxs.z - this.mins.z)
359                                         if(this.goalstack01 && !wasfreed(this.goalstack01))
360                                         {
361                                                 vector gno = (this.goalstack01.absmin + this.goalstack01.absmax) * 0.5;
362                                                 deviation = vectoangles(gno - this.origin) - vectoangles(gco - this.origin);
363                                                 while (deviation.y < -180) deviation.y = deviation.y + 360;
364                                                 while (deviation.y > 180) deviation.y = deviation.y - 360;
365
366                                                 if(fabs(deviation.y) < 20)
367                                                 if(bunnyhopdistance < vlen(this.origin - gno))
368                                                 if(fabs(gno.z - gco.z) < this.maxs.z - this.mins.z)
369                                                 {
370                                                         if(vdist(gco - gno, >, autocvar_bot_ai_bunnyhop_startdistance))
371                                                         if(checkpvs(this.origin + this.view_ofs, this.goalstack01))
372                                                         {
373                                                                 checkdistance = false;
374                                                         }
375                                                 }
376                                         }
377
378                                         if(checkdistance)
379                                         {
380                                                 this.aistatus &= ~AI_STATUS_RUNNING;
381                                                 // increase stop distance in case the goal is on a slope or a lower platform
382                                                 if(bunnyhopdistance > autocvar_bot_ai_bunnyhop_stopdistance + (this.origin.z - gco.z))
383                                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
384                                         }
385                                         else
386                                         {
387                                                 this.aistatus |= AI_STATUS_RUNNING;
388                                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
389                                         }
390                                 }
391                         }
392                         else
393                         {
394                                 this.bot_timelastseengoal = time;
395                         }
396         }
397         else
398         {
399                 this.bot_timelastseengoal = 0;
400         }
401
402 #if 0
403         // Release jump button
404         if(!cvar("sv_pogostick"))
405         if((IS_ONGROUND(this)) == 0)
406         {
407                 if(this.velocity.z < 0 || vlen(this.velocity)<maxspeed)
408                         PHYS_INPUT_BUTTON_JUMP(this) = false;
409
410                 // Strafe
411                 if(this.aistatus & AI_STATUS_RUNNING)
412                 if(vlen(this.velocity)>maxspeed)
413                 {
414                         deviation = vectoangles(dir) - vectoangles(this.velocity);
415                         while (deviation.y < -180) deviation.y = deviation.y + 360;
416                         while (deviation.y > 180) deviation.y = deviation.y - 360;
417
418                         if(fabs(deviation.y)>10)
419                                 CS(this).movement_x = 0;
420
421                         if(deviation.y>10)
422                                 CS(this).movement_y = maxspeed * -1;
423                         else if(deviation.y<10)
424                                 CS(this).movement_y = maxspeed;
425
426                 }
427         }
428 #endif
429 }
430
431 // return true when bot isn't getting closer to the current goal
432 bool havocbot_checkgoaldistance(entity this, vector gco)
433 {
434         float curr_dist_z = max(20, fabs(this.origin.z - gco.z));
435         float curr_dist_2d = max(20, vlen(vec2(this.origin - gco)));
436         float distance_time = this.goalcurrent_distance_time;
437         if(distance_time < 0)
438                 distance_time = -distance_time;
439         if(curr_dist_z >= this.goalcurrent_distance_z && curr_dist_2d >= this.goalcurrent_distance_2d)
440         {
441                 if(!distance_time)
442                         this.goalcurrent_distance_time = time;
443                 else if (time - distance_time > 0.5)
444                         return true;
445         }
446         else
447         {
448                 // reduce it a little bit so it works even with very small approaches to the goal
449                 this.goalcurrent_distance_z = max(20, curr_dist_z - 10);
450                 this.goalcurrent_distance_2d = max(20, curr_dist_2d - 10);
451                 this.goalcurrent_distance_time = 0;
452         }
453         return false;
454 }
455
456 entity havocbot_select_an_item_of_group(entity this, int gr)
457 {
458         entity selected = NULL;
459         float selected_dist2 = 0;
460         // select farthest item of this group from bot's position
461         IL_EACH(g_items, it.item_group == gr && it.solid,
462         {
463                 float dist2 = vlen2(this.origin - it.origin);
464                 if (dist2 < 600 ** 2 && dist2 > selected_dist2)
465                 {
466                         selected = it;
467                         selected_dist2 = vlen2(this.origin - selected.origin);
468                 }
469         });
470
471         if (!selected)
472                 return NULL;
473
474         set_tracewalk_dest(selected, this.origin, false);
475         if (!tracewalk(this, this.origin, STAT(PL_MIN, this), STAT(PL_MAX, this),
476                 tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode))
477         {
478                 return NULL;
479         }
480
481         return selected;
482 }
483
484 void havocbot_movetogoal(entity this)
485 {
486         vector diff;
487         vector dir;
488         vector flatdir;
489         vector evadeobstacle;
490         vector evadelava;
491         float maxspeed;
492         //float dist;
493         vector dodge;
494         //if (this.goalentity)
495         //      te_lightning2(this, this.origin, (this.goalentity.absmin + this.goalentity.absmax) * 0.5);
496         CS(this).movement = '0 0 0';
497         maxspeed = autocvar_sv_maxspeed;
498
499         PHYS_INPUT_BUTTON_JETPACK(this) = false;
500         // Jetpack navigation
501         if(this.navigation_jetpack_goal)
502         if(this.goalcurrent==this.navigation_jetpack_goal)
503         if(GetResourceAmount(this, RESOURCE_FUEL))
504         {
505                 if(autocvar_bot_debug_goalstack)
506                 {
507                         debuggoalstack(this);
508                         te_wizspike(this.navigation_jetpack_point);
509                 }
510
511                 // Take off
512                 if (!(this.aistatus & AI_STATUS_JETPACK_FLYING))
513                 {
514                         // Brake almost completely so it can get a good direction
515                         if(vdist(this.velocity, >, 10))
516                                 return;
517                         this.aistatus |= AI_STATUS_JETPACK_FLYING;
518                 }
519
520                 makevectors(this.v_angle.y * '0 1 0');
521                 dir = normalize(this.navigation_jetpack_point - this.origin);
522
523                 // Landing
524                 if(this.aistatus & AI_STATUS_JETPACK_LANDING)
525                 {
526                         // Calculate brake distance in xy
527                         float d = vlen(vec2(this.origin - (this.goalcurrent.absmin + this.goalcurrent.absmax) * 0.5));
528                         float vel2 = vlen2(vec2(this.velocity));
529                         float db = (vel2 / (autocvar_g_jetpack_acceleration_side * 2)) + 100;
530                         //LOG_INFOF("distance %d, velocity %d, brake at %d ", ceil(d), ceil(v), ceil(db));
531                         if(d < db || d < 500)
532                         {
533                                 // Brake
534                                 if (vel2 > (maxspeed * 0.3) ** 2)
535                                 {
536                                         CS(this).movement_x = dir * v_forward * -maxspeed;
537                                         return;
538                                 }
539                                 // Switch to normal mode
540                                 this.navigation_jetpack_goal = NULL;
541                                 this.aistatus &= ~AI_STATUS_JETPACK_LANDING;
542                                 this.aistatus &= ~AI_STATUS_JETPACK_FLYING;
543                                 return;
544                         }
545                 }
546                 else if(checkpvs(this.origin,this.goalcurrent))
547                 {
548                         // If I can see the goal switch to landing code
549                         this.aistatus &= ~AI_STATUS_JETPACK_FLYING;
550                         this.aistatus |= AI_STATUS_JETPACK_LANDING;
551                         return;
552                 }
553
554                 // Flying
555                 PHYS_INPUT_BUTTON_JETPACK(this) = true;
556                 if(this.navigation_jetpack_point.z - STAT(PL_MAX, this).z + STAT(PL_MIN, this).z < this.origin.z)
557                 {
558                         CS(this).movement_x = dir * v_forward * maxspeed;
559                         CS(this).movement_y = dir * v_right * maxspeed;
560                 }
561                 return;
562         }
563
564         // Handling of jump pads
565         if(this.jumppadcount)
566         {
567                 if(this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
568                 {
569                         this.aistatus |= AI_STATUS_OUT_JUMPPAD;
570                         navigation_poptouchedgoals(this);
571                         return;
572                 }
573                 else if(this.aistatus & AI_STATUS_OUT_JUMPPAD)
574                 {
575                         // If got stuck on the jump pad try to reach the farthest visible waypoint
576                         // but with some randomness so it can try out different paths
577                         if(!this.goalcurrent)
578                         {
579                                 entity newgoal = NULL;
580                                 IL_EACH(g_waypoints, vdist(it.origin - this.origin, <=, 1000),
581                                 {
582                                         if(it.wpflags & WAYPOINTFLAG_TELEPORT)
583                                         if(it.origin.z < this.origin.z - 100 && vdist(vec2(it.origin - this.origin), <, 100))
584                                                 continue;
585
586                                         traceline(this.origin + this.view_ofs, ((it.absmin + it.absmax) * 0.5), true, this);
587
588                                         if(trace_fraction < 1)
589                                                 continue;
590
591                                         if(!newgoal || ((random() < 0.8) && vlen2(it.origin - this.origin) > vlen2(newgoal.origin - this.origin)))
592                                                 newgoal = it;
593                                 });
594
595                                 if(newgoal)
596                                 {
597                                         this.ignoregoal = this.goalcurrent;
598                                         this.ignoregoaltime = time + autocvar_bot_ai_ignoregoal_timeout;
599                                         navigation_clearroute(this);
600                                         navigation_routetogoal(this, newgoal, this.origin);
601                                         if(autocvar_bot_debug_goalstack)
602                                                 debuggoalstack(this);
603                                         this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
604                                 }
605                         }
606                         else
607                         {
608                                 if (this.goalcurrent.bot_pickup)
609                                 {
610                                         entity jumppad_wp = this.goalcurrent_prev;
611                                         navigation_poptouchedgoals(this);
612                                         if(!this.goalcurrent && jumppad_wp.wp00)
613                                         {
614                                                 // head to the jumppad destination once bot reaches the goal item
615                                                 navigation_pushroute(this, jumppad_wp.wp00);
616                                         }
617                                 }
618                                 vector gco = (this.goalcurrent.absmin + this.goalcurrent.absmax) * 0.5;
619                                 if (this.origin.z > gco.z && vdist(vec2(this.velocity), <, autocvar_sv_maxspeed))
620                                         this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
621                                 else if(havocbot_checkgoaldistance(this, gco))
622                                 {
623                                         navigation_clearroute(this);
624                                         navigation_goalrating_timeout_force(this);
625                                 }
626                                 else
627                                         return;
628                         }
629                 }
630                 else
631                 {
632                         if(time - this.lastteleporttime > 0.2 && this.velocity.z > 0)
633                         {
634                                 vector velxy = this.velocity; velxy_z = 0;
635                                 if(vdist(velxy, <, autocvar_sv_maxspeed * 0.2))
636                                 {
637                                         LOG_TRACE("Warning: ", this.netname, " got stuck on a jumppad (velocity in xy is ", vtos(velxy), "), trying to get out of it now");
638                                         this.aistatus |= AI_STATUS_OUT_JUMPPAD;
639                                 }
640                                 return;
641                         }
642
643                         // Don't chase players while using a jump pad
644                         if(IS_PLAYER(this.goalcurrent) || IS_PLAYER(this.goalstack01))
645                                 return;
646                 }
647         }
648         else if(this.aistatus & AI_STATUS_OUT_JUMPPAD)
649                 this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
650
651         // If there is a trigger_hurt right below try to use the jetpack or make a rocketjump
652         if (skill > 6 && !(IS_ONGROUND(this)))
653         {
654                 #define ROCKETJUMP_DAMAGE() WEP_CVAR(devastator, damage) * 0.8 \
655                         * ((this.strength_finished > time) ? autocvar_g_balance_powerup_strength_selfdamage : 1) \
656                         * ((this.invincible_finished > time) ? autocvar_g_balance_powerup_invincible_takedamage : 1)
657
658                 tracebox(this.origin, this.mins, this.maxs, this.origin + '0 0 -65536', MOVE_NOMONSTERS, this);
659                 if(tracebox_hits_trigger_hurt(this.origin, this.mins, this.maxs, trace_endpos ))
660                 if(this.items & IT_JETPACK)
661                 {
662                         tracebox(this.origin, this.mins, this.maxs, this.origin + '0 0 65536', MOVE_NOMONSTERS, this);
663                         if(tracebox_hits_trigger_hurt(this.origin, this.mins, this.maxs, trace_endpos + '0 0 1' ))
664                         {
665                                 if(this.velocity.z<0)
666                                         PHYS_INPUT_BUTTON_JETPACK(this) = true;
667                         }
668                         else
669                                 PHYS_INPUT_BUTTON_JETPACK(this) = true;
670
671                         // If there is no goal try to move forward
672
673                         if(this.goalcurrent==NULL)
674                                 dir = v_forward;
675                         else
676                                 dir = normalize(( ( this.goalcurrent.absmin + this.goalcurrent.absmax ) * 0.5 ) - this.origin);
677
678                         vector xyvelocity = this.velocity; xyvelocity_z = 0;
679                         float xyspeed = xyvelocity * dir;
680
681                         if(xyspeed < (maxspeed / 2))
682                         {
683                                 makevectors(this.v_angle.y * '0 1 0');
684                                 tracebox(this.origin, this.mins, this.maxs, this.origin + (dir * maxspeed * 3), MOVE_NOMONSTERS, this);
685                                 if(trace_fraction==1)
686                                 {
687                                         CS(this).movement_x = dir * v_forward * maxspeed;
688                                         CS(this).movement_y = dir * v_right * maxspeed;
689                                         if (skill < 10)
690                                                 havocbot_keyboard_movement(this, this.origin + dir * 100);
691                                 }
692                         }
693
694                         this.havocbot_blockhead = true;
695
696                         return;
697                 }
698                 else if(GetResourceAmount(this, RESOURCE_HEALTH) + GetResourceAmount(this, RESOURCE_ARMOR) > ROCKETJUMP_DAMAGE())
699                 {
700                         if(this.velocity.z < 0)
701                         {
702                                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
703                                 {
704                                         .entity weaponentity = weaponentities[slot];
705
706                                         if(this.(weaponentity).m_weapon == WEP_Null && slot != 0)
707                                                 continue;
708
709                                         if(client_hasweapon(this, WEP_DEVASTATOR, weaponentity, true, false))
710                                         {
711                                                 CS(this).movement_x = maxspeed;
712
713                                                 if(this.rocketjumptime)
714                                                 {
715                                                         if(time > this.rocketjumptime)
716                                                         {
717                                                                 PHYS_INPUT_BUTTON_ATCK2(this) = true;
718                                                                 this.rocketjumptime = 0;
719                                                         }
720                                                         return;
721                                                 }
722
723                                                 this.(weaponentity).m_switchweapon = WEP_DEVASTATOR;
724                                                 this.v_angle_x = 90;
725                                                 PHYS_INPUT_BUTTON_ATCK(this) = true;
726                                                 this.rocketjumptime = time + WEP_CVAR(devastator, detonatedelay);
727                                                 return;
728                                         }
729                                 }
730                         }
731                 }
732                 else
733                 {
734                         // If there is no goal try to move forward
735                         if(this.goalcurrent==NULL)
736                                 CS(this).movement_x = maxspeed;
737                 }
738         }
739
740         // If we are under water with no goals, swim up
741         if(this.waterlevel && !this.goalcurrent)
742         {
743                 dir = '0 0 0';
744                 if(this.waterlevel>WATERLEVEL_SWIMMING)
745                         dir.z = 1;
746                 else if(this.velocity.z >= 0 && !(this.waterlevel == WATERLEVEL_WETFEET && this.watertype == CONTENT_WATER))
747                         PHYS_INPUT_BUTTON_JUMP(this) = true;
748                 else
749                         PHYS_INPUT_BUTTON_JUMP(this) = false;
750                 makevectors(this.v_angle.y * '0 1 0');
751                 vector v = dir * maxspeed;
752                 CS(this).movement.x = v * v_forward;
753                 CS(this).movement.y = v * v_right;
754                 CS(this).movement.z = v * v_up;
755         }
756
757         // if there is nowhere to go, exit
758         if (this.goalcurrent == NULL)
759                 return;
760
761
762         bool locked_goal = false;
763         if((this.goalentity && wasfreed(this.goalentity))
764                 || (this.goalcurrent == this.goalentity && this.goalentity.tag_entity))
765         {
766                 navigation_clearroute(this);
767                 navigation_goalrating_timeout_force(this);
768                 return;
769         }
770         else if(this.goalentity.tag_entity)
771         {
772                 navigation_goalrating_timeout_expire(this, 2);
773         }
774         else if(this.goalentity.bot_pickup)
775         {
776                 if(this.goalentity.bot_pickup_respawning)
777                 {
778                         if(this.goalentity.solid) // item respawned
779                                 this.goalentity.bot_pickup_respawning = false;
780                         else if(time < this.goalentity.scheduledrespawntime - 10) // item already taken (by someone else)
781                         {
782                                 if(checkpvs(this.origin, this.goalentity))
783                                 {
784                                         this.goalentity.bot_pickup_respawning = false;
785                                         navigation_goalrating_timeout_expire(this, random());
786                                 }
787                                 locked_goal = true; // wait for item to respawn
788                         }
789                         else if(this.goalentity == this.goalcurrent)
790                                 locked_goal = true; // wait for item to respawn
791                 }
792                 else if(!this.goalentity.solid && !boxesoverlap(this.goalentity.absmin, this.goalentity.absmax, this.absmin, this.absmax))
793                 {
794                         if(checkpvs(this.origin, this.goalentity))
795                         {
796                                 navigation_goalrating_timeout_expire(this, random());
797                         }
798                 }
799         }
800         if (this.goalcurrent == this.goalentity && this.goalentity_lock_timeout > time)
801                 locked_goal = true;
802
803         navigation_shortenpath(this);
804
805         if (IS_MOVABLE(this.goalcurrent))
806         {
807                 if (IS_DEAD(this.goalcurrent))
808                 {
809                         if (checkpvs(this.origin + this.view_ofs, this.goalcurrent))
810                         {
811                                 navigation_goalrating_timeout_force(this);
812                                 return;
813                         }
814                 }
815                 else if (this.bot_tracewalk_time < time)
816                 {
817                         set_tracewalk_dest(this.goalcurrent, this.origin, true);
818                         if (!(trace_ent == this || tracewalk(this, this.origin, this.mins, this.maxs,
819                                 tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode)))
820                         {
821                                 navigation_goalrating_timeout_force(this);
822                                 return;
823                         }
824                         this.bot_tracewalk_time = max(time, this.bot_tracewalk_time) + 0.25;
825                 }
826         }
827         if(!locked_goal)
828         {
829                 // optimize path finding by anticipating goalrating when bot is near a waypoint;
830                 // in this case path finding can start directly from a waypoint instead of
831                 // looking for all the reachable waypoints up to a certain distance
832                 if (navigation_poptouchedgoals(this))
833                 {
834                         if (this.goalcurrent)
835                         {
836                                 if (IS_MOVABLE(this.goalcurrent) && IS_DEAD(this.goalcurrent))
837                                 {
838                                         // remove even if not visible
839                                         navigation_goalrating_timeout_force(this);
840                                         return;
841                                 }
842                                 else if (navigation_goalrating_timeout_can_be_anticipated(this))
843                                         navigation_goalrating_timeout_force(this);
844                         }
845                         else
846                         {
847                                 entity old_goal = this.goalcurrent_prev;
848                                 if (old_goal.item_group && this.item_group != old_goal.item_group)
849                                 {
850                                         // Avoid multiple costly calls of path finding code that selects one of the closest
851                                         // item of the group by telling the bot to head directly to the farthest item.
852                                         // Next time we let the bot select a goal as usual which can be another item
853                                         // of this group (the closest one) and so on
854                                         this.item_group = old_goal.item_group;
855                                         entity new_goal = havocbot_select_an_item_of_group(this, old_goal.item_group);
856                                         if (new_goal)
857                                                 navigation_pushroute(this, new_goal);
858                                 }
859                         }
860                 }
861         }
862
863         // if ran out of goals try to use an alternative goal or get a new strategy asap
864         if(this.goalcurrent == NULL)
865         {
866                 navigation_goalrating_timeout_force(this);
867                 return;
868         }
869
870
871         if(autocvar_bot_debug_goalstack)
872                 debuggoalstack(this);
873
874         bool bunnyhop_forbidden = false;
875         vector destorg = get_closer_dest(this.goalcurrent, this.origin);
876
877         // in case bot ends up inside the teleport waypoint without touching
878         // the teleport itself, head to the teleport origin
879         if(this.goalcurrent.wpisbox && boxesoverlap(this.goalcurrent.absmin, this.goalcurrent.absmax, this.origin + eZ * this.mins.z, this.origin + eZ * this.maxs.z))
880         {
881                 bunnyhop_forbidden = true;
882                 destorg = this.goalcurrent.origin;
883                 if(destorg.z > this.origin.z)
884                         PHYS_INPUT_BUTTON_JUMP(this) = true;
885         }
886
887         diff = destorg - this.origin;
888
889         // 1. stop if too close to target player (even if frozen)
890         // 2. stop if the locked goal has been reached
891         if ((IS_PLAYER(this.goalcurrent) && vdist(diff, <, 80))
892                 || (this.goalcurrent == this.goalentity && time < this.goalentity_lock_timeout && vdist(diff, <, 10)))
893         {
894                 destorg = this.origin;
895                 diff = '0 0 0';
896         }
897
898         dir = normalize(diff);
899         flatdir = (diff.z == 0) ? dir : normalize(vec2(diff));
900
901         //if (this.bot_dodgevector_time < time)
902         {
903                 //this.bot_dodgevector_time = time + cvar("bot_ai_dodgeupdateinterval");
904                 //this.bot_dodgevector_jumpbutton = 1;
905                 evadeobstacle = '0 0 0';
906                 evadelava = '0 0 0';
907
908                 this.aistatus &= ~AI_STATUS_DANGER_AHEAD;
909                 makevectors(this.v_angle.y * '0 1 0');
910                 if (this.waterlevel)
911                 {
912                         if(this.waterlevel>WATERLEVEL_SWIMMING)
913                         {
914                                 if(!this.goalcurrent)
915                                         this.aistatus |= AI_STATUS_OUT_WATER;
916                                 else if(destorg.z > this.origin.z)
917                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
918                         }
919                         else
920                         {
921                                 dir = flatdir;
922                                 if(this.velocity.z >= 0 && !(this.watertype == CONTENT_WATER && destorg.z < this.origin.z) &&
923                                         ( !(this.waterlevel == WATERLEVEL_WETFEET && this.watertype == CONTENT_WATER) || this.aistatus & AI_STATUS_OUT_WATER))
924                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
925                                 else
926                                         PHYS_INPUT_BUTTON_JUMP(this) = false;
927                         }
928                 }
929                 else
930                 {
931                         float s;
932                         vector offset;
933                         if(this.aistatus & AI_STATUS_OUT_WATER)
934                                 this.aistatus &= ~AI_STATUS_OUT_WATER;
935
936                         // jump if going toward an obstacle that doesn't look like stairs we
937                         // can walk up directly
938                         vector deviation = '0 0 0';
939                         if (this.velocity)
940                         {
941                                 deviation = vectoangles(diff) - vectoangles(this.velocity);
942                                 while (deviation.y < -180) deviation.y += 360;
943                                 while (deviation.y > 180) deviation.y -= 360;
944                         }
945                         vector flat_diff = vec2(diff);
946                         offset = max(32, vlen(vec2(this.velocity)) * cos(deviation.y * DEG2RAD) * 0.2) * flatdir;
947                         vector actual_destorg = this.origin + offset;
948                         if (!this.goalstack01 || this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
949                         {
950                                 if (vlen2(flat_diff) < vlen2(offset))
951                                 {
952                                         actual_destorg.x = destorg.x;
953                                         actual_destorg.y = destorg.y;
954                                 }
955                         }
956                         else if (vdist(flat_diff, <, 32) && diff.z < -16) // destination is under the bot
957                         {
958                                 actual_destorg.x = destorg.x;
959                                 actual_destorg.y = destorg.y;
960                         }
961                         else if (vlen2(flat_diff) < vlen2(offset))
962                         {
963                                 vector next_goal_org = (this.goalstack01.absmin + this.goalstack01.absmax) * 0.5;
964                                 vector next_dir = normalize(vec2(next_goal_org - destorg));
965                                 float next_dist = vlen(vec2(this.origin + offset - destorg));
966                                 actual_destorg = vec2(destorg) + next_dist * next_dir;
967                                 actual_destorg.z = this.origin.z;
968                         }
969
970                         tracebox(this.origin, this.mins, this.maxs, actual_destorg, false, this);
971                         if (trace_fraction < 1)
972                         if (trace_plane_normal.z < 0.7)
973                         {
974                                 s = trace_fraction;
975                                 tracebox(this.origin + stepheightvec, this.mins, this.maxs, actual_destorg + stepheightvec, false, this);
976                                 if (trace_fraction < s + 0.01)
977                                 if (trace_plane_normal.z < 0.7)
978                                 {
979                                         s = trace_fraction;
980                                         tracebox(this.origin + jumpstepheightvec, this.mins, this.maxs, actual_destorg + jumpstepheightvec, false, this);
981                                         if (trace_fraction > s)
982                                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
983                                 }
984                         }
985
986                         // if bot for some reason doesn't get close to the current goal find another one
987                         if(!this.jumppadcount && !IS_PLAYER(this.goalcurrent))
988                         if(!(locked_goal && this.goalcurrent_distance_z < 50 && this.goalcurrent_distance_2d < 50))
989                         if(havocbot_checkgoaldistance(this, destorg))
990                         {
991                                 if(this.goalcurrent_distance_time < 0) // can't get close for the second time
992                                 {
993                                         navigation_clearroute(this);
994                                         navigation_goalrating_timeout_force(this);
995                                         return;
996                                 }
997
998                                 set_tracewalk_dest(this.goalcurrent, this.origin, false);
999                                 if (!tracewalk(this, this.origin, this.mins, this.maxs,
1000                                         tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode))
1001                                 {
1002                                         navigation_clearroute(this);
1003                                         navigation_goalrating_timeout_force(this);
1004                                         return;
1005                                 }
1006
1007                                 // give bot only another chance to prevent bot getting stuck
1008                                 // in case it thinks it can walk but actually can't
1009                                 this.goalcurrent_distance_z = FLOAT_MAX;
1010                                 this.goalcurrent_distance_2d = FLOAT_MAX;
1011                                 this.goalcurrent_distance_time = -time; // mark second try
1012                         }
1013
1014                         // Check for water/slime/lava and dangerous edges
1015                         // (only when the bot is on the ground or jumping intentionally)
1016
1017                         offset = (vdist(this.velocity, >, 32) ? this.velocity * 0.2 : v_forward * 32);
1018                         vector dst_ahead = this.origin + this.view_ofs + offset;
1019                         vector dst_down = dst_ahead - '0 0 3000';
1020                         traceline(this.origin + this.view_ofs, dst_ahead, true, NULL);
1021
1022                         bool unreachable = false;
1023                         s = CONTENT_SOLID;
1024                         if(trace_fraction == 1 && this.jumppadcount == 0 && !this.goalcurrent.wphardwired )
1025                         if((IS_ONGROUND(this)) || (this.aistatus & AI_STATUS_RUNNING) || (this.aistatus & AI_STATUS_ROAMING) || PHYS_INPUT_BUTTON_JUMP(this))
1026                         {
1027                                 // Look downwards
1028                                 traceline(dst_ahead , dst_down, true, NULL);
1029                                 //te_lightning2(NULL, this.origin + this.view_ofs, dst_ahead); // Draw "ahead" look
1030                                 //te_lightning2(NULL, dst_ahead, dst_down); // Draw "downwards" look
1031                                 if(trace_endpos.z < this.origin.z + this.mins.z)
1032                                 {
1033                                         s = pointcontents(trace_endpos + '0 0 1');
1034                                         if (s != CONTENT_SOLID)
1035                                         if (s == CONTENT_LAVA || s == CONTENT_SLIME)
1036                                                 evadelava = normalize(this.velocity) * -1;
1037                                         else if (s == CONTENT_SKY)
1038                                                 evadeobstacle = normalize(this.velocity) * -1;
1039                                         else if (tracebox_hits_trigger_hurt(dst_ahead, this.mins, this.maxs, trace_endpos))
1040                                         {
1041                                                 // the traceline check isn't enough but is good as optimization,
1042                                                 // when not true (most of the time) this tracebox call is avoided
1043                                                 tracebox(dst_ahead, this.mins, this.maxs, dst_down, true, this);
1044                                                 if (tracebox_hits_trigger_hurt(dst_ahead, this.mins, this.maxs, trace_endpos))
1045                                                 {
1046                                                         if (destorg.z > this.origin.z + jumpstepheightvec.z)
1047                                                         {
1048                                                                 // the goal is probably on an upper platform, assume bot can't get there
1049                                                                 unreachable = true;
1050                                                         }
1051                                                         else
1052                                                                 evadelava = normalize(this.velocity) * -1;
1053                                                 }
1054                                         }
1055                                 }
1056                         }
1057
1058                         dir = flatdir;
1059                         evadeobstacle.z = 0;
1060                         evadelava.z = 0;
1061                         makevectors(this.v_angle.y * '0 1 0');
1062
1063                         if(evadeobstacle || evadelava || (s == CONTENT_WATER))
1064                         {
1065                                 this.aistatus |= AI_STATUS_DANGER_AHEAD;
1066                                 if(IS_PLAYER(this.goalcurrent))
1067                                         unreachable = true;
1068                         }
1069                         if(unreachable)
1070                         {
1071                                 navigation_clearroute(this);
1072                                 navigation_goalrating_timeout_force(this);
1073                                 this.ignoregoal = this.goalcurrent;
1074                                 this.ignoregoaltime = time + autocvar_bot_ai_ignoregoal_timeout;
1075                         }
1076                 }
1077
1078                 dodge = havocbot_dodge(this);
1079                 dodge = dodge * bound(0,0.5+(skill+this.bot_dodgeskill)*0.1,1);
1080                 evadelava = evadelava * bound(1,3-(skill+this.bot_dodgeskill),3); //Noobs fear lava a lot and take more distance from it
1081                 traceline(this.origin, ( ( this.enemy.absmin + this.enemy.absmax ) * 0.5 ), true, NULL);
1082                 if(IS_PLAYER(trace_ent))
1083                         dir = dir * bound(0,(skill+this.bot_dodgeskill)/7,1);
1084
1085                 dir = normalize(dir + dodge + evadeobstacle + evadelava);
1086         //      this.bot_dodgevector = dir;
1087         //      this.bot_dodgevector_jumpbutton = PHYS_INPUT_BUTTON_JUMP(this);
1088         }
1089
1090         if(time < this.ladder_time)
1091         {
1092                 if(this.goalcurrent.origin.z + this.goalcurrent.mins.z > this.origin.z + this.mins.z)
1093                 {
1094                         if(this.origin.z + this.mins.z  < this.ladder_entity.origin.z + this.ladder_entity.maxs.z)
1095                                 dir.z = 1;
1096                 }
1097                 else
1098                 {
1099                         if(this.origin.z + this.mins.z  > this.ladder_entity.origin.z + this.ladder_entity.mins.z)
1100                                 dir.z = -1;
1101                 }
1102         }
1103
1104         //dir = this.bot_dodgevector;
1105         //if (this.bot_dodgevector_jumpbutton)
1106         //      PHYS_INPUT_BUTTON_JUMP(this) = true;
1107         CS(this).movement_x = dir * v_forward * maxspeed;
1108         CS(this).movement_y = dir * v_right * maxspeed;
1109         CS(this).movement_z = dir * v_up * maxspeed;
1110
1111         // Emulate keyboard interface
1112         if (skill < 10)
1113                 havocbot_keyboard_movement(this, destorg);
1114
1115         // Bunnyhop!
1116         //if(this.aistatus & AI_STATUS_ROAMING)
1117         if(!bunnyhop_forbidden && this.goalcurrent)
1118         if(skill+this.bot_moveskill >= autocvar_bot_ai_bunnyhop_skilloffset)
1119                 havocbot_bunnyhop(this, dir);
1120
1121         if ((dir * v_up) >= autocvar_sv_jumpvelocity*0.5 && (IS_ONGROUND(this))) PHYS_INPUT_BUTTON_JUMP(this) = true;
1122         if (((dodge * v_up) > 0) && random()*frametime >= 0.2*bound(0,(10-skill-this.bot_dodgeskill)*0.1,1)) PHYS_INPUT_BUTTON_JUMP(this) = true;
1123         if (((dodge * v_up) < 0) && random()*frametime >= 0.5*bound(0,(10-skill-this.bot_dodgeskill)*0.1,1)) this.havocbot_ducktime=time+0.3/bound(0.1,skill+this.bot_dodgeskill,10);
1124 }
1125
1126 entity havocbot_gettarget(entity this, bool secondary)
1127 {
1128         entity best = NULL;
1129         vector eye = CENTER_OR_VIEWOFS(this);
1130         IL_EACH(g_bot_targets, boolean((secondary) ? it.classname == "misc_breakablemodel" : it.classname != "misc_breakablemodel"),
1131         {
1132                 vector v = CENTER_OR_VIEWOFS(it);
1133                 if(vdist(v - eye, <, autocvar_bot_ai_enemydetectionradius))
1134                 if(!best || vlen2(CENTER_OR_VIEWOFS(best) - eye) > vlen2(v - eye))
1135                 if(bot_shouldattack(this, it))
1136                 {
1137                         traceline(eye, v, true, this);
1138                         if (trace_ent == it || trace_fraction >= 1)
1139                                 best = it;
1140                 }
1141         });
1142
1143         return best;
1144 }
1145
1146 void havocbot_chooseenemy(entity this)
1147 {
1148         if (autocvar_bot_nofire || IS_INDEPENDENT_PLAYER(this))
1149         {
1150                 this.enemy = NULL;
1151                 return;
1152         }
1153         if (this.enemy)
1154         {
1155                 if (!bot_shouldattack(this, this.enemy))
1156                 {
1157                         // enemy died or something, find a new target
1158                         this.enemy = NULL;
1159                         this.havocbot_chooseenemy_finished = time;
1160                 }
1161                 else if (this.havocbot_stickenemy)
1162                 {
1163                         // tracking last chosen enemy
1164                         // if enemy is visible
1165                         // and not really really far away
1166                         // and we're not severely injured
1167                         // then keep tracking for a half second into the future
1168                         traceline(this.origin+this.view_ofs, ( this.enemy.absmin + this.enemy.absmax ) * 0.5,false,NULL);
1169                         if (trace_ent == this.enemy || trace_fraction == 1)
1170                         if (vdist(((this.enemy.absmin + this.enemy.absmax) * 0.5) - this.origin, <, 1000))
1171                         if (GetResourceAmount(this, RESOURCE_HEALTH) > 30)
1172                         {
1173                                 // remain tracking him for a shot while (case he went after a small corner or pilar
1174                                 this.havocbot_chooseenemy_finished = time + 0.5;
1175                                 return;
1176                         }
1177                         // enemy isn't visible, or is far away, or we're injured severely
1178                         // so stop preferring this enemy
1179                         // (it will still take a half second until a new one is chosen)
1180                         this.havocbot_stickenemy = 0;
1181                 }
1182         }
1183         if (time < this.havocbot_chooseenemy_finished)
1184                 return;
1185         this.havocbot_chooseenemy_finished = time + autocvar_bot_ai_enemydetectioninterval;
1186         vector eye = this.origin + this.view_ofs;
1187         entity best = NULL;
1188         float bestrating = 100000000;
1189
1190         // Backup hit flags
1191         int hf = this.dphitcontentsmask;
1192
1193         // Search for enemies, if no enemy can be seen directly try to look through transparent objects
1194
1195         this.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
1196
1197         bool scan_transparent = false;
1198         bool scan_secondary_targets = false;
1199         bool have_secondary_targets = false;
1200         while(true)
1201         {
1202                 scan_secondary_targets = false;
1203 LABEL(scan_targets)
1204                 IL_EACH(g_bot_targets, it.bot_attack,
1205                 {
1206                         if(!scan_secondary_targets)
1207                         {
1208                                 if(it.classname == "misc_breakablemodel")
1209                                 {
1210                                         have_secondary_targets = true;
1211                                         continue;
1212                                 }
1213                         }
1214                         else if(it.classname != "misc_breakablemodel")
1215                                 continue;
1216
1217                         vector v = (it.absmin + it.absmax) * 0.5;
1218                         float rating = vlen2(v - eye);
1219                         if (vdist(v - eye, <, autocvar_bot_ai_enemydetectionradius))
1220                         if (bestrating > rating)
1221                         if (bot_shouldattack(this, it))
1222                         {
1223                                 traceline(eye, v, true, this);
1224                                 if (trace_ent == it || trace_fraction >= 1)
1225                                 {
1226                                         best = it;
1227                                         bestrating = rating;
1228                                 }
1229                         }
1230                 });
1231
1232                 if(!best && have_secondary_targets && !scan_secondary_targets)
1233                 {
1234                         scan_secondary_targets = true;
1235                         // restart the loop
1236                         bestrating = 100000000;
1237                         goto scan_targets;
1238                 }
1239
1240                 // I want to do a second scan if no enemy was found or I don't have weapons
1241                 // TODO: Perform the scan when using the rifle (requires changes on the rifle code)
1242                 if(best || STAT(WEAPONS, this)) // || this.weapon == WEP_RIFLE.m_id
1243                         break;
1244                 if(scan_transparent)
1245                         break;
1246
1247                 // Set flags to see through transparent objects
1248                 this.dphitcontentsmask |= DPCONTENTS_OPAQUE;
1249
1250                 scan_transparent = true;
1251         }
1252
1253         // Restore hit flags
1254         this.dphitcontentsmask = hf;
1255
1256         this.enemy = best;
1257         this.havocbot_stickenemy = true;
1258         if(best && best.classname == "misc_breakablemodel")
1259                 this.havocbot_stickenemy = false;
1260 }
1261
1262 float havocbot_chooseweapon_checkreload(entity this, .entity weaponentity, int new_weapon)
1263 {
1264         // bots under this skill cannot find unloaded weapons to reload idly when not in combat,
1265         // so skip this for them, or they'll never get to reload their weapons at all.
1266         // this also allows bots under this skill to be more stupid, and reload more often during combat :)
1267         if(skill < 5)
1268                 return false;
1269
1270         // if this weapon is scheduled for reloading, don't switch to it during combat
1271         if (this.(weaponentity).weapon_load[new_weapon] < 0)
1272         {
1273                 FOREACH(Weapons, it != WEP_Null, {
1274                         if(it.wr_checkammo1(it, this, weaponentity) + it.wr_checkammo2(it, this, weaponentity))
1275                                 return true; // other weapon available
1276                 });
1277         }
1278
1279         return false;
1280 }
1281
1282 void havocbot_chooseweapon(entity this, .entity weaponentity)
1283 {
1284         int i;
1285
1286         // ;)
1287         if(g_weaponarena_weapons == WEPSET(TUBA))
1288         {
1289                 this.(weaponentity).m_switchweapon = WEP_TUBA;
1290                 return;
1291         }
1292
1293         // TODO: clean this up by moving it to weapon code
1294         if(this.enemy==NULL)
1295         {
1296                 // If no weapon was chosen get the first available weapon
1297                 if(this.(weaponentity).m_weapon==WEP_Null)
1298                 FOREACH(Weapons, it != WEP_Null, {
1299                         if(client_hasweapon(this, it, weaponentity, true, false))
1300                         {
1301                                 this.(weaponentity).m_switchweapon = it;
1302                                 return;
1303                         }
1304                 });
1305                 return;
1306         }
1307
1308         // Do not change weapon during the next second after a combo
1309         float f = time - this.lastcombotime;
1310         if(f < 1)
1311                 return;
1312
1313         float w;
1314         float distance; distance=bound(10,vlen(this.origin-this.enemy.origin)-200,10000);
1315
1316         // Should it do a weapon combo?
1317         float af, ct, combo_time, combo;
1318
1319         af = ATTACK_FINISHED(this, 0);
1320         ct = autocvar_bot_ai_weapon_combo_threshold;
1321
1322         // Bots with no skill will be 4 times more slower than "godlike" bots when doing weapon combos
1323         // Ideally this 4 should be calculated as longest_weapon_refire / bot_ai_weapon_combo_threshold
1324         combo_time = time + ct + (ct * ((-0.3*(skill+this.bot_weaponskill))+3));
1325
1326         combo = false;
1327
1328         if(autocvar_bot_ai_weapon_combo)
1329         if(this.(weaponentity).m_weapon.m_id == this.(weaponentity).lastfiredweapon)
1330         if(af > combo_time)
1331         {
1332                 combo = true;
1333                 this.lastcombotime = time;
1334         }
1335
1336         distance *= (2 ** this.bot_rangepreference);
1337
1338         // Custom weapon list based on distance to the enemy
1339         if(bot_custom_weapon){
1340
1341                 // Choose weapons for far distance
1342                 if ( distance > bot_distance_far ) {
1343                         for(i=0; i < Weapons_COUNT && bot_weapons_far[i] != -1 ; ++i){
1344                                 w = bot_weapons_far[i];
1345                                 if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1346                                 {
1347                                         if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1348                                                 continue;
1349                                         this.(weaponentity).m_switchweapon = Weapons_from(w);
1350                                         return;
1351                                 }
1352                         }
1353                 }
1354
1355                 // Choose weapons for mid distance
1356                 if ( distance > bot_distance_close) {
1357                         for(i=0; i < Weapons_COUNT && bot_weapons_mid[i] != -1 ; ++i){
1358                                 w = bot_weapons_mid[i];
1359                                 if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1360                                 {
1361                                         if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1362                                                 continue;
1363                                         this.(weaponentity).m_switchweapon = Weapons_from(w);
1364                                         return;
1365                                 }
1366                         }
1367                 }
1368
1369                 // Choose weapons for close distance
1370                 for(i=0; i < Weapons_COUNT && bot_weapons_close[i] != -1 ; ++i){
1371                         w = bot_weapons_close[i];
1372                         if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1373                         {
1374                                 if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1375                                         continue;
1376                                 this.(weaponentity).m_switchweapon = Weapons_from(w);
1377                                 return;
1378                         }
1379                 }
1380         }
1381 }
1382
1383 void havocbot_aim(entity this)
1384 {
1385         if (time < this.nextaim)
1386                 return;
1387         this.nextaim = time + 0.1;
1388         vector myvel = this.velocity;
1389         if (!this.waterlevel)
1390                 myvel.z = 0;
1391         if(MUTATOR_CALLHOOK(HavocBot_Aim, this)) { /* do nothing */ }
1392         else if (this.enemy)
1393         {
1394                 vector enemyvel = this.enemy.velocity;
1395                 if (!this.enemy.waterlevel)
1396                         enemyvel.z = 0;
1397                 lag_additem(this, time + CS(this).ping, 0, 0, this.enemy, this.origin, myvel, (this.enemy.absmin + this.enemy.absmax) * 0.5, enemyvel);
1398         }
1399         else
1400                 lag_additem(this, time + CS(this).ping, 0, 0, NULL, this.origin, myvel, ( this.goalcurrent.absmin + this.goalcurrent.absmax ) * 0.5, '0 0 0');
1401 }
1402
1403 bool havocbot_moveto_refresh_route(entity this)
1404 {
1405         // Refresh path to goal if necessary
1406         entity wp;
1407         wp = this.havocbot_personal_waypoint;
1408         navigation_goalrating_start(this);
1409         navigation_routerating(this, wp, 10000, 10000);
1410         navigation_goalrating_end(this);
1411         return (this.goalentity != NULL);
1412 }
1413
1414 float havocbot_moveto(entity this, vector pos)
1415 {
1416         entity wp;
1417
1418         if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
1419         {
1420                 // Step 4: Move to waypoint
1421                 if(this.havocbot_personal_waypoint==NULL)
1422                 {
1423                         LOG_TRACE("Error: ", this.netname, " trying to walk to a non existent personal waypoint");
1424                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_GOING;
1425                         return CMD_STATUS_ERROR;
1426                 }
1427
1428                 if (!bot_strategytoken_taken)
1429                 if(this.havocbot_personal_waypoint_searchtime<time)
1430                 {
1431                         bot_strategytoken_taken = true;
1432                         if(havocbot_moveto_refresh_route(this))
1433                         {
1434                                 LOG_TRACE(this.netname, " walking to its personal waypoint (after ", ftos(this.havocbot_personal_waypoint_failcounter), " failed attempts)");
1435                                 this.havocbot_personal_waypoint_searchtime = time + 10;
1436                                 this.havocbot_personal_waypoint_failcounter = 0;
1437                         }
1438                         else
1439                         {
1440                                 this.havocbot_personal_waypoint_failcounter += 1;
1441                                 this.havocbot_personal_waypoint_searchtime = time + 2;
1442                                 if(this.havocbot_personal_waypoint_failcounter >= 30)
1443                                 {
1444                                         LOG_TRACE("Warning: can't walk to the personal waypoint located at ", vtos(this.havocbot_personal_waypoint.origin));
1445                                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1446                                         delete(this.havocbot_personal_waypoint);
1447                                         return CMD_STATUS_ERROR;
1448                                 }
1449                                 else
1450                                         LOG_TRACE(this.netname, " can't walk to its personal waypoint (after ", ftos(this.havocbot_personal_waypoint_failcounter), " failed attempts), trying later");
1451                         }
1452                 }
1453
1454                 if(autocvar_bot_debug_goalstack)
1455                         debuggoalstack(this);
1456
1457                 // Heading
1458                 vector dir = get_closer_dest(this.goalcurrent, this.origin);
1459                 dir = dir - (this.origin + this.view_ofs);
1460                 dir.z = 0;
1461                 bot_aimdir(this, dir, -1);
1462
1463                 // Go!
1464                 havocbot_movetogoal(this);
1465
1466                 if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_REACHED)
1467                 {
1468                         // Step 5: Waypoint reached
1469                         LOG_TRACE(this.netname, "'s personal waypoint reached");
1470                         delete(this.havocbot_personal_waypoint);
1471                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_REACHED;
1472                         return CMD_STATUS_FINISHED;
1473                 }
1474
1475                 return CMD_STATUS_EXECUTING;
1476         }
1477
1478         // Step 2: Linking waypoint
1479         if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_LINKING)
1480         {
1481                 // Wait until it is linked
1482                 if(!this.havocbot_personal_waypoint.wplinked)
1483                 {
1484                         LOG_TRACE(this.netname, " waiting for personal waypoint to be linked");
1485                         return CMD_STATUS_EXECUTING;
1486                 }
1487
1488                 this.havocbot_personal_waypoint_searchtime = time; // so we set the route next frame
1489                 this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1490                 this.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_GOING;
1491
1492                 // Step 3: Route to waypoint
1493                 LOG_TRACE(this.netname, " walking to its personal waypoint");
1494
1495                 return CMD_STATUS_EXECUTING;
1496         }
1497
1498         // Step 1: Spawning waypoint
1499         wp = waypoint_spawnpersonal(this, pos);
1500         if(wp==NULL)
1501         {
1502                 LOG_TRACE("Error: Can't spawn personal waypoint at ",vtos(pos));
1503                 return CMD_STATUS_ERROR;
1504         }
1505
1506         this.havocbot_personal_waypoint = wp;
1507         this.havocbot_personal_waypoint_failcounter = 0;
1508         this.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1509
1510         // if pos is inside a teleport, then let's mark it as teleport waypoint
1511         IL_EACH(g_teleporters, WarpZoneLib_BoxTouchesBrush(pos, pos, it, NULL),
1512         {
1513                 wp.wpflags |= WAYPOINTFLAG_TELEPORT;
1514                 this.lastteleporttime = 0;
1515         });
1516
1517 /*
1518         if(wp.wpflags & WAYPOINTFLAG_TELEPORT)
1519                 print("routing to a teleporter\n");
1520         else
1521                 print("routing to a non-teleporter\n");
1522 */
1523
1524         return CMD_STATUS_EXECUTING;
1525 }
1526
1527 float havocbot_resetgoal(entity this)
1528 {
1529         navigation_clearroute(this);
1530         return CMD_STATUS_FINISHED;
1531 }
1532
1533 void havocbot_setupbot(entity this)
1534 {
1535         this.bot_ai = havocbot_ai;
1536         this.cmd_moveto = havocbot_moveto;
1537         this.cmd_resetgoal = havocbot_resetgoal;
1538
1539         havocbot_chooserole(this);
1540 }
1541
1542 vector havocbot_dodge(entity this)
1543 {
1544         // LordHavoc: disabled because this is too expensive
1545         return '0 0 0';
1546 #if 0
1547         entity head;
1548         vector dodge, v, n;
1549         float danger, bestdanger, vl, d;
1550         dodge = '0 0 0';
1551         bestdanger = -20;
1552         // check for dangerous objects near bot or approaching bot
1553         head = findchainfloat(bot_dodge, true);
1554         while(head)
1555         {
1556                 if (head.owner != this)
1557                 {
1558                         vl = vlen(head.velocity);
1559                         if (vl > autocvar_sv_maxspeed * 0.3)
1560                         {
1561                                 n = normalize(head.velocity);
1562                                 v = this.origin - head.origin;
1563                                 d = v * n;
1564                                 if (d > (0 - head.bot_dodgerating))
1565                                 if (d < (vl * 0.2 + head.bot_dodgerating))
1566                                 {
1567                                         // calculate direction and distance from the flight path, by removing the forward axis
1568                                         v = v - (n * (v * n));
1569                                         danger = head.bot_dodgerating - vlen(v);
1570                                         if (bestdanger < danger)
1571                                         {
1572                                                 bestdanger = danger;
1573                                                 // dodge to the side of the object
1574                                                 dodge = normalize(v);
1575                                         }
1576                                 }
1577                         }
1578                         else
1579                         {
1580                                 danger = head.bot_dodgerating - vlen(head.origin - this.origin);
1581                                 if (bestdanger < danger)
1582                                 {
1583                                         bestdanger = danger;
1584                                         dodge = normalize(this.origin - head.origin);
1585                                 }
1586                         }
1587                 }
1588                 head = head.chain;
1589         }
1590         return dodge;
1591 #endif
1592 }