small optimizations and code style fixes

This commit is contained in:
jeefo 2015-06-24 15:38:48 +03:00
commit c28110cce2
12 changed files with 220 additions and 200 deletions

View file

@ -90,8 +90,6 @@ using namespace Math;
#define DLL_RETENTRY return #define DLL_RETENTRY return
#define DLL_GIVEFNPTRSTODLL extern "C" void __attribute__((visibility("default"))) #define DLL_GIVEFNPTRSTODLL extern "C" void __attribute__((visibility("default")))
static inline uint32 _lrotl (uint32 x, int r) { return (x << r) | (x >> (sizeof (x) * 8 - r));}
typedef int (*EntityAPI_t) (gamefuncs_t *, int); typedef int (*EntityAPI_t) (gamefuncs_t *, int);
typedef int (*NewEntityAPI_t) (newgamefuncs_t *, int *); typedef int (*NewEntityAPI_t) (newgamefuncs_t *, int *);
typedef int (*BlendAPI_t) (int, void **, void *, float (*)[3][4], float (*)[128][3][4]); typedef int (*BlendAPI_t) (int, void **, void *, float (*)[3][4], float (*)[128][3][4]);
@ -242,7 +240,8 @@ enum CollisionState
COLLISION_JUMP, COLLISION_JUMP,
COLLISION_DUCK, COLLISION_DUCK,
COLLISION_STRAFELEFT, COLLISION_STRAFELEFT,
COLLISION_STRAFERIGHT COLLISION_STRAFERIGHT,
COLLISION_BACKOFF
}; };
// counter-strike team id's // counter-strike team id's
@ -409,7 +408,8 @@ enum CollisionProbe
{ {
PROBE_JUMP = (1 << 0), // probe jump when colliding PROBE_JUMP = (1 << 0), // probe jump when colliding
PROBE_DUCK = (1 << 1), // probe duck when colliding PROBE_DUCK = (1 << 1), // probe duck when colliding
PROBE_STRAFE = (1 << 2) // probe strafing when colliding PROBE_STRAFE = (1 << 2), // probe strafing when colliding
PROBE_BACKOFF = (1 << 3) // probe going back when colliding
}; };
// vgui menus (since latest steam updates is obsolete, but left for old cs) // vgui menus (since latest steam updates is obsolete, but left for old cs)
@ -857,7 +857,7 @@ private:
float m_lastCollTime; // time until next collision check float m_lastCollTime; // time until next collision check
unsigned int m_collisionProbeBits; // bits of possible collision moves unsigned int m_collisionProbeBits; // bits of possible collision moves
unsigned int m_collideMoves[4]; // sorted array of movements unsigned int m_collideMoves[5]; // sorted array of movements
unsigned int m_collStateIndex; // index into collide moves unsigned int m_collStateIndex; // index into collide moves
CollisionState m_collisionState; // collision State CollisionState m_collisionState; // collision State
@ -1051,8 +1051,8 @@ private:
bool OutOfBombTimer (void); bool OutOfBombTimer (void);
void SelectLeaderEachTeam (int team); void SelectLeaderEachTeam (int team);
Vector CheckToss (const Vector &start, Vector end); const Vector &CheckThrow (const Vector &start, const Vector &stop);
Vector CheckThrow (const Vector &start, Vector end); const Vector &CheckToss (const Vector &start, const Vector &stop);
Vector CheckBombAudible (void); Vector CheckBombAudible (void);
const Vector &GetAimPosition (void); const Vector &GetAimPosition (void);
@ -1279,10 +1279,9 @@ private:
Array <CreateQueue> m_creationTab; // bot creation tab Array <CreateQueue> m_creationTab; // bot creation tab
Bot *m_bots[32]; // all available bots Bot *m_bots[32]; // all available bots
float m_maintainTime; // time to maintain bot creation quota
float m_maintainTime; // time to maintain bot creation quota
int m_lastWinner; // the team who won previous round int m_lastWinner; // the team who won previous round
int m_roundCount; // rounds passed
bool m_economicsGood[2]; // is team able to buy anything bool m_economicsGood[2]; // is team able to buy anything
bool m_deathMsgSent; // for fakeping bool m_deathMsgSent; // for fakeping
@ -1291,7 +1290,7 @@ private:
Array <entity_t> m_activeGrenades; Array <entity_t> m_activeGrenades;
protected: protected:
int CreateBot (String name, int difficulty, int personality, int team, int member); int CreateBot (const String &name, int difficulty, int personality, int team, int member);
public: public:
BotManager (void); BotManager (void);
@ -1320,7 +1319,7 @@ public:
void AddRandom (void) { AddBot ("", -1, -1, -1, -1); } void AddRandom (void) { AddBot ("", -1, -1, -1, -1); }
void AddBot (const String &name, int difficulty, int personality, int team, int member); void AddBot (const String &name, int difficulty, int personality, int team, int member);
void AddBot (String name, String difficulty, String personality, String team, String member); void AddBot (const String &name, const String &difficulty, const String &personality, const String &team, const String &member);
void FillServer (int selection, int personality = PERSONALITY_NORMAL, int difficulty = -1, int numToAdd = -1); void FillServer (int selection, int personality = PERSONALITY_NORMAL, int difficulty = -1, int numToAdd = -1);
void RemoveAll (bool zeroQuota = true); void RemoveAll (bool zeroQuota = true);
@ -1635,7 +1634,7 @@ extern bool TryFileOpen (const char *fileName);
extern bool IsDedicatedServer (void); extern bool IsDedicatedServer (void);
extern bool IsVisible (const Vector &origin, edict_t *ent); extern bool IsVisible (const Vector &origin, edict_t *ent);
extern bool IsAlive (edict_t *ent); extern bool IsAlive (edict_t *ent);
extern bool IsInViewCone (Vector origin, edict_t *ent); extern bool IsInViewCone (const Vector &origin, edict_t *ent);
extern int GetWeaponPenetrationPower (int id); extern int GetWeaponPenetrationPower (int id);
extern bool IsValidBot (edict_t *ent); extern bool IsValidBot (edict_t *ent);
extern bool IsValidPlayer (edict_t *ent); extern bool IsValidPlayer (edict_t *ent);
@ -1665,7 +1664,6 @@ extern void ServerPrint (const char *format, ...);
extern void ChartPrint (const char *format, ...); extern void ChartPrint (const char *format, ...);
extern void CenterPrint (const char *format, ...); extern void CenterPrint (const char *format, ...);
extern void ClientPrint (edict_t *ent, int dest, const char *format, ...); extern void ClientPrint (edict_t *ent, int dest, const char *format, ...);
extern void HudMessage (edict_t *ent, bool toCenter, Vector rgb, char *format, ...);
extern void AddLogEntry (bool outputToConsole, int logLevel, const char *format, ...); extern void AddLogEntry (bool outputToConsole, int logLevel, const char *format, ...);
extern void TraceLine (const Vector &start, const Vector &end, bool ignoreMonsters, bool ignoreGlass, edict_t *ignoreEntity, TraceResult *ptr); extern void TraceLine (const Vector &start, const Vector &end, bool ignoreMonsters, bool ignoreGlass, edict_t *ignoreEntity, TraceResult *ptr);

View file

@ -212,10 +212,10 @@ namespace Math
{ {
fld dword ptr[rad] fld dword ptr[rad]
fsincos fsincos
mov edx, dword ptr[cos] mov ebx, [cos]
mov eax, dword ptr[sin] fstp dword ptr[ebx]
fstp dword ptr[edx] mov ebx, [sin]
fstp dword ptr[eax] fstp dword ptr[ebx]
} }
#elif defined (__linux__) || defined (GCC) || defined (__APPLE__) #elif defined (__linux__) || defined (GCC) || defined (__APPLE__)
register double _cos, _sin; register double _cos, _sin;
@ -369,15 +369,6 @@ public:
return &x; return &x;
} }
inline float &operator [] (int index)
{
return (&x)[index];
}
inline const float &operator [] (int index) const
{
return (&x)[index];
}
inline const Vector operator + (const Vector &right) const inline const Vector operator + (const Vector &right) const
{ {
@ -410,11 +401,13 @@ public:
return Vector (inv * x, inv * y, inv * z); return Vector (inv * x, inv * y, inv * z);
} }
// cross product
inline const Vector operator ^ (const Vector &right) const inline const Vector operator ^ (const Vector &right) const
{ {
return Vector (y * right.z - z * right.y, z * right.x - x * right.z, x * right.y - y * right.x); return Vector (y * right.z - z * right.y, z * right.x - x * right.z, x * right.y - y * right.x);
} }
// dot product
inline float operator | (const Vector &right) const inline float operator | (const Vector &right) const
{ {
return x * right.x + y * right.y + z * right.z; return x * right.x + y * right.y + z * right.z;
@ -545,14 +538,14 @@ public:
} }
// //
// Function: SkipZ // Function: Get2D
// //
// Gets vector without Z axis. // Gets vector without Z axis.
// //
// Returns: // Returns:
// 2D vector from 3D vector. // 2D vector from 3D vector.
// //
inline Vector SkipZ (void) const inline Vector Get2D (void) const
{ {
return Vector (x, y, 0.0f); return Vector (x, y, 0.0f);
} }
@ -2473,7 +2466,7 @@ public:
// Returns: // Returns:
// Integer value of string. // Integer value of string.
// //
int ToInt (void) int ToInt (void) const
{ {
return atoi (m_bufferPtr); return atoi (m_bufferPtr);
} }

View file

@ -348,7 +348,7 @@ typedef struct
void (*pfnSetupVisibility) (struct edict_s *pViewEntity, struct edict_s *client, unsigned char **pvs, unsigned char **pas); void (*pfnSetupVisibility) (struct edict_s *pViewEntity, struct edict_s *client, unsigned char **pvs, unsigned char **pas);
void (*pfnUpdateClientData) (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd); void (*pfnUpdateClientData) (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd);
int (*pfnAddToFullPack) (struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet); int (*pfnAddToFullPack) (struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet);
void (*pfnCreateBaseline) (int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs); void (*pfnCreateBaseline) (int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, float* player_mins, float* player_maxs);
void (*pfnRegisterEncoders) (void); void (*pfnRegisterEncoders) (void);
int (*pfnGetWeaponData) (struct edict_s *player, struct weapon_data_s *info); int (*pfnGetWeaponData) (struct edict_s *player, struct weapon_data_s *info);

View file

@ -13,15 +13,15 @@
#define PRODUCT_NAME "Yet Another POD-Bot" #define PRODUCT_NAME "Yet Another POD-Bot"
#define PRODUCT_VERSION "2.7" #define PRODUCT_VERSION "2.7"
#define PRODUCT_AUTHOR "YaPB Dev Team" #define PRODUCT_AUTHOR "YaPB Dev Team"
#define PRODUCT_URL "http://yapb.ru/" #define PRODUCT_URL "http://yapb.jeefo.net"
#define PRODUCT_EMAIL "dmitry@jeefo.net" #define PRODUCT_EMAIL "dmitry@jeefo.net"
#define PRODUCT_LOGTAG "YAPB" #define PRODUCT_LOGTAG "YAPB"
#define PRODUCT_DESCRIPTION PRODUCT_NAME " v" PRODUCT_VERSION " - The Counter-Strike Bot" #define PRODUCT_DESCRIPTION PRODUCT_NAME " v" PRODUCT_VERSION " - The Counter-Strike Bot"
#define PRODUCT_COPYRIGHT "Copyright © 2015, by " PRODUCT_AUTHOR #define PRODUCT_COPYRIGHT "Copyright © 2003-2015, by " PRODUCT_AUTHOR
#define PRODUCT_LEGAL "Half-Life, Counter-Strike, Counter-Strike: Condition Zero, Steam, Valve is a trademark of Valve Corporation" #define PRODUCT_LEGAL "Half-Life, Counter-Strike, Counter-Strike: Condition Zero, Steam, Valve is a trademark of Valve Corporation"
#define PRODUCT_ORIGINAL_NAME "yapb.dll" #define PRODUCT_ORIGINAL_NAME "yapb.dll"
#define PRODUCT_INTERNAL_NAME "podbot" #define PRODUCT_INTERNAL_NAME "podbot"
#define PRODUCT_VERSION_DWORD 2,7,0,0 // major version, minor version, WIP (or Update) version #define PRODUCT_VERSION_DWORD 2,7,0,0
#define PRODUCT_SUPPORT_VERSION "1.0 - CZ" #define PRODUCT_SUPPORT_VERSION "1.0 - CZ"
#define PRODUCT_COMMENTS "http://github.com/jeefo/yapb/" #define PRODUCT_COMMENTS "http://github.com/jeefo/yapb/"
#define PRODUCT_DATE __DATE__ #define PRODUCT_DATE __DATE__

View file

@ -294,7 +294,7 @@ void Bot::CheckGrenadeThrow (void)
if (allowThrowing && m_seeEnemyTime + 2.0 < GetWorldTime ()) if (allowThrowing && m_seeEnemyTime + 2.0 < GetWorldTime ())
{ {
const Vector &enemyPredict = ((m_lastEnemy->v.velocity * 0.5).SkipZ () + m_lastEnemy->v.origin); const Vector &enemyPredict = ((m_lastEnemy->v.velocity * 0.5).Get2D () + m_lastEnemy->v.origin);
int searchTab[4], count = 4; int searchTab[4], count = 4;
float searchRadius = m_lastEnemy->v.velocity.GetLength2D (); float searchRadius = m_lastEnemy->v.velocity.GetLength2D ();
@ -345,7 +345,7 @@ void Bot::CheckGrenadeThrow (void)
bool allowThrowing = true; bool allowThrowing = true;
Array <int> inRadius; Array <int> inRadius;
g_waypoint->FindInRadius (inRadius, 256, m_lastEnemy->v.origin + (m_lastEnemy->v.velocity * 0.5).SkipZ ()); g_waypoint->FindInRadius (inRadius, 256, m_lastEnemy->v.origin + (m_lastEnemy->v.velocity * 0.5).Get2D ());
IterateArray (inRadius, i) IterateArray (inRadius, i)
{ {
@ -683,7 +683,6 @@ void Bot::FindItem (void)
edict_t *ent = NULL, *pickupItem = NULL; edict_t *ent = NULL, *pickupItem = NULL;
Bot *bot = NULL; Bot *bot = NULL;
bool allowPickup = false;
float distance, minDistance = 341.0; float distance, minDistance = 341.0;
const float searchRadius = 340.0f; const float searchRadius = 340.0f;
@ -727,6 +726,8 @@ void Bot::FindItem (void)
m_pickupItem = NULL; m_pickupItem = NULL;
m_pickupType = PICKUP_NONE; m_pickupType = PICKUP_NONE;
bool allowPickup = false;
while (!IsEntityNull (ent = FIND_ENTITY_IN_SPHERE (ent, pev->origin, searchRadius))) while (!IsEntityNull (ent = FIND_ENTITY_IN_SPHERE (ent, pev->origin, searchRadius)))
{ {
allowPickup = false; // assume can't use it until known otherwise allowPickup = false; // assume can't use it until known otherwise
@ -1081,14 +1082,13 @@ void Bot::SwitchChatterIcon (bool show)
if (g_gameVersion == CSV_OLD || yb_communication_type.GetInt () != 2) if (g_gameVersion == CSV_OLD || yb_communication_type.GetInt () != 2)
return; return;
for (int i = 0; i < GetMaxClients (); i++) for (int i = 0; i < GetMaxClients (); i++)
{ {
edict_t *ent = EntityOfIndex (i); if (!(g_clients[i].flags & CF_USED) || (g_clients[i].ent->v.flags & FL_FAKECLIENT) || g_clients[i].team != m_team)
if (!(ent->v.flags & FL_CLIENT) || (ent->v.flags & FL_FAKECLIENT) || GetTeam (ent) != m_team)
continue; continue;
MESSAGE_BEGIN (MSG_ONE, g_netMsg->GetId (NETMSG_BOTVOICE), NULL, ent); // begin message MESSAGE_BEGIN (MSG_ONE, g_netMsg->GetId (NETMSG_BOTVOICE), NULL, g_clients[i].ent); // begin message
WRITE_BYTE (show); // switch on/off WRITE_BYTE (show); // switch on/off
WRITE_BYTE (GetIndex ()); WRITE_BYTE (GetIndex ());
MESSAGE_END (); MESSAGE_END ();
@ -2067,8 +2067,6 @@ void Bot::SetConditions (void)
g_taskFilters[TASK_PICKUPITEM].desire = 0.0; g_taskFilters[TASK_PICKUPITEM].desire = 0.0;
} }
float desireLevel = 0.0;
// calculate desire to attack // calculate desire to attack
if ((m_states & STATE_SEEING_ENEMY) && ReactOnEnemy ()) if ((m_states & STATE_SEEING_ENEMY) && ReactOnEnemy ())
g_taskFilters[TASK_ATTACK].desire = TASKPRI_ATTACK; g_taskFilters[TASK_ATTACK].desire = TASKPRI_ATTACK;
@ -2109,7 +2107,8 @@ void Bot::SetConditions (void)
// FIXME: it probably should be also team/map dependant // FIXME: it probably should be also team/map dependant
if (IsEntityNull (m_enemy) && g_timeRoundMid < GetWorldTime () && !m_isUsingGrenade && m_currentWaypointIndex != g_waypoint->FindNearest (m_lastEnemyOrigin) && m_personality != PERSONALITY_CAREFUL) if (IsEntityNull (m_enemy) && g_timeRoundMid < GetWorldTime () && !m_isUsingGrenade && m_currentWaypointIndex != g_waypoint->FindNearest (m_lastEnemyOrigin) && m_personality != PERSONALITY_CAREFUL)
{ {
desireLevel = 4096.0 - ((1.0 - tempAgression) * distance); float desireLevel = 4096.0 - ((1.0 - tempAgression) * distance);
desireLevel = (100 * desireLevel) / 4096.0; desireLevel = (100 * desireLevel) / 4096.0;
desireLevel -= retreatLevel; desireLevel -= retreatLevel;
@ -2727,10 +2726,11 @@ void Bot::CheckRadioCommands (void)
g_timeNextBombUpdate = GetWorldTime () + 0.5; g_timeNextBombUpdate = GetWorldTime () + 0.5;
} }
// Does this Bot want to defuse?
// does this bot want to defuse?
if (GetTaskId () == TASK_NORMAL) if (GetTaskId () == TASK_NORMAL)
{ {
// Is he approaching this goal? // is he approaching this goal?
if (GetTask ()->data == bombPoint) if (GetTask ()->data == bombPoint)
{ {
GetTask ()->data = -1; GetTask ()->data = -1;
@ -3605,7 +3605,7 @@ void Bot::RunTask (void)
if (!IsEntityNull (m_enemy)) if (!IsEntityNull (m_enemy))
{ {
m_lastCollTime = GetWorldTime () + 0.5f; ResetCollideState ();
if (IsOnLadder ()) if (IsOnLadder ())
{ {
@ -3617,8 +3617,6 @@ void Bot::RunTask (void)
else else
{ {
TaskComplete (); TaskComplete ();
FindWaypoint ();
m_destOrigin = m_lastEnemyOrigin; m_destOrigin = m_lastEnemyOrigin;
} }
m_navTimeset = GetWorldTime (); m_navTimeset = GetWorldTime ();
@ -4220,13 +4218,12 @@ void Bot::RunTask (void)
if (!(m_states & STATE_SEEING_ENEMY)) if (!(m_states & STATE_SEEING_ENEMY))
{ {
m_moveSpeed = 0.0; m_strafeSpeed = 0.0f;
m_strafeSpeed = 0.0; m_moveSpeed = 0.0f;
m_moveToGoal = false; m_moveToGoal = false;
} }
else if (!(m_states & STATE_SUSPECT_ENEMY) && !IsEntityNull (m_enemy)) else if (!(m_states & STATE_SUSPECT_ENEMY) && !IsEntityNull (m_enemy))
destination = m_enemy->v.origin + (m_enemy->v.velocity.SkipZ () * 0.5); destination = m_enemy->v.origin + (m_enemy->v.velocity.Get2D () * 0.5);
m_isUsingGrenade = true; m_isUsingGrenade = true;
m_checkTerrain = false; m_checkTerrain = false;
@ -4297,13 +4294,11 @@ void Bot::RunTask (void)
if (!(m_states & STATE_SEEING_ENEMY)) if (!(m_states & STATE_SEEING_ENEMY))
{ {
m_moveSpeed = 0.0; m_strafeSpeed = 0.0f;
m_strafeSpeed = 0.0; m_moveSpeed = 0.0f;
m_moveToGoal = false;
} }
else if (!(m_states & STATE_SUSPECT_ENEMY) && !IsEntityNull (m_enemy)) else if (!(m_states & STATE_SUSPECT_ENEMY) && !IsEntityNull (m_enemy))
destination = m_enemy->v.origin + (m_enemy->v.velocity.SkipZ () * 0.5); destination = m_enemy->v.origin + (m_enemy->v.velocity.Get2D () * 0.5);
m_isUsingGrenade = true; m_isUsingGrenade = true;
m_checkTerrain = false; m_checkTerrain = false;
@ -4361,10 +4356,8 @@ void Bot::RunTask (void)
if (!(m_states & STATE_SEEING_ENEMY)) if (!(m_states & STATE_SEEING_ENEMY))
{ {
m_moveSpeed = 0.0; m_strafeSpeed = 0.0f;
m_strafeSpeed = 0.0; m_moveSpeed = 0.0f;
m_moveToGoal = false;
} }
m_checkTerrain = false; m_checkTerrain = false;
@ -5029,14 +5022,13 @@ void Bot::BotAI (void)
pev->button |= IN_MOVELEFT; pev->button |= IN_MOVELEFT;
} }
static float timeDebugUpdate = 0.0;
if (!IsEntityNull (g_hostEntity) && yb_debug.GetInt () >= 1) if (!IsEntityNull (g_hostEntity) && yb_debug.GetInt () >= 1)
{ {
int specIndex = g_hostEntity->v.iuser2; int specIndex = g_hostEntity->v.iuser2;
if (specIndex == IndexOfEntity (GetEntity ())) if (specIndex == IndexOfEntity (GetEntity ()))
{ {
static float timeDebugUpdate = 0.0;
static int index, goal, taskID; static int index, goal, taskID;
if (!m_tasks.IsEmpty ()) if (!m_tasks.IsEmpty ())
@ -5169,14 +5161,14 @@ void Bot::BotAI (void)
// set the aim flags // set the aim flags
sprintf (aimFlags, "%s%s%s%s%s%s%s%s", sprintf (aimFlags, "%s%s%s%s%s%s%s%s",
m_aimFlags & AIM_NAVPOINT ? " NavPoint" : "", (m_aimFlags & AIM_NAVPOINT) ? " NavPoint" : "",
m_aimFlags & AIM_CAMP ? " CampPoint" : "", (m_aimFlags & AIM_CAMP) ? " CampPoint" : "",
m_aimFlags & AIM_PREDICT_PATH ? " PredictPath" : "", (m_aimFlags & AIM_PREDICT_PATH) ? " PredictPath" : "",
m_aimFlags & AIM_LAST_ENEMY ? " LastEnemy" : "", (m_aimFlags & AIM_LAST_ENEMY) ? " LastEnemy" : "",
m_aimFlags & AIM_ENTITY ? " Entity" : "", (m_aimFlags & AIM_ENTITY) ? " Entity" : "",
m_aimFlags & AIM_ENEMY ? " Enemy" : "", (m_aimFlags & AIM_ENEMY) ? " Enemy" : "",
m_aimFlags & AIM_GRENADE ? " Grenade" : "", (m_aimFlags & AIM_GRENADE) ? " Grenade" : "",
m_aimFlags & AIM_OVERRIDE ? " Override" : ""); (m_aimFlags & AIM_OVERRIDE) ? " Override" : "");
// set the bot type // set the bot type
sprintf (botType, "%s%s%s", m_personality == PERSONALITY_RUSHER ? " Rusher" : "", sprintf (botType, "%s%s%s", m_personality == PERSONALITY_RUSHER ? " Rusher" : "",
@ -5652,7 +5644,7 @@ void Bot::DebugMsg (const char *format, ...)
AddLogEntry (false, LL_DEFAULT, "%s: %s", STRING (pev->netname), buffer); AddLogEntry (false, LL_DEFAULT, "%s: %s", STRING (pev->netname), buffer);
} }
Vector Bot::CheckToss (const Vector &start, Vector end) const Vector &Bot::CheckToss (const Vector &start, const Vector &stop)
{ {
// this function returns the velocity at which an object should looped from start to land near end. // this function returns the velocity at which an object should looped from start to land near end.
// returns null vector if toss is not feasible. // returns null vector if toss is not feasible.
@ -5660,7 +5652,7 @@ Vector Bot::CheckToss (const Vector &start, Vector end)
TraceResult tr; TraceResult tr;
float gravity = sv_gravity.GetFloat () * 0.55; float gravity = sv_gravity.GetFloat () * 0.55;
end = end - pev->velocity; Vector end = stop - pev->velocity;
end.z -= 15.0; end.z -= 15.0;
if (fabsf (end.z - start.z) > 500.0) if (fabsf (end.z - start.z) > 500.0)
@ -5707,12 +5699,12 @@ Vector Bot::CheckToss (const Vector &start, Vector end)
return nadeVelocity * 0.777; return nadeVelocity * 0.777;
} }
Vector Bot::CheckThrow (const Vector &start, Vector end) const Vector &Bot::CheckThrow (const Vector &start, const Vector &stop)
{ {
// this function returns the velocity vector at which an object should be thrown from start to hit end. // this function returns the velocity vector at which an object should be thrown from start to hit end.
// returns null vector if throw is not feasible. // returns null vector if throw is not feasible.
Vector nadeVelocity = (end - start); Vector nadeVelocity = (stop - start);
TraceResult tr; TraceResult tr;
float gravity = sv_gravity.GetFloat () * 0.55; float gravity = sv_gravity.GetFloat () * 0.55;
@ -5726,7 +5718,7 @@ Vector Bot::CheckThrow (const Vector &start, Vector end)
nadeVelocity = nadeVelocity * (1.0 / time); nadeVelocity = nadeVelocity * (1.0 / time);
nadeVelocity.z += gravity * time * 0.5; nadeVelocity.z += gravity * time * 0.5;
Vector apex = start + (end - start) * 0.5; Vector apex = start + (stop - start) * 0.5;
apex.z += 0.5 * gravity * (time * 0.5) * (time * 0.5); apex.z += 0.5 * gravity * (time * 0.5) * (time * 0.5);
TraceHull (start, apex, false, head_hull, GetEntity (), &tr); TraceHull (start, apex, false, head_hull, GetEntity (), &tr);
@ -5734,11 +5726,11 @@ Vector Bot::CheckThrow (const Vector &start, Vector end)
if (tr.flFraction != 1.0) if (tr.flFraction != 1.0)
return nullvec; return nullvec;
TraceHull (end, apex, true, head_hull, GetEntity (), &tr); TraceHull (stop, apex, true, head_hull, GetEntity (), &tr);
if (tr.flFraction != 1.0 || tr.fAllSolid) if (tr.flFraction != 1.0 || tr.fAllSolid)
{ {
float dot = -(tr.vecPlaneNormal | (apex - end).Normalize ()); float dot = -(tr.vecPlaneNormal | (apex - stop).Normalize ());
if (dot > 0.7 || tr.flFraction < 0.8) if (dot > 0.7 || tr.flFraction < 0.8)
return nullvec; return nullvec;

View file

@ -15,8 +15,8 @@ void StripTags (char *buffer)
{ {
// this function strips 'clan' tags specified below in given string buffer // this function strips 'clan' tags specified below in given string buffer
char *tagOpen[] = {"-=", "-[", "-]", "-}", "-{", "<[", "<]", "[-", "]-", "{-", "}-", "[[", "[", "{", "]", "}", "<", ">", "-", "|", "=", "+"}; char *tagOpen[] = {"-=", "-[", "-]", "-}", "-{", "<[", "<]", "[-", "]-", "{-", "}-", "[[", "[", "{", "]", "}", "<", ">", "-", "|", "=", "+", "(", ")"};
char *tagClose[] = {"=-", "]-", "[-", "{-", "}-", "]>", "[>", "-]", "-[", "-}", "-{", "]]", "]", "}", "[", "{", ">", "<", "-", "|", "=", "+"}; char *tagClose[] = {"=-", "]-", "[-", "{-", "}-", "]>", "[>", "-]", "-[", "-}", "-{", "]]", "]", "}", "[", "{", ">", "<", "-", "|", "=", "+", ")", "("};
int index, fieldStart, fieldStop, i; int index, fieldStart, fieldStop, i;
int length = strlen (buffer); // get length of string int length = strlen (buffer); // get length of string
@ -59,7 +59,6 @@ void StripTags (char *buffer)
// have we found a tag start? // have we found a tag start?
if (fieldStart >= 0 && fieldStart < 32) if (fieldStart >= 0 && fieldStart < 32)
{ {
fieldStop = fieldStart + strlen (tagOpen[index]); // set the tag stop
tagLength = strlen (tagOpen[index]); tagLength = strlen (tagOpen[index]);
for (i = fieldStart; i < length - tagLength; i++) for (i = fieldStart; i < length - tagLength; i++)
@ -72,7 +71,6 @@ void StripTags (char *buffer)
// have we found a tag stop ? // have we found a tag stop ?
if (fieldStart >= 0 && fieldStart < 32) if (fieldStart >= 0 && fieldStart < 32)
{ {
fieldStop = fieldStart + strlen (tagClose[index]); // set the tag
tagLength = strlen (tagClose[index]); tagLength = strlen (tagClose[index]);
for (i = fieldStart; i < length - tagLength; i++) for (i = fieldStart; i < length - tagLength; i++)

View file

@ -329,7 +329,7 @@ const Vector &Bot::GetAimPosition (void)
} }
m_lastEnemyOrigin = targetOrigin; m_lastEnemyOrigin = targetOrigin;
} }
const Vector &velocity = UsesSniper () ? nullvec : ((1.0f * m_frameInterval * m_enemy->v.velocity - 1.0 * m_frameInterval * pev->velocity) * m_frameInterval).SkipZ (); const Vector &velocity = UsesSniper () ? nullvec : ((1.0f * m_frameInterval * m_enemy->v.velocity - 1.0 * m_frameInterval * pev->velocity) * m_frameInterval).Get2D ();
if (m_difficulty < 3 && randomize != nullvec) if (m_difficulty < 3 && randomize != nullvec)
{ {
@ -560,10 +560,11 @@ bool Bot::DoFirePause (float distance, FireDelay *fireDelay)
else else
offset = 5.0; offset = 5.0;
float angle = sqrtf ((fabsf (pev->punchangle.y) * Math::MATH_PI / 180.0) * (fabsf (pev->punchangle.y) * Math::MATH_PI / 180.0) + (fabsf (pev->punchangle.x) * Math::MATH_PI / 180.0) * (fabsf (pev->punchangle.x) * Math::MATH_PI / 180.0)); const float xPunch = DegreeToRadian (pev->punchangle.x);
const float yPunch = DegreeToRadian (pev->punchangle.y);
// check if we need to compensate recoil // check if we need to compensate recoil
if (tanf (angle) * distance > offset + 30.0f + ((100 - (m_difficulty * 25)) / 100.f)) if (tanf (sqrtf (fabsf (xPunch * xPunch) + fabsf (yPunch * yPunch))) * distance > offset + 30.0f + ((100 - (m_difficulty * 25)) / 100.f))
{ {
if (m_firePause < GetWorldTime () - 0.4f) if (m_firePause < GetWorldTime () - 0.4f)
m_firePause = GetWorldTime () + Random.Float (0.4f, 0.4f + 0.3f * ((100 - (m_difficulty * 25)) / 100.f)); m_firePause = GetWorldTime () + Random.Float (0.4f, 0.4f + 0.3f * ((100 - (m_difficulty * 25)) / 100.f));
@ -603,7 +604,7 @@ void Bot::FireWeapon (void)
{ {
if (IsFriendInLineOfFire (distance)) if (IsFriendInLineOfFire (distance))
{ {
m_fightStyle = 1; m_fightStyle = 0;
m_lastFightStyleCheck = GetWorldTime (); m_lastFightStyleCheck = GetWorldTime ();
return; return;
@ -860,7 +861,7 @@ void Bot::FocusEnemy (void)
if (m_enemySurpriseTime > GetWorldTime ()) if (m_enemySurpriseTime > GetWorldTime ())
return; return;
enemyOrigin = (enemyOrigin - EyePosition ()).SkipZ (); enemyOrigin = (enemyOrigin - EyePosition ()).Get2D ();
float distance = enemyOrigin.GetLength (); // how far away is the enemy scum? float distance = enemyOrigin.GetLength (); // how far away is the enemy scum?
@ -910,7 +911,7 @@ void Bot::CombatFight (void)
if (m_currentWeapon == WEAPON_KNIFE) if (m_currentWeapon == WEAPON_KNIFE)
m_destOrigin = m_enemy->v.origin; m_destOrigin = m_enemy->v.origin;
enemyOrigin = (enemyOrigin - EyePosition ()).SkipZ (); // ignore z component (up & down) enemyOrigin = (enemyOrigin - EyePosition ()).Get2D (); // ignore z component (up & down)
float distance = enemyOrigin.GetLength (); // how far away is the enemy scum? float distance = enemyOrigin.GetLength (); // how far away is the enemy scum?

View file

@ -1,4 +1,4 @@
// //
// Yet Another POD-Bot, based on PODBot by Markus Klinge ("CountFloyd"). // Yet Another POD-Bot, based on PODBot by Markus Klinge ("CountFloyd").
// Copyright (c) YaPB Development Team. // Copyright (c) YaPB Development Team.
// //
@ -211,7 +211,7 @@ int BotCommandHandler (edict_t *ent, const char *arg0, const char *arg1, const c
g_hostEntity->v.movetype = MOVETYPE_NOCLIP; g_hostEntity->v.movetype = MOVETYPE_NOCLIP;
ServerPrint ("Noclip Cheat Enabled"); ServerPrint ("Noclip Cheat Enabled");
} }
g_editNoclip ^= true; // switch on/off (XOR it!) g_editNoclip = !g_editNoclip; // switch on/off (XOR it!)
} }
ServerCommand ("yapb wp mdl on"); ServerCommand ("yapb wp mdl on");
} }
@ -821,7 +821,7 @@ void InitConfig (void)
if (IsDedicatedServer ()) if (IsDedicatedServer ())
return; // dedicated server will use only english translation return; // dedicated server will use only english translation
enum Lang_t { Lang_Original, Lang_Translate, Lang_Default } langState = Lang_Default; enum Lang { Lang_Original, Lang_Translate } langState = static_cast <Lang> (2);
char buffer[1024]; char buffer[1024];
LanguageItem temp = {"", ""}; LanguageItem temp = {"", ""};
@ -1567,7 +1567,7 @@ void ClientCommand (edict_t *ent)
case 2: case 2:
if (FindNearestPlayer (reinterpret_cast <void **> (&bot), client->ent, 4096.0, true, true, true)) if (FindNearestPlayer (reinterpret_cast <void **> (&bot), client->ent, 4096.0, true, true, true))
{ {
if (!bot->m_hasC4 && !bot->HasHostage () && (bot->GetTaskId () != TASK_PLANTBOMB) && (bot->GetTaskId () != TASK_DEFUSEBOMB)) if (!bot->m_hasC4 && !bot->HasHostage () )
{ {
if (selection == 1) if (selection == 1)
{ {

View file

@ -29,6 +29,7 @@ BotManager::BotManager (void)
// this is a bot manager class constructor // this is a bot manager class constructor
m_lastWinner = -1; m_lastWinner = -1;
m_deathMsgSent = false;
m_economicsGood[TEAM_TF] = true; m_economicsGood[TEAM_TF] = true;
m_economicsGood[TEAM_CF] = true; m_economicsGood[TEAM_CF] = true;
@ -65,7 +66,7 @@ void BotManager::CallGameEntity (entvars_t *vars)
(*playerFunction) (vars); (*playerFunction) (vars);
} }
int BotManager::CreateBot (String name, int difficulty, int personality, int team, int member) int BotManager::CreateBot (const String &name, int difficulty, int personality, int team, int member)
{ {
// this function completely prepares bot entity (edict) for creation, creates team, difficulty, sets name etc, and // this function completely prepares bot entity (edict) for creation, creates team, difficulty, sets name etc, and
// then sends result to bot constructor // then sends result to bot constructor
@ -281,7 +282,7 @@ void BotManager::AddBot (const String &name, int difficulty, int personality, in
yb_quota.SetInt (GetBotsNum () + 1); yb_quota.SetInt (GetBotsNum () + 1);
} }
void BotManager::AddBot (String name, String difficulty, String personality, String team, String member) void BotManager::AddBot (const String &name, const String &difficulty, const String &personality, const String &team, const String &member)
{ {
// this function is same as the function above, but accept as parameters string instead of integers // this function is same as the function above, but accept as parameters string instead of integers
@ -738,7 +739,7 @@ Bot::Bot (edict_t *bot, int difficulty, int personality, int team, int member, c
char rejectReason[128]; char rejectReason[128];
int clientIndex = IndexOfEntity (bot); int clientIndex = IndexOfEntity (bot);
memset (this, 0, sizeof (Bot)); memset (this, 0, sizeof (*this));
pev = &bot->v; pev = &bot->v;

View file

@ -11,6 +11,9 @@
ConVar yb_aim_method ("yb_aim_method", "3", VT_NOSERVER); ConVar yb_aim_method ("yb_aim_method", "3", VT_NOSERVER);
// any user ever altered this stuff? left this for debug-only builds
#if !defined (NDEBUG)
ConVar yb_aim_damper_coefficient_x ("yb_aim_damper_coefficient_x", "0.22", VT_NOSERVER); ConVar yb_aim_damper_coefficient_x ("yb_aim_damper_coefficient_x", "0.22", VT_NOSERVER);
ConVar yb_aim_damper_coefficient_y ("yb_aim_damper_coefficient_y", "0.22", VT_NOSERVER); ConVar yb_aim_damper_coefficient_y ("yb_aim_damper_coefficient_y", "0.22", VT_NOSERVER);
@ -28,6 +31,8 @@ ConVar yb_aim_spring_stiffness_y ("yb_aim_spring_stiffness_y", "14.0", VT_NOSERV
ConVar yb_aim_target_anticipation_ratio ("yb_aim_target_anticipation_ratio", "5.0", VT_NOSERVER); ConVar yb_aim_target_anticipation_ratio ("yb_aim_target_anticipation_ratio", "5.0", VT_NOSERVER);
#endif
int Bot::FindGoal (void) int Bot::FindGoal (void)
{ {
// chooses a destination (goal) waypoint for a bot // chooses a destination (goal) waypoint for a bot
@ -269,6 +274,7 @@ void Bot::FilterGoals (const Array <int> &goals, int *result)
if (index > 0) if (index > 0)
index--; index--;
searchCount++;
continue; continue;
} }
result[index] = rand; result[index] = rand;
@ -311,7 +317,7 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
TraceResult tr; TraceResult tr;
edict_t *nearest = NULL; edict_t *nearest = NULL;
if (g_timeRoundStart + 10.0f < GetWorldTime () && FindNearestPlayer (reinterpret_cast <void **> (&nearest), GetEntity (), pev->maxspeed, true, false, true, true)) // found somebody? if (g_timeRoundStart + 10.0f < GetWorldTime () && FindNearestPlayer (reinterpret_cast <void **> (&nearest), GetEntity (), pev->maxspeed, true, false, true, true) && nearest != NULL && !(nearest->v.flags & FL_FAKECLIENT)) // found somebody?
{ {
MakeVectors (m_moveAngles); // use our movement angles MakeVectors (m_moveAngles); // use our movement angles
@ -327,16 +333,16 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
if ((nearest->v.origin - moved).GetLength2D () <= 48.0 || (nearestDistance <= 56.0 && nextFrameDistance < nearestDistance)) if ((nearest->v.origin - moved).GetLength2D () <= 48.0 || (nearestDistance <= 56.0 && nextFrameDistance < nearestDistance))
{ {
// to start strafing, we have to first figure out if the target is on the left side or right side // to start strafing, we have to first figure out if the target is on the left side or right side
Vector dirToPoint = (pev->origin - nearest->v.origin).SkipZ (); Vector dirToPoint = (pev->origin - nearest->v.origin).Get2D ();
if ((dirToPoint | g_pGlobals->v_right.SkipZ ()) > 0.0) if ((dirToPoint | g_pGlobals->v_right.Get2D ()) > 0.0)
SetStrafeSpeed (directionNormal, pev->maxspeed); SetStrafeSpeed (directionNormal, pev->maxspeed);
else else
SetStrafeSpeed (directionNormal, -pev->maxspeed); SetStrafeSpeed (directionNormal, -pev->maxspeed);
ResetCollideState (); ResetCollideState ();
if (nearestDistance < 56.0 && (dirToPoint | g_pGlobals->v_forward.SkipZ ()) < 0.0) if (nearestDistance < 56.0 && (dirToPoint | g_pGlobals->v_forward.Get2D ()) < 0.0)
m_moveSpeed = -pev->maxspeed; m_moveSpeed = -pev->maxspeed;
} }
} }
@ -345,6 +351,8 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
// FIXME: doesn't care for ladder movement (handled separately) should be included in some way // FIXME: doesn't care for ladder movement (handled separately) should be included in some way
if ((m_moveSpeed >= 10 || m_strafeSpeed >= 10) && m_lastCollTime < GetWorldTime ()) if ((m_moveSpeed >= 10 || m_strafeSpeed >= 10) && m_lastCollTime < GetWorldTime ())
{ {
bool cantMoveForward = false;
if (movedDistance < 2.0 && m_prevSpeed >= 1.0) // didn't we move enough previously? if (movedDistance < 2.0 && m_prevSpeed >= 1.0) // didn't we move enough previously?
{ {
// Then consider being stuck // Then consider being stuck
@ -357,7 +365,7 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
else // not stuck yet else // not stuck yet
{ {
// test if there's something ahead blocking the way // test if there's something ahead blocking the way
if (CantMoveForward (directionNormal, &tr) && !IsOnLadder ()) if ((cantMoveForward = CantMoveForward (directionNormal, &tr)) && !IsOnLadder ())
{ {
if (m_firstCollideTime == 0.0) if (m_firstCollideTime == 0.0)
m_firstCollideTime = GetWorldTime () + 0.2; m_firstCollideTime = GetWorldTime () + 0.2;
@ -376,7 +384,7 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
else else
{ {
// remember to keep pressing duck if it was necessary ago // remember to keep pressing duck if it was necessary ago
if (m_collideMoves[m_collStateIndex] == COLLISION_DUCK && IsOnFloor () || IsInWater ()) if (m_collideMoves[m_collStateIndex] == COLLISION_DUCK && (IsOnFloor () || IsInWater ()))
pev->button |= IN_DUCK; pev->button |= IN_DUCK;
} }
return; return;
@ -392,13 +400,15 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
bits = PROBE_STRAFE; bits = PROBE_STRAFE;
else if (IsInWater ()) else if (IsInWater ())
bits = (PROBE_JUMP | PROBE_STRAFE); bits = (PROBE_JUMP | PROBE_STRAFE);
else if (cantMoveForward)
bits = (PROBE_BACKOFF | PROBE_DUCK | PROBE_STRAFE);
else else
bits = ((Random.Long (0, 10) > 7 ? PROBE_JUMP : 0) | PROBE_STRAFE | PROBE_DUCK); bits = ((Random.Long (0, 10) > 5 ? PROBE_JUMP : 0) | PROBE_STRAFE | PROBE_DUCK);
// collision check allowed if not flying through the air // collision check allowed if not flying through the air
if (IsOnFloor () || IsOnLadder () || IsInWater ()) if (IsOnFloor () || IsOnLadder () || IsInWater ())
{ {
char state[8]; char state[10];
int i = 0; int i = 0;
// first 4 entries hold the possible collision states // first 4 entries hold the possible collision states
@ -406,6 +416,7 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
state[i++] = COLLISION_DUCK; state[i++] = COLLISION_DUCK;
state[i++] = COLLISION_STRAFELEFT; state[i++] = COLLISION_STRAFELEFT;
state[i++] = COLLISION_STRAFERIGHT; state[i++] = COLLISION_STRAFERIGHT;
state[i++] = COLLISION_BACKOFF;
// now weight all possible states // now weight all possible states
if (bits & PROBE_JUMP) if (bits & PROBE_JUMP)
@ -536,6 +547,26 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
state[i] = 0; state[i] = 0;
} }
if (bits & PROBE_BACKOFF)
{
state[i] = 0;
MakeVectors (m_moveAngles);
src = pev->origin;
dst = src - g_pGlobals->v_forward * 32;
TraceLine (src, dst, true, true, GetEntity (), &tr);
if (tr.flFraction != 1.0 || IsDeadlyDrop (dst))
state[i] -= 70;
else
state[i] += 40;
}
else
state[i] = 0;
i++;
// weighted all possible moves, now sort them to start with most probable // weighted all possible moves, now sort them to start with most probable
int temp = 0; int temp = 0;
bool isSorting = false; bool isSorting = false;
@ -543,26 +574,26 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
do do
{ {
isSorting = false; isSorting = false;
for (i = 0; i < 3; i++) for (i = 0; i < 4; i++)
{ {
if (state[i + 4] < state[i + 5]) if (state[i + 5] < state[i + 6])
{ {
temp = state[i]; temp = state[i];
state[i] = state[i + 1]; state[i] = state[i + 1];
state[i + 1] = temp; state[i + 1] = temp;
temp = state[i + 4]; temp = state[i + 5];
state[i + 4] = state[i + 5]; state[i + 5] = state[i + 6];
state[i + 5] = temp; state[i + 6] = temp;
isSorting = true; isSorting = true;
} }
} }
} while (isSorting); } while (isSorting);
for (i = 0; i < 4; i++) for (i = 0; i < 5; i++)
m_collideMoves[i] = state[i]; m_collideMoves[i] = state[i];
m_collideTime = GetWorldTime (); m_collideTime = GetWorldTime ();
@ -580,14 +611,14 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
m_collStateIndex++; m_collStateIndex++;
m_probeTime = GetWorldTime () + 0.5; m_probeTime = GetWorldTime () + 0.5;
if (m_collStateIndex > 4) if (m_collStateIndex > 5)
{ {
m_navTimeset = GetWorldTime () - 5.0; m_navTimeset = GetWorldTime () - 5.0;
ResetCollideState (); ResetCollideState ();
} }
} }
if (m_collStateIndex <= 4) if (m_collStateIndex <= 5)
{ {
switch (m_collideMoves[m_collStateIndex]) switch (m_collideMoves[m_collStateIndex])
{ {
@ -610,6 +641,11 @@ void Bot::CheckTerrain (float movedDistance, const Vector &dir, const Vector &di
pev->button |= IN_MOVERIGHT; pev->button |= IN_MOVERIGHT;
SetStrafeSpeed (directionNormal, pev->maxspeed); SetStrafeSpeed (directionNormal, pev->maxspeed);
break; break;
case COLLISION_BACKOFF:
pev->button |= IN_BACK;
m_moveSpeed = -pev->maxspeed;
break;
} }
} }
} }
@ -879,8 +915,6 @@ bool Bot::DoWaypointNav (void)
// need to find a button outside the lift // need to find a button outside the lift
if (m_liftState == LIFT_LOOKING_BUTTON_OUTSIDE) if (m_liftState == LIFT_LOOKING_BUTTON_OUTSIDE)
{ {
// lift is already used ?
bool liftUsed = false;
// button has been pressed, lift should come // button has been pressed, lift should come
if (m_buttonPushTime + 8.0 >= GetWorldTime ()) if (m_buttonPushTime + 8.0 >= GetWorldTime ())
@ -900,6 +934,9 @@ bool Bot::DoWaypointNav (void)
{ {
edict_t *button = FindNearestButton (STRING (m_liftEntity->v.targetname)); edict_t *button = FindNearestButton (STRING (m_liftEntity->v.targetname));
// lift is already used ?
bool liftUsed = false;
// if we got a valid button entity // if we got a valid button entity
if (!IsEntityNull (button)) if (!IsEntityNull (button))
{ {
@ -1244,7 +1281,7 @@ public:
return m_size == 0; return m_size == 0;
} }
inline PriorityQueue (int initialSize) inline PriorityQueue (int initialSize = MAX_WAYPOINTS * 0.5)
{ {
m_size = 0; m_size = 0;
m_heapSize = initialSize; m_heapSize = initialSize;
@ -1263,7 +1300,7 @@ public:
if (m_size >= m_heapSize) if (m_size >= m_heapSize)
{ {
m_heapSize += 100; m_heapSize += 100;
m_heap = (Node *)realloc (m_heap, sizeof (Node) * m_heapSize); m_heap = static_cast <Node *> (realloc (m_heap, sizeof (Node) * m_heapSize));
} }
m_heap[m_size].pri = pri; m_heap[m_size].pri = pri;
@ -1506,9 +1543,9 @@ float hfunctionSquareDist (int index, int, int goalIndex)
float zDist = fabsf (start->origin.z - goal->origin.z); float zDist = fabsf (start->origin.z - goal->origin.z);
if (xDist > yDist) if (xDist > yDist)
return 1.4 * yDist + (xDist - yDist) + zDist; return 1.4f * yDist + (xDist - yDist) + zDist;
return 1.4 * xDist + (yDist - xDist) + zDist; return 1.4f * xDist + (yDist - xDist) + zDist;
#endif #endif
} }
@ -1564,7 +1601,7 @@ void Bot::FindPath (int srcIndex, int destIndex, unsigned char pathType)
AStarState state; AStarState state;
} astar[MAX_WAYPOINTS]; } astar[MAX_WAYPOINTS];
PriorityQueue openList (MAX_WAYPOINTS * 0.5); PriorityQueue openList;
for (int i = 0; i < MAX_WAYPOINTS; i++) for (int i = 0; i < MAX_WAYPOINTS; i++)
{ {
@ -2468,12 +2505,9 @@ bool Bot::HeadTowardWaypoint (void)
bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr) bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr)
{ {
// Checks if bot is blocked in his movement direction (excluding doors) // checks if bot is blocked in his movement direction (excluding doors)
// use some TraceLines to determine if anything is blocking the current path of the bot. // use some TraceLines to determine if anything is blocking the current path of the bot.
Vector center = Vector (0, pev->angles.y, 0);
MakeVectors (center);
// first do a trace from the bot's eyes forward... // first do a trace from the bot's eyes forward...
Vector src = EyePosition (); Vector src = EyePosition ();
@ -2490,10 +2524,11 @@ bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr)
return true; // bot's head will hit something return true; // bot's head will hit something
} }
MakeVectors (Vector (0, pev->angles.y, 0));
// bot's head is clear, check at shoulder level... // bot's head is clear, check at shoulder level...
// trace from the bot's shoulder left diagonal forward to the right shoulder... // trace from the bot's shoulder left diagonal forward to the right shoulder...
src = EyePosition () + Vector (0, 0, -16) - g_pGlobals->v_right * 16; src = EyePosition () + Vector (0, 0, -16) - g_pGlobals->v_right * -16;
forward = EyePosition () + Vector (0, 0, -16) + g_pGlobals->v_right * 16 + normal * 24; forward = EyePosition () + Vector (0, 0, -16) + g_pGlobals->v_right * 16 + normal * 24;
TraceLine (src, forward, true, GetEntity (), tr); TraceLine (src, forward, true, GetEntity (), tr);
@ -2505,7 +2540,7 @@ bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr)
// bot's head is clear, check at shoulder level... // bot's head is clear, check at shoulder level...
// trace from the bot's shoulder right diagonal forward to the left shoulder... // trace from the bot's shoulder right diagonal forward to the left shoulder...
src = EyePosition () + Vector (0, 0, -16) + g_pGlobals->v_right * 16; src = EyePosition () + Vector (0, 0, -16) + g_pGlobals->v_right * 16;
forward = EyePosition () + Vector (0, 0, -16) - g_pGlobals->v_right * 16 + normal * 24; forward = EyePosition () + Vector (0, 0, -16) - g_pGlobals->v_right * -16 + normal * 24;
TraceLine (src, forward, true, GetEntity (), tr); TraceLine (src, forward, true, GetEntity (), tr);
@ -2537,7 +2572,7 @@ bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr)
else else
{ {
// trace from the left waist to the right forward waist pos // trace from the left waist to the right forward waist pos
src = pev->origin + Vector (0, 0, -17) - g_pGlobals->v_right * 16; src = pev->origin + Vector (0, 0, -17) - g_pGlobals->v_right * -16;
forward = pev->origin + Vector (0, 0, -17) + g_pGlobals->v_right * 16 + normal * 24; forward = pev->origin + Vector (0, 0, -17) + g_pGlobals->v_right * 16 + normal * 24;
// trace from the bot's waist straight forward... // trace from the bot's waist straight forward...
@ -2549,7 +2584,7 @@ bool Bot::CantMoveForward (const Vector &normal, TraceResult *tr)
// trace from the left waist to the right forward waist pos // trace from the left waist to the right forward waist pos
src = pev->origin + Vector (0, 0, -17) + g_pGlobals->v_right * 16; src = pev->origin + Vector (0, 0, -17) + g_pGlobals->v_right * 16;
forward = pev->origin + Vector (0, 0, -17) - g_pGlobals->v_right * 16 + normal * 24; forward = pev->origin + Vector (0, 0, -17) - g_pGlobals->v_right * -16 + normal * 24;
TraceLine (src, forward, true, GetEntity (), tr); TraceLine (src, forward, true, GetEntity (), tr);
@ -2906,7 +2941,6 @@ bool Bot::IsDeadlyDrop (const Vector &to)
if (tr.flFraction > 0.036) // We're not on ground anymore? if (tr.flFraction > 0.036) // We're not on ground anymore?
tr.flFraction = 0.036; tr.flFraction = 0.036;
float height;
float lastHeight = tr.flFraction * 1000.0; // height from ground float lastHeight = tr.flFraction * 1000.0; // height from ground
float distance = (to - check).GetLength (); // distance from goal float distance = (to - check).GetLength (); // distance from goal
@ -2923,7 +2957,7 @@ bool Bot::IsDeadlyDrop (const Vector &to)
if (tr.fStartSolid) // Wall blocking? if (tr.fStartSolid) // Wall blocking?
return false; return false;
height = tr.flFraction * 1000.0; // height from ground float height = tr.flFraction * 1000.0; // height from ground
if (lastHeight < height - 100) // Drops more than 100 Units? if (lastHeight < height - 100) // Drops more than 100 Units?
return true; return true;
@ -3113,15 +3147,31 @@ void Bot::FacePosition (void)
} }
else if (aimMethod == 3) else if (aimMethod == 3)
{ {
#if defined (NDEBUG)
Vector springStiffness (15.0f, 15.0f, 0.0f);
Vector damperCoefficient (0.22f, 0.22f, 0.0f);
Vector influence (0.26f, 0.18f, 0.0f);
Vector randomization (2.0f, 0.18f, 0.0f);
const float noTargetRatio = 0.6f;
const float offsetDelay = 0.5f;
const float targetRatio = 5.0f;
#else
Vector springStiffness (yb_aim_spring_stiffness_x.GetFloat (), yb_aim_spring_stiffness_y.GetFloat (), 0); Vector springStiffness (yb_aim_spring_stiffness_x.GetFloat (), yb_aim_spring_stiffness_y.GetFloat (), 0);
Vector damperCoefficient (yb_aim_damper_coefficient_x.GetFloat (), yb_aim_damper_coefficient_y.GetFloat (), 0); Vector damperCoefficient (yb_aim_damper_coefficient_x.GetFloat (), yb_aim_damper_coefficient_y.GetFloat (), 0);
Vector influence (yb_aim_influence_x_on_y.GetFloat (), yb_aim_influence_y_on_x.GetFloat (), 0); Vector influence (yb_aim_influence_x_on_y.GetFloat (), yb_aim_influence_y_on_x.GetFloat (), 0);
Vector randomization (yb_aim_deviation_x.GetFloat (), yb_aim_deviation_y.GetFloat (), 0); Vector randomization (yb_aim_deviation_x.GetFloat (), yb_aim_deviation_y.GetFloat (), 0);
const float noTargetRatio = yb_aim_notarget_slowdown_ratio.GetFloat ();
const float offsetDelay = yb_aim_offset_delay.GetFloat ();
const float targetRatio = yb_aim_target_anticipation_ratio.GetFloat ();
#endif
Vector stiffness = nullvec; Vector stiffness = nullvec;
Vector randomize = nullvec; Vector randomize = nullvec;
m_idealAngles = direction.SkipZ (); m_idealAngles = direction.Get2D ();
m_targetOriginAngularSpeed.ClampAngles (); m_targetOriginAngularSpeed.ClampAngles ();
m_idealAngles.ClampAngles (); m_idealAngles.ClampAngles ();
@ -3138,7 +3188,7 @@ void Bot::FacePosition (void)
if (IsValidPlayer (m_enemy)) if (IsValidPlayer (m_enemy))
{ {
m_targetOriginAngularSpeed = ((m_enemyOrigin - pev->origin + 1.5 * m_frameInterval * (1.0 * m_enemy->v.velocity) - 0.0 * g_pGlobals->frametime * pev->velocity).ToAngles () - (m_enemyOrigin - pev->origin).ToAngles ()) * 0.45 * yb_aim_target_anticipation_ratio.GetFloat () * static_cast <float> ((m_difficulty * 25) / 100); m_targetOriginAngularSpeed = ((m_enemyOrigin - pev->origin + 1.5 * m_frameInterval * (1.0 * m_enemy->v.velocity) - 0.0 * g_pGlobals->frametime * pev->velocity).ToAngles () - (m_enemyOrigin - pev->origin).ToAngles ()) * 0.45f * targetRatio * static_cast <float> ((m_difficulty * 25) / 100);
if (m_angularDeviation.GetLength () < 5.0) if (m_angularDeviation.GetLength () < 5.0)
springStiffness = (5.0 - m_angularDeviation.GetLength ()) * 0.25 * static_cast <float> ((m_difficulty * 25) / 100) * springStiffness + springStiffness; springStiffness = (5.0 - m_angularDeviation.GetLength ()) * 0.25 * static_cast <float> ((m_difficulty * 25) / 100) * springStiffness + springStiffness;
@ -3174,12 +3224,12 @@ void Bot::FacePosition (void)
m_randomizedIdealAngles = m_idealAngles + Vector (Random.Float (-randomize.x * 0.5, randomize.x * 1.5), Random.Float (-randomize.y, randomize.y), 0); m_randomizedIdealAngles = m_idealAngles + Vector (Random.Float (-randomize.x * 0.5, randomize.x * 1.5), Random.Float (-randomize.y, randomize.y), 0);
// set next time to do this // set next time to do this
m_randomizeAnglesTime = GetWorldTime () + Random.Float (0.4, yb_aim_offset_delay.GetFloat ()); m_randomizeAnglesTime = GetWorldTime () + Random.Float (0.4f, offsetDelay);
} }
float stiffnessMultiplier = yb_aim_notarget_slowdown_ratio.GetFloat (); float stiffnessMultiplier = noTargetRatio;
// take in account whether the bot was targeting someone in the last N seconds // take in account whether the bot was targeting someone in the last N seconds
if (GetWorldTime () - (m_playerTargetTime + yb_aim_offset_delay.GetFloat ()) < yb_aim_notarget_slowdown_ratio.GetFloat () * 10.0) if (GetWorldTime () - (m_playerTargetTime + offsetDelay) < noTargetRatio * 10.0)
{ {
stiffnessMultiplier = 1.0 - (GetWorldTime () - m_timeLastFired) * 0.1; stiffnessMultiplier = 1.0 - (GetWorldTime () - m_timeLastFired) * 0.1;
@ -3238,7 +3288,7 @@ void Bot::SetStrafeSpeed (const Vector &moveDir, float strafeSpeed)
MakeVectors (pev->angles); MakeVectors (pev->angles);
const Vector &los = (moveDir - pev->origin).Normalize2D (); const Vector &los = (moveDir - pev->origin).Normalize2D ();
float dot = los | g_pGlobals->v_forward.SkipZ (); float dot = los | g_pGlobals->v_forward.Get2D ();
if (dot > 0 && !CheckWallOnRight ()) if (dot > 0 && !CheckWallOnRight ())
m_strafeSpeed = strafeSpeed; m_strafeSpeed = strafeSpeed;

View file

@ -112,11 +112,11 @@ float GetShootingConeDeviation (edict_t *ent, Vector *position)
return g_pGlobals->v_forward | dir; return g_pGlobals->v_forward | dir;
} }
bool IsInViewCone (Vector origin, edict_t *ent) bool IsInViewCone (const Vector &origin, edict_t *ent)
{ {
MakeVectors (ent->v.v_angle); MakeVectors (ent->v.v_angle);
if (((origin - (ent->v.origin + ent->v.view_ofs)).Normalize () | g_pGlobals->v_forward) >= cosf (((ent->v.fov > 0 ? ent->v.fov : 90.0) * 0.5) * Math::MATH_PI / 180.0)) if (((origin - (ent->v.origin + ent->v.view_ofs)).Normalize () | g_pGlobals->v_forward) >= cosf (((ent->v.fov > 0 ? ent->v.fov : 90.0f) * 0.5f) * MATH_D2R))
return true; return true;
return false; return false;
@ -842,40 +842,6 @@ bool TryFileOpen (const char *fileName)
return false; return false;
} }
void HudMessage (edict_t *ent, bool toCenter, Vector rgb, char *format, ...)
{
if (!IsValidPlayer (ent) || IsValidBot (ent))
return;
va_list ap;
char buffer[1024];
va_start (ap, format);
vsprintf (buffer, format, ap);
va_end (ap);
MESSAGE_BEGIN (MSG_ONE, SVC_TEMPENTITY, NULL, ent);
WRITE_BYTE (TE_TEXTMESSAGE);
WRITE_BYTE (1);
WRITE_SHORT (FixedSigned16 (-1, 1 << 13));
WRITE_SHORT (FixedSigned16 (toCenter ? -1 : 0, 1 << 13));
WRITE_BYTE (2);
WRITE_BYTE (static_cast <int> (rgb.x));
WRITE_BYTE (static_cast <int> (rgb.y));
WRITE_BYTE (static_cast <int> (rgb.z));
WRITE_BYTE (0);
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (200);
WRITE_SHORT (FixedUnsigned16 (0.0078125, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (2, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (6, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (0.1, 1 << 8));
WRITE_STRING (const_cast <const char *> (&buffer[0]));
MESSAGE_END ();
}
void ServerPrint (const char *format, ...) void ServerPrint (const char *format, ...)
{ {
va_list ap; va_list ap;
@ -944,18 +910,10 @@ void ClientPrint (edict_t *ent, int dest, const char *format, ...)
if (IsEntityNull (ent) || ent == g_hostEntity) if (IsEntityNull (ent) || ent == g_hostEntity)
{ {
if (dest & 0x3ff)
ServerPrint (string); ServerPrint (string);
else
ServerPrint (string);
return; return;
} }
strcat (string, "\n"); strcat (string, "\n");
if (dest & 0x3ff)
(*g_engfuncs.pfnClientPrintf) (ent, static_cast <PRINT_TYPE> (dest &= ~0x3ff), FormatBuffer ("[YAPB] %s", string));
else
(*g_engfuncs.pfnClientPrintf) (ent, static_cast <PRINT_TYPE> (dest), string); (*g_engfuncs.pfnClientPrintf) (ent, static_cast <PRINT_TYPE> (dest), string);
} }
@ -1072,7 +1030,27 @@ void CheckWelcomeMessage (void)
ServerCommand ("speak \"%s\"", const_cast <char *> (sentences.GetRandomElement ().GetBuffer ())); ServerCommand ("speak \"%s\"", const_cast <char *> (sentences.GetRandomElement ().GetBuffer ()));
ChartPrint ("----- YaPB v%s (Build: %u), {%s}, (c) 2015, by %s -----", PRODUCT_VERSION, GenerateBuildNumber (), PRODUCT_DATE, PRODUCT_AUTHOR); ChartPrint ("----- YaPB v%s (Build: %u), {%s}, (c) 2015, by %s -----", PRODUCT_VERSION, GenerateBuildNumber (), PRODUCT_DATE, PRODUCT_AUTHOR);
HudMessage (g_hostEntity, true, Vector (Random.Long (33, 255), Random.Long (33, 255), Random.Long (33, 255)), "\nServer is running YaPB v%s (Build: %u)\nDeveloped by %s\n\n%s", PRODUCT_VERSION, GenerateBuildNumber (), PRODUCT_AUTHOR, g_waypoint->GetInfo ());
MESSAGE_BEGIN (MSG_ONE, SVC_TEMPENTITY, NULL, g_hostEntity);
WRITE_BYTE (TE_TEXTMESSAGE);
WRITE_BYTE (1);
WRITE_SHORT (FixedSigned16 (-1, 1 << 13));
WRITE_SHORT (FixedSigned16 (-1, 1 << 13));
WRITE_BYTE (2);
WRITE_BYTE (Random.Long (33, 255));
WRITE_BYTE (Random.Long (33, 255));
WRITE_BYTE (Random.Long (33, 255));
WRITE_BYTE (0);
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (Random.Long (230, 255));
WRITE_BYTE (200);
WRITE_SHORT (FixedUnsigned16 (0.0078125, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (2, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (6, 1 << 8));
WRITE_SHORT (FixedUnsigned16 (0.1, 1 << 8));
WRITE_STRING (FormatBuffer ("\nServer is running YaPB v%s (Build: %u)\nDeveloped by %s\n\n%s", PRODUCT_VERSION, GenerateBuildNumber (), PRODUCT_AUTHOR, g_waypoint->GetInfo ()));
MESSAGE_END ();
receiveTime = 0.0; receiveTime = 0.0;
isReceived = true; isReceived = true;

View file

@ -18,6 +18,10 @@ void Waypoint::Init (void)
{ {
// this function initialize the waypoint structures.. // this function initialize the waypoint structures..
m_learnVelocity = nullvec;
m_learnPosition = nullvec;
m_lastWaypoint = nullvec;
// have any waypoint path nodes been allocated yet? // have any waypoint path nodes been allocated yet?
if (m_waypointPaths) if (m_waypointPaths)
{ {
@ -1281,7 +1285,6 @@ bool Waypoint::IsNodeReachable (const Vector &src, const Vector &destination)
{ {
TraceResult tr; TraceResult tr;
float height, lastHeight;
float distance = (destination - src).GetLength (); float distance = (destination - src).GetLength ();
// is the destination not close enough? // is the destination not close enough?
@ -1335,7 +1338,7 @@ bool Waypoint::IsNodeReachable (const Vector &src, const Vector &destination)
TraceLine (check, down, ignore_monsters, g_hostEntity, &tr); TraceLine (check, down, ignore_monsters, g_hostEntity, &tr);
lastHeight = tr.flFraction * 1000.0; // height from ground float lastHeight = tr.flFraction * 1000.0; // height from ground
distance = (destination - check).GetLength (); // distance from goal distance = (destination - check).GetLength (); // distance from goal
while (distance > 10.0) while (distance > 10.0)
@ -1348,7 +1351,7 @@ bool Waypoint::IsNodeReachable (const Vector &src, const Vector &destination)
TraceLine (check, down, ignore_monsters, g_hostEntity, &tr); TraceLine (check, down, ignore_monsters, g_hostEntity, &tr);
height = tr.flFraction * 1000.0; // height from ground float height = tr.flFraction * 1000.0; // height from ground
// is the current height greater than the step height? // is the current height greater than the step height?
if (height < lastHeight - 18.0) if (height < lastHeight - 18.0)
@ -1802,12 +1805,11 @@ bool Waypoint::NodesValid (void)
int ctPoints = 0; int ctPoints = 0;
int goalPoints = 0; int goalPoints = 0;
int rescuePoints = 0; int rescuePoints = 0;
int connections;
int i, j; int i, j;
for (i = 0; i < g_numWaypoints; i++) for (i = 0; i < g_numWaypoints; i++)
{ {
connections = 0; int connections = 0;
for (j = 0; j < MAX_PATH_INDEX; j++) for (j = 0; j < MAX_PATH_INDEX; j++)
{ {
@ -1872,16 +1874,20 @@ bool Waypoint::NodesValid (void)
else if (m_paths[i]->index[k] == i) else if (m_paths[i]->index[k] == i)
{ {
AddLogEntry (true, LL_WARNING, "Waypoint %d - Pathindex %d points to itself!", i, k); AddLogEntry (true, LL_WARNING, "Waypoint %d - Pathindex %d points to itself!", i, k);
if (g_waypointOn && !IsDedicatedServer ())
{
(*g_engfuncs.pfnSetOrigin) (g_hostEntity, m_paths[i]->origin); (*g_engfuncs.pfnSetOrigin) (g_hostEntity, m_paths[i]->origin);
g_waypointOn = true; g_waypointOn = true;
g_editNoclip = true; g_editNoclip = true;
}
return false; return false;
} }
} }
} }
} }
if (g_mapType & MAP_CS) if (g_mapType & MAP_CS)
{ {
if (rescuePoints == 0) if (rescuePoints == 0)
@ -1951,11 +1957,14 @@ bool Waypoint::NodesValid (void)
if (!visited[i]) if (!visited[i])
{ {
AddLogEntry (true, LL_WARNING, "Path broken from Waypoint #0 to Waypoint #%d!", i); AddLogEntry (true, LL_WARNING, "Path broken from Waypoint #0 to Waypoint #%d!", i);
if (g_waypointOn && !IsDedicatedServer ())
{
(*g_engfuncs.pfnSetOrigin) (g_hostEntity, m_paths[i]->origin); (*g_engfuncs.pfnSetOrigin) (g_hostEntity, m_paths[i]->origin);
g_waypointOn = true; g_waypointOn = true;
g_editNoclip = true; g_editNoclip = true;
}
return false; return false;
} }
} }
@ -2008,11 +2017,14 @@ bool Waypoint::NodesValid (void)
if (!visited[i]) if (!visited[i])
{ {
AddLogEntry (true, LL_WARNING, "Path broken from Waypoint #%d to Waypoint #0!", i); AddLogEntry (true, LL_WARNING, "Path broken from Waypoint #%d to Waypoint #0!", i);
SET_ORIGIN (g_hostEntity, m_paths[i]->origin);
if (g_waypointOn && !IsDedicatedServer ())
{
(*g_engfuncs.pfnSetOrigin) (g_hostEntity, m_paths[i]->origin);
g_waypointOn = true; g_waypointOn = true;
g_editNoclip = true; g_editNoclip = true;
}
return false; return false;
} }
} }
@ -2452,14 +2464,11 @@ Waypoint::Waypoint (void)
m_learnJumpWaypoint = false; m_learnJumpWaypoint = false;
m_timeJumpStarted = 0.0; m_timeJumpStarted = 0.0;
m_learnVelocity = nullvec;
m_learnPosition = nullvec;
m_lastJumpWaypoint = -1; m_lastJumpWaypoint = -1;
m_cacheWaypointIndex = -1; m_cacheWaypointIndex = -1;
m_findWPIndex = -1; m_findWPIndex = -1;
m_visibilityIndex = 0; m_visibilityIndex = 0;
m_lastWaypoint = nullvec;
m_isOnLadder = false; m_isOnLadder = false;
m_pathDisplayTime = 0.0; m_pathDisplayTime = 0.0;