Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

5.0 KB
Raw Blame
//! The live passes' bindings as `shaders/live.wgsl` declares them (after `shaders/records.wgsl`, what it shares with
//! the kernel: live/targets.rs `live_source`), read with naga (the compiler wgpu uses) when the
//! crate is built, into `$OUT_DIR/live_layout.rs` (`src/live/layout.rs` includes it): each binding's name, number,
//! kind and element stride, and the bindings each entry point uses. The shader is the one place they are written;
//! what it cannot say (a buffer's size, a pass's grid) is `src/live/layout.rs`'s table. At build time, not at run
//! time: a browser's build has no naga (wgpu hands it the WGSL).

use naga::{AddressSpace, ImageClass, ImageDimension, ScalarKind, StorageAccess, TypeInner};
use std::fmt::Write;

fn main() {
    // `cfg(dlss)`: the `dlss` feature on a target NGX supports (x86-64 Windows or Linux); elsewhere it builds nothing.
    println!("cargo:rustc-check-cfg=cfg(dlss)");
    let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    if std::env::var_os("CARGO_FEATURE_DLSS").is_some() && std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64") && (os == "windows" || os == "linux") {
        println!("cargo:rustc-cfg=dlss");
    }
    // `cfg(metalfx)`: Apple's platforms, where MetalFX's scalers exist (macOS 13 / iOS 16; the denoised one 26). The
    // framework is loaded at run time (metalfx.m), so the same binary runs on systems without it.
    println!("cargo:rustc-check-cfg=cfg(metalfx)");
    if os == "macos" || os == "ios" {
        println!("cargo:rustc-cfg=metalfx");
        println!("cargo:rerun-if-changed=src/live/metalfx.m");
        cc::Build::new().file("src/live/metalfx.m").flag("-fobjc-arc").compile("threert_metalfx");
        println!("cargo:rustc-link-lib=framework=Foundation");
        println!("cargo:rustc-link-lib=framework=Metal");
    }
    let files = ["shaders/records.wgsl", "shaders/live.wgsl"];
    for path in files {
        println!("cargo:rerun-if-changed={path}");
    }
    println!("cargo:rerun-if-changed=build.rs");
    let src: String = files.iter().map(|path| std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{path}: {e}"))).collect();
    let module = naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src)));
    let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())
        .validate(&module)
        .unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src)));
    let mut out = String::from("// Generated by build.rs from shaders/live.wgsl: do not edit.\n\n");
    // Every bound global, in binding order.
    let mut bound: Vec<_> = module.global_variables.iter().filter_map(|(h, v)| v.binding.as_ref().map(|b| (b.binding, h, v))).collect();
    bound.sort_by_key(|b| b.0);
    out += "/// Each binding live.wgsl declares (group 0), in binding order.\npub const BINDINGS: &[Binding] = &[\n";
    for (binding, _, v) in &bound {
        let name = v.name.as_deref().unwrap_or_else(|| panic!("binding {binding} has no name"));
        assert_eq!(v.binding.as_ref().unwrap().group, 0, "live.wgsl binds group 0 only ({name})");
        let ty = &module.types[v.ty].inner;
        let kind = match (v.space, ty) {
            (AddressSpace::Uniform, _) => "Kind::Uniform".to_string(),
            (AddressSpace::Storage { access }, TypeInner::Array { size, stride, .. }) => {
                let len = match size {
                    naga::ArraySize::Constant(n) => n.get(),
                    _ => 0,
                };
                format!("Kind::Storage {{ read_only: {}, stride: {stride}, len: {len} }}", !access.contains(StorageAccess::STORE))
            }
            (AddressSpace::Handle, TypeInner::Image { dim, arrayed: false, class: ImageClass::Sampled { kind: ScalarKind::Float, multi: false } }) => {
                let dim = match dim {
                    ImageDimension::D2 => "D2",
                    ImageDimension::D3 => "D3",
                    d => panic!("{name}: a {d:?} texture"),
                };
                format!("Kind::Texture(wgpu::TextureViewDimension::{dim})")
            }
            (AddressSpace::Handle, TypeInner::Sampler { comparison: false }) => "Kind::Sampler".to_string(),
            (space, _) => panic!("{name}: binding {binding} is a {space:?} this build does not read"),
        };
        writeln!(out, "    Binding {{ name: \"{name}\", binding: {binding}, kind: {kind} }},").unwrap();
    }
    out += "];\n\n/// Each entry point and the bindings it uses.\npub const ENTRY_POINTS: &[(&str, &[u32])] = &[\n";
    for (k, e) in module.entry_points.iter().enumerate() {
        let uses = info.get_entry_point(k);
        let used: Vec<String> = bound.iter().filter(|(_, h, _)| !uses[*h].is_empty()).map(|(b, _, _)| b.to_string()).collect();
        writeln!(out, "    (\"{}\", &[{}]),", e.name, used.join(", ")).unwrap();
    }
    out += "];\n";
    let dest = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("live_layout.rs");
    std::fs::write(dest, out).unwrap();
}