Certainly! Below is the enhanced version of your Touchreward class. This modification incorporates scaling based on both the distance to the closest wall and the touch height. Additionally, it includes the cutoff logic to disable the reward if the ball is too high or about to score.
Key Enhancements:
- Distance to Closest Wall Scaling: The reward is scaled based on the distance of the ball from the closest wall. Closer proximity to walls can influence the reward to encourage strategic touches.
- Touch Height Scaling: The reward is also influenced by the height at which the ball is touched, promoting touches at optimal heights.
- Cutoff Logic: If the ball is too high or about to score, the reward is disabled to prevent undesired behaviors.
Modified Touchreward Class:
#include <algorithm> // For std::min and std::max
#include <cmath> // For sqrt and powf
class Touchreward : public RewardFunction {
public:
Vec prevVel;
Touchreward() : prevVel(Vec(0, 0, 0)) {}
virtual void Reset(const GameState& initialState) override {
prevVel = Vec(0, 0, 0);
}
// Function to calculate the distance to the closest wall
static float DistToClosestWall(float x, float y) {
float dist_side_wall = std::abs(4096.0f - std::abs(x));
float dist_back_wall = std::abs(5120.0f - std::abs(y));
// Corner calculation
float x1 = 4096.0f - 1152.0f;
float y1 = 5120.0f;
float x2 = 4096.0f;
float y2 = 5120.0f - 1152.0f;
float A = std::abs(x) - x1;
float B = std::abs(y) - y1;
float C = x2 - x1;
float D = y2 - y1;
float dot = A * C + B * D;
float len_sq = C * C + D * D;
float param = (len_sq != 0) ? dot / len_sq : -1.0f;
float xx, yy;
if (param < 0.0f) {
xx = x1;
yy = y1;
}
else if (param > 1.0f) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
float dx = std::abs(x) - xx;
float dy = std::abs(y) - yy;
float dist_corner_wall = std::sqrt(dx * dx + dy * dy);
return std::min({ dist_side_wall, dist_back_wall, dist_corner_wall });
}
virtual float GetReward(const PlayerData& player, const GameState& state, const Action& prevAction) override {
float reward = 0.0f;
// Calculate distance to the closest wall
float distance = DistToClosestWall(state.ball.pos.x, state.ball.pos.y);
// Normalize distance (assuming max distance is around 5120 units)
float distanceScale = 1.0f - (distance / 5120.0f);
distanceScale = std::clamp(distanceScale, 0.0f, 1.0f);
// Calculate touch height scaling
float touchHeight = state.ball.pos.z;
// Assuming a reasonable max height, e.g., 3000 units
float heightScale = 1.0f - (std::abs(touchHeight) / 3000.0f);
heightScale = std::clamp(heightScale, 0.0f, 1.0f);
if (player.ballTouchedStep) {
float velDiff = (prevVel - state.ball.vel).Length();
float currentVel = state.ball.vel.Length();
// Original reward based on velocity
float baseReward = (velDiff + currentVel) / (3000.0f * 2.0f);
baseReward = std::clamp(baseReward, 0.0f, 1.0f); // Ensure baseReward is between 0 and 1
// Combine with distance and height scaling
reward = baseReward * distanceScale * heightScale;
/*
// Debugging output
std::cout << "Vel diff: " << velDiff << "\n"
<< "Curr Vel: " << currentVel << "\n"
<< "Distance Scale: " << distanceScale << "\n"
<< "Height Scale: " << heightScale << "\n"
<< "Combined Reward: " << reward << "\n"
<< "Ball Pos: " << state.ball.pos << "\n"
<< "Previous Vel: " << prevVel << "\n";
*/
}
// Update previous velocity
prevVel = state.ball.vel;
// Implement cutoff logic based on touch height and extrapolated position
const float MIN_SCORE_TIME = 0.5f; // Example threshold, adjust as needed
const float MAX_EXTRAP_Z = 3000.0f; // Maximum allowable height, adjust as needed
float goalY = RLConst::SOCCAR_GOAL_SCORE_BASE_THRESHOLD_Y * (player.team == Team::BLUE ? 1.0f : -1.0f);
float distToGoalY = std::abs(state.ball.pos.y - goalY);
float velY = std::max(std::abs(state.ball.vel.y), 0.01f);
float extrapScoreTime = distToGoalY / velY;
Vec extrapScorePos = state.ball.pos + state.ball.vel * extrapScoreTime;
extrapScorePos.z += (CommonValues::GRAVITY_Z * (extrapScoreTime * extrapScoreTime)) / 2.0f;
if (extrapScoreTime <= MIN_SCORE_TIME || extrapScorePos.z >= MAX_EXTRAP_Z) {
reward = 0.0f; // Disable reward if the ball is about to score or go too high
}
return reward;
}
};
Explanation of Modifications:
-
Distance Scaling (distanceScale):
- Calculation: The distance to the closest wall is obtained using the
DistToClosestWall function. This distance is then normalized by dividing by the maximum expected distance (assumed to be 5120.0f units). The result is inverted (1.0f - ...) so that closer distances yield higher scaling factors.
- Clamping: Ensures that the scaling factor stays within
[0.0f, 1.0f].
-
Height Scaling (heightScale):
- Calculation: The height (
z position) of the ball is used to determine the scaling factor. Similar to distance scaling, it is normalized and inverted to favor lower touches.
- Assumption: A maximum height of
3000.0f units is used for normalization. Adjust this value based on your game's mechanics.
- Clamping: Ensures that the scaling factor stays within
[0.0f, 1.0f].
-
Combining Scales with Base Reward:
- The base reward, originally based on velocity differences, is multiplied by both
distanceScale and heightScale. This ensures that the reward is highest when the touch is both effective (in terms of velocity) and strategically positioned (in terms of distance and height).
-
Cutoff Logic:
- Goal Y Calculation: Determines the Y-coordinate of the goal based on the player's team.
- Extrapolated Score Time (
extrapScoreTime): Estimates the time it would take for the ball to reach the goal Y-coordinate based on its current Y-velocity.
- Extrapolated Position (
extrapScorePos): Predicts the future position of the ball after extrapScoreTime, including the effect of gravity.
- Conditions: If the ball is about to score (
extrapScoreTime <= MIN_SCORE_TIME) or its extrapolated Z-position is too high (extrapScorePos.z >= MAX_EXTRAP_Z), the reward is set to 0.0f to discourage such actions.
-
Additional Considerations:
- Clamping Base Reward: Ensures that the base reward derived from velocities does not exceed .
Notes:
- Constants: Ensure that constants like
MIN_SCORE_TIME, MAX_EXTRAP_Z, and normalization factors (5120.0f, 3000.0f) are set according to your game's specific requirements and mechanics.
- Vec Operations: The
Vec class is assumed to support necessary operations like subtraction and scalar multiplication. Ensure that these are properly defined in your codebase.
- Gravity (
CommonValues::GRAVITY_Z): Ensure that the gravity constant accurately reflects the physics in your game.
- Reward Scaling: You can experiment with different scaling functions (
sqrt, powf, etc.) for distanceScale and heightScale to better fit the desired behavior.
This implementation provides a more nuanced reward function that takes into account both the strategic positioning of touches and the physical dynamics of the ball, leading to more intelligent and effective behaviors in your reinforcement learning agent.