Type ‣ Vector ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


A vector in Zig is a special kind of array compatible with SIMD instructions of modern CPUs. It has a higher memory alignment requirement. For example, @Vector(4, f32) aligns to 16-byte boundary (128-bit), whereas [4]f32 only aligns to a 4-byte boundary (32-bit).

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;
}
<?php

$m = zigar_use(__DIR__ . '/vector-example-1.zig');

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

$p1 = $m->dot($v1, $v2);
echo "dot product = $p1\n";
$p2 = $m->cross($v1, $v2);
echo "cross product = [ ", implode(", ", (array) $p2), " ]\n";
dot product = -2.5
cross product = [ 9, -4.5, -5 ]

Types | Array