You've hit a common issue when transforming Axis-Aligned Bounding Boxes (AABBs) from model space to world space, especially when dealing with negative world positions. The problem stems from how AABBs are defined and how transformations interact with their minimum and maximum extents. Here's a breakdown of the issue and how to fix it, along with explanations and code examples:
Understanding the Problem
AABB's are defined by a minimum and maximum point. These points represent the corners of the box. When you transform an AABB, you need to transform both the minimum and maximum points. A naive approach of simply applying the transformation matrix to the center and then adding/subtracting the half-extents can fail when the world position is negative because the half-extents are applied after the transformation, potentially leading to incorrect bounds.
Why it fails with negative positions:
Imagine a box centered at (0,0,0) with half-extents (1,1,1). Its corners are (-1,-1,-1) to (1,1,1).
Now, let's say you want to move this box to world position (-5, -5, -5).
The Correct Solution: Transform All 8 Corners
The most robust and accurate way to transform an AABB is to transform all eight of its corners using the model-to-world transformation matrix. Then, you find the new minimum and maximum points from the transformed corners.
Code Example (GLSL-like pseudocode, adaptable to your environment):
// Assuming:
// - aabb_min: vec3 representing the minimum corner of the AABB in model space
// - aabb_max: vec3 representing the maximum corner of the AABB in model space
// - model_to_world_matrix: mat4 representing the transformation from model space to world space
vec3 transformed_corners[8];
// Calculate the 8 corners of the AABB in model space
transformed_corners[0] = vec3(aabb_min.x, aabb_min.y, aabb_min.z);
transformed_corners[1] = vec3(aabb_min.x, aabb_min.y, aabb_max.z);
transformed_corners[2] = vec3(aabb_min.x, aabb_max.y, aabb_min.z);
transformed_corners[3] = vec3(aabb_min.x, aabb_max.y, aabb_max.z);
transformed_corners[4] = vec3(aabb_max.x, aabb_min.y, aabb_min.z);
transformed_corners[5] = vec3(aabb_max.x, aabb_min.y, aabb_max.z);
transformed_corners[6] = vec3(aabb_max.x, aabb_max.y, aabb_min.z);
transformed_corners[7] = vec3(aabb_max.x, aabb_max.y, aabb_max.z);
// Transform each corner to world space
vec3 world_corners[8];
for (int i = 0; i < 8; ++i) {
world_corners[i] = model_to_world_matrix * transformed_corners[i];
}
// Find the new minimum and maximum corners in world space
vec3 world_aabb_min = world_corners[0];
vec3 world_aabb_max = world_corners[0];
for (int i = 1; i < 8; ++i) {
world_aabb_min = min(world_aabb_min, world_corners[i]);
world_aabb_max = max(world_aabb_max, world_corners[i]);
}
// Now world_aabb_min and world_aabb_max contain the correct AABB in world space