Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions aephysics/contact_solver_wide/module.ae
Original file line number Diff line number Diff line change
Expand Up @@ -1003,11 +1003,13 @@ store_wide_range(ctx: *StepContext, color: *GraphColor, start: int, end: int, hi
native.prefetch(next.manifolds.l7)
}
m = ptr_lane(&c.manifolds, l) as *Manifold
f1 = lane(c.friction_impulse.x, l)
f2 = lane(c.friction_impulse.y, l)
m.friction_impulse = math.narrow3(math.vec3(f1 * lane(c.tangent1.x, l) + f2 * lane(tangent2.x, l),
f1 * lane(c.tangent1.y, l) + f2 * lane(tangent2.y, l),
f1 * lane(c.tangent1.z, l) + f2 * lane(tangent2.z, l)))
// In single precision, as the reference stores it.
lw = l as long
f1 = lanes.lane8(c.friction_impulse.x, lw)
f2 = lanes.lane8(c.friction_impulse.y, lw)
m.friction_impulse = Vec3f { x: f1 * lanes.lane8(c.tangent1.x, lw) + f2 * lanes.lane8(tangent2.x, lw),
y: f1 * lanes.lane8(c.tangent1.y, lw) + f2 * lanes.lane8(tangent2.y, lw),
z: f1 * lanes.lane8(c.tangent1.z, lw) + f2 * lanes.lane8(tangent2.z, lw) }
m.twist_impulse = lane(c.twist_impulse, l)
m.rolling_impulse = Vec3f { x: lanes.lane8(c.rolling_impulse.x, l as long), y: lanes.lane8(c.rolling_impulse.y, l as long), z: lanes.lane8(c.rolling_impulse.z, l as long) }
point_count = m.point_count
Expand Down
9 changes: 3 additions & 6 deletions aephysics/dynamics/module.ae
Original file line number Diff line number Diff line change
Expand Up @@ -4056,8 +4056,7 @@ update_body_mass_data(w: *World, body: *Body) {
determinant = math.det(body.inertia)
if determinant > 0.0 {
sim.inv_inertia_local = math.narrow_mat3(math.invert_t(body.inertia))
rotation = math.make_matrix_from_quat(sim.transform.q)
sim.inv_inertia_world = math.narrow_mat3(math.mul_mm(math.mul_mm(rotation, math.widen_mat3(sim.inv_inertia_local)), math.transpose(rotation)))
sim.inv_inertia_world = math.rotate_inertiaf(math.narrow_quat(sim.transform.q), sim.inv_inertia_local)
}
// The centre of mass moves: the velocity follows the new material point.
old_center = sim.center
Expand Down Expand Up @@ -4112,8 +4111,7 @@ body_set_transform(id: BodyId, position: Vec3, rotation: Quat) {
sim.center = math.transform_point(sim.transform, math.widen3(sim.local_center))
sim.rotation0 = math.narrow_quat(rotation)
sim.center0 = sim.center
r = math.make_matrix_from_quat(rotation)
sim.inv_inertia_world = math.narrow_mat3(math.mul_mm(math.mul_mm(r, math.widen_mat3(sim.inv_inertia_local)), math.transpose(r)))
sim.inv_inertia_world = math.rotate_inertiaf(sim.rotation0, sim.inv_inertia_local)
shape_id = body.head_shape_id
while shape_id != NULL_INDEX {
s = world_shape_at(w, shape_id)
Expand Down Expand Up @@ -4424,8 +4422,7 @@ body_set_mass_data(id: BodyId, mass_data: MassData) {
determinant = math.det(body.inertia)
if determinant > 0.0 {
sim.inv_inertia_local = math.narrow_mat3(math.invert_t(body.inertia))
r = math.make_matrix_from_quat(sim.transform.q)
sim.inv_inertia_world = math.narrow_mat3(math.mul_mm(math.mul_mm(r, math.widen_mat3(sim.inv_inertia_local)), math.transpose(r)))
sim.inv_inertia_world = math.rotate_inertiaf(math.narrow_quat(sim.transform.q), sim.inv_inertia_local)
} else {
sim.inv_inertia_local = math.narrow_mat3(math.mat3_zero())
sim.inv_inertia_world = math.narrow_mat3(math.mat3_zero())
Expand Down
36 changes: 36 additions & 0 deletions aephysics/math/module.ae
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ exports (
mul_addf, mul_subf, mul_svf, crossf, normalizef, perpf, is_normalizedf,
min_vec3f, max_vec3f, lerpf, abs_f32, min_f32, max_f32, clamp_f32, sqrt_f32,
mul_mvf, add_mmf, transposef, detf, invert_matrixf, rotate_vectorf, inv_rotate_vectorf,
mul_mmf, make_matrix_from_quatf, rotate_inertiaf, abs_vec3f, modified_crossf,
mul_quatf, normalize_quatf,
PI, TWO_PI, PI_OVER_TWO, PI_OVER_FOUR, SQRT3, DEG_TO_RAD, RAD_TO_DEG, MIN_SCALE,
EPSILON, TINY, MAX_FLOAT, HUGE,
Expand Down Expand Up @@ -1342,6 +1343,41 @@ transposef(m: Matrix3f) -> Matrix3f {

detf(m: Matrix3f) -> f32 { return dotf(m.cx, crossf(m.cy, m.cz)) }

mul_mmf(a: Matrix3f, b: Matrix3f) -> Matrix3f { return Matrix3f { cx: mul_mvf(a, b.cx), cy: mul_mvf(a, b.cy), cz: mul_mvf(a, b.cz) } }

// b3MakeMatrixFromQuat: the rotation matrix of a unit quaternion.
make_matrix_from_quatf(q: Quatf) -> Matrix3f {
xx = q.x * q.x
yy = q.y * q.y
zz = q.z * q.z
xy = q.x * q.y
xz = q.x * q.z
xw = q.x * q.w
yz = q.y * q.z
yw = q.y * q.w
zw = q.z * q.w
return Matrix3f { cx: Vec3f { x: 1.0 - 2.0 * (yy + zz), y: 2.0 * (xy + zw), z: 2.0 * (xz - yw) },
cy: Vec3f { x: 2.0 * (xy - zw), y: 1.0 - 2.0 * (xx + zz), z: 2.0 * (yz + xw) },
cz: Vec3f { x: 2.0 * (xz + yw), y: 2.0 * (yz - xw), z: 1.0 - 2.0 * (xx + yy) } }
}

// A body's inverse inertia in world axes, R * I^-1 * R^T, in single
// precision as the reference keeps it (b3FinalizeBodiesTask,
// b3UpdateBodyMassData): the local inertia and the result are float, and
// the rotation is the body's, rounded to float.
rotate_inertiaf(q: Quatf, local: Matrix3f) -> Matrix3f {
rotation = make_matrix_from_quatf(q)
return mul_mmf(mul_mmf(rotation, local), transposef(rotation))
}

abs_vec3f(a: Vec3f) -> Vec3f { return Vec3f { x: abs_f32(a.x), y: abs_f32(a.y), z: abs_f32(a.z) } }

// b3ModifiedCross: the cross product with every term added, the bound of
// the arc an extent sweeps at the absolute angular rate.
modified_crossf(a: Vec3f, b: Vec3f) -> Vec3f {
return Vec3f { x: a.y * b.z + a.z * b.y, y: a.z * b.x + a.x * b.z, z: a.x * b.y + a.y * b.x }
}

// The inverse, or zero when singular.
invert_matrixf(m: Matrix3f) -> Matrix3f {
d = detf(m)
Expand Down
81 changes: 54 additions & 27 deletions aephysics/solver/module.ae
Original file line number Diff line number Diff line change
Expand Up @@ -236,40 +236,56 @@ integrate_positions(ctx: *StepContext) {
integrate_positions_range(ctx, 0, awake.body_states.count)
}

// The velocities, the change of position and the change of rotation are
// stored in single precision, and are advanced in it, as the reference
// advances them (b3IntegratePositionsTask): the speeds clamped, then the
// sub-step's motion added. Widened to double and back, the same sums cost
// six conversions a vector and a double square root a body.
integrate_positions_range(ctx: *StepContext, start: int, end: int) {
h = ctx.h
max_linear_speed = ctx.max_linear_velocity
max_angular_speed = MAX_ROTATION * ctx.inv_dt
h = ctx.h as f32
max_linear_speed = ctx.max_linear_velocity as f32
max_angular_speed = (MAX_ROTATION * ctx.inv_dt) as f32
max_linear_squared = max_linear_speed * max_linear_speed
max_angular_squared = max_angular_speed * max_angular_speed
i = start
while i < end {
state = state_at(ctx.states, i)
v = math.widen3(state.v)
wv = math.widen3(state.w)
v = state.v
wv = state.w
flags = state.flags
if (flags & dynamics.LOCK_LINEAR_X) != 0 { v.x = 0.0 }
if (flags & dynamics.LOCK_LINEAR_Y) != 0 { v.y = 0.0 }
if (flags & dynamics.LOCK_LINEAR_Z) != 0 { v.z = 0.0 }
if (flags & dynamics.LOCK_ANGULAR_X) != 0 { wv.x = 0.0 }
if (flags & dynamics.LOCK_ANGULAR_Y) != 0 { wv.y = 0.0 }
if (flags & dynamics.LOCK_ANGULAR_Z) != 0 { wv.z = 0.0 }
if math.dot(v, v) > max_linear_squared {
v = math.mul_sv(max_linear_speed / math.length(v), v)
if math.dotf(v, v) > max_linear_squared {
v = math.mul_svf(max_linear_speed / math.lengthf(v), v)
state.flags = state.flags | dynamics.IS_SPEED_CAPPED
}
if math.dot(wv, wv) > max_angular_squared && (flags & dynamics.ALLOW_FAST_ROTATION) == 0 {
wv = math.mul_sv(max_angular_speed / math.length(wv), wv)
if math.dotf(wv, wv) > max_angular_squared && (flags & dynamics.ALLOW_FAST_ROTATION) == 0 {
wv = math.mul_svf(max_angular_speed / math.lengthf(wv), wv)
state.flags = state.flags | dynamics.IS_SPEED_CAPPED
}
state.v = math.narrow3(v)
state.w = math.narrow3(wv)
state.dp = math.narrow3(math.mul_add(math.widen3(state.dp), h, v))
state.dq = math.narrow_quat(math.integrate_rotation(math.widen_quat(state.dq), math.mul_sv(h, wv)))
state.v = v
state.w = wv
state.dp = math.mul_addf(state.dp, h, v)
state.dq = integrate_rotationf(state.dq, math.mul_svf(h, wv))
i = i + 1
}
}

// b3IntegrateRotation in single precision, its sums in its order: the
// derivative (0.5 * delta, 0) * q, added to q, renormalised.
integrate_rotationf(q: Quatf, delta_rotation: Vec3f) -> Quatf {
half = math.mul_svf(0.5, delta_rotation)
qv = Vec3f { x: q.x, y: q.y, z: q.z }
// b3MulQuat(qd, q) with qd's scalar part zero.
t = math.mul_addf(math.mul_addf(math.crossf(half, qv), 0.0, qv), q.w, half)
qd_w = 0.0 * q.w - math.dotf(half, qv)
return math.normalize_quatf(Quatf { x: q.x + t.x, y: q.y + t.y, z: q.z + t.z, w: qd_w + q.w })
}

// --- continuous collision ------------------------------------------------------------------------------------

struct ContinuousContext {
Expand Down Expand Up @@ -508,23 +524,30 @@ finalize_range(start: int, end: int, worker: int, context: ptr) {
enable_sleep = w.enable_sleep
enable_continuous = w.enable_continuous
time_step = ctx.dt
inv_time_step = ctx.inv_dt
inv_time_step_f = ctx.inv_dt as f32
bullets = ctx.bullet_bodies as int[]
sim_index = start
while sim_index < end {
state = state_at(ctx.states, sim_index)
sim = sim_at(ctx.sims, sim_index)
v = math.widen3(state.v)
wv = math.widen3(state.w)
local_omega = math.inv_rotate_vector(sim.transform.q, wv)
local_delta_rotation = math.inv_rotate_vector(sim.transform.q, math.qv(math.widen_quat(state.dq)))
// The sleep velocity is the reference's single precision estimate
// (the rates, the extents and the step's motion are all float),
// under the rotation as it was before this step, rounded to float.
// The pose itself moves in double.
vf = state.v
wf = state.w
start_q = math.narrow_quat(sim.transform.q)
local_omega = math.inv_rotate_vectorf(start_q, wf)
local_delta_rotation = math.inv_rotate_vectorf(start_q, Vec3f { x: state.dq.x, y: state.dq.y, z: state.dq.z })
sim.center = math.add(sim.center, math.widen3(state.dp))
sim.transform.q = math.normalize_quat(math.mul_quat(math.widen_quat(state.dq), sim.transform.q))
velocity_arc = math.modified_cross(math.abs_vec3(local_omega), math.widen3(sim.max_extent))
max_velocity = math.length(v) + math.length(velocity_arc)
rotation_arc = math.modified_cross(math.abs_vec3(local_delta_rotation), math.widen3(sim.max_extent))
max_delta_position = math.length(math.widen3(state.dp)) + 2.0 * math.length(rotation_arc)
sleep_velocity = math.max_float(max_velocity, 0.5 * inv_time_step * max_delta_position)
velocity_arc = math.modified_crossf(math.abs_vec3f(local_omega), sim.max_extent)
max_velocity_f = math.lengthf(vf) + math.lengthf(velocity_arc)
rotation_arc = math.modified_crossf(math.abs_vec3f(local_delta_rotation), sim.max_extent)
max_delta_position_f = math.lengthf(state.dp) + 2.0 * math.lengthf(rotation_arc)
max_velocity = max_velocity_f as float
max_delta_position = max_delta_position_f as float
sleep_velocity = math.max_f32(max_velocity_f, 0.5 * inv_time_step_f * max_delta_position_f) as float
state.dp = math.vec3f_zero()
state.dq = math.quatf_identity()
sim.transform.p = math.sub(sim.center, math.rotate_vector(sim.transform.q, math.widen3(sim.local_center)))
Expand Down Expand Up @@ -562,8 +585,7 @@ finalize_range(start: int, end: int, worker: int, context: ptr) {
sim.rotation0 = math.narrow_quat(sim.transform.q)
body.sleep_time = body.sleep_time + time_step
}
rotation = math.make_matrix_from_quat(sim.transform.q)
sim.inv_inertia_world = math.narrow_mat3(math.mul_mm(math.mul_mm(rotation, math.widen_mat3(sim.inv_inertia_local)), math.transpose(rotation)))
sim.inv_inertia_world = math.rotate_inertiaf(math.narrow_quat(sim.transform.q), sim.inv_inertia_local)
island = dynamics.island_at(w, body.island_id)
if body.sleep_time < dynamics.TIME_TO_SLEEP {
basics.bitset_set(&tc.awake_island_bits, island.local_index)
Expand All @@ -584,8 +606,13 @@ finalize_range(start: int, end: int, worker: int, context: ptr) {
// when every contact does (enable_travel_speculation, #173); its
// shapes' own bounds stay where they are.
sweeps = ((w.enable_kinematic_speculation && body.kind == dynamics.BODY_KINEMATIC) || w.enable_travel_speculation) && time_step > 0.0
travel = math.mul_sv(time_step, v)
turn = time_step * math.length(wv) * math.length(math.widen3(sim.max_extent))
// The sweep's reach, worked out only for a body that sweeps.
travel = math.vec3_zero()
turn = 0.0
if sweeps {
travel = math.mul_sv(time_step, math.widen3(vf))
turn = time_step * math.length(math.widen3(wf)) * math.length(math.widen3(sim.max_extent))
}
while shape_id != NULL_INDEX {
s = dynamics.world_shape_at(w, shape_id)
s.aabb = shape.compute_fat_shape_aabb(&s.geometry, t, dynamics.SPECULATIVE_DISTANCE)
Expand Down
36 changes: 36 additions & 0 deletions bench/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1517,6 +1517,42 @@ GCC's -O3 heuristics decline them (they take a 72-byte matrix or a
32-byte quaternion by value, and grow as their own callees inline). The
budget stays; the case is with the Aether session.

### Single precision where the reference keeps it (2026-11-24, #236)

The suite now prints the solve's own stages under `AEPHYSICS_STAGES=1`,
and `bench/suite_box3d.c` the reference's beside them (`box3d solve
ms/step`). `AEPHYSICS_BENCH_NO_SLEEP=1` keeps every body awake in both,
so a long profile of a scene with few moving bodies (the large world)
keeps sampling their steps. Ours times every block and the reference
every stage, so our small stages read high by the clocks.

On the sleep scene two stages stood out beside the contact solver:
integrating the positions (0.068 ms against 0.044) and finalizing the
bodies (0.134 against 0.098). Both widened the float velocities and
motions to double, worked in double, and narrowed back, where the
reference works in float throughout: a body's sleep velocity took five
square roots of std.math (an out-of-line call, aether#3852), its world
inertia two double 3x3 products. Now the positions are integrated, the
sleep velocity estimated and the world inertia rotated (at all four
places it is made) in single precision, the reference's own sums; the
pose itself still moves in double. The sweep's reach is worked out only
for a body that sweeps, and the stored friction impulse is a float sum.

Pinned to one core, best of five, ms per step (before, after, Box3D):

| Scene | before | after | Box3D |
|---|---|---|---|
| sleep | 1.948 | 1.917 | 1.767 |
| large world | 0.0110 | 0.0107 | 0.0089 |
| convex pile | 9.63 | 9.49 | 8.57 |
| washer | 15.23 | 15.08 | 14.36 |

The results move (the golden trace and the figures' hashes in
test_human): the falling ragdolls sleep at step 256 where they slept at
271 (the reference's own builds: 273 and 274). That is the pile's chaos,
not the estimate: the sleep estimate alone back in double still sleeps
at 256, the inertia alone back in double at 264.

## Build flags (inlining)

Since Aether 0.937.0 (aether#3779) `ae build` gives an optimising build
Expand Down
8 changes: 8 additions & 0 deletions bench/suite.ae
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import aephysics.distance
import aephysics.dynamics
import aephysics.joint_solver
import aephysics.physics_world
import aephysics.solver

extern calloc(count: int, size: int) -> ptr
extern free(p: ptr)
Expand Down Expand Up @@ -123,6 +124,10 @@ run_steps(steps: int) -> int {

run(name: string, world_id: WorldId, scene_steps: int, scene: int) {
steps = run_steps(scene_steps)
// AEPHYSICS_BENCH_NO_SLEEP=1: no body sleeps, so a long profile of a
// scene with few moving bodies keeps sampling their steps.
no_sleep = os.getenv("AEPHYSICS_BENCH_NO_SLEEP")
if no_sleep != null && string.equals(no_sleep, "1") == 1 { physics_world.enable_sleeping(world_id, false) }
scene_step(scene, world_id, 0)
physics_world.step(world_id, TIME_STEP, SUB_STEPS)
pairs_ms = 0.0
Expand Down Expand Up @@ -154,6 +159,9 @@ run(name: string, world_id: WorldId, scene_steps: int, scene: int) {
println("aephysics suite: ${name}: ${steps} steps of ${counters.body_count} bodies ${ms(t1 - t0)} ms, ${ms(t1 - t0) / timed} ms per step (height sum ${height_sum(world_id)}, ${counters.contact_count} contacts, ${counters.joint_count} joints, ${awake} awake)")
println("aephysics phases ms/step: pairs ${pairs_ms / timed} collide ${collide_ms / timed}")
println("aephysics stages ms/step: solve ${solve_ms / timed} transforms ${transforms_ms / timed} refit ${refit_ms / timed} sleep ${sleep_ms / timed} sensors ${sensors_ms / timed}")
// The solve's own stages under AEPHYSICS_STAGES=1, beside the
// reference's (bench/suite_box3d.c prints the same columns).
solver.stage_report()
spinner_joint = g_spinner as JointId[]
if spinner_joint[0].index1 != 0 {
println("aephysics spinner angle ${joint_solver.revolute_joint_get_angle(spinner_joint[0])}")
Expand Down
20 changes: 20 additions & 0 deletions bench/suite_box3d.c
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ static void Run( const Scene* scene )

b3WorldId worldId = b3CreateWorld( &worldDef );
scene->create( worldId );
// AEPHYSICS_BENCH_NO_SLEEP=1, as bench/suite.ae reads it.
const char* noSleep = getenv( "AEPHYSICS_BENCH_NO_SLEEP" );
if ( noSleep != NULL && strcmp( noSleep, "1" ) == 0 )
{
b3World_EnableSleeping( worldId, false );
}

float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
Expand All @@ -83,6 +89,9 @@ static void Run( const Scene* scene )
}

double pairs = 0.0, collide = 0.0, solve = 0.0, transforms = 0.0, refit = 0.0, sleep = 0.0, sensors = 0.0;
// The solve's own stages, as bench/physics_world_box3d.c sums them, to
// read beside ours (AEPHYSICS_STAGES=1).
double prepare = 0.0, integrateV = 0.0, warm = 0.0, impulses = 0.0, integrateP = 0.0, relax = 0.0, restitution = 0.0, store = 0.0;
double t0 = now_ms();
for ( int stepIndex = 1; stepIndex < steps; ++stepIndex )
{
Expand All @@ -99,6 +108,14 @@ static void Run( const Scene* scene )
refit += p.refit;
sleep += p.sleepIslands;
sensors += p.sensors;
prepare += p.prepareConstraints;
integrateV += p.integrateVelocities;
warm += p.warmStart;
impulses += p.solveImpulses;
integrateP += p.integratePositions;
relax += p.relaxImpulses;
restitution += p.restitution;
store += p.storeImpulses;
}
double t1 = now_ms();

Expand All @@ -110,6 +127,9 @@ static void Run( const Scene* scene )
printf( "box3d phases ms/step: pairs %.6f collide %.6f\n", pairs / timed, collide / timed );
printf( "box3d stages ms/step: solve %.6f transforms %.6f refit %.6f sleep %.6f sensors %.6f\n", solve / timed, transforms / timed,
refit / timed, sleep / timed, sensors / timed );
printf( "box3d solve ms/step: prepare %.6f integrate_v %.6f warm %.6f solve %.6f integrate_p %.6f relax %.6f restitution %.6f store %.6f\n",
prepare / timed, integrateV / timed, warm / timed, impulses / timed, integrateP / timed, relax / timed, restitution / timed,
store / timed );
if ( strcmp( scene->name, "spinner" ) == 0 )
{
printf( "box3d spinner angle %.6f\n", GetSpinnerAngle() );
Expand Down
Loading
Loading