Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/facett

facett-core/tests/one_msaa_writer.rs

//! **THE MSAA RULING, WITH A SCANNER BEHIND IT: no MSAA in facett, and exactly one
//! writer says so.**
//!
//! The decision (2026-08-25, GFX_V2 §V2.12): **TAA is the 3D anti-aliasing scheme and
//! the analytic feather in `facett-map/src/gpu/line.wgsl` is the 2D one. MSAA is not
//! enabled, now or later.** The reasoning lives beside the writer it guards —
//! [`facett_core::render::gpu::msaa_state`] — and is not repeated here; what is repeated
//! is the part that makes a scanner necessary rather than a comment sufficient.
//!
//! ## Why a comment was not enough
//!
//! MEASURED at `ab4ba85e`: **26 × `MultisampleState::default()` and 26 ×
//! `sample_count: 1`** across `facett-*/src`, and zero `>= 2`. Fifty-two literals all
//! stating the same policy, in eleven crates, none of them able to see the other
//! fifty-one.
//!
//! That is not merely untidy, and the reason is the failure mode. Turning MSAA on is an
//! **all-sites** change: `MultisampleState::default()` is `count: 1`, so a pipeline left
//! on the default while its render target goes to 4× is a wgpu **validation failure** —
//! a hard error at draw time, not a soft downgrade to no antialiasing. Fifty-two chances
//! to miss one, on code paths nobody exercises. The LAW-5 form of "we do not do MSAA" is
//! one descriptor and one constant; then a future decision to do MSAA is two edits, and
//! every site follows whether or not anybody remembered it existed.
//!
//! ## AMENDED 2026-09-05: "now or later" lasted eleven days
//!
//! There is now exactly ONE multisampled target in the workspace — the map's offscreen
//! colour+depth pair, at 4× — and this file guards it rather than forbidding it. See
//! [`THE_EXCEPTION`]. The amendment is narrower than it sounds and it does not soften the
//! ruling above: what the 4× pair buys is per-sample **DEPTH**, not anti-aliasing, and
//! per-sample depth is the only way an edge fragment of a road can stop owning the whole
//! pixel's depth and erasing the road beneath it (lane MP-a turned depth testing on; lane
//! GG #2 is the consequence). Every argument the ruling makes about AA still stands, and
//! `picking`'s `R32Uint` target still cannot be multisampled at any count.
//!
//! What that means for THIS file is the thing worth carrying: the exception is pinned to
//! one declaration in one named file, and the 4× constant is accepted only inside the
//! crate that owns it. "facett does not do MSAA" became "facett does MSAA in exactly one
//! place, and here is the scanner that keeps it one" — which is the same guarantee, and
//! the reason a scanner was written instead of a comment.
//!
//! ## What this fails on
//!
//! | shape | verdict |
//! |---|---|
//! | `MultisampleState` named anywhere outside the writer | RED |
//! | …or more than once inside [`THE_EXCEPTION`] | RED |
//! | `sample_count:` set to anything but an `ACCEPTED` name | RED |
//! | `sample_count: MAP_MSAA_SAMPLES` outside the `facett-map` crate | RED |
//! | either token inside a `//` comment | ignored, deliberately |
//!
//! Comments are stripped for the same reason the GL law strips them: every one of these
//! names appears in prose explaining why MSAA is off, and a law that could not be
//! explained in a comment would be obeyed by deleting the explanation.
//!
//! The scan covers `src/`, `tests/`, `benches/` and `examples/` of every workspace
//! member — a test that builds its own pipeline against a 4× target is the same
//! validation failure as a shipped one, and `gpu_taa.rs`, `gpu_oit.rs` and
//! `line_gpu.rs` each held a literal when this was written.
//!
//! Run: `cargo test -p facett-core --test one_msaa_writer`

use facett_core::law;
use std::path::{Path, PathBuf};

fn root() -> PathBuf {
    law::workspace_root(Path::new(env!("CARGO_MANIFEST_DIR")))
}

/// The file that is allowed to name the type: the one writer itself.
const THE_WRITER: &str = "facett-core/src/render/gpu/mod.rs";

/// **The one sanctioned EXCEPTION to the no-MSAA ruling, named as a file** — lane GG #2,
/// 2026-09-05.
///
/// The map's offscreen colour+depth pair is 4×, and nothing else in the workspace is. It
/// is not an erosion of the ruling: the ruling is about ANTI-ALIASING, and this buys
/// per-sample **depth**, which nothing else can supply. Lane MP-a turned depth testing on
/// so the declared paint rank could survive being split across tiles; with one depth value
/// per pixel, a partially covered edge fragment has to choose between compositing and
/// owning the pixel, and it owns it — the way beneath is depth-rejected, never blended,
/// and what is left is the winner over bare paper. `facett_map::gpu::MAP_MSAA_SAMPLES`
/// carries the full measurement.
///
/// Every reason the ruling gives still stands where it was aimed: picking is `R32Uint` and
/// cannot be multisampled at all, TAA is still the 3D scheme, and the deferred G-buffer is
/// still untouched. That is precisely why this is a second named writer rather than a bump
/// of [`NO_MSAA_SAMPLES`] — raising that would put all fifty-odd sites on 4× and break the
/// ones the ruling is right about.
///
/// The exception is a FILE, and the check below pins it to a single declaration inside
/// that file, so "facett-map may do MSAA" cannot quietly become "facett-map does MSAA in
/// six places nobody compared".
const THE_EXCEPTION: &str = "facett-map/src/gpu/mod.rs";

/// The accepted right-hand sides for a `sample_count:` field: the no-MSAA constant in the
/// three forms a caller can legitimately spell it, and the map offscreen lane's constant
/// in the two forms its own crate and its own tests spell it. Nothing is accepted that is
/// not one of these five names — a literal `4` is as red as a literal `1`, because the
/// point is that grepping the tree answers "what is multisampled here" truthfully.
const ACCEPTED: [&str; 5] = [
    "NO_MSAA_SAMPLES",
    "facett_core::render::gpu::NO_MSAA_SAMPLES",
    "crate::render::gpu::NO_MSAA_SAMPLES",
    "MAP_MSAA_SAMPLES",
    "facett_map::gpu::MAP_MSAA_SAMPLES",
];

fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    for e in entries.flatten() {
        let p = e.path();
        if p.is_dir() {
            if p.file_name().is_some_and(|n| n == "target" || n == ".git") {
                continue;
            }
            rs_files(&p, out);
        } else if p.extension().is_some_and(|x| x == "rs") {
            out.push(p);
        }
    }
}

#[test]
fn the_multisample_policy_has_exactly_one_writer() {
    // The tokens are ASSEMBLED rather than written whole, so this file scans itself like
    // every other one. The alternative — exempting the guard from its own scan — is
    // exactly the hole the next real violation hides in: a file named
    // `one_msaa_writer.rs` is a plausible place for somebody to park a "just for the
    // test" 4× pipeline.
    let state_token = format!("Multisample{}", "State");
    let count_token = format!("sample{}count:", "_");

    let root = root();
    let mut files = Vec::new();
    for dir in law::source_roots(&root) {
        rs_files(&dir, &mut files);
    }

    // LIVENESS FIRST, and not as decoration: a scan that read nothing reports a clean
    // workspace, and "clean" is the verdict this file exists to make trustworthy.
    assert!(
        files.len() > 100,
        "the source scan read only {} .rs files under {} — it is not looking at the \
         workspace, so its clean verdict is worth nothing",
        files.len(),
        root.display()
    );
    // …and the one writer must actually BE there. If it were renamed away, every site
    // would look compliant because nothing would be left to compare them against.
    let writer = root.join(THE_WRITER);
    let writer_src = std::fs::read_to_string(&writer)
        .unwrap_or_else(|e| panic!("the one writer {THE_WRITER} must be readable: {e}"));
    assert!(
        writer_src.contains(&state_token) && writer_src.contains("NO_MSAA_SAMPLES"),
        "{THE_WRITER} no longer declares the shared multisample descriptor — the scan \
         below would then pass by having nothing to enforce"
    );

    // …and so must the EXCEPTION. Same argument, and it needs making twice: if
    // `MAP_MSAA_SAMPLES` were renamed or deleted, the `ACCEPTED` entries below would go on
    // waving through a `sample_count:` that no longer names anything, and the one 4× site
    // in the workspace would be unguarded for exactly as long as nobody looked.
    let exception_src = std::fs::read_to_string(root.join(THE_EXCEPTION))
        .unwrap_or_else(|e| panic!("the one exception {THE_EXCEPTION} must be readable: {e}"));
    assert!(
        exception_src.contains("MAP_MSAA_SAMPLES"),
        "{THE_EXCEPTION} no longer declares MAP_MSAA_SAMPLES — the sanctioned 4× exception \
         is gone, so `ACCEPTED` should lose it too rather than stay as a hole"
    );

    let mut hits: Vec<String> = Vec::new();
    for file in &files {
        let rel = file.strip_prefix(&root).unwrap_or(file).display().to_string().replace('\\', "/");
        if rel == THE_WRITER {
            continue; // the one writer
        }
        // The map's offscreen lane is the one place allowed to name the 4× constant —
        // scoped to the CRATE, not granted workspace-wide, so a `sample_count:
        // MAP_MSAA_SAMPLES` appearing in facett-core or facett-map3d is still red.
        let in_the_exception_crate = rel.starts_with("facett-map/");
        let Ok(text) = std::fs::read_to_string(file) else { continue };
        // How many times the exception file names the type. One is the sanctioned
        // `map_msaa_state()`; a second is somebody parking a fresh literal beside it.
        let mut named_here = 0usize;
        for (i, raw) in text.lines().enumerate() {
            let code = raw.split("//").next().unwrap_or("");
            if code.contains(&state_token) {
                named_here += 1;
                if !(rel == THE_EXCEPTION && named_here == 1) {
                    hits.push(format!(
                        "{rel}:{}: names the multisample type directly — call \
                         `facett_core::render::gpu::msaa_state()`, or for the map's \
                         offscreen pair `facett_map::gpu::map_msaa_state()`: {}",
                        i + 1,
                        raw.trim()
                    ));
                }
            }
            if let Some(rest) = code.split_once(&count_token) {
                let value = rest.1.trim().trim_end_matches(',').trim();
                let is_map = value.contains("MAP_MSAA_SAMPLES");
                if !ACCEPTED.contains(&value) || (is_map && !in_the_exception_crate) {
                    hits.push(format!(
                        "{rel}:{}: pins a sample count to a literal — use \
                         `facett_core::render::gpu::NO_MSAA_SAMPLES`: {}",
                        i + 1,
                        raw.trim()
                    ));
                }
            }
        }
    }

    assert!(
        hits.is_empty(),
        "THE MSAA RULING HAS {} WRITERS, NOT ONE (plus the sanctioned exception in \
         {THE_EXCEPTION}). Each of these states the policy independently, so changing the \
         sample count would be an all-sites edit and a missed site is a wgpu VALIDATION \
         FAILURE, not a downgrade. Route them through \
         `facett_core::render::gpu::msaa_state()` / `NO_MSAA_SAMPLES`, whose doc carries \
         the ruling and the reasoning:\n  {}",
        hits.len(),
        hits.join("\n  ")
    );
}