UNPKG

@thi.ng/shader-ast-stdlib

Version:

Function collection for modular GPGPU / shader programming with @thi.ng/shader-ast

88 lines (87 loc) 2.07 kB
import { F, V3 } from "@thi.ng/shader-ast/api/types"; import { defn, ret } from "@thi.ng/shader-ast/ast/function"; import { FLOAT0, PHI, vec3 } from "@thi.ng/shader-ast/ast/lit"; import { add, reciprocal, sub } from "@thi.ng/shader-ast/ast/ops"; import { abs, dot, max, pow } from "@thi.ng/shader-ast/builtin/math"; const __normalize = ([x, y, z]) => { const m = 1 / Math.hypot(x, y, z); return [x * m, y * m, z * m]; }; const phi = PHI.val; const GDF = [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1], [0, 1, phi + 1], [0, -1, phi + 1], [phi + 1, 0, 1], [-phi - 1, 0, 1], [1, phi + 1, 0], [-1, phi + 1, 0], [0, phi, 1], [0, -phi, 1], [1, 0, phi], [-1, 0, phi], [phi, 1, 0], [-phi, 1, 0] ].map((v) => vec3(...__normalize(v))); const __defGDF = (id, vecs) => [ defn(F, id, [V3, F], (p, r) => [ ret( sub( vecs.reduce( (acc, v) => max(acc, abs(dot(p, v))), FLOAT0 ), r ) ) ]), defn(F, id + "Smooth", [V3, F, F], (p, r, e) => [ ret( sub( pow( vecs.reduce( (acc, v) => add(acc, pow(abs(dot(p, v)), e)), FLOAT0 ), reciprocal(e) ), r ) ) ]) ]; const [sdfOctahedron, sdfOctahedronSmooth] = __defGDF( "sdfOctahedron", GDF.slice(3, 7) ); const [sdfDodecahedron, sdfDodecahedronSmooth] = __defGDF( "sdfDodecahedron", GDF.slice(13) ); const [sdfIcosahedron, sdfIcosahedronSmooth] = __defGDF( "sdfIcosahedron", GDF.slice(3, 13) ); const [sdfTruncatedOctahedron, sdfTruncatedOctahedronSmooth] = __defGDF( "sdfTruncatedOctahedron", GDF.slice(0, 7) ); const [sdfTruncatedIcosahedron, sdfTruncatedIcosahedronSmooth] = __defGDF("sdfTruncatedIcosahedron", GDF.slice(3)); export { sdfDodecahedron, sdfDodecahedronSmooth, sdfIcosahedron, sdfIcosahedronSmooth, sdfOctahedron, sdfOctahedronSmooth, sdfTruncatedIcosahedron, sdfTruncatedIcosahedronSmooth, sdfTruncatedOctahedron, sdfTruncatedOctahedronSmooth };