Skip to content
Chung Leong edited this page Feb 15, 2024 · 6 revisions

Vector is a special kind of arrays compatible with SIMD instructions of modern CPUs. They meet higher memory alignment requirements. For example, @Vector(4, f32) aligns to 16 bytes (128-bit), whereas [4]f32 only aligns to 4 bytes.

pub const Vector = @Vector(3, f32);

pub fn dot(v1: Vector, v2: Vector) f32 {
    return @reduce(.Add, v1 * v2);
}

pub fn cross(v1: Vector, v2: Vector) Vector {
    const p1 = @shuffle(f32, v1, undefined, @Vector(3, i32){ 1, 2, 0 }) * @shuffle(f32, v2, undefined, @Vector(3, i32){ 2, 0, 1 });
    const p2 = @shuffle(f32, v1, undefined, @Vector(3, i32){ 2, 0, 1 }) * @shuffle(f32, v2, undefined, @Vector(3, i32){ 1, 2, 0 });
    return p1 - p2;
}
import { Vector, cross, dot } from './vector-example-1.zig';

const v1 = new Vector([ 0.5, 1, 0 ]);
const v2 = new Vector([ 3, -4, 9 ]);

const p1 = dot(v1, v2);
console.log(`dot product = ${p1}`);
const p2 = cross(v1, v2);
console.log(`cross product = [ ${[ ...p2 ]} ]`);
Clone this wiki locally