196 lines
30 KiB
Markdown
196 lines
30 KiB
Markdown
# physics
|
||||
|
|
The numbers of physical space and what's in it, as games, their renderers, and their physics work them, in five libraries:
|
|||
|
|
|
|||
|
|
| Library | What it is |
|
|||
|
|
|---|---|
|
|||
|
|
| `malunal.linear` | Vectors of two, three, and four `f32`s, rotations as quaternions, and matrices of three by three and four by four |
|
|||
|
|
| `malunal.geometry` | The shapes of space made of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them |
|
|||
|
|
| `malunal.photometry` | Light in the units it's measured in, lumens, candela, lux, and nits, converted between them; exposure values; and the colors of temperatures |
|
|||
|
|
| `malunal.physics2d` | What collides in a plane: circles, capsules, and convex polygons, where and how deep two meet, rays, a tree of boxes, and a grid of solid cells, as a tilemap's walls are |
|
|||
|
|
| `malunal.physics3d` | What collides in space: spheres, capsules, and convex hulls, boxes among them, where and how deep two meet, rays, a tree of boxes, and the triangles of a surface, as a level's ground and walls are |
|
|||
|
|
|
|||
|
|
It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads only std's `containers`, `math`, and `serial`. An executable optimized with `-O2` works what `linear` and `geometry` do to whole vectors as SIMD lanes, which the virtual machine works a number at a time, giving the same bits. It was the package `linear`, of `linear` and `geometry`, until `photometry`, `physics2d`, and `physics3d` joined them.
|
|||
|
|
|
|||
|
|
```sakura
|
|||
|
|
import std::math;
|
|||
|
|
import malunal::linear;
|
|||
|
|
|
|||
|
|
val up := vec3::up;
|
|||
|
|
var at := vec3{ 1, 2, 3 };
|
|||
|
|
at = at + vec3{ x = 0.5 } * 2; # vec3{ 2, 2, 3 }
|
|||
|
|
val ahead := at.cross(up).normalized();
|
|||
|
|
val far := at.dot(ahead) + at.length;
|
|||
|
|
|
|||
|
|
val turn := quat::axis_angle(vec3::back, math::pi as f32 / 2);
|
|||
|
|
val turned := turn * vec3::right; # vec3::up, as near as f32 gets
|
|||
|
|
val both := quat::euler(0.3, -1.1, 0.7) * turn; # turn, then the other
|
|||
|
|
|
|||
|
|
val place := mat4::compose(vec3{ 5, 0, -2 }, turn, vec3::one);
|
|||
|
|
val moved := place.transform_point(vec3::zero); # vec3{ 5, 0, -2 }
|
|||
|
|
val clip := mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 100) * mat4::look_at(vec3{ 0, 2, 10 }, vec3::zero);
|
|||
|
|
|
|||
|
|
val inertia := mat3::rotation(turn) * mat3::scaling(vec3{ 2, 1, 1 }) * mat3::rotation(turn).transposed();
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
```sakura
|
|||
|
|
import malunal::linear;
|
|||
|
|
import malunal::geometry;
|
|||
|
|
|
|||
|
|
val seen := frustum::of(clip); # the camera's six planes, facing in
|
|||
|
|
val crate := bounds::around(vec3{ 4, 1, -6 }, vec3::one);
|
|||
|
|
val drawn := seen.overlaps(crate); # true: it's in view
|
|||
|
|
val under := ray::toward(vec3{ 0, 2, 10 }, crate.center);
|
|||
|
|
val reach := under.hit(crate) is some(t) ? t : -1; # how far along it meets the box
|
|||
|
|
val ground := plane::through(vec3::zero, vec3::up);
|
|||
|
|
val lying := ground.side_of(sphere{ vec3{ 0, 0.5, 0 }, 1 }); # side::across
|
|||
|
|
val carried := crate.transformed(place); # the box holding the crate moved
|
|||
|
|
```
|
|||
|
|
```sakura
|
|||
|
|
import malunal::linear;
|
|||
|
|
import malunal::photometry;
|
|||
|
|
|
|||
|
|
val bulb := candela_of_lumens(lumens::bulb_60w); # about 63.7 candela, every way
|
|||
|
|
val torch := candela_of_lumens(300, 0.2); # 300 lumens gathered into a cone of 0.2 radians each way
|
|||
|
|
val lit := lux_of_candela(bulb, 2); # what it lights a surface 2 meters away with
|
|||
|
|
val metered := ev100_of_lux(lux::office); # about 7.3, as a meter where it's lit reads
|
|||
|
|
val scale := exposure_of_ev100(metered); # what light in nits is multiplied by, so exposed
|
|||
|
|
val warm := color_of_temperature(2700); # a warm bulb's color, linear sRGB
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
```sakura
|
|||
|
|
import malunal::linear;
|
|||
|
|
import malunal::physics2d;
|
|||
|
|
|
|||
|
|
val crate := shape::box(vec2{ 0.5, 0.5 });
|
|||
|
|
val ball := shape::circle(0.25);
|
|||
|
|
val met := collide(&crate, pose::of(vec2{ 0, 0 }), &ball, pose::of(vec2{ 0.6, 0.1 })); # the manifold: normal, points, depths
|
|||
|
|
val ray := crate.ray_cast(pose::of(vec2{ 3, 0 }, 0.3), vec2::zero, vec2{ 1, 0 }, 10); # where a ray first meets the turned crate
|
|||
|
|
|
|||
|
|
var tree := aabb_tree::new();
|
|||
|
|
val leaf := tree.insert(crate.bounds(pose::identity), 7); # a box and a number of the user's
|
|||
|
|
tree.query(aabb::around(vec2::zero, vec2{ 2, 2 }), def(leaf: u32, data: u64): bool { ...; return true; });
|
|||
|
|
|
|||
|
|
var walls := grid::new(20, 10); # solid cells, as a tilemap's walls
|
|||
|
|
walls.set(3, 0, true);
|
|||
|
|
walls.collide(pose::identity, &ball, pose::of(vec2{ 3.5, 1.2 }), def(x: u32, y: u32, m: manifold): bool { ...; return true; });
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
```sakura
|
|||
|
|
import malunal::linear;
|
|||
|
|
import malunal::physics3d;
|
|||
|
|
|
|||
|
|
val crate := shape::box(vec3{ 0.5, 0.5, 0.5 });
|
|||
|
|
val rock := shape::hull_of(places.view()).expect("..."); # the convex hull of places, as many as 32 its corners
|
|||
|
|
val met := collide(&crate, pose::identity, &rock, pose::of(vec3{ 0.2, 0.9, 0 }, turn)); # the manifold: normal, one to four points, depths
|
|||
|
|
val hit := crate.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, vec3{ 1, 0, 0 }, 10); # where a ray first meets the crate
|
|||
|
|
|
|||
|
|
val ground := triangle_mesh::new(points.view(), indices.view()); # a level's triangles, in a tree of their own
|
|||
|
|
ground.collide(pose::identity, &crate, pose::of(vec3{ 0, 0.45, 0 }), 0, def(t: u32, m: manifold): bool { ...; return true; });
|
|||
|
|
```
|
|||
|
|
`tests/linear.sakura`, `tests/geometry.sakura`, `tests/photometry.sakura`, `tests/physics2d.sakura`, and `tests/physics3d.sakura` drive all of it, and `tools/bench.sakura` and `tools/geometry_bench.sakura` time `linear` and `geometry`.
|
|||
|
|
|
|||
|
|
A project reads it by requiring this folder, or its remote, and naming the libraries it uses among a target's `deps`, as `malunal.geometry`, whose module is `malunal::geometry`; each brings `malunal.linear`, which they read:
|
|||
|
|
|
|||
|
|
```yaml
|
|||
|
|
requires:
|
|||
|
|
- https://git.malunal.studio/malunal/physics@v1.0.0
|
|||
|
|
targets:
|
|||
|
|
- name: game
|
|||
|
|
type: program
|
|||
|
|
deps: [malunal.geometry, malunal.photometry, malunal.physics2d, malunal.physics3d]
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## Layout
|
|||
|
|
| Path | Holds |
|
|||
|
|
|---|---|
|
|||
|
|
| `linear/linear.sakura` | The conventions, and reading a value of four `f32`s as one `f32x4` where it lies |
|
|||
|
|
| `linear/vec2.sakura` | `vec2`: a place or direction in a plane |
|
|||
|
|
| `linear/vec3.sakura` | `vec3`: a place or direction in space, and the axes' directions |
|
|||
|
|
| `linear/vec4.sakura` | `vec4`: a place of space with its `w`, as a matrix projects one |
|
|||
|
|
| `linear/quat.sakura` | `quat`: rotations by an axis and angle, by angles about each axis, by where they look, and of a basis; turning vectors, following, undoing, and `slerp` |
|
|||
|
|
| `linear/mat3.sakura` | `mat3`: rotations, scales, and what turns directions, as an inertia tensor; transposes, determinants, and inverses |
|
|||
|
|
| `linear/mat4.sakura` | `mat4`: moving, turning, scaling, and composing them; perspective and orthographic projections; `look_at`; points and directions moved; inverses |
|
|||
|
|
| `geometry/geometry.sakura` | The conventions of `geometry`, and the dot products and lanes its shapes are worked with |
|
|||
|
|
| `geometry/ray.sakura` | `ray`: a half line from a place, its places, and where it first meets a plane, a sphere, or a box |
|
|||
|
|
| `geometry/plane.sakura` | `plane`: through a place or three, how far a place is in front, and which `side` of it a box or sphere lies on |
|
|||
|
|
| `geometry/bounds.sakura` | `bounds`: a box along the axes, of places or a sphere; what it holds and meets; grown, merged, and moved by a matrix |
|
|||
|
|
| `geometry/sphere.sakura` | `sphere`: what it holds and meets, and the least one holding a box |
|
|||
|
|
| `geometry/frustum.sakura` | `frustum`: the six planes of what a projection sees, and whether a place, a box, or a sphere is within them |
|
|||
|
|
| `photometry/photometry.sakura` | The units, and lumens, candela, lux, and nits converted between them, of lights every way and within cones; lumens of watts; and what's commonly lit, as `lux::office`, `nits::clear_sky`, and `lumens::bulb_60w` |
|
|||
|
|
| `photometry/exposure.sakura` | Exposure values at ISO 100, of a camera's settings or what its meter reads, and what light is multiplied by, so exposed |
|
|||
|
|
| `photometry/temperature.sakura` | The color of a black body's light at a temperature, as lamps' colors are named |
|
|||
|
|
| `physics2d/physics2d.sakura` | The conventions of `physics2d`, and the nearest points of segments |
|
|||
|
|
| `physics2d/pose.sakura` | `rot`, a rotation in the plane, and `pose`, where a body is and which way it's turned |
|
|||
|
|
| `physics2d/aabb.sakura` | `aabb`, a box along the plane's axes: what it holds and meets, grown, merged, and where a ray meets it |
|
|||
|
|
| `physics2d/shape.sakura` | `shape`: circles, capsules, segments, boxes, and convex polygons, as the hull of places; the box holding one, what it holds, and where a ray first meets it |
|
|||
|
|
| `physics2d/collide.sakura` | `collide` and `overlaps`: the `manifold` of where two shapes meet, its normal and one or two points, each with its depth |
|
|||
|
|
| `physics2d/tree.sakura` | `aabb_tree`: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray |
|
|||
|
|
| `physics2d/grid.sakura` | `grid`: solid cells, the manifolds of a shape against them, but for the faces they share, and rays passed from cell to cell |
|
|||
|
|
| `physics3d/physics3d.sakura` | The conventions of `physics3d`, and the nearest points of segments |
|
|||
|
|
| `physics3d/pose.sakura` | `pose`, where a body is in space and which way it's turned, as a place and a quaternion |
|
|||
|
|
| `physics3d/hull.sakura` | `hull`: a convex polyhedron's corners, faces, and edges; made as a box, as a triangle, or around places, coplanar triangles made one face |
|
|||
|
|
| `physics3d/shape.sakura` | `shape`: spheres, capsules, boxes, and convex hulls; the box holding one, what it holds, and where a ray first meets it |
|
|||
|
|
| `physics3d/collide.sakura` | `collide` and `overlaps`: the `manifold` of where two shapes meet, its normal and one to four points, each with its depth and the features that met |
|
|||
|
|
| `physics3d/tree.sakura` | `aabb_tree`: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray |
|
|||
|
|
| `physics3d/mesh.sakura` | `triangle_mesh`: the triangles of a surface, in a tree, their shared edges flat or hollow passed over, met by shapes and rays |
|
|||
|
|
|
|||
|
|
## How it works
|
|||
|
|
- **Space** is right-handed: x to the right, y up, z toward the viewer, so a camera looks down its -z. Matrices are column-major, as GLSL reads them, and multiply a vector on their right, so `a * b` does `b`, then `a`, as quaternions' products do. Projections give a clip space of y up and depth from 0 at the near plane to 1 at the far one, as Vulkan's with its y flipped. Angles are radians.
|
|||
|
|
- **Plain fields**: each type is of `f32` fields, aligned as an `f32`, so a struct holding one lays it out wherever it falls, as C and the GPU do, and the virtual machine reads a field as quickly as any. `vec3` holds a fourth `f32` no one names, so it's 16 bytes, an `f32x4`'s, as `vec4` and `quat` are. It's 0 as a literal leaves it, as `vec3{ 1, 2, 3 }` and `vec3{ y = 1 }` do, and printing a `vec3` shows it as `_w`. A `mat3`'s columns are `vec3`s, so it's laid out as std140 lays out a GLSL `mat3`; a `mat4` is its 16 numbers, column after column.
|
|||
|
|
- **Lanes**: an executable optimized with `-O2` holds `simd` vectors in registers, so it reads a `vec3`, `vec4`, or `quat` as one `f32x4` from where it is, aligned or not, and works lanes at once: adding, subtracting, scaling, and dividing vectors, their least, greatest, and absolute numbers, `lerp`, dots, lengths, `distance`, and `normalized`, and what a matrix makes of a vector or another matrix, each of its columns scaled by a number splat into every lane, and added, as a `quat` turns a vector by its matrix. What gathers one vector's numbers into other lanes, as a cross product or a quaternions' product would, it works a number at a time, as `simd::shuffle` gathers them a lane at a time. `lanes_held()` says which way while compiling, so only that way's code is kept. `lanes()` and `of_lanes` give a `vec3`'s, `vec4`'s, or `quat`'s numbers as an `f32x4`, for code of one's own to work.
|
|||
|
|
- **The same bits**: the virtual machine, which works lanes one at a time, and constants work everything a number at a time, in the order the lanes do, so either way gives the same bits; `tests/linear.sakura` folds the bits of a long chain of operations, and the machine and an executable each check they're those.
|
|||
|
|
- **Shapes**: `geometry`'s shapes are of `linear`'s vectors and plain `f32`s. A `frustum` is of a matrix's clip space as `linear`'s projections make it, so `frustum::of(projection * view)` gives the world's planes, and `frustum::of(projection)` the camera's; it holds its planes' numbers a lane each, so an executable tests a place, a box, or a sphere against four planes at once, then the other two. A box against a frustum is tested by its corner furthest in front of each plane, so one beside a corner of the frustum, outside it but in front of every plane, counts as seen, which draws it for nothing, and one in view always counts. A place on a shape's surface is within it, and two shapes touching meet. A ray's distances are counted in lengths of its direction, so they're distances where it's of length 1, as `ray::toward` makes it, and a ray beginning within a sphere or box meets it at 0. What gives a number of a few, as a dot product does, is worked a number at a time: of the lanes of `vec3::dot`, then worked as numbers, a ray's tests ran two to three times as slow. A ray's test against a box compares its numbers rather than calling `math::min` and `math::max`, which keep NaN and `-0` as IEEE 754 orders them at three times the cost, so a ray running along a face, in its plane, may meet the box or pass by.
|
|||
|
|
- **Written and read**: each type but `frustum` is `@serial`, so `std::serial`, and any format of it, as `std::yaml` and `std::json`, writes and reads it: a vector or rotation as a mapping of its numbers, as `{x: 1, y: 0.1, z: -2.5}`, each the shortest text reading back as the same `f32`, with `vec3`'s fourth number left out; a `mat3` as its axes; a `mat4` as a sequence of its 16 numbers, column after column; and `geometry`'s shapes by their fields. Read with `serial::options{ defaults = true }`, a number left out is 0, and a rotation's `w` 1. A `frustum` holds its planes as lanes, and is made again of its matrix.
|
|||
|
|
- **Light's units**: `photometry` gives each of light's quantities in its own unit, as real lights are measured: a source's luminous flux in lumens, all the light it gives, as a bulb is sold by; its luminous intensity in candela, the light it gives one way, in each steradian; the illuminance of a surface in lux, the light falling on it; and a surface's or a sky's luminance in nits, candela a square meter, the light it gives back toward an eye. A light every way spreads its lumens over 4π steradians, and one within a cone over the cone's solid angle, 2π(1 - cos angle), of its angle from its axis to its edge, as glTF gives a spot light's; a surface so far from a light of so many candela is lit by candela over the distance squared; and a matte surface gives back what lights it over π, by the fraction it gives back. An exposure value at ISO 100 is of a camera's aperture, shutter, and ISO, or of what a meter reads, calibrated as reflected-light meters are, by 12.5, and incident-light meters, by 250, so a scene exposed as a meter where it's lit reads gives a white surface about two thirds of the most a camera records, 1.2 × 2^EV100 nits, and middle grey about an eighth. A temperature's color is of Krystek's fit of the Planckian locus, made linear sRGB of CIE 1931's XYZ. What's commonly lit and sold is named as constants of empty types, so `lux::office` and `lumens::bulb_60w` read as what they are.
|
|||
|
|
- **Collision in a plane**: `physics2d` takes each shape as a hull, its points where its pose places them, and its radius around them: a circle of one point, a capsule of two, of no radius a segment, and a polygon of three to eight corners, counterclockwise, each edge's normal facing out. Two circles meet as their middles near; a circle and a hull as the circle's middle nears the hull's edges, or lies within it; and two hulls by the edge of either holding them furthest apart, as the separating axis theorem finds it. Where their hulls overlap, or their round sides near along a face, the other's nearest edge is clipped to the face, as Box2D clips one, so a box resting flat on another, or a capsule lying on one, meets it at two points; where only their round sides meet, at one, along the line between the hulls' nearest points. A manifold's normal is from the first shape toward the second, and each point midway between their surfaces, with how deep the one is within the other; two shapes touching meet, at a depth of 0. A ray meets a circle by its quadratic, a polygon as Cyrus and Beck clip a line by each edge's side, and a capsule by its flat sides between its ends, else its round ends; one beginning within a shape meets it at 0, facing back along it.
|
|||
|
|
- **The tree**: an `aabb_tree` keeps a box and a number of the user's at each leaf, each branch the least box holding its two children, so a query passes down only the branches that reach what it asks, and a ray's narrows as it meets what's nearer. A leaf's box is grown by the tree's margin, so what moves a little stays within it and the tree isn't changed; a leaf is put where it grows the boxes above it least, and each branch it passes is turned, as an AVL tree turns one, where one child is two or more deeper than the other: 500 boxes in any order make a tree 18 deep at most.
|
|||
|
|
- **Grids**: a `grid` holds solid cells, from its origin at the bottom left of its first, each a box of its cell size. A shape meets each solid cell it reaches as a box, but a manifold pushing it into a solid neighbor, along the axis it pushes most, is passed over, as that's a face two cells share: so a body sliding along a floor of many cells slides as along one, never caught on the seams between them, the ghost collisions of tile maps. A ray passes from cell to cell as Amanatides and Woo pass one, entering by a face, which is its normal.
|
|||
|
|
- **Collision in space**: `physics3d` takes each shape as a core with its radius around it: a sphere's a place, a capsule's a segment, and a hull itself, of no radius. A hull is plain data, as many as 32 corners, its faces convex polygons, counterclockwise from outside, and each edge between two faces; `hull::of` makes the least one around places by adding them one at a time, the furthest first, each replacing the faces it sees with faces from their horizon to it, then makes the triangles of one plane one face, so a box of eight places is six squares. Two spheres or capsules meet as their cores near, a capsule lying along another at two points. A sphere or capsule and a hull meet as the core nears the hull's surface, by its places nearest a face it's in front of and its edges', a capsule lying along a face at two; or, where the core passes within the hull, by the face, or the axis across an edge and the segment, holding them furthest apart. Two hulls meet by the face of either, or the pair of edges, one of each, holding them furthest apart, as the separating axis theorem finds it, testing only the pairs of edges whose arcs on the sphere of directions cross, as Gregorius tests them, so they're a face of the hulls' Minkowski difference; a flat hull's edges, a triangle's, are tested by how far the hulls reach along each axis. At a face, the other's face most against it is clipped to its sides, as Sutherland and Hodgman clip, at as many as four points, those holding most of what the rest hold; at two edges, at one, between them. A face of the second hull is taken over the first's only where it holds them apart by a millimeter and 2 percent more, and an edge over a face by a millimeter and 5 percent, so the same pair meets the same way from one step to the next, as deep as it is to within those. Each point has an id of the features that met there, for a solver to carry over what it found; within a `margin`, shapes apart are given points too, of depths below 0. A ray meets a sphere by its quadratic, a capsule's side as Ericson meets a cylinder, and its ends as spheres, and a hull as Cyrus and Beck clip a line by each face's side.
|
|||
|
|
- **Meshes**: a `triangle_mesh` keeps its triangles, those of no area left out, in a tree of their boxes, and a shape meets each triangle it reaches as a flat hull. An edge two triangles share is passed over where they're flat, turning less than 5 degrees, or hollow, as Jolt's active edges are: a shape meeting a triangle by such an edge, or a corner of such edges only, is pushed out as the triangle's face pushes it, as deep as it is below the face's plane, so a body sliding across a floor of many triangles slides as along one. A ray meets each triangle from either side, as Möller and Trumbore find it, its normal facing back along the ray.
|
|||
|
|
- **Nothing fused**: a product is rounded before it's added, not fused with the sum as `fma` does. FMA3 works a fused sum as one instruction, but a column waiting on the sum before it is slower than one adding products worked at once: `mat4 * mat4` took 39 cycles fused, against 32, and `transform_point` 7 against 6. The same bits would also have the machine work each fused sum as `std::math::fma` does without FMA3, many instructions for one.
|
|||
|
|
|
|||
|
|
## Speed
|
|||
|
|
`blossom run malunal.linear.bench` works each operation over 1,024 values 2,000 times, each pass a function of its own, as a system is, its operations called from elsewhere too, built with `-O2`, here on an i5-13420H held at 2.1 GHz by its low-power profile, against the same worked a number at a time on a `vec3` of 12 bytes, as hearth's scenes worked them before `linear`. They need the compiler of 2026-10-28 or later, which works `f32`s in single precision and splats a number into lanes with one instruction; before it, what a matrix made of a vector was faster a number at a time.
|
|||
|
|
|
|||
|
|
| What | Before | `linear` | |
|
|||
|
|
|---|---|---|---|
|
|||
|
|
| `p + v * dt` of `vec3`s | 9.66 ns | 2.00 ns | 4.8x |
|
|||
|
|
| `dot` of `vec3`s | 3.83 ns | 3.84 ns | 1.0x |
|
|||
|
|
| `vec3::normalized` | 13.4 ns | 2.85 ns | 4.7x |
|
|||
|
|
| `quat * vec3` | 68.6 ns | 24.9 ns | 2.8x |
|
|||
|
|
| `mat4 * mat4` | 35.7 ns | 13.5 ns | 2.6x |
|
|||
|
|
| `mat4::transform_point` | 11.1 ns | 2.67 ns | 4.2x |
|
|||
|
|
| `mat3 * mat3` | 42.0 ns | 5.26 ns | 8.0x |
|
|||
|
|
| `quat * quat` | 16.8 ns | 15.3 ns | 1.1x |
|
|||
|
|
| `vec3::cross` | 11.2 ns | 12.8 ns | 0.88x |
|
|||
|
|
| `mat3 * vec3` | | 2.64 ns | |
|
|||
|
|
| `mat4 * vec4` | | 2.95 ns | |
|
|||
|
|
| `mat4::inverse` | | 96.4 ns | |
|
|||
|
|
|
|||
|
|
What works whole vectors gains most, and what a matrix makes of a vector with it: integrating places by velocities, as physics does for every body, is nearly five times as fast, and `mat3 * mat3` eight. What builds a `vec3` a number at a time, as `cross` does, runs about as it did of 12 bytes, since the caller reads the 16 bytes back at once, which waits on the numbers written one at a time. How fast the same operation runs hangs on the code around it, by as much as three times either way, as code inlined into a large function slows; these are of small functions, as a game's systems are. hearth's scenes turning 2,000 entities' transforms, a rotation's product, `normalized`, and a `mat4` composed for each, took 42.7 ns an entity on a Ryzen 9 9950X3D, as they did before `linear`, with the compiler before 2026-10-28.
|
|||
|
|
|
|||
|
|
`blossom run malunal.geometry.bench` times `geometry`'s tests the same way, here on battery, in the low-power profile, the best of five runs, against the same written a number at a time on a `vec3` of 12 bytes, a plane at a time, and with `math::min` and `math::max`:
|
|||
|
|
|
|||
|
|
| What | Before | `geometry` | |
|
|||
|
|
|---|---|---|---|
|
|||
|
|
| `frustum::overlaps` of `bounds` | 20.3 ns | 10.0 ns | 2.0x |
|
|||
|
|
| `frustum::overlaps` of a `sphere` | 7.38 ns | 4.50 ns | 1.6x |
|
|||
|
|
| `ray::hit` of `bounds` | 61.2 ns | 19.7 ns | 3.1x |
|
|||
|
|
| `ray::hit` of a `sphere` | 10.9 ns | 12.0 ns | 0.91x |
|
|||
|
|
| `bounds::transformed` | 25.2 ns | 22.1 ns | 1.1x |
|
|||
|
|
|
|||
|
|
Culling a scene's boxes by a camera's frustum, which a renderer does for everything it might draw, is twice as fast, of four planes at once: of eight, as one `f32x8`, it was no faster than a plane at a time, and in one build twice as slow, as the compiler moves vectors of 32 bytes through memory a half at a time where a function works several. A ray meeting a box is three times as fast for comparing its numbers. A ray meeting a sphere works as the plain code does, but gives a `maybe<f32>`, which the compiler returns through memory.
|
|||
|
|
|
|||
|
|
## Testing
|
|||
|
|
`blossom test` runs `tests/linear.sakura` twice: `malunal.linear.tests` on the machine, a number at a time, with every read and write checked, and `malunal.linear.lanes.tests` as an executable built with `-O2`, as lanes. Each checks the types' sizes; vectors' arithmetic, dots, crosses, lengths, and the rest; rotations turning, following one another, undone, and between; projections, and undoing them; matrices of three's rotations, scales, transposes, determinants, and inverses; values read where a struct puts them, unaligned; values written as JSON and read back; and the bits of a long chain of all of it.
|
|||
|
|
|
|||
|
|
It runs `tests/geometry.sakura` the same two ways, as `malunal.geometry.tests` and `malunal.geometry.lanes.tests`: the shapes' sizes; planes through places, distances to them, and which side a box or sphere lies on; boxes and spheres holding places and boxes, meeting, grown, merged, and moved; rays meeting planes, spheres, and boxes from outside, from within, and passing by; a camera's frustum of a perspective and of an orthographic projection, its planes facing in, and what it reaches; shapes written as JSON and read back; and the bits of a long chain of all of it. The bits are folded by `math::wrapping_mul`, as FNV-1a wraps, which a checked program's own arithmetic must name.
|
|||
|
|
|
|||
|
|
`malunal.photometry.tests` runs `tests/photometry.sakura`: lumens and candela of bulbs every way and gathered into cones, and of watts; lux at distances, and nits of surfaces lit by them, white and grey, and of a clear sky; exposure values of the sunny 16 rule, at another ISO, and of meters, what they multiply light by and back, and a white surface and a grey card exposed as a meter reads, from moonlight to sunlight; and the colors of a warm bulb, of daylight, and of a blue sky, bluer as hotter all the way, and past either end as either.
|
|||
|
|
|
|||
|
|
`malunal.physics2d.tests` runs `tests/physics2d.sakura`: rotations and poses, within one another and found again; boxes' corners and normals, polygons around places, leaving out what's within and along their edges, and none of a line or of nine corners, capsules, pills, the boxes holding turned shapes, and what they hold; circles meeting circles, touching, and apart, a ball on a box's face, by its corner, and within it, both ways around, and a ball by a capsule's side; a box resting on a slab at two points, apart, and the other way around, a crate on its corner at one, a capsule lying on the slab at two and standing by its corner at one, capsules side by side and crossing, and a segment across a box; rays meeting a ball, from within it, passing by, and short of it, a turned box, a capsule's side and end, and a segment from either side; 500 boxes in a tree, sound, moved and half removed, found as a brute search finds them, the nearest along a ray, and every one removed; and a grid's floor and wall met, a box resting across two cells, sunk over a seam, the face the cells share passed over, against the wall, the grid placed elsewhere, and rays into its floor and wall, from outside it, short of it, and from within a cell.
|
|||
|
|
|
|||
|
|
`malunal.physics3d.tests` runs `tests/physics3d.sakura`: poses, within one another, found again, and undone; boxes' faces facing out, each edge between two at right angles, turned and moved; hulls around a cube's corners and places within it, on its faces, and along its edges, of six square faces, a tetrahedron, and an icosahedron of 20 triangles, and none of flat places or of 40 corners; triangles, flat; spheres and capsules meeting, touching, apart, and within a margin, capsules lying along one another at two points and crossing at one; a ball on a box's face, by its edge, by its corner, within it, both ways around, and over a turned box; a capsule lying on a box at two points, standing by its edge at one, and stood within it; a crate resting on a slab at four points, apart, within a margin, the other way around, and turned, on its edge at two, on its corner at one, and edge across edge at one; rays meeting a ball, a turned box, and a capsule's side, along and across it, and its end; 500 boxes in a tree, as in `physics2d`'s; and a room of triangles, a floor of 128 and a wall: a crate resting across four squares, a ball sunk beside a seam pushed up by every triangle, against the wall, and in its corner, and rays into its floor, from below it, and into its wall. Then, against searches of their own: 400 pairs of boxes and of hulls of places, turned every way, met where no axis of every face and every pair of edges parts them, and as deep as the axis parting them least, to within the faces taken over others as good; and 200 spheres and capsules against turned boxes, met as their nearest places say, a capsule's found among a thousand along its segment.
|
|||
|
|
|
|||
|
|
## Not yet
|
|||
|
|
Vectors of several values at once, as eight `vec3`s in three `f32x8`s, which physics passes over its bodies with, and which the bench's own tries found ten to twenty times as fast as one at a time; `f64` vectors; and `vec2`s worked as lanes, which hold half an `f32x4`. Of `geometry`: triangles, capsules, and boxes turned with what they hold, and rays and the tests between them; testing many boxes against a frustum at once, their numbers lanes of several; and the frustum of a projection whose depth runs the other way, or without end. Of `photometry`: radiometric units and spectra, and luminance of what a camera sees, for exposure that adapts. Of `physics2d`: bodies that move by forces and push one another apart, with friction and restitution, and joints; shapes swept along a motion, as time of impact finds where they first meet; rounded polygons; chains of segments, one-way platforms, and terrain; mass and inertia of shapes; each benchmarked against Box2D. Of `physics3d`: the same bodies in space, benchmarked against Jolt; shapes swept along a motion; cylinders, rounded hulls, and hulls of more than 32 corners, made fewer; heightfields; a mesh's triangles kept by a tree built once, from the top down, rather than one inserted at a time; and a triangle met without making a whole hull of it each time.
|