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