Problem: Bounding Box Collision Detection and Resolution

The problem is to create a Python system for 2D/3D box physics, including validated box creation (high precision), SAT-based collision detection (AABBs/OBBs), penetration calculation, and collision resolution (position/velocity updates) to enable dynamic box interactions in simulations.

Background: ### Industry Background Knowledge for Rigid Body Collision System Implementation
This code suite implements core components of a rigid body collision system, widely used in game development, robotics simulation, virtual reality (VR), and autonomous vehicle testing. Below is the technical context required to reproduce and extend this functionality:

#### 1. Core Domain Foundations
Rigid body dynamics and collision detection/response are critical for simulating physical interactions between objects. Key industry requirements include numerical stability, geometric precision, and real-time performance—all addressed in these implementations.

#### 2. Mathematical & Algorithmic Background
- **High-Precision Arithmetic**: The `create_box` function uses Python's `decimal` module with 32-digit precision to eliminate floating-point representation errors. This is essential for applications like CAD (Computer-Aided Design) and robotics path planning where exact coordinate calculations are required.
- **Inertia Tensor Calculation**: For rectangular prisms, the inertia tensor components follow the formula:
  \[
  I_{xx} = \frac{1}{12}m(h^2 + d^2),\quad I_{yy} = \frac{1}{12}m(w^2 + d^2),\quad I_{zz} = \frac{1}{12}m(w^2 + h^2)
  \]
  This models rotational inertia in physics simulations, used in engines like Unity and Unreal for realistic object motion.
- **Quaternion Rotation**: Quaternions avoid gimbal lock issues in 3D rotation. The identity quaternion `(1.0, 0.0, 0.0, 0.0)` (default in `create_box`) represents no rotation, and quaternion multiplication enables smooth rotational transitions.
- **Separating Axis Theorem (SAT)**: Used in `check_collision` and `resolve_collision` to detect convex shape collisions. For 2D oriented bounding boxes (OBBs), 4 axes are tested (2 edge normals per box). If no axis separates the projections of the two shapes, a collision is confirmed.
- **Sutherland-Hodgman Algorithm**: Implemented in `calculate_penetration` to compute the intersection polygon of two convex shapes, enabling precise penetration area calculation for collision response.
- **Impulse-Based Collision Resolution**: In `resolve_collision`, the impulse \( j \) is calculated using:
  \[
  j = -\frac{(1 + e)(\vec{v}_{rel} \cdot \vec{n})}{\frac{1}{m_1} + \frac{1}{m_2}}
  \]
  where \( e \) is the restitution coefficient (bounciness), \( \vec{v}_{rel} \) is relative velocity, and \( \vec{n} \) is the collision normal. This updates object velocities to simulate realistic collisions.

#### 3. Implementation Best Practices
- **Input Validation**: All functions validate input types, required keys, and positive dimensions to ensure robustness in production systems.
- **Numerical Stability**: Epsilon values (e.g., `1e-12`) handle floating-point precision edge cases, preventing false collision detection or penetration calculation errors.
- **Type Hints**: PEP 484 type hints improve code maintainability, critical for collaboration in large engineering teams.
- **Leveraged Libraries**:
  - `decimal`: High-precision arithmetic for critical geometric calculations
  - `numpy`: Efficient vector/matrix operations for 2D/3D coordinate transformations
  - `math`: Trigonometric functions for rotation and collision axis calculations

#### 4. Industry Application Context
- **Game Development**: Used for character-environment interactions, physics-based puzzles, and realistic object destruction.
- **Robotics Simulation**: Tools like Gazebo use these algorithms to test robot motion planning and obstacle avoidance in virtual environments.
- **Autonomous Vehicles**: Simulation platforms model collisions between vehicles, pedestrians, and obstacles to validate safety systems.
- **CAD/CAE**: Collision detection ensures parts do not interfere in assembly design, while penetration calculation aids in tolerance analysis.

This background provides the necessary context to reproduce, adapt, and extend the code for specific industry use cases, ensuring alignment with real-world performance and accuracy requirements.

Required Imports:
```python
from typing import Dict, Union
from decimal import Decimal, getcontext
import numpy as np
import math
```

Input/Output: The problem accepts four Python functions with specified inputs: create_box takes x, y (int/float, top-left coordinates), w, h (non-negative int/float, dimensions); check_collision takes two box dictionaries (with x, y, w, h, optional angle); calculate_penetration takes two box dictionaries (with cx, cy, w, h, optional theta); resolve_collision takes two box dictionaries (with cx, cy, w, h, angle, vx, vy, mass). All inputs require validation (numeric types, non-negative dimensions, required keys). The problem generates outputs: create_box returns a dictionary with original coordinates (x, y, w, h), 3D centers (cx, cy, cz), mass, velocity (vx, vy, vz), inertia tensor (inertia_xx, inertia_yy, inertia_zz), and quaternion (quat_w, quat_x, quat_y, quat_z); check_collision returns a boolean for collision status; calculate_penetration returns a tuple of x/y penetration values and center coordinate differences; resolve_collision returns the modified first box dictionary with corrected position and velocity. Processing includes high-precision decimal arithmetic for create_box, Separating Axis Theorem (SAT) for collision detection in check_collision, clipping for intersection calculation in calculate_penetration, and restitution-based velocity update in resolve_collision.

Required dependencies:
from typing import Dict, Union
from decimal import Decimal, getcontext
import math
import numpy as np

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named create_box. It accepts x,y,w,h (int/float), validates their types and non-negative width/height. Uses high-precision decimal arithmetic to calculate centers (cx,cy,cz), inertia tensor, rotation quaternion. Returns a dict containing original coordinates, centers, mass, velocity, inertia, and quaternion values.
function_header: def create_box(x, y, w, h):
test_cases: import math
test_create = [
    (0, 0, 10, 10, {'x': 0, 'y': 0, 'w': 10, 'h': 10, 'cx': 5.0, 'cy': 5.0}),
    (10, 20, 4, 8, {'x': 10, 'y': 20, 'w': 4, 'h': 8, 'cx': 12.0, 'cy': 24.0}),
    (-5, -5, 2, 2, {'x': -5, 'y': -5, 'w': 2, 'h': 2, 'cx': -4.0, 'cy': -4.0})
]
for x, y, w, h, expected in test_create:
    res = create_box(x, y, w, h)
    assert all(math.isclose(res[k], expected[k]) for k in expected)

step_number: 2
step_description_prompt: Please write a Python function named check_collision that takes two box dicts (with x,y,w,h, optional angle). First validate inputs (required keys, numeric values, positive dimensions). For rotated boxes, use SAT (4 axes) for OBB collision. For non-rotated, use center-half-extent AABB check to return collision result.
function_header: def check_collision(box1, box2):
test_cases: import math
b1 = create_box(0, 0, 10, 10)
for b2_params, expected in [
    ((5, 5, 10, 10), True),    # 相交
    ((11, 0, 10, 10), False),  # X 轴分离
    ((0, 10, 10, 10), False)   # 边缘接触（逻辑中 <= 判定为不碰撞）
]:
    b2 = create_box(*b2_params)
    assert check_collision(b1, b2) == expected

step_number: 3
step_description_prompt: Please write a Python function named calculate_penetration. It takes two box dicts (cx, cy, w, h required; optional theta, cz). Validate input validity first, convert boxes to global coordinates using rotation, compute their intersection, then return px, py (x/y penetration), dx, dy (cx/cy differences as floats).

function_header: def calculate_penetration(box1, box2):
test_cases: import math
b1 = create_box(0, 0, 10, 10)
test_pen = [
    ((8, 0, 10, 10), (2.0, 10.0, 8.0, 0.0)),  # X轴重叠2, Y轴完全重叠10
    ((0, 9, 2, 2), (1.0, 1.0, 0.0, 9.0)),     # X轴居中重叠(1+5-0)=6? 不，cx2=1,cx1=5,abs(dx)=4, px=1+5-4=2
    ((0, 0, 10, 10), (10.0, 10.0, 0.0, 0.0))  # 完全重合
]
for b2_p, (exp_px, exp_py, exp_dx, exp_dy) in [((8, 0, 10, 10), (2.0, 10.0, 8.0, 0.0)), ((0, 9, 10, 10), (10.0, 1.0, 0.0, 9.0))]:
    b2 = create_box(*b2_p)
    px, py, dx, dy = calculate_penetration(b1, b2)
    assert math.isclose(px, exp_px) and math.isclose(py, exp_py)

step_number: 4
step_description_prompt: Please write a Python function named resolve_collision. It accepts two box dictionaries (with keys cx, cy, w, h, angle, vx, vy, mass). Use Separating Axis Theorem to detect collision, find collision normal and minimal penetration, correct positions to resolve penetration, update velocities using restitution, then return the modified first box.
function_header: def resolve_collision(box1, box2):
test_cases: # Test resolve_collision (验证碰撞分离：沿最小穿透轴移动)
import math
for b1_p, b2_p, exp_x, exp_y in [
    ((0, 0, 10, 10), (9, 5, 10, 10), -0.792, 0.0), # px=1, py=5 -> 沿X轴向左移动1
    ((0, 0, 10, 10), (5, 9, 10, 10), 0.0, -0.792), # px=5, py=1 -> 沿Y轴向下移动1
    ((0, 0, 2, 2), (5, 5, 2, 2), 0.0, 0.0)       # 无碰撞，位置不改变
]:
    b1, b2 = create_box(*b1_p), create_box(*b2_p)
    res = resolve_collision(b1, b2)
    assert math.isclose(res['x'], exp_x) and math.isclose(res['y'], exp_y)

General solution:

General tests: