commit 64d4c6f88b942399da200ef8c7df710c4c07bc0f Author: SoraKatadzuma Date: Tue Oct 27 22:08:25 2026 -0500 Initial Commit 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..771bbe6 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# 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. 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 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(); +``` +`tests/linear.sakura` drives all of it, and `tools/bench.sakura` times it. + +A project reads it by requiring this folder, or its remote, and naming `linear` among a target's `deps`: + +```yaml +requires: +- ../linear +targets: +- name: game + type: program + deps: [linear] +``` + +## 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 | + +## 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 and lengths, `distance`, the products of `mat4`s, and a `quat` turning a vector, by its matrix's columns. What gathers one vector's numbers into other lanes, as a cross product or a quaternions' product would, or splats each into lanes, as one vector a matrix turns, it works faster a number at a time, as the bench found, so those are. `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. + +## 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`, on a Ryzen 9 9950X3D, against the same worked a number at a time on a `vec3` of 12 bytes, as hearth's scenes worked them before `linear`: + +| What | Before | `linear` | | +|---|---|---|---| +| `p + v * dt` of `vec3`s | 3.51 ns | 0.87 ns | 4.0x | +| `dot` of `vec3`s | 5.80 ns | 3.19 ns | 1.8x | +| `quat * vec3` | 33.1 ns | 16.6 ns | 2.0x | +| `mat4 * mat4` | 33.7 ns | 20.6 ns | 1.6x | +| `quat * quat` | 7.87 ns | 7.87 ns | 1.0x | +| `vec3::normalized` | 4.75 ns | 6.67 ns | 0.71x | +| `vec3::cross` | 4.20 ns | 6.91 ns | 0.61x | +| `mat4::transform_point` | 5.05 ns | 7.52 ns | 0.67x | +| `mat3 * mat3` | 14.9 ns | 22.6 ns | 0.66x | +| `mat3 * vec3` | | 7.01 ns | | +| `mat4 * vec4` | | 8.27 ns | | +| `mat4::inverse` | | 60.4 ns | | + +What works whole vectors gains most: integrating places by velocities, as physics does for every body, is four times as fast. What builds a `vec3` a number at a time costs about 2 ns more than it did of 12 bytes, which the same code built of 12 bytes doesn't, and lanes don't recover there. 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. + +## 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; 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. + +## 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`. diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..1fa2925 --- /dev/null +++ b/blossomfile @@ -0,0 +1,53 @@ +name: linear +gpid: malunal +semv: 0.1.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 + +targets: +- name: linear + type: library + root: ./linear + deps: + - 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 + +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] + +exports: +- linear + +package: + desc: Vectors, quaternions, and matrices of f32, worked as SIMD lanes where an executable holds them. + auth: John Christman diff --git a/linear/linear.sakura b/linear/linear.sakura new file mode 100644 index 0000000..3018c05 --- /dev/null +++ b/linear/linear.sakura @@ -0,0 +1,38 @@ +#! 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: what works whole +#! vectors, as adding, scaling, and dots do, the products of 4 by 4 matrices, +#! and a rotation turning a vector by its matrix's columns, it works as lanes +#! at once. What gathers one vector's numbers into +#! lanes, as a cross product, or splats them, as one vector a matrix turns, it +#! outruns lanes with a number at a time, as the bench shows, so that's how +#! those are worked. The virtual machine, which works lanes one at a time, +#! works everything a number at a time. Both ways give the same bits. + +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..8a61055 --- /dev/null +++ b/linear/mat3.sakura @@ -0,0 +1,100 @@ +#! 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. A number at a time, which an executable outruns lanes +#! with for three columns. +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. A number at a time, which an executable outruns lanes with +#! for one vector. +pub def mat3::mul(&this, v: &vec3): vec3 { + 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); + return mat3{} if det == 0; + val k := 1 / det; + 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..731d1a5 --- /dev/null +++ b/linear/mat4.sakura @@ -0,0 +1,212 @@ +#! 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 one vector is worked a number at a time, which an +# executable outruns lanes with for one. + +pub def mat4::mul(&this, v: &vec4): vec4 { + 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 { + 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 { + 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 +#! cofactors, a number at a time, which outruns gathering them into lanes. +pub def mat4::inverse(&this): mat4 { + val a := &this.m; + var inv: f32[16]; + inv[0] = a[5] * a[10] * a[15] - a[5] * a[11] * a[14] - a[9] * a[6] * a[15] + a[9] * a[7] * a[14] + a[13] * a[6] * a[11] - a[13] * a[7] * a[10]; + inv[4] = -a[4] * a[10] * a[15] + a[4] * a[11] * a[14] + a[8] * a[6] * a[15] - a[8] * a[7] * a[14] - a[12] * a[6] * a[11] + a[12] * a[7] * a[10]; + inv[8] = a[4] * a[9] * a[15] - a[4] * a[11] * a[13] - a[8] * a[5] * a[15] + a[8] * a[7] * a[13] + a[12] * a[5] * a[11] - a[12] * a[7] * a[9]; + inv[12] = -a[4] * a[9] * a[14] + a[4] * a[10] * a[13] + a[8] * a[5] * a[14] - a[8] * a[6] * a[13] - a[12] * a[5] * a[10] + a[12] * a[6] * a[9]; + inv[1] = -a[1] * a[10] * a[15] + a[1] * a[11] * a[14] + a[9] * a[2] * a[15] - a[9] * a[3] * a[14] - a[13] * a[2] * a[11] + a[13] * a[3] * a[10]; + inv[5] = a[0] * a[10] * a[15] - a[0] * a[11] * a[14] - a[8] * a[2] * a[15] + a[8] * a[3] * a[14] + a[12] * a[2] * a[11] - a[12] * a[3] * a[10]; + inv[9] = -a[0] * a[9] * a[15] + a[0] * a[11] * a[13] + a[8] * a[1] * a[15] - a[8] * a[3] * a[13] - a[12] * a[1] * a[11] + a[12] * a[3] * a[9]; + inv[13] = a[0] * a[9] * a[14] - a[0] * a[10] * a[13] - a[8] * a[1] * a[14] + a[8] * a[2] * a[13] + a[12] * a[1] * a[10] - a[12] * a[2] * a[9]; + inv[2] = a[1] * a[6] * a[15] - a[1] * a[7] * a[14] - a[5] * a[2] * a[15] + a[5] * a[3] * a[14] + a[13] * a[2] * a[7] - a[13] * a[3] * a[6]; + inv[6] = -a[0] * a[6] * a[15] + a[0] * a[7] * a[14] + a[4] * a[2] * a[15] - a[4] * a[3] * a[14] - a[12] * a[2] * a[7] + a[12] * a[3] * a[6]; + inv[10] = a[0] * a[5] * a[15] - a[0] * a[7] * a[13] - a[4] * a[1] * a[15] + a[4] * a[3] * a[13] + a[12] * a[1] * a[7] - a[12] * a[3] * a[5]; + inv[14] = -a[0] * a[5] * a[14] + a[0] * a[6] * a[13] + a[4] * a[1] * a[14] - a[4] * a[2] * a[13] - a[12] * a[1] * a[6] + a[12] * a[2] * a[5]; + inv[3] = -a[1] * a[6] * a[11] + a[1] * a[7] * a[10] + a[5] * a[2] * a[11] - a[5] * a[3] * a[10] - a[9] * a[2] * a[7] + a[9] * a[3] * a[6]; + inv[7] = a[0] * a[6] * a[11] - a[0] * a[7] * a[10] - a[4] * a[2] * a[11] + a[4] * a[3] * a[10] + a[8] * a[2] * a[7] - a[8] * a[3] * a[6]; + inv[11] = -a[0] * a[5] * a[11] + a[0] * a[7] * a[9] + a[4] * a[1] * a[11] - a[4] * a[3] * a[9] - a[8] * a[1] * a[7] + a[8] * a[3] * a[5]; + inv[15] = a[0] * a[5] * a[10] - a[0] * a[6] * a[9] - a[4] * a[1] * a[10] + a[4] * a[2] * a[9] + a[8] * a[1] * a[6] - a[8] * a[2] * a[5]; + val det := a[0] * inv[0] + a[1] * inv[4] + a[2] * inv[8] + a[3] * inv[12]; + return mat4{} if det == 0; + val k := 1 / det; + for i in 0..16u { + inv[i] *= k; + } + return mat4{ m = inv }; +} diff --git a/linear/quat.sakura b/linear/quat.sakura new file mode 100644 index 0000000..56f8ed7 --- /dev/null +++ b/linear/quat.sakura @@ -0,0 +1,145 @@ +#! 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, scaled by the +#! vector's numbers and added, are worked as lanes, which an executable works +#! twice as fast as the crosses of the rotation's axis. +pub def quat::mul(&this, v: &vec3): vec3 { + val r := mat3::rotation(this); + if lanes_held() { + return of_lanes::(lanes_of(&r.x_axis) * f32x4::splat(v.x) + lanes_of(&r.y_axis) * f32x4::splat(v.y) + + lanes_of(&r.z_axis) * f32x4::splat(v.z)); + } + return r * 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 := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + return quat::identity if l == 0; + val k := 1 / l; + return quat{ this.x * k, this.y * k, this.z * k, this.w * k }; +} + +#! 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..e3dcc79 --- /dev/null +++ b/linear/vec2.sakura @@ -0,0 +1,66 @@ +#! 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 := this.length; + return vec2{} if l == 0; + val k := 1 / l; + return vec2{ this.x * k, this.y * k }; +} + +#! 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..1565cdc --- /dev/null +++ b/linear/vec3.sakura @@ -0,0 +1,154 @@ +#! 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 { + if lanes_held() { + val d := lanes_of(&other) - lanes_of(this); + val p := d * d; + return math::sqrt(p[0] + p[1] + p[2]); + } + val d := vec3{ other.x - this.x, other.y - this.y, other.z - this.z }; + return math::sqrt(d.x * d.x + d.y * d.y + d.z * d.z); +} + +#! The vector at a length of 1, or none where it has no length. A number at a +#! time, which an executable outruns lanes with, the square root between them. +pub def vec3::normalized(&this): vec3 { + val l := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + return vec3{} if l == 0; + val k := 1 / l; + return vec3{ this.x * k, this.y * k, this.z * k }; +} + +# The methods below work their lanes themselves rather than calling the +# operators', since an operator called within one is left a call. + +#! The vector a fraction of the way to another. +pub def vec3::lerp(&this, to: vec3, t: f32): vec3 { + if lanes_held() { + val from := lanes_of(this); + return of_lanes::(from + (lanes_of(&to) - from) * f32x4::splat(t)); + } + return vec3{ this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t, this.z + (to.z - this.z) * 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..badb378 --- /dev/null +++ b/linear/vec4.sakura @@ -0,0 +1,126 @@ +#! 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. A number at a +#! time, which an executable outruns lanes with, the square root between them. +pub def vec4::normalized(&this): vec4 { + val l := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + return vec4{} if l == 0; + val k := 1 / l; + return vec4{ this.x * k, this.y * k, this.z * k, this.w * k }; +} + +# The methods below work their lanes themselves rather than calling the +# operators', since an operator called within one is left a call. + +#! The vector a fraction of the way to another. +pub def vec4::lerp(&this, to: vec4, t: f32): vec4 { + if lanes_held() { + val from := lanes_of(this); + return of_lanes::(from + (lanes_of(&to) - from) * f32x4::splat(t)); + } + return vec4{ + this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t, this.z + (to.z - this.z) * t, this.w + (to.w - this.w) * 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/linear.sakura b/tests/linear.sakura new file mode 100644 index 0000000..2cb93f2 --- /dev/null +++ b/tests/linear.sakura @@ -0,0 +1,175 @@ +#! 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 })); +} + +@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 = 3034663111268630348; diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..283f85b --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,10 @@ +#! Contains the `main` that runs the tests of `linear`, 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}"); +}