From 68f041cec46dfd1779919207b5221a8708f8c07b Mon Sep 17 00:00:00 2001 From: SoraKatadzuma Date: Tue, 27 Oct 2026 22:08:25 -0500 Subject: [PATCH] Initial Commit --- .editorconfig | 9 ++ .gitignore | 1 + README.md | 114 ++++++++++++++ blossomfile | 90 +++++++++++ geometry/bounds.sakura | 119 ++++++++++++++ geometry/frustum.sakura | 137 ++++++++++++++++ geometry/geometry.sakura | 51 ++++++ geometry/plane.sakura | 70 +++++++++ geometry/ray.sakura | 86 ++++++++++ geometry/sphere.sakura | 38 +++++ linear/linear.sakura | 43 +++++ linear/mat3.sakura | 102 ++++++++++++ linear/mat4.sakura | 234 +++++++++++++++++++++++++++ linear/quat.sakura | 141 +++++++++++++++++ linear/vec2.sakura | 64 ++++++++ linear/vec3.sakura | 136 ++++++++++++++++ linear/vec4.sakura | 114 ++++++++++++++ tests/geometry.sakura | 159 +++++++++++++++++++ tests/linear.sakura | 179 +++++++++++++++++++++ tests/main.sakura | 10 ++ tools/bench.sakura | 304 ++++++++++++++++++++++++++++++++++++ tools/geometry_bench.sakura | 236 ++++++++++++++++++++++++++++ 22 files changed, 2437 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 README.md create mode 100644 blossomfile create mode 100644 geometry/bounds.sakura create mode 100644 geometry/frustum.sakura create mode 100644 geometry/geometry.sakura create mode 100644 geometry/plane.sakura create mode 100644 geometry/ray.sakura create mode 100644 geometry/sphere.sakura create mode 100644 linear/linear.sakura create mode 100644 linear/mat3.sakura create mode 100644 linear/mat4.sakura create mode 100644 linear/quat.sakura create mode 100644 linear/vec2.sakura create mode 100644 linear/vec3.sakura create mode 100644 linear/vec4.sakura create mode 100644 tests/geometry.sakura create mode 100644 tests/linear.sakura create mode 100644 tests/main.sakura create mode 100644 tools/bench.sakura create mode 100644 tools/geometry_bench.sakura diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/README.md b/README.md new file mode 100644 index 0000000..7582150 --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# linear +Vectors of two, three, and four `f32`s, rotations as quaternions, and matrices of three by three and four by four: the numbers of space as games, their renderers, and their physics work it. Beside it, `geometry` makes the shapes of space of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads only std's `math`. An executable optimized with `-O2` works what it does to whole vectors as SIMD lanes, which the virtual machine works a number at a time, giving the same bits. + +```sakura +import std::math; +import 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 linear; +import 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 +``` +`tests/linear.sakura` and `tests/geometry.sakura` drive all of it, and `tools/bench.sakura` and `tools/geometry_bench.sakura` time it. + +A project reads it by requiring this folder, or its remote, and naming `linear`, or `geometry`, which reads `linear` and brings it, among a target's `deps`: + +```yaml +requires: +- ../linear +targets: +- name: game + type: program + deps: [geometry] +``` + +## 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 | + +## 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. +- **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 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 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`, which the compiler returns through memory. + +## Testing +`blossom test` runs `tests/linear.sakura` twice: `linear.tests` on the machine, a number at a time, with every read and write checked, and `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; and the bits of a long chain of all of it. + +It runs `tests/geometry.sakura` the same two ways, as `geometry.tests` and `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; and the bits of a long chain of all of it. + +## 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. diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..5480f2c --- /dev/null +++ b/blossomfile @@ -0,0 +1,90 @@ +name: linear +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 + +targets: +- name: linear + type: library + root: ./linear + deps: + - std.math + +# The shapes of space, made of `linear`'s vectors, and the tests between them. +- name: geometry + type: library + root: ./geometry + deps: + - linear + - std.math + +# Times what `linear` does against the same written a number at a time; see +# its header. +- name: linear.bench + type: program + level: ${level} + deps: + - linear + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/bench.sakura + +# Times what `geometry` does against the same written a number at a time; see +# its header. +- name: geometry.bench + type: program + level: ${level} + deps: + - geometry + - linear + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/geometry_bench.sakura + +tests: +# On the machine, which works each number at a time. +- name: linear.tests + type: program + deps: [linear, std.math, std.testing] + srcs: [tests/main.sakura, tests/linear.sakura] + +# The same tests built with `-O2`, which works vectors as lanes, and gives the +# same bits. +- name: linear.lanes.tests + type: program + runs: native + level: 2 + deps: [linear, std.math, std.testing] + srcs: [tests/main.sakura, tests/linear.sakura] + +# `geometry`'s, the same two ways. +- name: geometry.tests + type: program + deps: [geometry, linear, std.math, std.testing] + srcs: [tests/main.sakura, tests/geometry.sakura] + +- name: geometry.lanes.tests + type: program + runs: native + level: 2 + deps: [geometry, linear, std.math, std.testing] + srcs: [tests/main.sakura, tests/geometry.sakura] + +exports: +- linear +- geometry + +package: + desc: Vectors, quaternions, and matrices of f32, and the shapes of space made of them, worked as SIMD lanes where an executable holds them. + auth: John Christman diff --git a/geometry/bounds.sakura b/geometry/bounds.sakura new file mode 100644 index 0000000..3293be4 --- /dev/null +++ b/geometry/bounds.sakura @@ -0,0 +1,119 @@ +#! Contains `bounds`, a box along the axes: the least corner and the greatest of +#! what it holds, as of a mesh, a body, or a part of a scene, so whether two +#! meet, or a ray or a camera reaches one, is a few comparisons. + +import std::math; +import linear; +module geometry; + +#! A box along the axes, from its least corner to its greatest. +pub struct bounds { + pub var min: vec3; + pub var max: vec3; +} + +#! The box holding nothing, from infinity to minus infinity, which takes the +#! place or box it's first grown by. +pub val bounds::empty := bounds{ + vec3{ math::infinity::(), math::infinity::(), math::infinity::() }, + vec3{ -math::infinity::(), -math::infinity::(), -math::infinity::() }, +}; + +#! The box of a center, reaching so far from it along each axis. +pub def bounds::around(center: vec3, half_size: vec3): bounds { + return bounds{ center - half_size, center + half_size }; +} + +#! The least box holding places, or `empty` of none. +pub def bounds::of(points: span): bounds { + var made := bounds::empty; + for p in points { + made = made.including(p); + } + return made; +} + +#! The least box holding a sphere. +pub def bounds::of(s: sphere): bounds { + return bounds::around(s.center, vec3{ s.radius, s.radius, s.radius }); +} + +pub val bounds::center: vec3 { + get => (this.min + this.max) * 0.5; +} + +pub val bounds::size: vec3 { + get => this.max - this.min; +} + +#! How far it reaches from its center along each axis. +pub val bounds::half_size: vec3 { + get => (this.max - this.min) * 0.5; +} + +#! Whether it holds nothing, as `empty` does: a least corner past its greatest. +pub val bounds::is_empty: bool { + get => this.min.x > this.max.x || this.min.y > this.max.y || this.min.z > this.max.z; +} + +pub def bounds::equals(&this, other: &bounds): bool { + return this.min == other.min && this.max == other.max; +} + +#! Whether a place is within it. +pub def bounds::contains(&this, p: vec3): bool { + return p.x >= this.min.x && p.y >= this.min.y && p.z >= this.min.z + && p.x <= this.max.x && p.y <= this.max.y && p.z <= this.max.z; +} + +#! Whether another box is within it whole. +pub def bounds::contains(&this, other: bounds): bool { + return this.contains(other.min) && this.contains(other.max); +} + +#! Whether it and another box meet. +pub def bounds::overlaps(&this, other: bounds): bool { + return this.min.x <= other.max.x && this.min.y <= other.max.y && this.min.z <= other.max.z + && this.max.x >= other.min.x && this.max.y >= other.min.y && this.max.z >= other.min.z; +} + +#! Whether it and a sphere meet. +pub def bounds::overlaps(&this, s: sphere): bool { + return s.overlaps(this); +} + +#! Its place nearest another: the place itself where it's within. +pub def bounds::closest(&this, p: vec3): vec3 { + return p.max(this.min).min(this.max); +} + +#! The box grown to hold a place too. +pub def bounds::including(&this, p: vec3): bounds { + return bounds{ this.min.min(p), this.max.max(p) }; +} + +#! The least box holding it and another. +pub def bounds::merged(&this, other: bounds): bounds { + return bounds{ this.min.min(other.min), this.max.max(other.max) }; +} + +#! The least box along the axes holding this one moved, turned, and scaled by a +#! matrix that doesn't project: its center moved, and its reach along each of +#! its own axes turned, each number made positive, and added. +pub def bounds::transformed(&this, by: mat4): bounds { + return bounds::empty if this.is_empty; + val half := this.half_size; + val m := &by.m; + if lanes_held() { + # Each column as lanes, read where it lies, as `mat4`'s products read them. + val reach := lanes_at(&m[0]).abs() * f32x4::splat(half.x) + lanes_at(&m[4]).abs() * f32x4::splat(half.y) + + lanes_at(&m[8]).abs() * f32x4::splat(half.z); + return bounds::around(by.transform_point(this.center), vec3::of_lanes(reach)); + } + val reach := vec3{ + math::abs(m[0]) * half.x + math::abs(m[4]) * half.y + math::abs(m[8]) * half.z, + math::abs(m[1]) * half.x + math::abs(m[5]) * half.y + math::abs(m[9]) * half.z, + math::abs(m[2]) * half.x + math::abs(m[6]) * half.y + math::abs(m[10]) * half.z, + }; + return bounds::around(by.transform_point(this.center), reach); +} diff --git a/geometry/frustum.sakura b/geometry/frustum.sakura new file mode 100644 index 0000000..d4a997c --- /dev/null +++ b/geometry/frustum.sakura @@ -0,0 +1,137 @@ +#! Contains `frustum`, the part of space a camera sees: the six planes bounding +#! what a projection draws, each facing in, and whether a place, a box, or a +#! sphere is within them, so a renderer draws only what might be seen. The +#! planes' numbers are lanes, so an executable holding vectors in registers +#! tests four planes at once, then the other two: as two vectors of four, which +#! it holds in registers as it works them, where one of eight went through +#! memory a half at a time, twice as slow. + +import linear; +module geometry; + +#! The part of space a camera sees, within six planes facing in: left, right, +#! bottom, top, near, and far. It holds their normals' `x`s, `y`s, and `z`s, and +#! how far the origin is in front of each, eight of each, read as two `f32x4`s; +#! the last two are of planes of zeros, which nothing is behind. +pub struct frustum { + var _x: f32[8]; + var _y: f32[8]; + var _z: f32[8]; + var _d: f32[8]; +} + +#! The frustum of what a matrix projects into its clip space, its planes in the +#! space it projects from: of `projection * view`, the world's, and of a +#! projection alone, the camera's. Clip space bounds x and y between -w and w, +#! and depth between 0 and w, so each plane is the matrix's row of w with +#! another row added or taken away, and the near plane its row of depth alone. +pub def frustum::of(clip: mat4): frustum { + val m := &clip.m; + val x := vec4{ m[0], m[4], m[8], m[12] }; + val y := vec4{ m[1], m[5], m[9], m[13] }; + val z := vec4{ m[2], m[6], m[10], m[14] }; + val w := vec4{ m[3], m[7], m[11], m[15] }; + return frustum::of_planes([plane_of(w + x), plane_of(w - x), plane_of(w + y), plane_of(w - y), plane_of(z), plane_of(w - z)]); +} + +# The plane of a matrix's row: the places that, with a 1 after them, it makes +# 0 of, in front where it makes more, made of length 1. +def plane_of(row: vec4): plane { + val l := row.xyz.length; + return plane{ row.xyz / l, -row.w / l }; +} + +#! The frustum of six planes facing in: left, right, bottom, top, near, and far. +pub def frustum::of_planes(planes: plane[6]): frustum { + var made := frustum{}; + for i in 0..6u { + made._x[i] = planes[i].normal.x; + made._y[i] = planes[i].normal.y; + made._z[i] = planes[i].normal.z; + made._d[i] = -planes[i].distance; + } + return made; +} + +#! Its planes: left, right, bottom, top, near, and far. +pub val frustum::planes: plane[6] { + get { + var made: plane[6]; + for i in 0..6u { + made[i] = plane{ vec3{ this._x[i], this._y[i], this._z[i] }, -this._d[i] }; + } + return made; + } +} + +#! Whether a place is within it. +pub def frustum::contains(&this, p: vec3): bool { + if lanes_held() { + val x := f32x4::splat(p.x); + val y := f32x4::splat(p.y); + val z := f32x4::splat(p.z); + return in_front(this.ahead(0, x, y, z), this.ahead(4, x, y, z)); + } + for i in 0..6u { + return false if this._x[i] * p.x + this._y[i] * p.y + this._z[i] * p.z + this._d[i] < 0; + } + return true; +} + +#! Whether a box might be seen: whether, of each plane, the box's corner +#! furthest in front of it is in front. A box beside a corner of the frustum, +#! outside it but in front of every plane, counts as seen, which a renderer +#! draws for nothing; one it reaches always counts. +pub def frustum::overlaps(&this, b: bounds): bool { + if lanes_held() { + return in_front(this.ahead_of(0, &b), this.ahead_of(4, &b)); + } + for i in 0..6u { + val x := this._x[i] < 0 ? b.min.x : b.max.x; + val y := this._y[i] < 0 ? b.min.y : b.max.y; + val z := this._z[i] < 0 ? b.min.z : b.max.z; + return false if this._x[i] * x + this._y[i] * y + this._z[i] * z + this._d[i] < 0; + } + return true; +} + +#! Whether a sphere might be seen: whether its center is no further behind any +#! plane than its radius. As of a box, one beside a corner counts too. +pub def frustum::overlaps(&this, s: sphere): bool { + val c := s.center; + if lanes_held() { + val x := f32x4::splat(c.x); + val y := f32x4::splat(c.y); + val z := f32x4::splat(c.z); + val r := f32x4::splat(s.radius); + return in_front(this.ahead(0, x, y, z) + r, this.ahead(4, x, y, z) + r); + } + for i in 0..6u { + return false if this._x[i] * c.x + this._y[i] * c.y + this._z[i] * c.z + this._d[i] + s.radius < 0; + } + return true; +} + +# How far places, a lane each, are in front of four planes from one, as lanes. +def frustum::ahead(&this, first: u64, x: f32x4, y: f32x4, z: f32x4): f32x4 { + return lanes_at(&this._x[first]) * x + lanes_at(&this._y[first]) * y + lanes_at(&this._z[first]) * z + lanes_at(&this._d[first]); +} + +# How far a box's corner furthest in front of each of four planes from one is +# in front of it, as lanes. +def frustum::ahead_of(&this, first: u64, b: &bounds): f32x4 { + val zero := f32x4::splat(0); + val x := lanes_at(&this._x[first]); + val y := lanes_at(&this._y[first]); + val z := lanes_at(&this._z[first]); + return x * select(x.less(&zero), f32x4::splat(b.min.x), f32x4::splat(b.max.x)) + + y * select(y.less(&zero), f32x4::splat(b.min.y), f32x4::splat(b.max.y)) + + z * select(z.less(&zero), f32x4::splat(b.min.z), f32x4::splat(b.max.z)) + lanes_at(&this._d[first]); +} + +# Whether something is in front of each of eight planes, by how far it's in +# front of each, as lanes. +def in_front(first: f32x4, last: f32x4): bool { + val zero := f32x4::splat(0); + return (first.less(&zero) | last.less(&zero)).none(); +} diff --git a/geometry/geometry.sakura b/geometry/geometry.sakura new file mode 100644 index 0000000..0363101 --- /dev/null +++ b/geometry/geometry.sakura @@ -0,0 +1,51 @@ +#! Contains `geometry`: the shapes of space, made of `linear`'s vectors, and +#! what games, their renderers, and their physics ask of them: where a ray first +#! meets a plane, a sphere, or a box, which side of a plane something lies on, +#! whether boxes and spheres meet or hold a place, and whether a camera's +#! frustum reaches something, so only what it might see is drawn. +#! +#! Space is `linear`'s: right-handed, y up, and a camera looking down its -z. A +#! frustum is of a matrix's clip space as `linear`'s projections make it, depth +#! from 0 at the near plane to 1 at the far one. +#! +#! Each shape is of `linear`'s vectors and plain `f32`s, worked as lanes where +#! `linear` works them, and a frustum holds its six planes' numbers a lane +#! each, so an executable optimized with `-O2` tests a place, a box, or a sphere +#! against four planes at once, then the other two. What gives a number of a +#! few, as a dot product does, is a number at a time, as `linear`'s `cross` is: +#! lanes taken apart to be added, then worked as numbers, ran two to three times +#! as slow. The virtual machine works everything a number at a time, in the order +#! the lanes do, so either way gives the same answers and the same bits. +#! +#! A place exactly on a shape's surface is within it: a box holds its corners, +#! a sphere the places at its radius, and two boxes touching meet. + +import linear; +module geometry; + + +# The dot product of two vectors, a number at a time, in the order `vec3::dot` +# adds them. +def dot_of(a: &vec3, b: &vec3): f32 { + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +# The square of the distance between two places, a number at a time, as the +# dot product of `a - b` with itself gives it. +def distance_squared(a: &vec3, b: &vec3): f32 { + val x := a.x - b.x; + val y := a.y - b.y; + val z := a.z - b.z; + return x * x + y * y + z * z; +} + +# The lesser of two numbers, and the greater: of a NaN, either may be given, +# where `math::min` and `math::max` work three times as long to give it. +def least(a: f32, b: f32): f32 { return b < a ? b : a; } +def most(a: f32, b: f32): f32 { return a < b ? b : a; } + +# Four numbers as lanes, read from where the first lies, which needs no +# alignment. +def lanes_at(first: &f32): f32x4 { + return ((first as *f32) as *f32x4)[0]; +} diff --git a/geometry/plane.sakura b/geometry/plane.sakura new file mode 100644 index 0000000..fe56d03 --- /dev/null +++ b/geometry/plane.sakura @@ -0,0 +1,70 @@ +#! Contains `plane`, a flat surface without end, and which side of one something +#! lies on: what bounds a frustum, a floor or a wall a ray meets, and what splits +#! a space in two. + +import linear; +module geometry; + +#! A plane: the places as far along its normal, a direction of length 1, as +#! `distance`. Its front is the side the normal points to. +pub struct plane { + pub var normal: vec3; + pub var distance: f32; +} + +#! Which side of a plane something lies on. +pub enum side: u8 { + front, #! Wholly where the normal points. + back, #! Wholly behind. + across, #! On both sides, or touching it. +} + +#! The plane through a place, facing a direction, made of length 1. +pub def plane::through(point: vec3, normal: vec3): plane { + val n := normal.normalized(); + return plane{ n, n.dot(point) }; +} + +#! The plane through three places, facing where they turn counterclockwise, as +#! a triangle's front does. +pub def plane::of_points(a: vec3, b: vec3, c: vec3): plane { + return plane::through(a, (b - a).cross(c - a)); +} + +pub def plane::equals(&this, other: &plane): bool { + return this.normal == other.normal && this.distance == other.distance; +} + +#! How far a place is in front of the plane, negative behind it. +pub def plane::distance_to(&this, p: vec3): f32 { + return dot_of(&this.normal, &p) - this.distance; +} + +#! The plane's place nearest another. +pub def plane::closest(&this, p: vec3): vec3 { + return p - this.normal * this.distance_to(p); +} + +#! The same plane facing the other way. +pub def plane::flipped(&this): plane { + return plane{ -this.normal, -this.distance }; +} + +#! Which side of the plane a box lies on: how far its center is in front, +#! against how far the box reaches along the normal. +pub def plane::side_of(&this, b: bounds): side { + val half := b.half_size; + return side_at(this.distance_to(b.center), dot_of(&half, &this.normal.abs())); +} + +#! Which side of the plane a sphere lies on. +pub def plane::side_of(&this, s: sphere): side { + return side_at(this.distance_to(s.center), s.radius); +} + +# The side of what is centered so far in front of a plane, and reaches so far. +def side_at(at: f32, reach: f32): side { + return side::front if at > reach; + return side::back if at < -reach; + return side::across; +} diff --git a/geometry/ray.sakura b/geometry/ray.sakura new file mode 100644 index 0000000..5e28ab2 --- /dev/null +++ b/geometry/ray.sakura @@ -0,0 +1,86 @@ +#! Contains `ray`, a half line from a place in a direction, and where it first +#! meets a plane, a sphere, or a box, as picking what's under a pointer, a line +#! of sight, or a shot asks. + +import std::math; +import linear; +module geometry; + +#! A half line from a place in a direction. How far along it something lies is +#! counted in lengths of its direction, so it's a distance where the direction +#! is of length 1, as `toward` makes it. +pub struct ray { + pub var origin: vec3; + pub var direction: vec3; +} + +#! The ray from a place toward another, its direction of length 1. +pub def ray::toward(origin: vec3, target: vec3): ray { + return ray{ origin, (target - origin).normalized() }; +} + +pub def ray::equals(&this, other: &ray): bool { + return this.origin == other.origin && this.direction == other.direction; +} + +#! The place so far along it. +pub def ray::at(&this, t: f32): vec3 { + return this.origin + this.direction * t; +} + +#! Its place nearest another, from its origin on. +pub def ray::closest(&this, p: vec3): vec3 { + val d := &this.direction; + val toward := (p.x - this.origin.x) * d.x + (p.y - this.origin.y) * d.y + (p.z - this.origin.z) * d.z; + val along := toward / dot_of(d, d); + return this.at(along > 0 ? along : 0); +} + +#! How far along it it meets a plane, from either side, or none where it runs +#! beside the plane or away from it. +pub def ray::hit(&this, p: plane): maybe { + val toward := dot_of(&p.normal, &this.direction); + return nothing {} if toward == 0; + val t := p.distance_to(this.origin) / -toward; + return nothing {} if !(t >= 0); + return t; +} + +#! How far along it it first meets a sphere, 0 where it begins within, or none +#! where it passes by or away. +pub def ray::hit(&this, s: sphere): maybe { + val d := &this.direction; + val mx := this.origin.x - s.center.x; + val my := this.origin.y - s.center.y; + val mz := this.origin.z - s.center.z; + val c := mx * mx + my * my + mz * mz - s.radius * s.radius; + return 0f if c <= 0; + # Outside, and moving away from the center or across it, it never comes nearer. + val b := mx * d.x + my * d.y + mz * d.z; + return nothing {} if b >= 0; + val a := dot_of(d, d); + val e := b * b - a * c; + return nothing {} if e < 0; + return (-b - math::sqrt(e)) / a; +} + +#! How far along it it first meets a box, 0 where it begins within, or none +#! where it passes by or away: where it is between the box's faces along every +#! axis at once. One along a face, in its plane, may meet the box or pass by. +pub def ray::hit(&this, b: bounds): maybe { + # Along an axis it doesn't move along, it's between the faces everywhere, or + # nowhere, as dividing by zero gives infinities. + val ix := 1 / this.direction.x; + val iy := 1 / this.direction.y; + val iz := 1 / this.direction.z; + val x0 := (b.min.x - this.origin.x) * ix; + val x1 := (b.max.x - this.origin.x) * ix; + val y0 := (b.min.y - this.origin.y) * iy; + val y1 := (b.max.y - this.origin.y) * iy; + val z0 := (b.min.z - this.origin.z) * iz; + val z1 := (b.max.z - this.origin.z) * iz; + val enter := most(most(least(x0, x1), least(y0, y1)), most(least(z0, z1), 0)); + val leave := least(least(most(x0, x1), most(y0, y1)), most(z0, z1)); + return nothing {} if !(enter <= leave); + return enter; +} diff --git a/geometry/sphere.sakura b/geometry/sphere.sakura new file mode 100644 index 0000000..ed1d91d --- /dev/null +++ b/geometry/sphere.sakura @@ -0,0 +1,38 @@ +#! Contains `sphere`, the places within a distance of a center: what holds a +#! body for the quickest test of whether two might meet, their distance against +#! the sum of their radii. + +import linear; +module geometry; + +#! The places within `radius` of `center`. +pub struct sphere { + pub var center: vec3; + pub var radius: f32; +} + +#! The least sphere holding a box: of its center, reaching its corners. +pub def sphere::of(b: bounds): sphere { + return sphere{ b.center, b.half_size.length }; +} + +pub def sphere::equals(&this, other: &sphere): bool { + return this.center == other.center && this.radius == other.radius; +} + +#! Whether a place is within it. +pub def sphere::contains(&this, p: vec3): bool { + return distance_squared(&p, &this.center) <= this.radius * this.radius; +} + +#! Whether it and another sphere meet. +pub def sphere::overlaps(&this, other: sphere): bool { + val reach := this.radius + other.radius; + return distance_squared(&other.center, &this.center) <= reach * reach; +} + +#! Whether it and a box meet: whether the box's place nearest its center is +#! within it. +pub def sphere::overlaps(&this, b: bounds): bool { + return this.contains(b.closest(this.center)); +} diff --git a/linear/linear.sakura b/linear/linear.sakura new file mode 100644 index 0000000..4c7e8b2 --- /dev/null +++ b/linear/linear.sakura @@ -0,0 +1,43 @@ +#! Contains `linear`: vectors of two, three, and four `f32`s, rotations as +#! quaternions, and matrices of three by three and four by four, the numbers of +#! space as games, their renderers, and their physics work it. +#! +#! Space is right-handed: x to the right, y up, and z toward the viewer, so a +#! camera looks down its own -z. A matrix is column-major, as GLSL reads one, +#! and multiplies a vector on its right: `m * v`. 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 +#! is with its y flipped. Angles are radians. +#! +#! Each type is of plain `f32` fields, so it's laid out as C and the GPU lay +#! out its numbers, and the virtual machine reads a field as quickly as any. +#! `vec3`, `vec4`, and `quat` are 16 bytes, `vec3` holding a fourth number no one +#! names, so an executable optimized with `-O2`, which holds `simd` vectors in +#! registers, reads each as one `f32x4` from where it is, and works it as lanes +#! at once: adding, scaling, dots, lengths, 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. What gathers one vector's numbers into +#! other lanes, as a cross product and a quaternions' product would, it works a +#! number at a time, as `simd::shuffle` gathers them a lane at a time. The +#! virtual machine, which works lanes one at a time, works everything a number +#! at a time, in the order the lanes do, so both ways give the same bits. +#! +#! A product is rounded before it's added, not fused with the sum as `fma` does: +#! a column waiting on the fused sum before it is slower than one adding +#! products worked at once, and the virtual machine would work each fused sum +#! as `std::math` does without FMA3, many instructions for one. + +module linear; + + +# The lanes of a value of four `f32`s, as `vec3`, `vec4`, and `quat` are, read +# from where it is, which needs no alignment. +def lanes_of(v: &T): f32x4 { + return ((v as *T) as *f32x4)[0]; +} + +# The value of four `f32`s whose numbers are lanes. +def of_lanes(lanes: f32x4): T where T: zeroable { + var made: T; + ((&mut made) as *mut f32x4)[0] = lanes; + return made; +} diff --git a/linear/mat3.sakura b/linear/mat3.sakura new file mode 100644 index 0000000..f265444 --- /dev/null +++ b/linear/mat3.sakura @@ -0,0 +1,102 @@ +#! Contains `mat3`, a matrix of three by three: a rotation, a scale, or what +#! turns and stretches a direction without moving it, as an inertia tensor +#! does. Its columns are `vec3`s, each 16 bytes, so it's laid out as std140 +#! lays out a GLSL `mat3`, and its columns are added and scaled as lanes. + +module linear; + +#! A matrix of three by three, column after column: where it takes x, y, and z. +pub struct mat3 { + pub var x_axis: vec3; + pub var y_axis: vec3; + pub var z_axis: vec3; +} + +#! The matrix that changes nothing. +pub val mat3::identity := mat3{ vec3::right, vec3::up, vec3::back }; + +#! Turning by a rotation. +pub def mat3::rotation(by: quat): mat3 { + val q := by; + val xx := q.x * q.x; + val yy := q.y * q.y; + val zz := q.z * q.z; + val xy := q.x * q.y; + val xz := q.x * q.z; + val yz := q.y * q.z; + val wx := q.w * q.x; + val wy := q.w * q.y; + val wz := q.w * q.z; + return mat3{ + vec3{ 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy) }, + vec3{ 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx) }, + vec3{ 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy) }, + }; +} + +#! Scaling along each axis. +pub def mat3::scaling(by: vec3): mat3 { + return mat3{ vec3{ by.x, 0, 0 }, vec3{ 0, by.y, 0 }, vec3{ 0, 0, by.z } }; +} + +#! The matrix doing another, then this: each of the other's columns, as this +#! turns and scales it. +pub def mat3::mul(&this, other: &mat3): mat3 { + return mat3{ this * other.x_axis, this * other.y_axis, this * other.z_axis }; +} + +#! A direction the matrix turns and scales: each column, scaled by one of its +#! numbers, added. +pub def mat3::mul(&this, v: &vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.x_axis) * f32x4::splat(v.x) + lanes_of(&this.y_axis) * f32x4::splat(v.y) + + lanes_of(&this.z_axis) * f32x4::splat(v.z)); + } + return vec3{ + this.x_axis.x * v.x + this.y_axis.x * v.y + this.z_axis.x * v.z, + this.x_axis.y * v.x + this.y_axis.y * v.y + this.z_axis.y * v.z, + this.x_axis.z * v.x + this.y_axis.z * v.y + this.z_axis.z * v.z, + }; +} + +pub def mat3::mul(&this, by: &f32): mat3 { + return mat3{ this.x_axis * by, this.y_axis * by, this.z_axis * by }; +} + +pub def mat3::add(&this, other: &mat3): mat3 { + return mat3{ this.x_axis + other.x_axis, this.y_axis + other.y_axis, this.z_axis + other.z_axis }; +} + +pub def mat3::sub(&this, other: &mat3): mat3 { + return mat3{ this.x_axis - other.x_axis, this.y_axis - other.y_axis, this.z_axis - other.z_axis }; +} + +pub def mat3::equals(&this, other: &mat3): bool { + return this.x_axis == other.x_axis && this.y_axis == other.y_axis && this.z_axis == other.z_axis; +} + +#! Its rows as its columns, which for a rotation is the rotation back. +pub def mat3::transposed(&this): mat3 { + return mat3{ + vec3{ this.x_axis.x, this.y_axis.x, this.z_axis.x }, + vec3{ this.x_axis.y, this.y_axis.y, this.z_axis.y }, + vec3{ this.x_axis.z, this.y_axis.z, this.z_axis.z }, + }; +} + +#! How much it scales a volume, negative where it mirrors one. +pub val mat3::determinant: f32 { + get => this.x_axis.dot(this.y_axis.cross(this.z_axis)); +} + +#! The matrix undoing this, or none where nothing can, as a scale of zero: each +#! row the cross product of the other two columns, over the determinant. +pub def mat3::inverse(&this): mat3 { + val a := this.y_axis.cross(this.z_axis); + val b := this.z_axis.cross(this.x_axis); + val c := this.x_axis.cross(this.y_axis); + val det := this.x_axis.dot(a); + # Scaled by 0 where nothing undoes it, so it returns once. + val k := det != 0 ? 1 / det : 0; + return mat3{ a * k, b * k, c * k }.transposed(); +} diff --git a/linear/mat4.sakura b/linear/mat4.sakura new file mode 100644 index 0000000..36df521 --- /dev/null +++ b/linear/mat4.sakura @@ -0,0 +1,234 @@ +#! Contains `mat4`, a matrix of four by four: what moves, turns, and scales a +#! place, or projects it, as a camera does. Its numbers are column after +#! column, so a column is 16 bytes, read as one `f32x4`, and its products are +#! each column scaled and added at once. + +import std::math; +module linear; + +#! A matrix of four by four, column after column. +pub struct mat4 { + pub var m: f32[16]; +} + +#! The matrix that changes nothing. +pub val mat4::identity := mat4{ m = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }; + +#! Moving by a vector. +pub def mat4::translation(by: vec3): mat4 { + var made := mat4::identity; + made.m[12] = by.x; + made.m[13] = by.y; + made.m[14] = by.z; + return made; +} + +#! Scaling along each axis. +pub def mat4::scaling(by: vec3): mat4 { + var made := mat4::identity; + made.m[0] = by.x; + made.m[5] = by.y; + made.m[10] = by.z; + return made; +} + +#! Turning by a rotation. +pub def mat4::rotation(by: quat): mat4 { + return mat4::compose(vec3::zero, by, vec3::one); +} + +#! Scaling, then turning, then moving: what a transform does. +pub def mat4::compose(translation: vec3, rotation: quat, scale: vec3): mat4 { + val q := rotation; + val xx := q.x * q.x; + val yy := q.y * q.y; + val zz := q.z * q.z; + val xy := q.x * q.y; + val xz := q.x * q.z; + val yz := q.y * q.z; + val wx := q.w * q.x; + val wy := q.w * q.y; + val wz := q.w * q.z; + return mat4{ m = [ + (1 - 2 * (yy + zz)) * scale.x, 2 * (xy + wz) * scale.x, 2 * (xz - wy) * scale.x, 0, + 2 * (xy - wz) * scale.y, (1 - 2 * (xx + zz)) * scale.y, 2 * (yz + wx) * scale.y, 0, + 2 * (xz + wy) * scale.z, 2 * (yz - wx) * scale.z, (1 - 2 * (xx + yy)) * scale.z, 0, + translation.x, translation.y, translation.z, 1, + ] }; +} + +#! A perspective projection, as a camera's: its field of view up and down, the +#! width over the height it's drawn at, and the nearest and furthest it draws. +pub def mat4::perspective(fov_y: f32, aspect: f32, near: f32, far: f32): mat4 { + val f := 1 / math::tan(fov_y / 2); + var made := mat4{}; + made.m[0] = f / aspect; + made.m[5] = f; + made.m[10] = far / (near - far); + made.m[11] = -1; + made.m[14] = near * far / (near - far); + return made; +} + +#! An orthographic projection of a box: its edges, and how near and far it +#! reaches down -z. +pub def mat4::orthographic(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32): mat4 { + var made := mat4::identity; + made.m[0] = 2 / (right - left); + made.m[5] = 2 / (top - bottom); + made.m[10] = 1 / (near - far); + made.m[12] = -(right + left) / (right - left); + made.m[13] = -(top + bottom) / (top - bottom); + made.m[14] = near / (near - far); + return made; +} + +#! The view of a camera at a place looking at another, y as near to `up` as it +#! can be: what moves the world into the camera's space. +pub def mat4::look_at(eye: vec3, target: vec3, up: vec3 = vec3::up): mat4 { + return mat4::compose(eye, quat::looking(target - eye, up), vec3::one).inverse(); +} + +#! The matrix doing another, then this: each of the other's columns, each of +#! this one's columns scaled by one of its numbers, added. +pub def mat4::mul(&this, other: &mat4): mat4 { + var made := mat4{}; + if lanes_held() { + val c0 := lanes_of(&this.m[0]); + val c1 := lanes_of(&this.m[4]); + val c2 := lanes_of(&this.m[8]); + val c3 := lanes_of(&this.m[12]); + val out := (&mut made) as *mut f32x4; + for c in 0..4u { + out[c] = c0 * f32x4::splat(other.m[c * 4]) + c1 * f32x4::splat(other.m[c * 4 + 1]) + + c2 * f32x4::splat(other.m[c * 4 + 2]) + c3 * f32x4::splat(other.m[c * 4 + 3]); + } + return made; + } + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1] + + this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3]; + } + } + return made; +} + +#! What the matrix makes of a vector, as a projection makes a place of clip +#! space: each column, scaled by one of its numbers, added. +pub def mat4::mul(&this, v: &vec4): vec4 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y) + + lanes_of(&this.m[8]) * f32x4::splat(v.z) + lanes_of(&this.m[12]) * f32x4::splat(v.w)); + } + return vec4{ + this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z + this.m[12] * v.w, + this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z + this.m[13] * v.w, + this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z + this.m[14] * v.w, + this.m[3] * v.x + this.m[7] * v.y + this.m[11] * v.z + this.m[15] * v.w, + }; +} + +pub def mat4::equals(&this, other: &mat4): bool { + for i in 0..16u { + return false if this.m[i] != other.m[i]; + } + return true; +} + +#! A place moved by the matrix, which moves, turns, and scales but doesn't +#! project. +pub def mat4::transform_point(&this, p: vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(p.x) + lanes_of(&this.m[4]) * f32x4::splat(p.y) + + lanes_of(&this.m[8]) * f32x4::splat(p.z) + lanes_of(&this.m[12])); + } + return vec3{ + this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12], + this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13], + this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14], + }; +} + +#! A direction turned and scaled by the matrix, which a move doesn't change. +pub def mat4::transform_vector(&this, v: vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y) + + lanes_of(&this.m[8]) * f32x4::splat(v.z)); + } + return vec3{ + this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z, + this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z, + this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z, + }; +} + +#! Where the matrix moves the origin to. +pub val mat4::translation_of: vec3 { + get => vec3{ this.m[12], this.m[13], this.m[14] }; +} + +#! A column, from 0. +pub def mat4::column(&this, which: u64): vec4 { + return vec4{ this.m[which * 4], this.m[which * 4 + 1], this.m[which * 4 + 2], this.m[which * 4 + 3] }; +} + +#! What it does to directions: its first three columns' first three numbers. +pub def mat4::linear_part(&this): mat3 { + return mat3{ + vec3{ this.m[0], this.m[1], this.m[2] }, + vec3{ this.m[4], this.m[5], this.m[6] }, + vec3{ this.m[8], this.m[9], this.m[10] }, + }; +} + +pub def mat4::transposed(&this): mat4 { + var made := mat4{}; + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r * 4 + c]; + } + } + return made; +} + +#! The matrix undoing this, or none where nothing can, as a scale of zero: of +#! the determinants of two by two its first two columns make, and its last +#! two, each cofactor of three of them, which is half the work of the +#! cofactors written out, a number at a time. +pub def mat4::inverse(&this): mat4 { + val a := &this.m; + val s0 := a[0] * a[5] - a[4] * a[1]; + val s1 := a[0] * a[6] - a[4] * a[2]; + val s2 := a[0] * a[7] - a[4] * a[3]; + val s3 := a[1] * a[6] - a[5] * a[2]; + val s4 := a[1] * a[7] - a[5] * a[3]; + val s5 := a[2] * a[7] - a[6] * a[3]; + val c5 := a[10] * a[15] - a[14] * a[11]; + val c4 := a[9] * a[15] - a[13] * a[11]; + val c3 := a[9] * a[14] - a[13] * a[10]; + val c2 := a[8] * a[15] - a[12] * a[11]; + val c1 := a[8] * a[14] - a[12] * a[10]; + val c0 := a[8] * a[13] - a[12] * a[9]; + val det := s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0; + # Scaled by 0 where nothing undoes it, so it returns once. + val k := det != 0 ? 1 / det : 0; + return mat4{ m = [ + (a[5] * c5 - a[6] * c4 + a[7] * c3) * k, + (a[2] * c4 - a[1] * c5 - a[3] * c3) * k, + (a[13] * s5 - a[14] * s4 + a[15] * s3) * k, + (a[10] * s4 - a[9] * s5 - a[11] * s3) * k, + (a[6] * c2 - a[4] * c5 - a[7] * c1) * k, + (a[0] * c5 - a[2] * c2 + a[3] * c1) * k, + (a[14] * s2 - a[12] * s5 - a[15] * s1) * k, + (a[8] * s5 - a[10] * s2 + a[11] * s1) * k, + (a[4] * c4 - a[5] * c2 + a[7] * c0) * k, + (a[1] * c2 - a[0] * c4 - a[3] * c0) * k, + (a[12] * s4 - a[13] * s2 + a[15] * s0) * k, + (a[9] * s2 - a[8] * s4 - a[11] * s0) * k, + (a[5] * c1 - a[4] * c3 - a[6] * c0) * k, + (a[0] * c3 - a[1] * c1 + a[2] * c0) * k, + (a[13] * s1 - a[12] * s3 - a[14] * s0) * k, + (a[8] * s3 - a[9] * s1 + a[10] * s0) * k, + ] }; +} diff --git a/linear/quat.sakura b/linear/quat.sakura new file mode 100644 index 0000000..b6670d5 --- /dev/null +++ b/linear/quat.sakura @@ -0,0 +1,141 @@ +#! Contains `quat`, a rotation as a quaternion of length 1: made of an axis and +#! an angle, of angles about each axis, or of a direction to look in; turning +#! vectors, following one another, undone, and turned between at an even rate. + +import std::math; +module linear; + +#! A rotation, as a quaternion of length 1. +pub struct quat { + pub var x: f32; + pub var y: f32; + pub var z: f32; + pub var w: f32 = 1; +} + +#! No rotation. +pub val quat::identity := quat{ 0, 0, 0, 1 }; + +#! Its numbers as lanes, for code of its own to work several at once. +pub def quat::lanes(&this): f32x4 { return lanes_of(this); } + +#! The quaternion of lanes. +pub def quat::of_lanes(lanes: f32x4): quat { return of_lanes::(lanes); } + +#! A rotation about an axis, by an angle, counterclockwise as the axis points +#! at the viewer. +pub def quat::axis_angle(axis: vec3, angle: f32): quat { + val a := axis.normalized(); + val s := math::sin(angle / 2); + return quat{ a.x * s, a.y * s, a.z * s, math::cos(angle / 2) }; +} + +#! A rotation by angles about each axis, as a camera's is: about z, its roll, +#! then about x, its pitch, then about y, its yaw. +pub def quat::euler(x: f32, y: f32, z: f32): quat { + return quat::axis_angle(vec3::up, y) * quat::axis_angle(vec3::right, x) * quat::axis_angle(vec3::back, z); +} + +#! The rotation turning -z, where a camera looks, to a direction, and y as near +#! to `up` as it can be. +pub def quat::looking(direction: vec3, up: vec3 = vec3::up): quat { + val f := direction.normalized(); + var r := f.cross(up).normalized(); + if r.length == 0 { + # Looking along `up`, any right will do. + r = f.cross(math::abs(f.x) < 0.9 ? vec3::right : vec3::up).normalized(); + } + val u := r.cross(f); + return quat::of_basis(r, u, -f); +} + +#! The rotation whose matrix's columns are three axes, at right angles, each of +#! length 1, as `mat3::rotation` gives them. +pub def quat::of_basis(x: vec3, y: vec3, z: vec3): quat { + val trace := x.x + y.y + z.z; + if trace > 0 { + val s := math::sqrt(trace + 1) * 2; + return quat{ (y.z - z.y) / s, (z.x - x.z) / s, (x.y - y.x) / s, s / 4 }; + } + if x.x > y.y && x.x > z.z { + val s := math::sqrt(1 + x.x - y.y - z.z) * 2; + return quat{ s / 4, (y.x + x.y) / s, (z.x + x.z) / s, (y.z - z.y) / s }; + } + if y.y > z.z { + val s := math::sqrt(1 + y.y - x.x - z.z) * 2; + return quat{ (y.x + x.y) / s, s / 4, (z.y + y.z) / s, (z.x - x.z) / s }; + } + val s := math::sqrt(1 + z.z - x.x - y.y) * 2; + return quat{ (z.x + x.z) / s, (z.y + y.z) / s, s / 4, (x.y - y.x) / s }; +} + +#! The rotation of this after another: `a * b` turns by `b`, then by `a`. A +#! number at a time, which an executable outruns gathering the other's numbers +#! into lanes with. +pub def quat::mul(&this, o: &quat): quat { + return quat{ + o.x * this.w + o.w * this.x + o.z * this.y - o.y * this.z, + o.y * this.w - o.z * this.x + o.w * this.y + o.x * this.z, + o.z * this.w + o.y * this.x - o.x * this.y + o.w * this.z, + o.w * this.w - o.x * this.x - o.y * this.y - o.z * this.z, + }; +} + +#! A vector turned by the rotation, by its matrix, whose columns are scaled by +#! the vector's numbers and added as lanes, which an executable works three +#! times as fast as the crosses of the rotation's axis. +pub def quat::mul(&this, v: &vec3): vec3 { + return mat3::rotation(this) * v; +} + +pub def quat::equals(&this, other: &quat): bool { + return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w; +} + +pub def quat::dot(&this, other: quat): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2] + p[3]; + } + return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w; +} + +pub val quat::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The rotation back. +pub def quat::inverse(&this): quat { + return quat{ -this.x, -this.y, -this.z, this.w }; +} + +#! The quaternion at a length of 1, as rounding keeps a rotation turned many +#! times. +pub def quat::normalized(&this): quat { + val l := this.length; + if lanes_held() { + return l > 0 ? of_lanes::(lanes_of(this) / f32x4::splat(l)) : quat::identity; + } + return l > 0 ? quat{ this.x / l, this.y / l, this.z / l, this.w / l } : quat::identity; +} + +#! The rotation a fraction of the way to another, turning at an even rate by +#! the shorter way. +pub def quat::slerp(&this, to: quat, t: f32): quat { + var cos := this.dot(to); + var end := to; + if cos < 0 { + cos = -cos; + end = quat{ -to.x, -to.y, -to.z, -to.w }; + } + var a := 1 - t; + var b := t; + if cos < 0.9995 { + val angle := math::acos(cos); + val s := math::sin(angle); + a = math::sin((1 - t) * angle) / s; + b = math::sin(t * angle) / s; + } + val made := quat{ this.x * a + end.x * b, this.y * a + end.y * b, this.z * a + end.z * b, this.w * a + end.w * b }; + return made.normalized(); +} diff --git a/linear/vec2.sakura b/linear/vec2.sakura new file mode 100644 index 0000000..5ce45f6 --- /dev/null +++ b/linear/vec2.sakura @@ -0,0 +1,64 @@ +#! Contains `vec2`, a vector of two: a place or a direction in a plane, as of +#! a window's pixels, a glyph's outline, or a texture. It's 8 bytes, half the +#! lanes of an `f32x4`, so it's worked a number at a time. + +import std::math; +module linear; + +#! A vector of two: a place or a direction in a plane. +pub struct vec2 { + pub var x: f32; + pub var y: f32; +} + +pub val vec2::zero := vec2{ 0, 0 }; +pub val vec2::one := vec2{ 1, 1 }; + +pub def vec2::add(&this, other: &vec2): vec2 { return vec2{ this.x + other.x, this.y + other.y }; } +pub def vec2::sub(&this, other: &vec2): vec2 { return vec2{ this.x - other.x, this.y - other.y }; } +pub def vec2::mul(&this, by: &f32): vec2 { return vec2{ this.x * by, this.y * by }; } +pub def vec2::mul(&this, other: &vec2): vec2 { return vec2{ this.x * other.x, this.y * other.y }; } +pub def vec2::div(&this, by: &f32): vec2 { return vec2{ this.x / by, this.y / by }; } +pub def vec2::div(&this, other: &vec2): vec2 { return vec2{ this.x / other.x, this.y / other.y }; } +pub def vec2::negate(&this): vec2 { return vec2{ -this.x, -this.y }; } +pub def vec2::equals(&this, other: &vec2): bool { return this.x == other.x && this.y == other.y; } + +pub def vec2::dot(&this, other: vec2): f32 { return this.x * other.x + this.y * other.y; } + +#! The z of the cross product of the two as vectors of three in the plane z is +#! 0: positive where `other` is counterclockwise of this. +pub def vec2::cross(&this, other: vec2): f32 { return this.x * other.y - this.y * other.x; } + +#! The vector turned a quarter counterclockwise. +pub def vec2::perpendicular(&this): vec2 { return vec2{ -this.y, this.x }; } + +pub val vec2::length: f32 { + get => math::sqrt(this.x * this.x + this.y * this.y); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec2::length_squared: f32 { + get => this.x * this.x + this.y * this.y; +} + +pub def vec2::distance(&this, other: vec2): f32 { return (other - this).length; } + +#! The vector at a length of 1, or none where it has no length. +pub def vec2::normalized(&this): vec2 { + val l := math::sqrt(this.x * this.x + this.y * this.y); + return l > 0 ? vec2{ this.x / l, this.y / l } : vec2{}; +} + +#! The vector a fraction of the way to another. +pub def vec2::lerp(&this, to: vec2, t: f32): vec2 { + return vec2{ this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t }; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec2::min(&this, other: vec2): vec2 { return vec2{ math::min(this.x, other.x), math::min(this.y, other.y) }; } + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec2::max(&this, other: vec2): vec2 { return vec2{ math::max(this.x, other.x), math::max(this.y, other.y) }; } + +#! Each number's distance from zero. +pub def vec2::abs(&this): vec2 { return vec2{ math::abs(this.x), math::abs(this.y) }; } diff --git a/linear/vec3.sakura b/linear/vec3.sakura new file mode 100644 index 0000000..0382dab --- /dev/null +++ b/linear/vec3.sakura @@ -0,0 +1,136 @@ +#! Contains `vec3`, a vector of three: a place or a direction in space. It holds +#! a fourth number no one names, so it's 16 bytes, an `f32x4`'s, which an +#! executable holding vectors in registers works at once. + +import std::math; +module linear; + +#! A vector of three: a place or a direction in space. +pub struct vec3 { + pub var x: f32; + pub var y: f32; + pub var z: f32; + # Unnamed, so the vector is four lanes; what its lane holds means nothing. + var _w: f32; +} + +pub val vec3::zero := vec3{ 0, 0, 0 }; +pub val vec3::one := vec3{ 1, 1, 1 }; +pub val vec3::right := vec3{ 1, 0, 0 }; +pub val vec3::left := vec3{ -1, 0, 0 }; +pub val vec3::up := vec3{ 0, 1, 0 }; +pub val vec3::down := vec3{ 0, -1, 0 }; +#! Toward the viewer: a camera looks the other way. +pub val vec3::back := vec3{ 0, 0, 1 }; +#! Away from the viewer, where a camera looks. +pub val vec3::forward := vec3{ 0, 0, -1 }; + +#! Its numbers as lanes, the fourth meaning nothing, for code of its own to +#! work several at once. +pub def vec3::lanes(&this): f32x4 { return lanes_of(this); } + +#! The vector of the first three of lanes. +pub def vec3::of_lanes(lanes: f32x4): vec3 { return of_lanes::(lanes); } + +pub def vec3::add(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) + lanes_of(other)) if lanes_held(); + return vec3{ this.x + other.x, this.y + other.y, this.z + other.z }; +} + +pub def vec3::sub(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) - lanes_of(other)) if lanes_held(); + return vec3{ this.x - other.x, this.y - other.y, this.z - other.z }; +} + +pub def vec3::mul(&this, by: &f32): vec3 { + return of_lanes::(lanes_of(this) * f32x4::splat(by)) if lanes_held(); + return vec3{ this.x * by, this.y * by, this.z * by }; +} + +pub def vec3::mul(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) * lanes_of(other)) if lanes_held(); + return vec3{ this.x * other.x, this.y * other.y, this.z * other.z }; +} + +pub def vec3::div(&this, by: &f32): vec3 { + return of_lanes::(lanes_of(this) / f32x4::splat(by)) if lanes_held(); + return vec3{ this.x / by, this.y / by, this.z / by }; +} + +pub def vec3::div(&this, other: &vec3): vec3 { + if lanes_held() { + # The unnamed lanes divide 0 by 0, which is kept from the vector. + var made := of_lanes::(lanes_of(this) / lanes_of(other)); + made._w = 0; + return made; + } + return vec3{ this.x / other.x, this.y / other.y, this.z / other.z }; +} + +pub def vec3::negate(&this): vec3 { + return of_lanes::(-lanes_of(this)) if lanes_held(); + return vec3{ -this.x, -this.y, -this.z }; +} + +pub def vec3::equals(&this, other: &vec3): bool { + return this.x == other.x && this.y == other.y && this.z == other.z; +} + +pub def vec3::dot(&this, other: vec3): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2]; + } + return this.x * other.x + this.y * other.y + this.z * other.z; +} + +#! The vector at right angles to both, by the right hand: x cross y is z. Its +#! lanes would be shuffled, which no instruction does, so it's a number at a +#! time. +pub def vec3::cross(&this, other: vec3): vec3 { + return vec3{ + this.y * other.z - this.z * other.y, + this.z * other.x - this.x * other.z, + this.x * other.y - this.y * other.x, + }; +} + +pub val vec3::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec3::length_squared: f32 { + get => this.dot(this); +} + +pub def vec3::distance(&this, other: vec3): f32 { return (other - this).length; } + +#! The vector at a length of 1, or none where it has no length. +pub def vec3::normalized(&this): vec3 { + val l := this.length; + return l > 0 ? this / l : vec3{}; +} + +#! The vector a fraction of the way to another. +pub def vec3::lerp(&this, to: vec3, t: f32): vec3 { + return this + (to - this) * t; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec3::min(&this, other: vec3): vec3 { + return of_lanes::(lanes_of(this).min(&lanes_of(&other))) if lanes_held(); + return vec3{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z) }; +} + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec3::max(&this, other: vec3): vec3 { + return of_lanes::(lanes_of(this).max(&lanes_of(&other))) if lanes_held(); + return vec3{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z) }; +} + +#! Each number's distance from zero. +pub def vec3::abs(&this): vec3 { + return of_lanes::(lanes_of(this).abs()) if lanes_held(); + return vec3{ math::abs(this.x), math::abs(this.y), math::abs(this.z) }; +} diff --git a/linear/vec4.sakura b/linear/vec4.sakura new file mode 100644 index 0000000..99b536a --- /dev/null +++ b/linear/vec4.sakura @@ -0,0 +1,114 @@ +#! Contains `vec4`, a vector of four: a place of space with its `w`, as a +#! matrix projects one, or four numbers worked alike, as a color's. It's an +#! `f32x4`'s 16 bytes, which an executable holding vectors in registers works at +#! once. + +import std::math; +module linear; + +#! A vector of four, as a point of space with its `w`. +pub struct vec4 { + pub var x: f32; + pub var y: f32; + pub var z: f32; + pub var w: f32; +} + +pub val vec4::zero := vec4{ 0, 0, 0, 0 }; +pub val vec4::one := vec4{ 1, 1, 1, 1 }; + +#! Its numbers as lanes, for code of its own to work several at once. +pub def vec4::lanes(&this): f32x4 { return lanes_of(this); } + +#! The vector of lanes. +pub def vec4::of_lanes(lanes: f32x4): vec4 { return of_lanes::(lanes); } + +pub def vec4::add(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) + lanes_of(other)) if lanes_held(); + return vec4{ this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w }; +} + +pub def vec4::sub(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) - lanes_of(other)) if lanes_held(); + return vec4{ this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w }; +} + +pub def vec4::mul(&this, by: &f32): vec4 { + return of_lanes::(lanes_of(this) * f32x4::splat(by)) if lanes_held(); + return vec4{ this.x * by, this.y * by, this.z * by, this.w * by }; +} + +pub def vec4::mul(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) * lanes_of(other)) if lanes_held(); + return vec4{ this.x * other.x, this.y * other.y, this.z * other.z, this.w * other.w }; +} + +pub def vec4::div(&this, by: &f32): vec4 { + return of_lanes::(lanes_of(this) / f32x4::splat(by)) if lanes_held(); + return vec4{ this.x / by, this.y / by, this.z / by, this.w / by }; +} + +pub def vec4::div(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) / lanes_of(other)) if lanes_held(); + return vec4{ this.x / other.x, this.y / other.y, this.z / other.z, this.w / other.w }; +} + +pub def vec4::negate(&this): vec4 { + return of_lanes::(-lanes_of(this)) if lanes_held(); + return vec4{ -this.x, -this.y, -this.z, -this.w }; +} + +pub def vec4::equals(&this, other: &vec4): bool { + return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w; +} + +pub def vec4::dot(&this, other: vec4): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2] + p[3]; + } + return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w; +} + +pub val vec4::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec4::length_squared: f32 { + get => this.dot(this); +} + +#! The vector at a length of 1, or none where it has no length. +pub def vec4::normalized(&this): vec4 { + val l := this.length; + return l > 0 ? this / l : vec4{}; +} + +#! The vector a fraction of the way to another. +pub def vec4::lerp(&this, to: vec4, t: f32): vec4 { + return this + (to - this) * t; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec4::min(&this, other: vec4): vec4 { + return of_lanes::(lanes_of(this).min(&lanes_of(&other))) if lanes_held(); + return vec4{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z), math::min(this.w, other.w) }; +} + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec4::max(&this, other: vec4): vec4 { + return of_lanes::(lanes_of(this).max(&lanes_of(&other))) if lanes_held(); + return vec4{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z), math::max(this.w, other.w) }; +} + +#! Each number's distance from zero. +pub def vec4::abs(&this): vec4 { + return of_lanes::(lanes_of(this).abs()) if lanes_held(); + return vec4{ math::abs(this.x), math::abs(this.y), math::abs(this.z), math::abs(this.w) }; +} + +#! Its first three. +pub val vec4::xyz: vec3 { + get => vec3{ this.x, this.y, this.z }; +} diff --git a/tests/geometry.sakura b/tests/geometry.sakura new file mode 100644 index 0000000..0249f85 --- /dev/null +++ b/tests/geometry.sakura @@ -0,0 +1,159 @@ +#! Contains the tests of `geometry`: planes, and which side of one something +#! lies on; boxes and spheres holding places and meeting; rays meeting each +#! shape; a camera's frustum reaching what it sees; and the same bits whether +#! numbers are worked as lanes or one at a time, which `geometry.tests` and +#! `geometry.lanes.tests` each check. + +import std::testing; +import std::math; +import linear; +import geometry; + +# Whether two numbers are within a millionth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-5; +} + +def near(a: vec3, b: vec3): bool { + return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z); +} + +# How far along a ray it meets a shape, or -1 where it doesn't. +def hit_at(found: maybe): f32 { + return found is some(t) ? t : -1; +} + +@test def lays_out_its_shapes(t: &mut tester): void { + t.expects(size_of::() == 32 && size_of::() == 20 && size_of::() == 32 && size_of::() == 20); + t.expects(size_of::() == 128 && align_of::() == 4 && align_of::() == 4); +} + +@test def measures_planes(t: &mut tester): void { + val floor := plane::through(vec3{ 0, 2, 0 }, vec3{ 0, 5, 0 }); + t.expects(floor.normal == vec3::up && floor.distance == 2); + t.expects(floor.distance_to(vec3{ 3, 5, -1 }) == 3 && floor.distance_to(vec3::zero) == -2); + t.expects(floor.closest(vec3{ 3, 5, -1 }) == vec3{ 3, 2, -1 } && floor.flipped().distance_to(vec3::zero) == 2); + # Turning counterclockwise as seen from +z, it faces +z. + val wall := plane::of_points(vec3{ 0, 0, 1 }, vec3{ 1, 0, 1 }, vec3{ 0, 1, 1 }); + t.expects(wall.normal == vec3::back && wall.distance == 1); + t.expects(floor.side_of(bounds::around(vec3{ 0, 4, 0 }, vec3::one)) == side::front); + t.expects(floor.side_of(bounds::around(vec3{ 0, 2.5, 0 }, vec3::one)) == side::across); + t.expects(floor.side_of(bounds::around(vec3{ 5, -1, 5 }, vec3::one)) == side::back); + # A sphere touching it is on both sides. + t.expects(floor.side_of(sphere{ vec3::zero, 2 }) == side::across && floor.side_of(sphere{ vec3{ 0, -1, 0 }, 2 }) == side::back); +} + +@test def holds_and_meets_boxes_and_spheres(t: &mut tester): void { + val b := bounds{ vec3{ -1, 0, -1 }, vec3{ 1, 2, 1 } }; + t.expects(b.center == vec3{ 0, 1, 0 } && b.size == vec3{ 2, 2, 2 } && b.half_size == vec3::one); + t.expects(b.contains(vec3{ 1, 2, 1 }) && !b.contains(vec3{ 1, 2.5, 1 })); + t.expects(b.contains(bounds::around(b.center, vec3{ 0.5, 0.5, 0.5 })) && !b.contains(bounds::around(b.center, vec3{ 2, 0.5, 0.5 }))); + # Touching at a corner, they meet. + t.expects(b.overlaps(bounds{ vec3{ 1, 2, 1 }, vec3{ 3, 3, 3 } }) && !b.overlaps(bounds{ vec3{ 1.5, 0, 0 }, vec3{ 3, 1, 1 } })); + t.expects(b.closest(vec3{ 5, 1, -3 }) == vec3{ 1, 1, -1 } && b.closest(vec3{ 0, 1, 0 }) == vec3{ 0, 1, 0 }); + val points: vec3[3] = [vec3{ 1, 5, -2 }, vec3{ -3, 0, 4 }, vec3{ 2, 1, 0 }]; + t.expects(bounds::of(points[:]) == bounds{ vec3{ -3, 0, -2 }, vec3{ 2, 5, 4 } } && bounds::of(points[0:0]) == bounds::empty); + t.expects(bounds::empty.is_empty && !b.is_empty && bounds::empty.including(vec3::one) == bounds{ vec3::one, vec3::one }); + t.expects(b.merged(bounds::around(vec3{ 4, 0, 0 }, vec3::one)) == bounds{ vec3{ -1, -1, -1 }, vec3{ 5, 2, 1 } }); + # A quarter turn about z takes the box's reach along y to x, and along x to y. + val quarter := quat::axis_angle(vec3::back, math::pi as f32 / 2); + val turned := bounds::around(vec3::zero, vec3{ 1, 2, 3 }).transformed(mat4::compose(vec3{ 10, 0, 0 }, quarter, vec3::one)); + t.expects(near(turned.min, vec3{ 8, -1, -3 }) && near(turned.max, vec3{ 12, 1, 3 })); + t.expects(bounds::empty.transformed(mat4::identity).is_empty); + + val s := sphere{ vec3::zero, 2 }; + t.expects(s.contains(vec3{ 0, 2, 0 }) && !s.contains(vec3{ 1.5, 1.5, 0 })); + # Touching, they meet. + t.expects(s.overlaps(sphere{ vec3{ 3, 0, 0 }, 1 }) && !s.overlaps(sphere{ vec3{ 3, 0, 0.5 }, 0.9 })); + t.expects(s.overlaps(b) && b.overlaps(s) && !s.overlaps(bounds::around(vec3{ 3, 3, 0 }, vec3::one))); + t.expects(bounds::of(s) == bounds::around(vec3::zero, vec3{ 2, 2, 2 })); + t.expects(sphere::of(b).center == b.center && near(sphere::of(b).radius, math::sqrt(3f))); +} + +@test def casts_rays(t: &mut tester): void { + val r := ray::toward(vec3{ 0, 0, 10 }, vec3::zero); + t.expects(r.direction == vec3::forward && r.at(4) == vec3{ 0, 0, 6 }); + t.expects(r.closest(vec3{ 3, 0, 5 }) == vec3{ 0, 0, 5 } && r.closest(vec3{ 0, 0, 20 }) == r.origin); + # A wall ahead is met from in front, and one behind, and a floor it runs beside, aren't. + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::back))) == 9); + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::forward))) == 9); + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 11 }, vec3::back))) == -1 && hit_at(r.hit(plane::through(vec3::zero, vec3::up))) == -1); + # A sphere ahead is met at its surface, one begun within at 0, and one beside or behind not at all. + t.expects(hit_at(r.hit(sphere{ vec3::zero, 2 })) == 8 && hit_at(ray{ vec3::zero, vec3::up }.hit(sphere{ vec3::zero, 2 })) == 0); + t.expects(hit_at(r.hit(sphere{ vec3{ 3, 0, 0 }, 2 })) == -1 && hit_at(r.hit(sphere{ vec3{ 0, 0, 12 }, 1 })) == -1); + # A box ahead is met at its face, one begun within at 0, and one beside or behind not at all. + val b := bounds::around(vec3::zero, vec3::one); + t.expects(hit_at(r.hit(b)) == 9 && hit_at(ray{ vec3::zero, vec3{ 1, 2, 3 } }.hit(b)) == 0); + t.expects(hit_at(r.hit(bounds::around(vec3{ 3, 0, 0 }, vec3::one))) == -1 && hit_at(r.hit(bounds::around(vec3{ 0, 0, 12 }, vec3::one))) == -1); + # Slanting in, it meets the box where it crosses x = -1. + t.expects(near(hit_at(ray::toward(vec3{ -5, -5, 0 }, vec3::zero).hit(b)), 4 * math::sqrt(2f))); +} + +@test def culls_by_a_cameras_frustum(t: &mut tester): void { + # Looking from z = 10 at the origin, a quarter turn wide, from 1 to 100 away. + val f := frustum::of(mat4::perspective(math::pi as f32 / 2, 1, 1, 100) * mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero)); + # Its planes face in, so the place it looks at is in front of each. + for p in f.planes { + t.expects(p.distance_to(vec3::zero) > 0 && near(p.normal.length, 1)); + } + # The far plane is the difference of two rows nearly alike, so as near as an `f32` of 90 gets. + t.expects(near(f.planes[4].distance_to(vec3{ 0, 0, 9 }), 0) && math::abs(f.planes[5].distance_to(vec3{ 0, 0, -90 })) < 1e-3); + t.expects(f.contains(vec3::zero) && f.contains(vec3{ 9, 0, 0 })); + t.expects(!f.contains(vec3{ 0, 0, 9.5 }) && !f.contains(vec3{ 0, 0, -95 }) && !f.contains(vec3{ 11, 0, 0 }) && !f.contains(vec3{ 0, -11, 0 })); + # A box or sphere reaching in from beside is seen, and one wholly beside or behind isn't. + t.expects(f.overlaps(bounds::around(vec3{ 11, 0, 0 }, vec3{ 2, 1, 1 })) && !f.overlaps(bounds::around(vec3{ 14, 0, 0 }, vec3{ 2, 1, 1 }))); + t.expects(f.overlaps(bounds::around(vec3{ 0, 0, 9.5 }, vec3::one)) && !f.overlaps(bounds::around(vec3{ 0, 0, 12 }, vec3::one))); + t.expects(f.overlaps(sphere{ vec3{ 0, 0, 9.5 }, 1 }) && !f.overlaps(sphere{ vec3{ 0, 0, 11 }, 1 })); + t.expects(f.overlaps(sphere{ vec3{ 0, 11, 0 }, 1.5 }) && !f.overlaps(sphere{ vec3{ 0, 13, 0 }, 1.5 })); + # Made of its own planes, it's the same. + val again := frustum::of_planes(f.planes); + for i in 0..6u { + t.expects(again.planes[i] == f.planes[i]); + } + # A projection alone gives the frustum in the camera's space, an orthographic one a box. + val o := frustum::of(mat4::orthographic(-10, 10, -10, 10, 0, 50)); + t.expects(o.contains(vec3{ 9.5, -9.5, -49 }) && !o.contains(vec3{ 10.5, 0, -1 }) && !o.contains(vec3{ 0, 0, 1 }) && !o.contains(vec3{ 0, 0, -51 })); +} + +# The bits of each number, folded together, as FNV-1a folds bytes. +def fold(hash: u64, x: f32): u64 { + var held := x; + val bits := ((&mut held) as *mut u32)[0] as u64; + return (hash ^ bits) * 0x100000001B3; +} + +def fold(hash: u64, v: vec3): u64 { + return fold(fold(fold(hash, v.x), v.y), v.z); +} + +def fold(hash: u64, yes: bool): u64 { + return (hash ^ (yes ? 1 : 2)) * 0x100000001B3; +} + +@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void { + var h: u64 = 0xCBF29CE484222325; + val f := frustum::of(mat4::perspective(1.1, 1.5, 0.5, 60) * mat4::look_at(vec3{ 3, 4, 12 }, vec3{ 0, 1, 0 })); + val turn := quat::axis_angle(vec3{ 0.2, 1, -0.4 }, 0.37); + var p := vec3{ 0.3, -1.7, 2.9 }; + for i in 0..64u { + p = turn * (p * 1.07 + vec3{ 0.11, -0.05, 0.2 }); + val b := bounds::around(p, (turn * vec3{ 0.5, 1.25, 0.75 }).abs()); + val s := sphere{ p * 0.5, 1.5 }; + val r := ray::toward(vec3{ 20, -3, 7 }, p); + val wall := plane::of_points(p, p + vec3::right, p + turn * vec3::up); + val moved := b.transformed(mat4::compose(p, turn, vec3{ 1, 2, 0.5 })); + h = fold(fold(fold(h, moved.min), moved.max), b.closest(s.center)); + h = fold(fold(fold(h, hit_at(r.hit(b))), hit_at(r.hit(s))), hit_at(r.hit(wall))); + h = fold(fold(fold(h, r.closest(s.center)), wall.distance_to(s.center)), wall.closest(vec3::zero)); + h = fold(fold(fold(h, f.contains(p)), f.overlaps(b)), f.overlaps(s)); + h = fold(fold(fold(h, b.overlaps(s)), s.overlaps(moved)), b.overlaps(moved)); + h = fold(fold(h, wall.side_of(b) == side::across), wall.side_of(s) == side::front); + } + val corners: vec3[3] = [p, p * 2, -p]; + h = fold(fold(h, sphere::of(bounds::of(corners[:])).radius), f.planes[3].normal); + t.expects(h == expected_bits); +} + +# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a +# number at a time. +const expected_bits: u64 = 16338969092856802616; diff --git a/tests/linear.sakura b/tests/linear.sakura new file mode 100644 index 0000000..0d7ed24 --- /dev/null +++ b/tests/linear.sakura @@ -0,0 +1,179 @@ +#! Contains the tests of `linear`: vectors of two, three, and four; rotations; +#! matrices of three and four; projections; values read as lanes where they lie +#! unaligned; and the same bits whether numbers are worked as lanes or one at a +#! time, which `linear.tests` and `linear.lanes.tests` each check. + +import std::testing; +import std::math; +import linear; + +# Whether two numbers are within a millionth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-5; +} + +def near(a: vec3, b: vec3): bool { + return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z); +} + +def near(a: &mat4, b: &mat4): bool { + for i in 0..16u { + return false if !near(a.m[i], b.m[i]); + } + return true; +} + +def near(a: &mat3, b: &mat3): bool { + return near(a.x_axis, b.x_axis) && near(a.y_axis, b.y_axis) && near(a.z_axis, b.z_axis); +} + +@test def lays_out_its_numbers_as_lanes(t: &mut tester): void { + t.expects(size_of::() == 8 && size_of::() == 16 && size_of::() == 16 && size_of::() == 16); + t.expects(size_of::() == 48 && size_of::() == 64); + # Each is of `f32`s, so a field of one is wherever the struct holding it puts it. + t.expects(align_of::() == 4 && align_of::() == 4); + val v := vec3{ 1, 2, 3 }; + t.expects(v.x == 1 && v.y == 2 && v.z == 3 && vec3{ y = 5 } == vec3{ 0, 5, 0 }); +} + +@test def adds_scales_and_measures_vectors(t: &mut tester): void { + val a := vec3{ 1, 2, 3 }; + val b := vec3{ 4, -5, 6 }; + t.expects(a + b == vec3{ 5, -3, 9 } && a - b == vec3{ -3, 7, -3 } && -a == vec3{ -1, -2, -3 }); + t.expects(a * 2 == vec3{ 2, 4, 6 } && a * b == vec3{ 4, -10, 18 } && b / 2 == vec3{ 2, -2.5, 3 }); + t.expects(b / a == vec3{ 4, -2.5, 2 }); + t.expects(a.dot(b) == 12 && a.length_squared == 14 && near(a.length, math::sqrt(14f))); + t.expects(near(a.normalized().length, 1) && vec3::zero.normalized() == vec3::zero); + t.expects(near(vec3{ 0, 3, 4 }.distance(vec3::zero), 5)); + t.expects(a.lerp(b, 0.5) == vec3{ 2.5, -1.5, 4.5 }); + t.expects(a.min(b) == vec3{ 1, -5, 3 } && a.max(b) == vec3{ 4, 2, 6 } && b.abs() == vec3{ 4, 5, 6 }); + t.expects(vec3::right.cross(vec3::up) == vec3::back && vec3::up.cross(vec3::right) == vec3::forward); + + val c := vec2{ 3, 4 }; + t.expects(c + vec2::one == vec2{ 4, 5 } && c * 2 == vec2{ 6, 8 } && c.length == 5 && c.dot(vec2{ 1, 1 }) == 7); + t.expects(vec2{ 1, 0 }.cross(vec2{ 0, 1 }) == 1 && vec2{ 1, 0 }.perpendicular() == vec2{ 0, 1 }); + t.expects(near(c.normalized().length, 1) && c.lerp(vec2::zero, 0.5) == vec2{ 1.5, 2 }); + + val d := vec4{ 1, 2, 3, 4 }; + t.expects(d + vec4::one == vec4{ 2, 3, 4, 5 } && d * 0.5 == vec4{ 0.5, 1, 1.5, 2 } && d.dot(d) == 30); + t.expects(d.xyz == a && -d == vec4{ -1, -2, -3, -4 } && near(d.normalized().length, 1)); + t.expects(d.min(vec4{ 2, 2, 2, 2 }) == vec4{ 1, 2, 2, 2 } && (d - vec4{ 5, 5, 5, 5 }).abs() == vec4{ 4, 3, 2, 1 }); +} + +@test def turns_and_moves_vectors(t: &mut tester): void { + val quarter: f32 = math::pi as f32 / 2; + # A quarter turn about y takes x to -z, and about z takes x to y. + t.expects(near(quat::axis_angle(vec3::up, quarter) * vec3::right, vec3{ 0, 0, -1 })); + t.expects(near(quat::axis_angle(vec3::back, quarter) * vec3::right, vec3::up)); + # Turning by a rotation and then back changes nothing. + val q := quat::euler(0.3, -1.1, 0.7); + t.expects(near(q.length, 1) && near(q.inverse() * (q * vec3{ 1, 2, 3 }), vec3{ 1, 2, 3 })); + # Turning by one rotation after another is turning by their product. + val r := quat::axis_angle(vec3{ 1, 1, 0 }, 0.4); + t.expects(near((q * r) * vec3{ 1, 2, 3 }, q * (r * vec3{ 1, 2, 3 }))); + # A matrix composed of a transform does what the transform does. + val m := mat4::compose(vec3{ 5, 0, -2 }, q, vec3{ 2, 2, 2 }); + t.expects(near(m.transform_point(vec3{ 1, 0, 0 }), vec3{ 5, 0, -2 } + q * vec3{ 2, 0, 0 })); + t.expects(near(m.transform_vector(vec3{ 1, 0, 0 }), q * vec3{ 2, 0, 0 })); + t.expects(near(&(m * m.inverse()), &mat4::identity)); + val p := m * vec4{ 1, 0, 0, 1 }; + t.expects(near(p.xyz, m.transform_point(vec3{ 1, 0, 0 })) && near(p.w, 1)); + # Halfway between no turn and a third of one is a sixth. + val half := quat::identity.slerp(quat::axis_angle(vec3::up, 4 * quarter / 3), 0.5); + t.expects(near(half * vec3::right, vec3{ 0.5, 0, -math::sqrt(3f) / 2 })); + # Looking at a place turns -z toward it. + t.expects(near(quat::looking(vec3{ 1, 0, 0 }) * vec3::forward, vec3::right)); +} + +@test def projects_into_clip_space(t: &mut tester): void { + # The near plane is depth 0, the far one 1, and y points up. + val p := mat4::perspective(math::pi as f32 / 2, 2, 1, 100); + val near_point := p * vec4{ 0, 1, -1, 1 }; + t.expects(near(near_point.z / near_point.w, 0) && near(near_point.y / near_point.w, 1)); + val far_point := p * vec4{ 0, 0, -100, 1 }; + t.expects(near(far_point.z / far_point.w, 1)); + val o := mat4::orthographic(0, 200, 100, 0, -1, 1); + val corner := o * vec4{ 200, 100, 0, 1 }; + t.expects(near(corner.x, 1) && near(corner.y, -1) && near(corner.z, 0.5)); + # A camera looking at the origin from +z sees it straight ahead. + val view := mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero); + t.expects(near(view.transform_point(vec3::zero), vec3{ 0, 0, -10 })); + # A projection is undone, and a scale of zero can't be. + val clip := p * view; + t.expects(near(&(clip * clip.inverse()), &mat4::identity) && near(&(clip.inverse() * clip), &mat4::identity)); + t.expects(mat4::scaling(vec3::zero).inverse() == mat4{}); +} + +@test def works_matrices_of_three(t: &mut tester): void { + val q := quat::euler(0.3, -1.1, 0.7); + val r := mat3::rotation(q); + # A rotation's matrix turns as the rotation does, and its transpose back. + t.expects(near(r * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 }) && near(&(r * r.transposed()), &mat3::identity)); + t.expects(near(r.determinant, 1) && near(&r.inverse(), &r.transposed())); + # The rotation of a rotation's matrix is the rotation. + val back := quat::of_basis(r.x_axis, r.y_axis, r.z_axis); + t.expects(near(back * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 })); + val s := mat3::scaling(vec3{ 2, 4, 8 }); + t.expects(s.determinant == 64 && near(&(s * s.inverse()), &mat3::identity) && mat3::scaling(vec3::zero).inverse() == mat3{}); + t.expects(near(&(r * s), &mat4::compose(vec3::zero, q, vec3{ 2, 4, 8 }).linear_part())); + t.expects(s + s == s * 2 && (s - s) == mat3{}); +} + +# A value lying where a struct puts it, four bytes past a 16-byte boundary. +struct placed { + var tag: u32; + var at: vec3; + var turn: quat; + var by: mat4; +} + +@test def reads_values_where_they_lie(t: &mut tester): void { + var p := placed{ tag = 7, at = vec3{ 1, 2, 3 }, turn = quat::axis_angle(vec3::back, math::pi as f32 / 2), by = mat4::translation(vec3{ 1, 1, 1 }) }; + p.at = p.at * 2 + vec3::one; + t.expects(p.tag == 7 && p.at == vec3{ 3, 5, 7 }); + t.expects(near(p.turn * vec3::right, vec3::up) && near(p.by.transform_point(p.at), vec3{ 4, 6, 8 })); + t.expects(near(&(p.by * p.by), &mat4::translation(vec3{ 2, 2, 2 }))); + # Its lanes, and a vector of lanes. + val l := p.at.lanes(); + t.expects(l[0] == 3 && l[1] == 5 && l[2] == 7 && vec3::of_lanes(l) == p.at); + t.expects(vec4::of_lanes(f32x4::of([1.0, 2.0, 3.0, 4.0])) == vec4{ 1, 2, 3, 4 }); +} + +# The bits of each number, folded together, as FNV-1a folds bytes. +def fold(hash: u64, x: f32): u64 { + var held := x; + val bits := ((&mut held) as *mut u32)[0] as u64; + return (hash ^ bits) * 0x100000001B3; +} + +def fold(hash: u64, v: vec3): u64 { + return fold(fold(fold(hash, v.x), v.y), v.z); +} + +def fold(hash: u64, q: quat): u64 { + return fold(fold(fold(fold(hash, q.x), q.y), q.z), q.w); +} + +@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void { + var h: u64 = 0xCBF29CE484222325; + var v := vec3{ 0.1, -2.3, 4.5 }; + var q := quat::euler(0.2, 0.9, -0.4); + var m := mat4::compose(vec3{ 1, 2, 3 }, q, vec3{ 1.5, 0.5, 2 }); + val turn := quat::axis_angle(vec3{ 0.3, 1, -0.2 }, 0.05); + for i in 0..64u { + v = (v + vec3{ 0.25, 0.5, -0.125 }) * 0.9; + v = q * v; + v = m.transform_point(v) - m.transform_vector(v).normalized(); + q = (q * turn).normalized(); + m = m * mat4::rotation(turn); + h = fold(fold(fold(h, v), q), v.dot(vec3{ 1, 2, 3 })); + h = fold(h, (m * vec4{ v.x, v.y, v.z, 1 }).w); + h = fold(h, (mat3::rotation(q) * v).lerp(v.min(vec3::one).abs(), 0.25)); + } + h = fold(fold(h, q.slerp(quat::identity, 0.3)), m.inverse().m[7]); + t.expects(h == expected_bits); +} + +# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a +# number at a time. +const expected_bits: u64 = 2409136494821621507; diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..edc728c --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,10 @@ +#! Contains the `main` that runs the tests of `linear` and `geometry`, each in a +#! copy of the program of its own. `blossom test` runs them, and `-- --only TEXT` +#! those whose name holds the text. + +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} diff --git a/tools/bench.sakura b/tools/bench.sakura new file mode 100644 index 0000000..0c1b06a --- /dev/null +++ b/tools/bench.sakura @@ -0,0 +1,304 @@ +#! Times what `linear` does most, each over a thousand values two thousand +#! times, against the same worked a number at a time on a `vec3` of 12 bytes, +#! as hearth's scenes worked it before: adding and scaling vectors, their dots +#! and lengths, quaternions' products and turns, and matrices' products, +#! points, and inverses. +#! +#! Each pass is a function of its own, as a system is, and what it times is +#! called from elsewhere too, so nothing is inlined only for being called once: +#! the code an executable makes of a loop hangs on what is around it. +#! +#! `blossom build`, then run `linear.bench`, as an executable optimized with +#! `-O2`: the VM works numbers one at a time either way. + +import std::io; +import std::math; +import std::time; +import std::containers; +import linear; + +# A vector of three of 12 bytes, and the rest, as they were before. +struct old3 { var x: f32; var y: f32; var z: f32; } +struct oldq { var x: f32; var y: f32; var z: f32; var w: f32; } +struct oldm { var m: f32[16]; } + +def old3::add(&this, o: &old3): old3 { return old3{ this.x + o.x, this.y + o.y, this.z + o.z }; } +def old3::mul(&this, by: &f32): old3 { return old3{ this.x * by, this.y * by, this.z * by }; } +def old3::dot(&this, o: old3): f32 { return this.x * o.x + this.y * o.y + this.z * o.z; } +def old3::cross(&this, o: old3): old3 { return old3{ this.y * o.z - this.z * o.y, this.z * o.x - this.x * o.z, this.x * o.y - this.y * o.x }; } +def old3::normalized(&this): old3 { + val l := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + return l > 0 ? old3{ this.x / l, this.y / l, this.z / l } : old3{}; +} + +def oldq::mul(&this, o: &oldq): oldq { + return oldq{ + this.w * o.x + this.x * o.w + this.y * o.z - this.z * o.y, + this.w * o.y - this.x * o.z + this.y * o.w + this.z * o.x, + this.w * o.z + this.x * o.y - this.y * o.x + this.z * o.w, + this.w * o.w - this.x * o.x - this.y * o.y - this.z * o.z, + }; +} + +def oldq::turn(&this, v: &old3): old3 { + val q := old3{ this.x, this.y, this.z }; + val t := q.cross(v) * 2; + return v + t * this.w + q.cross(t); +} + +def oldm::mul(&this, other: &oldm): oldm { + var made := oldm{}; + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1] + + this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3]; + } + } + return made; +} + +# A matrix of three as one would be worked a number at a time. +struct old33 { var x: old3; var y: old3; var z: old3; } + +def old33::turned(&this, v: &old3): old3 { + return old3{ + this.x.x * v.x + this.y.x * v.y + this.z.x * v.z, + this.x.y * v.x + this.y.y * v.y + this.z.y * v.z, + this.x.z * v.x + this.y.z * v.y + this.z.z * v.z, + }; +} + +def old33::mul(&this, o: &old33): old33 { + return old33{ this.turned(&o.x), this.turned(&o.y), this.turned(&o.z) }; +} + +def oldm::point(&this, p: old3): old3 { + return old3{ + this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12], + this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13], + this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14], + }; +} + +const count: u64 = 1024; +const rounds: u64 = 2000; +const dt: f32 = 0.016; + +# What each pass works over. +struct data { + var ps: vector; + var vs: vector; + var qs: vector; + var ms: vector; + var rs: vector; + var ws: vector; + var out: vector; + var ops: vector; + var ovs: vector; + var oqs: vector; + var oms: vector; + var oout: vector; + var ors: vector; + var r_out: vector; + var or_out: vector; + var sum: f32; +} + +# How long a pass took, for each value, beside what it took before. +def report(what: strview, started: &instant, before: f64): f64 { + val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64; + if before == 0 { + println($"{what}: {ns} ns"); + } else { + println($"{what}: {ns} ns, before {before} ns, {before / ns}x"); + } + return ns; +} + +def step_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.ops[i] + d.ovs[i] * dt; } } + return report("vec3 p + v * dt, before", &at, 0); +} +def step(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ps[i] + d.vs[i] * dt; } } + _ = report("vec3 p + v * dt", &at, before); +} + +def dots_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.ops[i].dot(d.ovs[i]); } } + return report("vec3 dot, before", &at, 0); +} +def dots(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.ps[i].dot(d.vs[i]); } } + _ = report("vec3 dot", &at, before); +} + +def normals_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ovs[i] = (d.ovs[i] + d.ops[i]).normalized(); } } + return report("vec3 normalized, before", &at, 0); +} +def normals(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.vs[i] = (d.vs[i] + d.ps[i]).normalized(); } } + _ = report("vec3 normalized", &at, before); +} + +def crosses_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ovs[i] = d.ovs[i].cross(d.ops[i]); } } + return report("vec3 cross, before", &at, 0); +} +def crosses(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.vs[i] = d.vs[i].cross(d.ps[i]); } } + _ = report("vec3 cross", &at, before); +} + +def turns_before(d: &mut data, by: &oldq): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.oqs[i] = d.oqs[i] * by; } } + return report("quat * quat, before", &at, 0); +} +def turns(d: &mut data, by: &quat, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.qs[i] = d.qs[i] * by; } } + _ = report("quat * quat", &at, before); +} + +def rotations_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oqs[i].turn(&d.ops[i]); } } + return report("quat * vec3, before", &at, 0); +} +def rotations(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.qs[i] * d.ps[i]; } } + _ = report("quat * vec3", &at, before); +} + +def directions(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.rs[i] * d.ps[i]; } } + _ = report("mat3 * vec3", &at, 0); +} + +def tensors_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.or_out[i] = d.ors[i] * d.ors[(i + 1) % count]; } } + return report("mat3 * mat3, a number at a time", &at, 0); +} +def tensors(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.r_out[i] = d.rs[i] * d.rs[(i + 1) % count]; } } + _ = report("mat3 * mat3", &at, before); +} + +def products_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.oout[i] = d.oms[i] * d.oms[(i + 1) % count]; } } + return report("mat4 * mat4, before", &at, 0); +} +def products(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i] * d.ms[(i + 1) % count]; } } + _ = report("mat4 * mat4", &at, before); +} + +def projections(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ws[i] = d.ms[i] * d.ws[i]; } } + _ = report("mat4 * vec4", &at, 0); +} + +def points_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oms[i].point(d.ops[i]); } } + return report("mat4 transform_point, before", &at, 0); +} +def points(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ms[i].transform_point(d.ps[i]); } } + _ = report("mat4 transform_point", &at, before); +} + +def inverses(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i].inverse(); } } + _ = report("mat4 inverse", &at, 0); +} + +# Each of what's timed, called once more, so none is called from one place. +def elsewhere(d: &mut data): void { + d.ps[0] = d.ps[1] + d.vs[1] * 2; + d.ops[0] = d.ops[1] + d.ovs[1] * 2; + d.sum += d.ps[1].dot(d.vs[1]) + d.ops[1].dot(d.ovs[1]); + d.vs[0] = d.vs[1].normalized().cross(d.ps[1]); + d.ovs[0] = d.ovs[1].normalized().cross(d.ops[1]); + d.qs[0] = d.qs[1] * d.qs[2]; + d.oqs[0] = d.oqs[1] * d.oqs[2]; + d.ps[0] = d.qs[1] * (d.rs[1] * d.ps[1]); + d.ops[0] = d.oqs[1].turn(&d.ops[1]); + d.out[0] = d.ms[1] * d.ms[2]; + d.oout[0] = d.oms[1] * d.oms[2]; + d.r_out[0] = d.rs[1] * d.rs[2]; + d.or_out[0] = d.ors[1] * d.ors[2]; + d.ws[0] = d.ms[1] * d.ws[1]; + d.ps[0] = d.ms[1].transform_point(d.ps[1]); + d.ops[0] = d.oms[1].point(d.ops[1]); + d.out[0] = d.ms[1].inverse(); +} + +def main(): void { + println($"lanes held: {lanes_held()}"); + var d := data{ + ps = vector::::new(), vs = vector::::new(), qs = vector::::new(), ms = vector::::new(), + rs = vector::::new(), ws = vector::::new(), out = vector::::new(), ops = vector::::new(), + ovs = vector::::new(), oqs = vector::::new(), oms = vector::::new(), oout = vector::::new(), + ors = vector::::new(), r_out = vector::::new(), or_out = vector::::new(), + }; + for i in 0..count { + d.ps.append(vec3{ i as f32 * 0.001, 1, 2 }); + d.vs.append(vec3{ 0.5, 0.25, 0.125 }); + d.ops.append(old3{ i as f32 * 0.001, 1, 2 }); + d.ovs.append(old3{ 0.5, 0.25, 0.125 }); + val q := quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01); + d.qs.append(q); + d.oqs.append(oldq{ q.x, q.y, q.z, q.w }); + val r := mat3::rotation(q); + d.rs.append(r); + d.ors.append(old33{ + old3{ r.x_axis.x, r.x_axis.y, r.x_axis.z }, old3{ r.y_axis.x, r.y_axis.y, r.y_axis.z }, old3{ r.z_axis.x, r.z_axis.y, r.z_axis.z }, + }); + val m := mat4::compose(vec3{ i as f32, 1, 2 }, q, vec3{ 1, 2, 1 }); + d.ms.append(m); + d.oms.append(oldm{ m = m.m }); + d.ws.append(vec4{ i as f32, 1, 2, 1 }); + } + d.out.resize(count); + d.oout.resize(count); + d.r_out.resize(count); + d.or_out.resize(count); + elsewhere(&mut d); + + step(&mut d, step_before(&mut d)); + dots(&mut d, dots_before(&mut d)); + normals(&mut d, normals_before(&mut d)); + crosses(&mut d, crosses_before(&mut d)); + val turn := quat::axis_angle(vec3::up, 0.001); + turns(&mut d, &turn, turns_before(&mut d, &oldq{ turn.x, turn.y, turn.z, turn.w })); + rotations(&mut d, rotations_before(&mut d)); + directions(&mut d); + tensors(&mut d, tensors_before(&mut d)); + products(&mut d, products_before(&mut d)); + projections(&mut d); + points(&mut d, points_before(&mut d)); + inverses(&mut d); + + # What was worked, so none of it is left out. + println($"checks: {d.sum} {d.ps[3].y} {d.ops[3].y} {d.vs[5].x} {d.ovs[5].x} {d.qs[7].w} {d.oqs[7].w} {d.out[9].m[5]} {d.oout[9].m[5]} {d.ws[2].y}"); +} diff --git a/tools/geometry_bench.sakura b/tools/geometry_bench.sakura new file mode 100644 index 0000000..edc8aa0 --- /dev/null +++ b/tools/geometry_bench.sakura @@ -0,0 +1,236 @@ +#! Times what `geometry` does most, each over a thousand values two thousand +#! times, against the same worked a number at a time on a `vec3` of 12 bytes: +#! a camera's frustum culling boxes and spheres, rays meeting boxes and +#! spheres, and boxes moved by matrices. +#! +#! Each pass is a function of its own, as a system is, and what it times is +#! called from elsewhere too, so nothing is inlined only for being called once: +#! the code an executable makes of a loop hangs on what is around it. +#! +#! `blossom build`, then run `geometry.bench`, as an executable optimized with +#! `-O2`: the VM works numbers one at a time either way. + +import std::io; +import std::math; +import std::time; +import std::containers; +import linear; +import geometry; + +# The shapes as they'd be written a number at a time, of vectors of 12 bytes. +struct old3 { var x: f32; var y: f32; var z: f32; } +struct oldp { var x: f32; var y: f32; var z: f32; var d: f32; } +struct oldb { var min: old3; var max: old3; } +struct olds { var center: old3; var radius: f32; } +struct oldr { var origin: old3; var direction: old3; } +struct oldm { var m: f32[16]; } + +# Whether a box is in front of each of six planes, of the corner furthest in +# front of each, a plane at a time. +def oldb::seen(&this, planes: &oldp[6]): bool { + for i in 0..6u { + val p := planes[i]; + val x := p.x < 0 ? this.min.x : this.max.x; + val y := p.y < 0 ? this.min.y : this.max.y; + val z := p.z < 0 ? this.min.z : this.max.z; + return false if p.x * x + p.y * y + p.z * z - p.d < 0; + } + return true; +} + +def olds::seen(&this, planes: &oldp[6]): bool { + for i in 0..6u { + val p := planes[i]; + return false if p.x * this.center.x + p.y * this.center.y + p.z * this.center.z - p.d + this.radius < 0; + } + return true; +} + +# Where a ray meets a box, or -1, between the box's faces along each axis. +def oldr::hit(&this, b: &oldb): f32 { + val ix := 1 / this.direction.x; + val iy := 1 / this.direction.y; + val iz := 1 / this.direction.z; + val x0 := (b.min.x - this.origin.x) * ix; + val x1 := (b.max.x - this.origin.x) * ix; + val y0 := (b.min.y - this.origin.y) * iy; + val y1 := (b.max.y - this.origin.y) * iy; + val z0 := (b.min.z - this.origin.z) * iz; + val z1 := (b.max.z - this.origin.z) * iz; + val enter := math::max(math::max(math::min(x0, x1), math::min(y0, y1)), math::max(math::min(z0, z1), 0)); + val leave := math::min(math::min(math::max(x0, x1), math::max(y0, y1)), math::max(z0, z1)); + return enter <= leave ? enter : -1; +} + +# Where a ray meets a sphere, or -1. +def oldr::hit(&this, s: &olds): f32 { + val mx := this.origin.x - s.center.x; + val my := this.origin.y - s.center.y; + val mz := this.origin.z - s.center.z; + val c := mx * mx + my * my + mz * mz - s.radius * s.radius; + return 0 if c <= 0; + val b := mx * this.direction.x + my * this.direction.y + mz * this.direction.z; + return -1 if b >= 0; + val a := this.direction.x * this.direction.x + this.direction.y * this.direction.y + this.direction.z * this.direction.z; + val d := b * b - a * c; + return d < 0 ? -1 : (-b - math::sqrt(d)) / a; +} + +# The box holding a box a matrix moves. +def oldb::moved(&this, by: &oldm): oldb { + val m := &by.m; + val cx := (this.min.x + this.max.x) * 0.5; + val cy := (this.min.y + this.max.y) * 0.5; + val cz := (this.min.z + this.max.z) * 0.5; + val hx := (this.max.x - this.min.x) * 0.5; + val hy := (this.max.y - this.min.y) * 0.5; + val hz := (this.max.z - this.min.z) * 0.5; + val x := m[0] * cx + m[4] * cy + m[8] * cz + m[12]; + val y := m[1] * cx + m[5] * cy + m[9] * cz + m[13]; + val z := m[2] * cx + m[6] * cy + m[10] * cz + m[14]; + val rx := math::abs(m[0]) * hx + math::abs(m[4]) * hy + math::abs(m[8]) * hz; + val ry := math::abs(m[1]) * hx + math::abs(m[5]) * hy + math::abs(m[9]) * hz; + val rz := math::abs(m[2]) * hx + math::abs(m[6]) * hy + math::abs(m[10]) * hz; + return oldb{ old3{ x - rx, y - ry, z - rz }, old3{ x + rx, y + ry, z + rz } }; +} + +const count: u64 = 1024; +const rounds: u64 = 2000; + +# What each pass works over. +struct data { + var boxes: vector; + var spheres: vector; + var rays: vector; + var ms: vector; + var moved: vector; + var oboxes: vector; + var ospheres: vector; + var orays: vector; + var oms: vector; + var omoved: vector; + var seen: u64; + var sum: f32; +} + +# How long a pass took, for each value, beside what it took before. +def report(what: strview, started: &instant, before: f64): f64 { + val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64; + if before == 0 { + println($"{what}: {ns} ns"); + } else { + println($"{what}: {ns} ns, before {before} ns, {before / ns}x"); + } + return ns; +} + +def culled_boxes_before(d: &mut data, planes: &oldp[6]): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += d.oboxes[i].seen(planes) ? 1 : 0; } } + return report("frustum overlaps bounds, before", &at, 0); +} +def culled_boxes(d: &mut data, f: &frustum, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.boxes[i]) ? 1 : 0; } } + _ = report("frustum overlaps bounds", &at, before); +} + +def culled_spheres_before(d: &mut data, planes: &oldp[6]): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += d.ospheres[i].seen(planes) ? 1 : 0; } } + return report("frustum overlaps sphere, before", &at, 0); +} +def culled_spheres(d: &mut data, f: &frustum, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.spheres[i]) ? 1 : 0; } } + _ = report("frustum overlaps sphere", &at, before); +} + +def boxes_hit_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.oboxes[(i + 1) % count]); } } + return report("ray hit bounds, before", &at, 0); +} +def boxes_hit(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.boxes[(i + 1) % count]) is some(t) ? t : -1; } } + _ = report("ray hit bounds", &at, before); +} + +def spheres_hit_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.ospheres[(i + 1) % count]); } } + return report("ray hit sphere, before", &at, 0); +} +def spheres_hit(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.spheres[(i + 1) % count]) is some(t) ? t : -1; } } + _ = report("ray hit sphere", &at, before); +} + +def moves_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.omoved[i] = d.oboxes[i].moved(&d.oms[i]); } } + return report("bounds transformed, before", &at, 0); +} +def moves(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.moved[i] = d.boxes[i].transformed(d.ms[i]); } } + _ = report("bounds transformed", &at, before); +} + +# Each of what's timed, called once more, so none is called from one place. +def elsewhere(d: &mut data, f: &frustum, planes: &oldp[6]): void { + d.seen += (f.overlaps(d.boxes[1]) ? 1 : 0) + (d.oboxes[1].seen(planes) ? 1 : 0); + d.seen += (f.overlaps(d.spheres[1]) ? 1 : 0) + (d.ospheres[1].seen(planes) ? 1 : 0); + d.sum += d.orays[1].hit(&d.oboxes[2]) + d.orays[1].hit(&d.ospheres[2]); + d.sum += (d.rays[1].hit(d.boxes[2]) is some(t) ? t : -1) + (d.rays[1].hit(d.spheres[2]) is some(u) ? u : -1); + d.moved[0] = d.boxes[1].transformed(d.ms[1]); + d.omoved[0] = d.oboxes[1].moved(&d.oms[1]); +} + +def old3_of(v: vec3): old3 { + return old3{ v.x, v.y, v.z }; +} + +def main(): void { + println($"lanes held: {lanes_held()}"); + var d := data{ + boxes = vector::::new(), spheres = vector::::new(), rays = vector::::new(), ms = vector::::new(), + moved = vector::::new(), oboxes = vector::::new(), ospheres = vector::::new(), + orays = vector::::new(), oms = vector::::new(), omoved = vector::::new(), + }; + # A camera at the middle of a field of boxes, seeing about half of them. + val f := frustum::of(mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 400) * mat4::look_at(vec3{ 0, 5, 0 }, vec3{ 0, 0, -10 })); + var planes: oldp[6]; + for i in 0..6u { + val p := f.planes[i]; + planes[i] = oldp{ p.normal.x, p.normal.y, p.normal.z, p.distance }; + } + for i in 0..count { + val at := vec3{ (i % 32) as f32 * 8 - 128, (i % 3) as f32, (i / 32) as f32 * 8 - 128 }; + val b := bounds::around(at, vec3{ 1, 2, 1.5 }); + d.boxes.append(b); + d.oboxes.append(oldb{ old3_of(b.min), old3_of(b.max) }); + d.spheres.append(sphere{ at, 2 }); + d.ospheres.append(olds{ old3_of(at), 2 }); + val r := ray::toward(vec3{ 0, 5, 0 }, at); + d.rays.append(r); + d.orays.append(oldr{ old3_of(r.origin), old3_of(r.direction) }); + val m := mat4::compose(at, quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01), vec3{ 1, 2, 1 }); + d.ms.append(m); + d.oms.append(oldm{ m = m.m }); + } + d.moved.resize(count); + d.omoved.resize(count); + elsewhere(&mut d, &f, &planes); + + culled_boxes(&mut d, &f, culled_boxes_before(&mut d, &planes)); + culled_spheres(&mut d, &f, culled_spheres_before(&mut d, &planes)); + boxes_hit(&mut d, boxes_hit_before(&mut d)); + spheres_hit(&mut d, spheres_hit_before(&mut d)); + moves(&mut d, moves_before(&mut d)); + + # What was worked, so none of it is left out. + println($"checks: {d.seen} {d.sum} {d.moved[3].max.y} {d.omoved[3].max.y}"); +}