커밋 af54ddad5의 AUTHORING.md를 그대로 옮긴 것으로, 이 절의 본문은 아직 영어입니다. 패키지는 0.2.0에서 쓸 typeshade라는 이름으로 가져옵니다.
fp64
After this page you can declare a double-precision value in a shader, know which operations it supports, and bind the guard texture the emulation needs.
A GPU has no 64-bit float type. In this package f64 is emulated: one value is a pair of
f32 numbers, a high part and a low part, and the number is their unevaluated sum. That
gives about 48 bits of significand, the fraction bits that decide how many digits a value
keeps, over the ordinary f32 exponent range. A value near 1e8, a position in world units
for one, where one f32 step is already 8 units, still resolves detail far below one unit.
You write f64 as a type like any other, and a pass rewrites every f64 into a vec2<f32>
and injects the emulation functions the shader then calls, before any backend sees it. WGSL,
GLSL and the CPU oracle agree on the results.
The 48 bits assume the GPU rounds f32 +, - and * to nearest, ties to even. Every shipping
GPU does, but neither specification promises it: GLSL ES 3.00 leaves the rounding mode undefined
and lets a subnormal flush to zero, and WGSL fixes no rounding mode. The figure rests on that
hardware practice; §39 of docs/use-typeshade-surface.md has the detail.
Declaring an f64 value
Write f64 where you would write f32: in a uniform field, in a parameter, in a local or in a
scalar module constant. A module initializer folds before emit; its final double and both
f32 words must be finite. The module constant rules describe its precision boundaries. The
operators, the comparisons and the builtins keep their spelling, so a body converted from f32
usually changes only in its signature.
"use typeshade";
class Uniforms { origin: f64; // one vec2<f32> slot: the host writes splitF64(value)}
declare const u: uniform<Uniforms>;
export function k(x: f64, s: f32): f32 { return f32(sqrt((x + u.origin) * s));}Nothing on the module announces fp64. The lowering pass finds the f64 types itself.
Conversions
An f32 widens to f64 implicitly beside an f64, and the widen is exact, so x + dx for an f64
x and an f32 dx needs no conversion. f64(x) is the explicit spelling of that widen, for
a value that has to be f64 before it meets any arithmetic. A literal in a position the
surrounding type declares f64, a declaration, a parameter, a field or the other side of an
operator, keeps the whole double, and so does f64(0.1). Narrowing is always explicit:
f32(x) adds the two halves back together and gives an f32, losing the extra precision.
% and the integer casts i32(x) and u32(x) on an f64 are refused; narrow to f32 first.
"use typeshade";
export function g(a: f32, b: f64): f32 { const widened = f64(a); // exact const lit: f64 = 1e-9; // a literal in a declared f64 position keeps the double return f32(widened + lit + b); // the explicit narrow}There is no author-facing way to split a double into its two words and rebuild it. A double
two stages need is read in each of them from a uniform or a storage binding, or narrowed to
an f32 at the boundary.
The operations f64 supports
The four arithmetic operations, every comparison, abs, cos, floor, fract, max,
min, mix, round, sin and sqrt accept f64 operands. Anything else on an f64 operand
is refused at the call, naming that list and the narrow to write, so narrow the value with
f32(x) first and finish that part of the computation in f32. sin and cos are less
accurate than the arithmetic around them. Relative error for the transcendental itself
floors at about 2^-36, and it grows with the size of the argument through the range
reduction.
"use typeshade";
// A triangle wave on a coordinate that has outgrown f32.export function stripe(x: f64): f32 { const y = x * 0.5; const f = y - floor(y); return f32(min(f, 1. - f));}The guard texture
A shader compiler may reassociate float arithmetic, and reassociation deletes exactly the
small correction terms this emulation is built on. Every emitted helper therefore threads a
value the compiler cannot see through those terms: a 1 read from a texture. Any module whose
f64 arithmetic calls one of those helpers gets a texture_2d<f32> binding named _fp64
injected for it, at group 0 and the first free binding, and it appears in reflect() as an
ordinary 2D texture. A module that only compares, widens, narrows, negates or scales f64
values by a power of two calls none of them and gets no binding, so a host reads reflect()
rather than binding _fp64 to every pipeline. The host binds a 1 by 1 texture whose texel
reads exactly 1.0, white RGBA8 or R32F holding 1.0.
The value lives in a texture because some drivers specialize a pipeline on the uniform
values they observe and re-optimize it, which folds the correction terms away again; no
compiler treats a texel as a constant.
Each function that does f64 arithmetic reads the texel once, at the top of its body, and
passes it to the helpers as a parameter, so a loop reads it before it starts rather than on
every iteration. On GLSL the texture is declared uniform highp sampler2D _fp64;: GLSL ES
3.00 gives sampler2D a default precision of lowp in both stages, and a texel fetch returns
its sampler’s precision.
Two things to do at the host. If the bind group layout is fixed, pin the slot: add
fp64Guard({ group, binding }).binding to the module’s bindings. And on Apple GPUs the guard
is not enough, because the platform’s default fast math collapses the float lowering anyway.
Pass whatever device signals you have to recommendFp64Flavor and hand the result to the
emit as fp64Flavor; on those devices it selects an integer lowering, which needs no guard
binding at all.
// m: the module of the first example on this page.import { emitModule, fp64Guard, recommendFp64Flavor, type ModuleDecl } from 'typeshade'
const pinned: ModuleDecl = { ...m, bindings: [...m.bindings, fp64Guard({ group: 0, binding: 3 }).binding],}
const flavor = recommendFp64Flavor({ userAgent: navigator.userAgent })const wgsl = emitModule(pinned, { fp64Flavor: flavor })The emulation owns two name spaces in the emitted shader. A function name starting with
df64_, or a struct name starting with DF64Vec or DF64Mat, fails emit with SD0043.
Packing and layout
An f64 uniform field occupies one plain vec2<f32> slot, size 8 and align 8. Pack it on the
host with splitF64(x), which returns the [hi, lo] pair in the order the shader reads it.
A value interpolated from the vertex stage to the fragment stage, a varying, cannot be f64,
because interpolating a hi/lo pair across a triangle is numerically wrong: an f64 on an
entry’s location<n, T> parameter, an IO struct field or an entry’s return is refused. Interpolate
an f32 quantity instead, or carry the value in a uniform and do the f64 arithmetic in the
fragment stage. A scalar f64 vertex input is the one exception, since it is a buffer read and
the pair fits its one slot.
import { splitF64 } from 'typeshade'
const [hi, lo] = splitF64(-8_234_567.890123)new Float32Array(uniformBuffer, 0, 2).set([hi, lo])Vectors
vec2f64, vec3f64 and vec4f64 are the vector types, built with vec2f64(x, y) and its
siblings. Components, swizzles, componentwise arithmetic with f64, f32 and number broadcast,
the componentwise builtins of the scalar list but sqrt, plus normalize, and the reductions
dot, length and distance, which give back an f64, all read the same as their f32
counterparts. A lane is a read: v.x = … is refused, so rebuild the whole vector. vec3(v)
narrows one per lane. A vector lowers to a struct holding a hi plane and a lo plane, so
componentwise work runs once for the whole vector.
"use typeshade";
class P { center: vec2f64;}
declare const p: uniform<P>;
export function d(x: f64, y: f64): f32 { const q = vec2f64(x, y) - p.center; return f32(dot(q, q)); // the subtraction and the dot both run in f64}A vector uniform field takes its struct layout: 16 bytes for two components, 32 bytes for three or four under std140. A vector vertex attribute would need two slots and is refused.
What it costs
One f64 operation is several f32 operations, ten or more for a multiply or an add. So opt in
per value: hold the coordinates that need the range in f64, narrow as soon as the difference
is small enough for f32, and let the rest of the shader run at f32 speed.
"use typeshade";
// The subtraction needs the range; the shading after it does not.export function shade(world: f64, camera: f64): f32 { return f32(world - camera) * 0.5 + 0.5;}Two f64 multiplies cost less, with nothing to write differently. x * x is a square, about
30% cheaper than a general multiply, as long as computing x has no side effect, such as a
call that writes a storage binding. A multiply or a divide by a power-of-two literal, 2.0,
0.5 or -4.0, scales the two f32 words and nothing else, which is exact barring overflow and
underflow: two f32 operations, none for 1.0, and a sign change for -1.0. A scale that can grow the value
(by more than 1) applies to a value computed at run time; a constant keeps the general
multiply, so that WGSL, which evaluates constants while it creates the shader and refuses one
that overflows, never has to.
One example in the gallery, examples/gallery/fp64-lane-stripes/fp64-lane-stripes.shade.ts, runs one formula on both
types side by side, and shows the f32 half collapsing to a flat field while the f64 half
keeps its stripes.