Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# Golden CLI output is compared byte for byte, so Windows checkouts must keep LF line endings.
core/src/cli/golden/** text eol=lf
# The translator's expected WGSL is compared byte for byte too.
shaders/msl2wgsl/tests/golden/** text eol=lf
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,12 @@ jobs:
working-directory: shaders/msl2wgsl
run: cargo run --release --features check -- --check

- name: Translator tests and the expected WGSL
# A shader or translator change that alters the WGSL fails here until the expected files
# are rewritten: DEEPFIELD_BLESS=1 cargo test --test golden
working-directory: shaders/msl2wgsl
run: cargo test --release --locked

rust-linux:
# The Rust scene logic and wgpu renderer build off Windows too (the wallpaper, tray and Win32
# calls are left out), the first step towards sharing them with Linux and the Mac.
Expand Down
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ dev command line; read it before touching rendering or adding a scene.
- The Windows port (`windows/`) runs the same shaders, translated from the Metal to WGSL at build
time, so write each shader once, in Metal, within the subset the translator takes (listed in
`render-wgpu/wgsl/README.md`). `cargo run --features check -- --check` in `shaders/msl2wgsl`
checks that a shader change translates and validates (CI runs it too).
checks that a shader change translates and validates (CI runs it too). When a change alters the
WGSL, run `DEEPFIELD_BLESS=1 cargo test --test golden` there and commit the golden files.
- Both apps render from the Rust core's scene physics, camera and events (`core/src/`;
`core/src/frame.rs` fills every buffer the GPU reads), so write them once, in Rust. The config
is still modeled on both sides (Swift's `WallpaperConfig` and `core/src/config.rs`), but its
Expand Down
17 changes: 15 additions & 2 deletions render-wgpu/wgsl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ bindings file and an entry in its layout in `render-wgpu/src/renderer.rs`.
- Without the Windows build (on a Mac, say), from `shaders/msl2wgsl`:
`cargo run --features check -- --check` translates and validates every module the same way,
and `--out DIR` writes them out to read. CI runs the check on every pull request.
- `cargo test` there runs the translator's tests: a snippet for each rule below (with the WGSL it
should give, or the error it must give), and the WGSL of every module against the expected copy
in `shaders/msl2wgsl/tests/golden`. A change to a `.metal` file or the translator that alters
the WGSL fails that test until the expected files are rewritten with
`DEEPFIELD_BLESS=1 cargo test --test golden`; commit them with the change, after reading the
diff. CI runs the tests too.
- From the repo root, `DEEPFIELD_METAL=shaders` translates the Metal when the program starts
instead of using the copy built in, and `DEEPFIELD_SHADERS=render-wgpu\wgsl` reads the
bindings files from this folder, so a shader edit shows up without a rebuild.
Expand All @@ -61,10 +67,14 @@ The translator handles the Metal the shaders use, and writes out what Metal does
even whole number is taken as its magnitude (what the Metal compiler's folding into `x * x`
gave); any other base is kept at zero or above with `max(x, 0.0)`, which leaves a
non-negative base exactly as it was. Write `sq(x)` for squares regardless.
- `round` goes through a `metal_round_*` helper (`trunc`, then a step away from zero when the
fraction is at least a half): Metal rounds
halves away from zero, WGSL's `round` to even (which is Metal's `rint`).
- Samplers: a `constexpr sampler` maps to one of the samplers the bindings declare, by its
addressing: clamped (`linearClamp`), repeating east-west and clamped at the poles
(`mipRepeat`), or mirrored (`mirrored`). A sampler without a mip filter reads level 0, as on
the Mac.
(`mipRepeat`), or mirrored (`mirrored`). All three filter linearly, so `filter::linear` is
required (Metal's default is nearest); only `mipRepeat` has a mip filter. A sampler without a
mip filter reads level 0, as on the Mac. Any other property or combination stops the build.

## Metal the translator doesn't take

Expand All @@ -79,3 +89,6 @@ Keep shader code within what it handles. If the build stops on one of these, rew
- `x++` inside a loop condition or on the right of `&&` or `||`
- a resource (texture, buffer, sampler) passed to a function as anything but a plain name
- a new kind of sampler (other addressing or filtering); add a binding for it first
- a mip level on `read` or `get_width`/`get_height`, or a `sample` option other than `level()`
- a builtin or constructor with extra or missing arguments
- a kernel without its workgroup size in `MODULES`
4 changes: 4 additions & 0 deletions shaders/msl2wgsl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ check = ["dep:naga"]

[dependencies]
naga = { version = "23", features = ["wgsl-in"], optional = true }

[dev-dependencies]
# the tests validate what they translate, as `--check` does
naga = { version = "23", features = ["wgsl-in"] }
2 changes: 1 addition & 1 deletion shaders/msl2wgsl/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub struct Declarator {
#[derive(Clone, Debug)]
pub enum Stmt {
Decl { ty: Type, konst: bool, vars: Vec<Declarator>, line: usize },
Sampler { name: String, args: Vec<String> },
Sampler { name: String, args: Vec<String>, line: usize },
Expr(Expr, usize),
If(Expr, Box<Stmt>, Option<Box<Stmt>>, usize),
For { init: Option<Box<Stmt>>, cond: Option<Expr>, step: Vec<Expr>, body: Box<Stmt>, line: usize },
Expand Down
149 changes: 129 additions & 20 deletions shaders/msl2wgsl/src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,71 @@ fn swizzle_index(c: char) -> Option<usize> {
}
}

// ---------- samplers ----------

/// What a `constexpr sampler` becomes: one of the samplers the bindings declare.
#[derive(Clone, Debug)]
struct SamplerUse {
/// the WGSL sampler global
global: &'static str,
/// a mip filter, so `sample` without `level()` picks the level itself
mip: bool,
/// `coord::pixel`: coordinates in texels
pixel: bool,
}

/// Maps a `constexpr sampler`'s properties onto one of the three samplers the bindings declare
/// (render-wgpu/src/renderer.rs). Anything those can't reproduce is an error, so a new kind of
/// sampler can't quietly read with the wrong filtering or addressing on Windows.
fn sampler_use(args: &[String]) -> R<SamplerUse> {
let mut filter = None;
let mut mip = false;
// Metal's defaults: clamp to edge on both axes
let (mut s, mut t) = ("clamp_to_edge", "clamp_to_edge");
let mut pixel = false;
for a in args {
let (key, value) = a.split_once("::").ok_or(format!("sampler property {a} isn't one the translator knows"))?;
match (key, value) {
("filter", v) => filter = Some(v.to_string()),
("mip_filter", "linear") => mip = true,
("mip_filter", "none") => mip = false,
("address", v @ ("clamp_to_edge" | "repeat" | "mirrored_repeat")) => (s, t) = (v, v),
("s_address", v @ ("clamp_to_edge" | "repeat" | "mirrored_repeat")) => s = v,
("t_address", v @ ("clamp_to_edge" | "repeat" | "mirrored_repeat")) => t = v,
("coord", "pixel") => pixel = true,
("coord", "normalized") => pixel = false,
_ => return Err(format!("sampler property {a} has no matching sampler in the bindings")),
}
}
if filter.as_deref() != Some("linear") {
// Metal's default filter is nearest; every sampler the bindings declare is linear
return Err("a sampler needs filter::linear (the bindings have no nearest sampler)".into());
}
let global = match (s, t, mip) {
("clamp_to_edge", "clamp_to_edge", false) => "linearClamp",
("repeat", "clamp_to_edge", _) => "mipRepeat",
("mirrored_repeat", "mirrored_repeat", false) => "mirrored",
_ => {
let m = if mip { ", mip_filter::linear" } else { "" };
return Err(format!("no sampler in the bindings has s_address::{s}, t_address::{t}{m}"));
}
};
Ok(SamplerUse { global, mip, pixel })
}

/// How many arguments a Metal builtin takes; a call with any other count is an error rather than
/// extra arguments silently dropped.
fn builtin_arity(n: &str) -> Option<usize> {
Some(match n {
"sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "sinh" | "cosh" | "tanh" | "exp" | "exp2" | "log" | "log2" | "sqrt" | "rsqrt"
| "floor" | "ceil" | "fract" | "trunc" | "round" | "rint" | "saturate" | "radians" | "degrees" | "dfdx" | "dfdy" | "fwidth" | "abs"
| "sign" | "length" | "length_squared" | "normalize" | "all" | "any" => 1,
"dot" | "distance" | "cross" | "reflect" | "pow" | "atan2" | "min" | "max" | "step" | "fmod" => 2,
"clamp" | "fma" | "smoothstep" | "mix" | "select" => 3,
_ => return None,
})
}

// ---------- the generator ----------

#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
Expand Down Expand Up @@ -321,7 +386,7 @@ struct Var {

struct Ctx {
scopes: Vec<HashMap<String, Var>>,
samplers: HashMap<String, Vec<String>>,
samplers: HashMap<String, SamplerUse>,
ret: Type,
assigned: HashSet<String>,
/// statements an expression needs run before the statement it's in
Expand Down Expand Up @@ -357,6 +422,8 @@ pub struct Gen<'p> {
refs: Refs,
/// the Metal line of the statement being written, for error messages
line: usize,
/// helper functions the module needs (Metal builtins WGSL lacks), by name
helpers: BTreeMap<String, String>,
}

pub fn generate(prog: &Program, spec: &ModuleSpec) -> R<String> {
Expand All @@ -377,6 +444,7 @@ pub fn generate(prog: &Program, spec: &ModuleSpec) -> R<String> {
tmp: 0,
current: String::new(),
line: 0,
helpers: BTreeMap::new(),
refs: prog
.funcs
.iter()
Expand All @@ -386,6 +454,12 @@ pub fn generate(prog: &Program, spec: &ModuleSpec) -> R<String> {
m
}),
};
for (e, p, _) in spec.renames {
let f = spec.entries.contains(e).then(|| g.by_name.get(*e)).flatten().map(|v| &prog.funcs[v[0]]);
if !f.is_some_and(|f| f.params.iter().any(|q| q.name == *p && q.pass == Pass::Resource)) {
return Err(format!("{}: the rename of {e}'s {p} matches no resource parameter of an entry point", spec.name));
}
}
for e in spec.entries {
let fi = *g.by_name.get(*e).and_then(|v| v.first()).ok_or(format!("{}: no entry point {e}", spec.name))?;
let f = &prog.funcs[fi];
Expand Down Expand Up @@ -429,6 +503,10 @@ pub fn generate(prog: &Program, spec: &ModuleSpec) -> R<String> {
s.push('\n');
}
s.push('\n');
for h in g.helpers.values() {
s.push_str(h);
s.push('\n');
}
for (_, f) in &g.out {
s.push_str(f);
s.push('\n');
Expand Down Expand Up @@ -531,13 +609,15 @@ impl<'p> Gen<'p> {
Stage::Fragment => head.push_str(&format!("@fragment\nfn {name}({}) -> @location(0) vec4<f32> {{\n", params.join(", "))),
Stage::Vertex => head.push_str(&format!("@vertex\nfn {name}({}) -> {} {{\n", params.join(", "), ty_name(&f.ret))),
Stage::Kernel => {
// no default: the grid is rounded up to whole workgroups, so each kernel states its
// size and whether it needs a bounds check in MODULES
let (wg, bounds) = self
.spec
.kernels
.iter()
.find(|k| k.0 == f.name)
.map(|k| (k.1, k.2))
.unwrap_or(((8, 8), None));
.ok_or(format!("kernel {} has no workgroup size in MODULES", f.name))?;
let gid = builtin_gid.clone().ok_or("a kernel needs thread_position_in_grid")?;
head.push_str(&format!(
"@compute @workgroup_size({}, {})\nfn {name}(@builtin(global_invocation_id) {gid}3: vec3<u32>) {{\n let {gid} = {gid}3.xy;\n",
Expand Down Expand Up @@ -602,7 +682,7 @@ impl<'p> Gen<'p> {
ctx.can_hoist = true;
match s {
Stmt::Decl { line, .. } | Stmt::Expr(_, line) | Stmt::If(.., line) | Stmt::For { line, .. } | Stmt::While(.., line)
| Stmt::DoWhile(.., line) | Stmt::Switch(.., line) | Stmt::Return(_, line) => self.line = *line,
| Stmt::DoWhile(.., line) | Stmt::Switch(.., line) | Stmt::Return(_, line) | Stmt::Sampler { line, .. } => self.line = *line,
_ => {}
}
match s {
Expand All @@ -612,8 +692,9 @@ impl<'p> Gen<'p> {
self.body(ctx, &Stmt::Block(v.clone()), out)?;
out.push(Self::line(ctx, "}"));
}
Stmt::Sampler { name, args } => {
ctx.samplers.insert(name.clone(), args.clone());
Stmt::Sampler { name, args, .. } => {
let u = sampler_use(args)?;
ctx.samplers.insert(name.clone(), u);
}
Stmt::Decl { ty, konst, vars, .. } => {
for d in vars {
Expand Down Expand Up @@ -1214,8 +1295,10 @@ impl<'p> Gen<'p> {
if self.struct_idx.contains_key(n) {
let st = self.prog.structs[self.struct_idx[n]].clone();
let mut parts = Vec::new();
for (k, f) in st.fields.iter().enumerate() {
let a = args.get(k).ok_or(format!("{n}(...) needs every field"))?;
if args.len() != st.fields.len() {
return Err(format!("{n}(...) takes its {} fields, got {} values", st.fields.len(), args.len()));
}
for (f, a) in st.fields.iter().zip(args) {
parts.push(self.expr_to(ctx, a, &f.ty)?.s);
}
return Ok(V::new(format!("{}({})", wname(n), parts.join(", ")), Type::Struct(n.into()), P_PRIMARY));
Expand Down Expand Up @@ -1375,7 +1458,7 @@ impl<'p> Gen<'p> {
return Err(format!("a vector component (.{f}) passed by reference isn't supported"));
}
}
let lv = self.lvalue(ctx, a)?;
let lv = self.lvalue(ctx, a).map_err(|e| format!("{e}: a `thread` argument must be a variable, field or element (no pointer arithmetic)"))?;
Ok((format!("&{}", lv.s), lv.ty))
}

Expand All @@ -1384,6 +1467,18 @@ impl<'p> Gen<'p> {
let Type::Texture { sc, .. } = ov.ty else { return Err(format!(".{m}() on a {}", ty_name(&ov.ty))) };
let t = ov.s.clone();
let v4 = Type::Vector(sc, 4);
let arity = match m {
"read" => 1..=1,
"write" => 2..=2,
"get_width" | "get_height" => 0..=0,
"sample" => 2..=3,
_ => return Err(format!("unsupported texture method {m}")),
};
if !arity.contains(&args.len()) {
// a mip level (`read(p, lod)`, `get_width(lod)`) would otherwise be dropped
let n = if arity.start() == arity.end() { arity.start().to_string() } else { format!("{} or {}", arity.start(), arity.end()) };
return Err(format!(".{m}() takes {n} arguments here, got {} (a mip level isn't supported)", args.len()));
}
match m {
"read" => {
let p = self.expr(ctx, &args[0])?;
Expand All @@ -1398,23 +1493,16 @@ impl<'p> Gen<'p> {
"get_height" => Ok(V::new(format!("textureDimensions({t}).y"), Type::Scalar(Sc::U32), P_PRIMARY)),
"sample" => {
let Expr::Ident(sn) = &args[0] else { return Err("sample() needs a sampler by name".into()) };
let props = ctx.samplers.get(sn).cloned().ok_or(format!("unknown sampler {sn}"))?;
let has = |p: &str| props.iter().any(|a| a == p);
let global = if has("address::mirrored_repeat") {
"mirrored"
} else if has("s_address::repeat") || has("address::repeat") {
"mipRepeat"
} else {
"linearClamp"
};
let su = ctx.samplers.get(sn).cloned().ok_or(format!("unknown sampler {sn}"))?;
let global = su.global;
let mut uv = self.expr_to(ctx, &args[1], &Type::Vector(Sc::F32, 2))?;
if has("coord::pixel") {
if su.pixel {
uv = V::new(format!("{} / vec2<f32>(textureDimensions({t}))", uv.wrapped()), uv.ty, 10);
}
let level = match args.get(2) {
Some(Expr::Call(l, la)) if l == "level" => Some(self.expr_to(ctx, &la[0], &Type::Scalar(Sc::F32))?.s),
Some(Expr::Call(l, la)) if l == "level" && la.len() == 1 => Some(self.expr_to(ctx, &la[0], &Type::Scalar(Sc::F32))?.s),
Some(_) => return Err("only level() is supported as a sample option".into()),
None if props.iter().any(|a| a.starts_with("mip_filter")) => None,
None if su.mip => None,
None => Some("0.0".into()), // no mip filter: Metal reads the top level
};
Ok(match level {
Expand All @@ -1431,7 +1519,25 @@ impl<'p> Gen<'p> {
}
}

/// Metal's `round` takes halves away from zero; WGSL's takes them to even (Metal's `rint`).
fn metal_round(&mut self, x: String, t: Type) -> V {
let tn = ty_name(&t);
let half = conv(&literal("0.5"), &t).map(|v| v.s).unwrap_or_else(|_| "0.5".into());
let name = format!("metal_round_{}", tn.replace(['<', '>'], ""));
self.helpers.entry(name.clone()).or_insert_with(|| {
// exact: x - trunc(x) has no rounding error, where floor(abs(x) + 0.5) rounds
// 0.49999997 up and is wrong for odd values from 2^23
format!("// Metal's round: halves away from zero\nfn {name}(x: {tn}) -> {tn} {{\n let t = trunc(x);\n return select(t, t + sign(x), abs(x - t) >= {half});\n}}\n")
});
V::new(format!("{name}({x})"), t, P_PRIMARY)
}

fn builtin(&mut self, ctx: &mut Ctx, n: &str, args: &[Expr]) -> R<V> {
if let Some(k) = builtin_arity(n) {
if args.len() != k {
return Err(format!("{n} takes {k} argument{}, got {}", if k == 1 { "" } else { "s" }, args.len()));
}
}
let vals: Vec<V> = args.iter().map(|a| self.expr(ctx, a)).collect::<R<_>>()?;
let f32s = Sc::F32;
let call = |name: &str, parts: Vec<String>, ty: Type| Ok(V::new(format!("{name}({})", parts.join(", ")), ty, P_PRIMARY));
Expand All @@ -1443,6 +1549,9 @@ impl<'p> Gen<'p> {
let v = one(&vals)?;
let t = v.ty.with_sc(f32s);
let a = conv(&v, &t)?;
if n == "round" {
return Ok(self.metal_round(a.s, t));
}
let name = match n {
"rsqrt" => "inverseSqrt",
"dfdx" => "dpdx",
Expand Down
Loading
Loading