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