32 KiB
Plan: vectors, matrices and quaternions
Written 2026-10-14, and brought up to date 2026-10-20 for what was built since (method
bounds, std::math, simd and the optimizer's passes), probed and measured again.
This is a proposal. std is yours, so the decisions at the end are yours to make. Nothing
in std is built yet. Two compiler bugs the first probes found are fixed already (see
"Fixed along the way").
Comes after the ffi plan, now built: std::sys is system, and @foreign and
@link are extern sections.
Built in the rebuild alone (roadmap.md, decision 1). Where this plan says both compilers, C's half is left out. What was measured in C stays as measured.
What it is: the objects of 2D and 3D math, with their operators:
- vectors of two, three and four numbers;
- square matrices of two, three and four columns;
- quaternions, for rotations;
- transforms of a position, a rotation and a scale;
- the camera's matrices, as Vulkan, OpenGL and Direct3D want them.
Its users:
- programs drawing through Vulkan, whose vertices, uniforms and push constants hold these;
- games and simulations: movement, collision, physics and cameras;
- tools reading 3D formats, such as glTF, whose nodes are transforms;
- grids and screens, with vectors of integers as keys and positions.
It builds on what's built:
- Operators by method (the README's "Operators").
a + b,m * vandq * rare methods. std::math(std/math/, built 2026-10-14). A length needs itssqrt, a rotation itssinandcos, andslerpitsacos. Itsrealtrait says which types those apply to. Its constants aref64s, sof32code writesmath::pi as f32.- Bounds on a generic type's methods (built 2026-10-19), so
lengthiswhere T: real. simd(std/simd.sakura, built 2026-10-14), whichvec4may work through (decision 11).
Probed: again on 2026-10-20 (plans/linear/ in the scratchpad), under both
compilers, in the VM and as executables at -O2. Every result here was the same
everywhere. Two that weren't are under "Found along the way".
struct vec3<T> : additive, indexable<u64, T> where T: numericwithadd,sub,negate,mulandequalsgave+,-,-v,*,==and+=:- for
f32,f64andi32; - with
v * 2.0taking the constant as the vector's own number; - with a vector times a vector, and a vector times a number, as overloads of
mul.
- for
- A number on the left, as
2.0f * v, throughdef f32::mul(&this, v: &vec3<f32>). But2.0 * vis still refused for anf32vector: an untyped2.0is anf64, which asks forf64::mul(decision 2). - A matrix times a vector, as columns times components, summed, and
mat3f::identity()through the alias. - Indexing:
v[1] = 9, throughindexableand the fields read as an array, andv[3]stopping the program. - A swizzle,
a.xy, as a property. - Methods for reals alone, as
def vec3<T>::length(&this): T where T: real, now in both compilers. Asking it of avec3<i32>is an error where it's written, naming the bound. - Hashing integers alone, as
def vec2<T>::hash(&this): u64 where T: integer, so avec2<i32>keys adict. - Constants made by
crossandlength, and a Vulkan projection throughmath::tanwith itsclip_spacedefaulted, in both compilers. - One type of any length,
struct vec<T, const N: u64>holding aT[N], with its operators,length, andcrossrefusing other lengths byif const N != 3 { compile_error(...) }(decision 3).
Measured on 2026-10-20, the best of five, pinned to a performance core of a busy
machine: ten million steps of total = total + step * half on vec3<f32>, against the
same written as three fields. The 2026-10-14 times are in parentheses.
| Where | Operators | Fields |
|---|---|---|
The rebuild, -O2 |
166 ms (400) | 67 ms (60) |
C, -O2 |
417 ms, the same with 0.5 written in place of half (430, and 2.1 s) |
159 ms (126) |
- Inlining is done. Both compilers inline
addandmulat-O2now, with a dozen callers too. The rebuild movesstep * halfout of the loop, and zeroes nothing and checks no pointers in it. - What's left is the rebuild's, for
f32and other 4-byte numbers:- each
f32operation is still done in double precision. An add isaddsd, thencvtsd2ssandcvtss2sd: three instructions for oneaddss. The fields pay it too, and take twice whatf64's do: 67 ms against 31; - the vector's fields are written to the stack and read back each step: 36
instructions a step, against the fields' 12. A
vec3<i32>does the same, 23 ms against 11, while avec3<f64>stays in registers, its operators as fast as its fields: 29 ms and 31.
- each
- C no longer boxes an
f32lent by reference.step * 0.5andstep.mul(0.5)cost what they cost with a variable. Its code is still about 2.5 times as slow as the rebuild's, and doesf32in double precision too. - Lanes: a
vec4<f32>whoseaddandmulread its fields as onef32x4wherelanes_held()took 73 ms, against 67 written as four fields, and 182 where its operators work field by field. The bits were the same.
So the types can be built today. Vectors of f64 are as fast as written out already.
Those of f32 need the rebuild's code generator, or lanes for vec4 (decision 11).
What's there now
- Operators by method (the README's "Operators"), chosen by the right operand, with
a number on the left asking its own type, and
a += basa = a + b. - Numbers' methods beside the compiler's: a program may declare
f32::multaking a vector. - Bounds on a generic type's methods, in both compilers since 2026-10-19, as
def vec3<T>::length(&this): T where T: real. Only the instances meeting them have the method. - Constant parameters and
for const, sovec<T, 3>can be written, one body for every length (decision 3). indexable, properties,if const, and static methods through an alias, asmat3f::identity(). Generic types have no associated variables, sovec3<T>::zerois a function.std::math(the README's "Math"):sqrt,sin,cos,tan,acos,atan2andfmaof anyreal, with the same bits in the VM, in executables and in constants. It has noradians,degrees,lerp,smoothsteporremapyet.simd<L[N]>(the README's "Vectors"):f32x4and the rest, held in registers by the rebuild's-O2executables, whichlanes_held()says while compiling. Anf32x4is 16 bytes aligned to 4, as a packedvec4fis.f32is rounded after every operation, in the VM and in executables, so the two agree. Both compilers' executables work it in double precision.
What it needs
- Vectors of 2, 3 and 4, of any number:
f32andf64for geometry, and integers for grids and pixels. - Their arithmetic as operators: with each other component by component, with a number on either side, and negation.
- Their geometry: dot and cross products, length, distance, normalizing, interpolating, reflecting and projecting.
- Matrices of 2, 3 and 4:
- products with each other and with vectors;
- transposing, the determinant and the inverse;
- translating, scaling and rotating;
- looking at a point;
- perspective and orthographic projections.
- Quaternions:
- from an axis and an angle, from Euler angles, from one direction to another, and from a matrix;
- composing and rotating vectors;
- interpolating;
- to a matrix and back.
- Transforms: a position, a rotation and a scale, combined, inverted, applied and interpolated.
- Layouts C and the GPU read, so a
vec3<f32>is three floats one after another. - The same bits in the VM, in executables, and in constants.
- As fast as written out, at
-O2.
How it fits the rules
- Plain data. Vectors, matrices and quaternions copy freely, hold nothing, close
nothing, and are
equatable. Vectors of integers arehashable, by ahashboundedwhere T: integer, so they key adict. - Arithmetic is operators, by method. A vector is
additive. It isn'tnumeric, since*between two vectors isn't a ring's product, and there's no%. - Nothing stops the program.
- Normalizing a zero vector gives NaNs, as IEEE 754 does, and
normalize_orgives a fallback. - An inverse is a
maybe, which isnothingwhere the determinant is zero. - So nothing calls
contract, and every function runs in a constant in C too, which refuses constants that could reachcontract.
- Normalizing a zero vector gives NaNs, as IEEE 754 does, and
- Methods for reals alone are bounded
where T: real, so asking one of avec3iis an error where it's written. Quaternions and transforms are of reals alone, bounded so on the type. - The same bits everywhere:
- each operation rounds as its type does, and nothing fuses a multiply and an add but
math::fma; - the functions are
std::math's, which agree by construction; simd's lanes give the bits the fields would, sovec4may take either way.
- each operation rounds as its type does, and nothing fuses a multiply and an add but
The types (decisions 1 to 5)
module std::math;
pub struct vec2<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; }
pub struct vec3<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; }
pub struct vec4<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }
#! Column by column, as GLSL, SPIR-V and Vulkan lay them out (decision 5).
pub struct mat2<T> where T: numeric { pub var columns: vec2<T>[2]; }
pub struct mat3<T> where T: numeric { pub var columns: vec3<T>[3]; }
pub struct mat4<T> where T: numeric { pub var columns: vec4<T>[4]; }
#! A rotation, `w` last, as glm, Eigen and glTF hold it.
pub struct quat<T> where T: real { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }
#! Where something is, how it's turned, and how large, applied scale first.
pub struct transform<T> where T: real {
pub var translation: vec3<T>;
pub var rotation: quat<T>;
pub var scale: vec3<T>;
}
pub type vec2f = vec2<f32>; pub type vec3f = vec3<f32>; pub type vec4f = vec4<f32>;
pub type vec2d = vec2<f64>; pub type vec3d = vec3<f64>; pub type vec4d = vec4<f64>;
pub type vec2i = vec2<i32>; pub type vec3i = vec3<i32>; pub type vec4i = vec4<i32>;
pub type mat3f = mat3<f32>; pub type mat4f = mat4<f32>; pub type quatf = quat<f32>;
# and mat2f, the f64 ones, and transformf
The operations
Vectors, for any T:
a + b a - b -a a += b # component by component
a * b a / b # component by component
v * s v / s s * v # by a number; s * v for f32, f64 and i32
a == b # every component equal
v[i] # a component, read or written
pub def vec3<T>::dot(&this, other: &vec3<T>): T;
pub def vec3<T>::cross(&this, other: &vec3<T>): vec3<T>; # vec3 alone
pub def vec3<T>::length_squared(&this): T;
pub def vec3<T>::min(&this, other: &vec3<T>): vec3<T>; # also max, clamp, abs
pub def vec3<T>::sum(&this): T;
pub def vec3<T>::cast<U>(&this): vec3<U>; # each as `as` converts it
pub def vec3<T>::hash(&this): u64 where T: integer; # so integers key a dict
pub def vec3<T>::of(xy: vec2<T>, z: T): vec3<T>; # and vec4::of(xyz, w)
pub val vec3<T>::xy: vec2<T>; # a property; the other swizzles (decision 9)
pub def vec3<T>::zero(): vec3<T>; # also one, x_axis, y_axis, z_axis, as vec3f::zero()
Vectors, where T is f32 or f64:
pub def vec3<T>::length(&this): T where T: real; # and so is each below
pub def vec3<T>::distance(&this, other: &vec3<T>): T;
pub def vec3<T>::normalize(&this): vec3<T>; # NaNs for a zero vector
pub def vec3<T>::normalize_or(&this, fallback: vec3<T>): vec3<T>;
pub def vec3<T>::lerp(&this, to: &vec3<T>, t: T): vec3<T>;
pub def vec3<T>::reflect(&this, normal: &vec3<T>): vec3<T>;
pub def vec3<T>::project_onto(&this, onto: &vec3<T>): vec3<T>;
pub def vec3<T>::angle_to(&this, other: &vec3<T>): T; # radians
pub def vec3<T>::near(&this, other: &vec3<T>, tolerance: T): bool;
Matrices:
m * n m * v m * s m + n m - n m == n m[c] # m[c] is column c
pub def mat4<T>::identity(): mat4<T>;
pub def mat4<T>::of_rows(rows: vec4<T>[4]): mat4<T>;
pub def mat4<T>::transpose(&this): mat4<T>;
pub def mat4<T>::determinant(&this): T;
pub def mat4<T>::row(&this, index: u64): vec4<T>;
pub def mat4<T>::translation(by: vec3<T>): mat4<T>;
pub def mat4<T>::scaling(by: vec3<T>): mat4<T>;
# Each of these is `where T: real`.
pub def mat4<T>::inverse(&this): maybe<mat4<T>>;
pub def mat4<T>::rotation(axis: vec3<T>, angle: T): mat4<T>; # also rotation_x, _y, _z
pub def mat4<T>::look_at(eye: vec3<T>, target: vec3<T>, up: vec3<T>): mat4<T>;
pub def mat4<T>::perspective(fov_y: T, aspect: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
pub def mat4<T>::orthographic(left: T, right: T, bottom: T, top: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
pub def mat4<T>::transform_point(&this, point: vec3<T>): vec3<T>; # w of 1, divided through
pub def mat4<T>::transform_direction(&this, direction: vec3<T>): vec3<T>; # w of 0
pub def mat4<T>::normal_matrix(&this): maybe<mat3<T>>; # the inverse transposed
#! Where depth runs and which way y points after projecting (decision 6).
pub enum clip_space: u8 {
vulkan, #! depth 0 to 1, y down
opengl, #! depth -1 to 1, y up
direct3d, #! depth 0 to 1, y up, as Metal and WebGPU too
}
Quaternions:
q * r q * v q == r -q
pub def quat<T>::identity(): quat<T>;
pub def quat<T>::of_axis_angle(axis: vec3<T>, angle: T): quat<T>;
pub def quat<T>::of_euler(yaw: T, pitch: T, roll: T): quat<T>; # decision 8
pub def quat<T>::between(from: vec3<T>, to: vec3<T>): quat<T>; # the shortest arc
pub def quat<T>::look_rotation(forward: vec3<T>, up: vec3<T>): quat<T>;
pub def quat<T>::of_matrix(m: mat3<T>): quat<T>;
pub def quat<T>::conjugate(&this): quat<T>; # also inverse, normalize, dot, length
pub def quat<T>::slerp(&this, to: &quat<T>, t: T): quat<T>;
pub def quat<T>::nlerp(&this, to: &quat<T>, t: T): quat<T>;
pub def quat<T>::matrix(&this): mat3<T>; # also matrix4
pub def quat<T>::axis(&this): vec3<T>; # also angle, euler
Transforms and helpers:
a * b # b, then a
pub def transform<T>::identity(): transform<T>;
pub def transform<T>::inverse(&this): transform<T>;
pub def transform<T>::matrix(&this): mat4<T>;
pub def transform<T>::apply(&this, point: vec3<T>): vec3<T>; # also apply_direction
pub def transform<T>::lerp(&this, to: &transform<T>, t: T): transform<T>;
pub def radians<T>(degrees: T): T where T: real; # also degrees
pub def lerp<T>(from: T, to: T, t: T): T where T: real;
pub def smoothstep<T>(edge0: T, edge1: T, x: T): T where T: real;
pub def remap<T>(x: T, from_low: T, from_high: T, to_low: T, to_high: T): T where T: real;
Using it
A camera's matrices for Vulkan:
import std;
import std::math;
val view := mat4f::look_at(eye, vec3f::zero(), vec3f::y_axis());
val projection := mat4f::perspective(math::radians(60.0f), width / height, 0.1, 100);
val model := transform::<f32>{ translation = at, rotation = facing, scale = vec3f::one() }.matrix();
push.mvp = projection * view * model; # a mat4f, as the shader's mat4 reads it
Turning, and easing between two turns:
val quarter := quatf::of_axis_angle(vec3f::y_axis(), math::pi as f32 / 2);
val ahead := quarter * vec3f{ x = 0, y = 0, z = -1 }; # now (-1, 0, 0)
val halfway := facing.slerp(&target, 0.5);
A grid:
var tiles := dict::<vec2i, tile>::new();
val east := vec2i{ x = 1, y = 0 };
tiles.set(position + east, tile::grass);
How each part works
- Layout (decision 4):
- Each type is its fields one after another, as C's arrays are. A
vec3<f32>is 12 bytes, and amat4<f32>64, as Vulkan's vertex formats, glm and SPIR-V's storage buffers take them. - std140 uniform blocks align a
vec3to 16. Matching that is the program's to do, as with any struct a shader reads. - A
vec4fis laid out as anf32x4is, so it can be read as one (decision 11).
- Each type is its fields one after another, as C's arrays are. A
- Indexing reads the fields as a fixed array, through a pointer to the first,
&this.x, so an index out of range stops the program as any array's does, and needs nocontract. (&thisis a&&vec3<T>, a reference to the reference, so it isn't the vector's address.) - A number on the left is a method on that number:
f32::mul,f64::mulandi32::mul, each taking a vector, matrix or quaternion, for the aliases above. Other number types put the number on the right. - Reals alone:
length,normalizeand the rest are boundedwhere T: real, so asking them of avec3iis a mistake where it's written, naming the bound.- Matrices' inverses, rotations and projections do the same.
quatandtransformare boundedrealon the type, since a turn of integers means nothing.
- Named vectors are static functions, as
vec3f::zero()andvec3f::y_axis(), since a generic type has no associated variables. - Matrices (decision 5):
- Column
cism[c], and the element in rowrof it ism[c][r], as in GLSL. m * vtreatsvas a column, andm * nappliesnfirst. Soprojection * view * modelreads right to left, as shaders do.inverseis by cofactors, givingnothingwhere the determinant is exactly zero.
- Column
- Projections (decision 6):
- View space is right-handed: the camera looks down -Z, with +Y up, in every case.
- Only the projection differs by
clip_space:vulkanmaps near to 0 and far to 1, and negates y, since Vulkan's y points down;openglmaps them to -1 and 1;direct3dmaps them to 0 and 1, with y up.
- Quaternions (decision 8):
- Hamilton's:
i * jisk. q * rrotates byrfirst, as matrices compose.q * vrotatesvbyq, asv + 2w(u × v) + 2u × (u × v), whereuis(x, y, z). That needs no matrix.slerptakes the shorter way, negating one where their dot is negative. It falls back tonlerpwhere they're nearly the same, whereacosloses precision.of_euler(yaw, pitch, roll)turns byrollabout Z, thenpitchabout X, thenyawabout Y, for +Y up.eulergives them back, with pitch from -π/2 to π/2.
- Hamilton's:
- Transforms apply scale, then rotation, then translation.
a * bappliesbfirst.inverseis exact where the scale is the same on every axis.- Otherwise the true inverse shears, which a transform can't hold. So
inversegives the nearest transform, andmatrix().inverse()the exact matrix.
- Equality is exact, so a vector holding a NaN equals nothing, itself included.
nearcompares within a tolerance. - Printing: interpolation shows the fields, as
vec3<f32>{x = 1, y = 2, z = 3}.describegives(1, 2, 3).
Performance (decision 11)
What 2026-10-14 asked of the rebuild's code generator is half done, after its
optimizer's passes of 2026-10-18 (performance.md): small methods
returning a struct are inlined, and nothing in the probe's loop is zeroed or checked for
null. What's left is for f32 and other 4-byte numbers:
f32arithmetic in single precision (built 2026-10-28, see the CHANGELOG):addss,subss,mulss,divssandsqrtssround exactly as computing in double and rounding does, since a double holds more than twice a float's bits.- So the results are the same bits, and the VM needn't change.
- That's 1 instruction for 3, and removes the conversions' latency from every chain.
It speeds every
f32, not only vectors: written as fields,f32took twicef64's time.
- Vectors of 4-byte numbers in registers, as those of 8-byte ones are. A
vec3<f32>'s and avec3<i32>'s fields go to the stack and back each step, where avec3<f64>'s stay in registers. This phase finds what keeps them in memory. - Lanes for
vec4, in std:- Where
lanes_held(),add,sub,muland the rest of avec4of 4-byte numbers read its fields as onesimd<T[4]>, through&this.x, since anf32x4is laid out as a packedvec4fis. Elsewhere, in the VM, constants and C's executables, they take the fields. - The probe's
vec4<f32>took 73 ms so, against 67 written as fields. - A
mat4's columns arevec4s, so its products would be four lanes' multiplies and adds. vec2andvec3off32aren't 16 or 32 bytes, and wait for the code generator.
- Where
- The target: vector arithmetic within 1.5 times the same written as fields, at
-O2, measured by the probe.
C's code isn't sped up here. The rebuild is the compiler that's going forward, and C's results are already right.
Testing
test/std/linear.sakura, written withstd::testing, covers:- vectors: every operator for
f32,f64andi32, a number on each side, indexing past the end stopping a forked copy, swizzles,cast,hashin adict, and the identities:a × bperpendicular to both,a · aits length squared, andnormalizeof zero giving NaNs; - matrices: products against values worked out by hand,
inverseround trips to within a tolerance, a singular matrix'snothing, anddeterminantof rotations being 1; - projections: for each
clip_space, a point on the near plane mapping to its near depth and one on the far plane to its far depth, and y's direction; - quaternions: rotating a vector agreeing with
matrix()doing it,of_matrixback again,slerpat 0, 1 and halfway, the shorter way, Euler angles round trips away from the poles, andbetweenof opposite vectors; - transforms:
matrix()agreeing withapply, andinverseundoing it; - constants:
const forward := vec3f::x_axis().cross(&vec3f::y_axis())and a constant projection, the same in both compilers.
- vectors: every operator for
- A program of the corpus prints the bits of many results, so the VM, executables and both compilers are compared exactly.
- Where they run: in the VM, as executables at
-O0and-O2, and withrun --checks. The rebuild's analyzer must check them with 0 notes. - The probe's timings are run before and after decision 11's work.
Phases
About 1,700 lines of std and 900 of tests. Every program's check would grow by about 5%: a copy of std/simd.sakura's 1,075 lines of generic methods, added to std, cost 3% of a one-line program's check in both compilers (2026-10-20, a busy machine). Decision 11 is work in the rebuild's code generator, sized once its first part, finding what keeps 4-byte fields in memory, is done.
- Vectors, with everything that needs no
sqrt: operators,dot,cross, indexing, swizzles,minandmax, and hashing. - Matrices, with products,
transpose,determinant,inverse,translationandscaling. - What needs
std::math: lengths, normalizing, interpolating,look_at, rotations, projections, quaternions and transforms, and the helpers. - Lanes for
vec4andmat4, and the rebuild's code generator (decision 11). - A "Vectors and matrices" section in the README, beside its "Vectors" of
simd.
Each can begin now: std::math was built the day this was written.
Fixed along the way
These were found by the probes and fixed on 2026-10-14. Both compilers passed every
check after. Both fixes still hold: the corpus program below gave its expected output
under both compilers, in the VM and at -O2, on 2026-10-20.
- C passed 0 for a constant on the right of an operator whose method takes
&f32.v * 2.0on avec3<f32>gave a zero vector, since the constant was lent as thef64it is alone. It's now lent as anf32, as a call's argument is, in*, in*=, and in*=on a property. The rebuild was right already. - The rebuild called
def f32::mul(&this, v: &vec3<f32>)a cycle. That happened wherevec3's bound asks formul, since deciding thatf32isnumericworked out the program's methods onf32first, this one among them. It now asks the compiler's own methods on a number first, as C does. - A program of the corpus covers both:
operators_lend_constants_as_their_methods_take_them_1.
Found along the way
2.0 * vis refused for anf32vector, still, in both, since an untyped constant on the left asks its own type,f64.2.0f * vandv * 2.0work. Letting a constant on the left take the type of a method that fits would change the README's rule for a number on the left (decision 2 here).- The rebuild does
f32arithmetic in double precision, rounding after each operation, as C's executables do too: three instructions for oneaddss. - The rebuild keeps a struct of 4-byte numbers in memory through a loop, where one of 8-byte numbers stays in registers (Performance).
- Generic types have no associated variables, and the compilers differ in how they
say so. C refuses
val vec3<T>::zero := .... The rebuild takes the declaration, but reading it gives avec3<T>no instance made:val z: vec3f = vec3f::zerois a mismatch, and interpolating it prints nothing. An alias's own,val vec3f::zero := ..., works in both. - The rebuild doesn't report
compile_errorin a property's getter while checking. Forvec<T, N>'sz, guarded byif const N < 3 { compile_error(...) }, C reports the error where avec2'szis read. The rebuild checks it clean, andrunstops with "Checking an instance lowering asked for made notes.", without the note. In a method, ascross, both report it while checking. - "Vector" now names three things:
vector<T>, the README's "Vectors" ofsimd, and these. - No longer so (2026-10-20):
- Neither compiler inlined a small method returning a struct at
-O2. Both do. - C boxed an
f32temporary lent by reference, five times the cost of lending a variable. It costs what a variable does. - C refused bounds on a generic type's methods, where the rebuild took them, which
is why reals were checked inside the methods by
if const. Both take them since 2026-10-19.
- Neither compiler inlined a small method returning a struct at
Later, where wanted
- Geometry: rays, planes, boxes, spheres and frustums, and the tests between them.
- Rectangular matrices, as 3×4 for affine transforms, and matrices of any size for numerical work. Decision 3's (b) would bring them.
- Lanes for
vec2andvec3off32, which aren't 16 or 32 bytes.vec4's are in decision 11, nowsimdis built. - std140 and std430 layouts, as types padded for uniform and storage buffers.
- Reversed and infinite depth in projections, for precision far away.
- Dual quaternions, for skinning, and rotors, from geometric algebra.
- Writing vectors as arrays in JSON, as glTF does, through a serial format option.
- One
lerpfor numbers and vectors, through a trait like the README'sscales<S>, which std doesn't name.
Decisions for you
- Where it lives:
- (a)
std::math, beside its functions, in std/math/ (recommended). One import gives a program drawing in 3D everything it uses. - (b)
std::linear, of its own. A program wanting onlysqrtdoesn't seevec3, but most that want one want both. Neither saves checking, since every program is checked with all of std.
- (a)
- The numbers inside:
- (a) Generic, as
vec3<T>, with aliases forf32,f64andi32(recommended). One body serves floats, doubles and grids.2.0 * vneeds2.0ffor anf32vector, or the rule for a number on the left changes so a constant there takes the type of a method that fits. - (b)
f32alone, as many game libraries default to, withvec3dandvec3iwritten again where wanted.2.0 * vstill needs2.0f. - (c) Generic, with no aliases.
- (a) Generic, as
- Lengths, open now that constant parameters and
for constmake the second possible:- (a) A type for each,
vec2,vec3andvec4, with fields (recommended). Literals name the fields,vec3f{ x = 1, y = 2, z = 3 }, reflection and@serialsee them, andcrossand the swizzles are only where they mean something. - (b) One of any length,
vec<T, const N: u64>holding aT[N], with the same aliases. One body serves every length, and matrices of any shape would come with it. Butxtoware properties, a literal isvec3f{ c = [1, 2, 3] }, andcross,zandwrefuse the wrong lengths byif const N != 3 { compile_error(...) }, which the rebuild reports from a property only as it runs, without the message.
- (a) A type for each,
- Layout:
- (a) Packed, as C's arrays (recommended). Vertex buffers and C libraries read
them as they are, and a
vec4fis laid out as anf32x4is. - (b)
vec3andvec4aligned to 16, as std140 likes them. Avec3would take 16 bytes, and wouldn't match a vertex format of three floats.simddoesn't need it: anf32x4is aligned to 4.
- (a) Packed, as C's arrays (recommended). Vertex buffers and C libraries read
them as they are, and a
- Matrices:
- (a) Column by column, with vectors as columns,
m * v(recommended). As GLSL, SPIR-V, Vulkan, OpenGL and glm have it, so a matrix goes to a shader as it is. - (b) Row by row, with vectors as rows,
v * m, as Direct3D's older math libraries have it.
- (a) Column by column, with vectors as columns,
- Clip space:
- (a) A parameter naming the API, Vulkan by default (recommended).
- (b) Vulkan alone. Simpler, but OpenGL and WebGPU programs would fix every projection by hand.
- (c) A function for each, as
perspective_vulkanandperspective_gl.
- Angles:
- (a) Radians, as plain numbers, with
radiansanddegrees(recommended). Asmath::sintakes them, and every library has it. - (b) An
angletype, made bydegrees(90)orradians(x), asdurationis made of a unit. Degrees can't then be passed for radians, at the cost of converting at everysin.
- (a) Radians, as plain numbers, with
- Euler angles:
- (a) One order, yaw about Y, pitch about X and roll about Z, for +Y up (recommended). That's what cameras and characters want.
- (b) Every order, chosen by an enum, for tools reading other programs' conventions.
- (c) None: axes and angles, and directions, alone.
- Swizzles:
- (a) The common ones as properties (recommended):
xy,xzandyzof avec3orvec4, andxyzof avec4. - (b) Every one, written by a tool: 336 for a
vec4, of two to four components. It's about 1,000 more lines of std, which every program's check pays about 3% for, by the measure in "Phases". - (c) A method, as
v.swizzle(2, 0, 1).
- (a) The common ones as properties (recommended):
- What's in it:
- (a) Vectors, square matrices, quaternions, transforms and the helpers, with geometry later (recommended).
- (b) Geometry now too: rays, planes, boxes, spheres and frustums.
- (c) Vectors and matrices alone.
- Speed, where inlining is settled and
f64vectors are as fast as written out:- (a) Both, as part of this plan (recommended): in the rebuild's code generator,
f32in single precision and 4-byte fields held in registers; in std,vec4's andmat4's operations of 4-byte numbers throughsimdwherelanes_held().f32vector code is otherwise 2.5 times slower than the same written out. - (b) Lanes alone, in std.
vec4is fast now, andmat4's products would be too, butvec2andvec3off32stay 2.5 times slower until the code generator's own plan. - (c) Left to the code generator's own plan, with
f32vectors slow until then. - (d) Accepted.
- (a) Both, as part of this plan (recommended): in the rebuild's code generator,