Refresh the checkbox sweep fix on current craft-libs main

This commit is contained in:
skylartaylor committed 2026-11-29 19:22:30 +01:00
commit 98952bc975
63 files changed
+12071 -160

No files matched your search

+2 -2
View File
@@ -3,9 +3,9 @@ name: Shared audio
on:
push:
branches: [main]
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
pull_request:
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
workflow_dispatch:
permissions:
+2 -2
View File
@@ -3,9 +3,9 @@ name: Shared media
on:
push:
branches: [main]
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
pull_request:
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
workflow_dispatch:
permissions:
+2 -2
View File
@@ -3,9 +3,9 @@ name: Shared video
on:
push:
branches: [main]
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
pull_request:
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
workflow_dispatch:
permissions:
Generated
+30
View File
@@ -1905,6 +1905,7 @@ dependencies = [
"craft-pst",
"craft-quit",
"craft-raster-codecs",
"craft-raster3d",
"craft-raw",
"craft-review",
"craft-rtf",
@@ -3254,9 +3255,11 @@ dependencies = [
"craft-ui-macros",
"craft-xml",
"egui",
"global-hotkey",
"serde",
"serde_json",
"tempfile",
"x11rb",
]
[[package]]
@@ -3803,6 +3806,7 @@ dependencies = [
"craft-docpath",
"craft-host",
"craft-i18n",
"craft-testkit",
"craft-theme",
"fmv-macos-events",
"futures-lite",
@@ -4017,6 +4021,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-raster3d"
version = "0.1.0"
dependencies = [
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
@@ -4747,6 +4759,7 @@ dependencies = [
"base64 0.22.1",
"chrono",
"craft-host",
"craft-testkit",
"craft-theme",
"craft-ui",
"dunce",
@@ -6943,6 +6956,23 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "global-hotkey"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70"
dependencies = [
"crossbeam-channel",
"keyboard-types",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"once_cell",
"thiserror 2.0.21",
"windows-sys 0.59.0",
"x11rb",
"xkeysym",
]
[[package]]
name = "glow"
version = "0.17.0"
+1
View File
@@ -236,6 +236,7 @@ craft-text = { path = "crates/text" }
craft-tcraft = { path = "crates/tcraft" }
craft-texture = { path = "crates/texture" }
craft-pbr = { path = "crates/pbr" }
craft-raster3d = { path = "crates/raster3d" }
craft-tga = { path = "crates/tga" }
craft-timeline = { path = "crates/timeline" }
craft-tiff = { path = "crates/tiff" }
+8
View File
@@ -486,3 +486,11 @@ The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's
original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed
MIT OR Apache-2.0. Source notice retained:
Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors.
The CPU renderer in crates/raster3d (rasterizer, shading, shadow maps, resolve and encoding) and
the copy of it in crates/raster3d/tests/it/reference/ are moved from:
- EffectCraft, crates/render/src/three_d/adv.rs, adv/raster.rs, adv/shade.rs and adv/scene.rs,
revision 2f16feb12f4d5ef601b35b2858f9c9a87077f61e, licensed under the MIT License or the Apache
License, Version 2.0, at your option.
https://github.com/storytold/effectcraft
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
+7 -1
View File
@@ -394,6 +394,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
documents, the Quit menu item id and the unsaved-changes question one document at a time
(`CloseGuard`). The prompt and the saving stay in each app.
- [`craft-raster3d`](crates/raster3d/README.md): a CPU renderer for a prepared 3D scene, from
EffectCraft: clipping, rasterization with a top-left fill rule, physically based shading,
shadow maps, a box resolve of supersampled output and sRGB encoding. Scenes and sizes are
checked before the target is allocated. `Limits` bounds sizes and coverage work. Preparation can
allocate clipping and triangle buffers before a work-limit error. Building the scene stays in each app.
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
for a small neutral model (paragraphs, character formatting, outline levels, tables).
@@ -436,7 +441,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
test when the variable the caller names is `1`. Any other value of that variable except empty fails
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
under `target/fixtures` and publishes each one under a lock. Not published.
under `target/fixtures` and publishes each one under a lock. Its `temp` module makes a new test folder, private to the user on
Unix, that is removed with its contents when dropped (best effort). Not published.
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
+29
View File
@@ -241,6 +241,35 @@ fn temp_name_format_is_valid() {
assert!(name.ends_with(".craft_tmp"));
}
#[test]
fn temp_name_keeps_long_non_latin_names_under_the_name_limit() {
// 62 four-byte characters plus ".json" is a valid 253-byte name.
let file = format!("{}.json", "\u{1F600}".repeat(62));
assert_eq!(file.len(), 253);
let name = temp_name(&file);
assert!(name.len() <= 255, "{} bytes", name.len());
assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(TEMP_STEM_BYTES / 4))));
assert!(name.ends_with(".craft_tmp"));
}
#[test]
fn temp_name_cuts_at_a_character_boundary() {
// TEMP_STEM_BYTES - 1 ASCII bytes, then a two-byte character that would end one byte past the limit.
let file = format!("{}\u{e9}tail", "a".repeat(TEMP_STEM_BYTES - 1));
let name = temp_name(&file);
assert!(name.starts_with(&format!(".{}.", "a".repeat(TEMP_STEM_BYTES - 1))));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn saves_a_long_non_latin_name() {
let d = TempDir::new("long-name");
let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62)));
assert!(atomic_write(&p, b"saved").is_ok());
assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec()));
assert_no_temp(&d.0);
}
/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there.
#[derive(Clone, Copy, Debug)]
enum Obstacle {
+7 -1
View File
@@ -6,7 +6,7 @@
//! that says whose storage this is, a Save As page that picks a folder and
//! names a file, and a save that refuses to overwrite somebody else's work.
//!
//! Three things shape the implementation.
//! Four things shape the implementation.
//!
//! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A
//! host writes that half. This module never learns what it reaches. That keeps
@@ -21,6 +21,12 @@
//! list under a heading reads to a user as a broken window. A feature the
//! provider does not have is therefore absent, heading and all.
//!
//! Nothing here acts on a stale answer. Every answer carries the account
//! generation its job was issued in, and [`pump`] drops one whose generation
//! is no longer current, so a reply that arrives after a sign-out or a new
//! sign-in is not applied to the session that replaced its own. A new kind of
//! answer follows the same rule.
//!
//! The application supplies [`CloudApp`]. That is what it alone can answer.
//! What its documents are, how bytes become one and back, and the words it
//! shows them in.
+29 -17
View File
@@ -5,12 +5,11 @@
//! look or change, add a note, decide whether an email goes out, and see who
//! already has access so one of them can be taken away again.
//!
//! Three things shape the implementation.
//! Four things shape the implementation.
//!
//! Nothing here opens a socket. Every call goes through [`ShareBackend`], and
//! nothing here reaches the network. A host writes the backend, and this
//! module never learns what it talks to.
//! this file.
//!
//! Nothing here blocks. Answers arrive on a channel and are read once per
//! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it
@@ -21,6 +20,17 @@
//! false until the service says sharing exists, and an app hides its Share
//! control rather than offering a button that fails. Contacts and mail are
//! reported separately and are hidden the same way.
//!
//! Nothing here acts on a stale answer. Every request carries a sequence
//! number, and its answer comes back with it. An answer is applied only while
//! the request it answers still stands: an answer to a query the
//! user has typed past, a link granted or an account linked for a sheet that
//! has since closed or moved to another document, and a capabilities answer
//! to a question asked before [`ShareDialog::refresh`],
//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A
//! withdrawal is the one answer applied by share id instead: the share is gone
//! on the service, so it leaves every list that still shows it. A new kind of
//! answer follows the sequence rule.
use std::collections::HashMap;
use std::sync::mpsc::{Receiver, Sender};
@@ -226,7 +236,9 @@ struct Sheet {
/// Where it could be saved. `None` until the answer arrives.
destinations: Option<Vec<Destination>>,
destinations_seq: Option<u64>,
link_seq: Option<u64>,
/// Account links in flight, by request. More than one can be: every
/// unlinked destination stays clickable while another one links.
linking: Vec<u64>,
/// Which one is selected, by id.
destination: Option<String>,
/// The name typed while the document still has nowhere to live.
@@ -248,7 +260,7 @@ impl Sheet {
Sheet {
destinations: None,
destinations_seq: None,
link_seq: None,
linking: Vec::new(),
destination: None,
save_as: title.clone(),
saving: None,
@@ -740,16 +752,16 @@ impl ShareDialog {
}
}
Answer::Linked => {
// An account arrived, so the list is stale. With no sheet open
// there is no list to reload.
if self.open.is_some() {
if let Some(sheet) = &mut self.open {
sheet.destinations = None;
}
let seq = self.issue(Request::Destinations);
if let Some(sheet) = &mut self.open {
sheet.destinations_seq = Some(seq);
}
// Only for the sheet that asked: after the sheet closed, moved
// to another document or the account signed out, a late
// answer asks the service for nothing.
let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return };
// An account arrived, so the list is stale.
sheet.linking.retain(|s| *s != seq);
sheet.destinations = None;
let seq = self.issue(Request::Destinations);
if let Some(sheet) = &mut self.open {
sheet.destinations_seq = Some(seq);
}
}
Answer::Withdrawn { share_id } => {
@@ -802,8 +814,8 @@ impl ShareDialog {
sheet.destinations_seq = None;
sheet.destinations = Some(Vec::new());
sheet.save_error = Some(reason);
} else if sheet.link_seq == Some(seq) {
sheet.link_seq = None;
} else if sheet.linking.contains(&seq) {
sheet.linking.retain(|s| *s != seq);
sheet.save_error = Some(reason);
}
}
@@ -845,7 +857,7 @@ impl ShareDialog {
// application's business and not this crate's.
let seq = self.issue(Request::Link { destination });
if let Some(sheet) = &mut self.open {
sheet.link_seq = Some(seq);
sheet.linking.push(seq);
sheet.error = None;
}
}
+43
View File
@@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() {
assert!(copied(&ctx).is_empty(), "nor after the sheet closed");
}
fn destinations_asked(backend: &Silent) -> usize {
backend.seen().iter().filter(|r| **r == Request::Destinations).count()
}
fn last_link(dialog: &ShareDialog) -> u64 {
dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked")
}
#[test]
fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() {
let (ctx, mut dialog, _) = ready();
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
let first = last_link(&dialog);
// A second destination is clicked before the first one answers.
dialog.apply(&ctx, vec![Act::Link("mail".into())]);
let second = last_link(&dialog);
dialog.receive(&ctx, first, Ok(Answer::Linked));
let sheet = dialog.open.as_ref().expect("open");
assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again");
assert_eq!(sheet.linking, [second], "the later link is still in flight");
dialog.receive(&ctx, second, Err("no account".into()));
let sheet = dialog.open.as_ref().expect("open");
assert!(sheet.linking.is_empty());
assert_eq!(sheet.save_error.as_deref(), Some("no account"));
let (ctx, mut dialog, backend) = ready();
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
let linking = last_link(&dialog);
dialog.close();
dialog.open("files/plan.docx", "Plan");
let before = destinations_asked(&backend);
dialog.receive(&ctx, linking, Ok(Answer::Linked));
assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan");
let (ctx, mut dialog, backend) = ready();
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
let linking = last_link(&dialog);
dialog.signed_out();
let before = destinations_asked(&backend);
dialog.receive(&ctx, linking, Ok(Answer::Linked));
assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out");
}
/// Whether one frame of the sheet offers "Get a link" as a button that can
/// be pressed, read off the accessibility tree.
fn link_button_enabled(dialog: &mut ShareDialog) -> Option<bool> {
+4
View File
@@ -238,6 +238,7 @@ craft-shared-vec = { workspace = true, optional = true }
craft-ease = { workspace = true, optional = true }
craft-i18n-build = { workspace = true, optional = true }
craft-pbr = { workspace = true, optional = true }
craft-raster3d = { workspace = true, optional = true }
[features]
ui = [
@@ -622,6 +623,7 @@ jxl-encode = ["jxl", "craft-jxl/encode"]
keymap = ["dep:craft-keymap"]
keymap-egui = ["keymap", "craft-keymap/egui"]
keymap-global = ["keymap", "craft-keymap/global"]
kiwi = ["dep:craft-kiwi"]
@@ -801,6 +803,8 @@ quit = ["dep:craft-quit"]
raster-codecs = ["dep:craft-raster-codecs"]
raster3d = ["dep:craft-raster3d"]
raw = ["dep:craft-raw"]
raw-arw = ["raw", "craft-raw/arw"]
raw-cr2 = ["raw", "craft-raw/cr2"]
+2
View File
@@ -331,6 +331,8 @@ pub use craft_pst as pst;
pub use craft_quit as quit;
#[cfg(feature = "raster-codecs")]
pub use craft_raster_codecs as raster_codecs;
#[cfg(feature = "raster3d")]
pub use craft_raster3d as raster3d;
#[cfg(feature = "raw")]
pub use craft_raw as raw;
#[cfg(feature = "review")]
+4 -1
View File
@@ -106,7 +106,10 @@ index, bytes, role }` literals; any struct with those fields and that name in sc
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
`has_script(tag)`, `is_cjk()` and `weight()`.
`has_script(tag)`, `is_cjk()` and `weight()`. Tests and tables written by hand build a face with
`EmbeddedFace::new(family, style, scripts, bytes)`, which sets no `role`, plus `.with_index(n)`
for a face in a collection; both are `const fn`. Code that uses `new` keeps compiling when a
field with a default is added; a struct literal does not.
## Document fonts
+20
View File
@@ -87,6 +87,26 @@ pub struct EmbeddedFace {
}
impl EmbeddedFace {
/// A face at index 0 of `bytes` with no `role`, for tests and for tables written by hand. Code
/// that builds faces with `new` keeps compiling when a field with a default is added; a struct
/// literal does not.
///
/// ```
/// use craft_fonts_build::EmbeddedFace;
///
/// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2);
/// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2));
/// ```
pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self {
Self { family, style, scripts, index: 0, bytes, role: None }
}
/// The same face at `index` in a font collection (`.ttc`).
#[must_use]
pub const fn with_index(self, index: u32) -> Self {
Self { index, ..self }
}
/// `"<family> <style>"`, e.g. `"Noto Sans Arabic Regular"`.
pub fn name(&self) -> String {
format!("{} {}", self.family, self.style)
+15 -1
View File
@@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use crate::cmap::Cmap;
use crate::embed::Env;
use crate::{Embed, Error};
use crate::{Embed, EmbeddedFace, Error};
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/craft-fonts")
@@ -46,6 +46,20 @@ fn run(embed: Embed, dir: Option<&Path>, required: Option<&str>) -> Run {
Run { result: result.map(|faces| faces.iter().map(|f| format!("{} {}", f.family, f.style)).collect()), cargo, table }
}
#[test]
fn embedded_face_new_starts_at_index_zero() {
const SCRIPTS: &[&str] = &["Jpan", "Latn"];
const FACE: EmbeddedFace = EmbeddedFace::new("Sans JP", "Bold", SCRIPTS, b"font");
assert_eq!((FACE.family, FACE.style, FACE.scripts, FACE.index, FACE.bytes), ("Sans JP", "Bold", SCRIPTS, 0, &b"font"[..]));
assert_eq!(FACE.role, None);
let in_collection = FACE.with_index(3);
assert_eq!(in_collection.index, 3);
assert_eq!(
(in_collection.family, in_collection.style, in_collection.bytes, in_collection.role),
(FACE.family, FACE.style, FACE.bytes, FACE.role)
);
}
#[test]
fn serve_replaces_a_stale_copy_of_the_same_size() {
let scratch = Scratch::new("serve-stale");
+9
View File
@@ -23,6 +23,13 @@ craft-host = { workspace = true }
craft-tracked = { workspace = true }
craft-ui-macros = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
global-hotkey = { version = "0.9", optional = true }
# The systems where global-hotkey grabs keys through X11.
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
x11rb = { version = "0.13.1", optional = true }
[dev-dependencies]
# `serde` for setting `RawInput` fields only the suite's egui fork has.
egui = { workspace = true }
@@ -32,3 +39,5 @@ tempfile = "3"
[features]
# The egui key conversions.
egui = ["dep:egui", "craft-host/ui"]
# System-wide hotkeys (the `global` module); not built for wasm32.
global = ["dep:global-hotkey", "dep:x11rb"]
+73 -1
View File
@@ -18,7 +18,7 @@ supplies its command catalog, its file-format readers and its UI.
`Keymap::with_reserved`, e.g. `reserved::system(platform)` for the operating system's window
switching and closing chords. A reserved chord cannot be assigned or bound.
- Dependencies: `serde`, `serde_json` and `roxmltree`; `craft-i18n` and `craft-host`; `egui` with the
`egui` feature.
`egui` feature; `global-hotkey`, and `x11rb` on Linux and the BSDs, with the `global` feature.
## A catalog and dispatch
@@ -364,3 +364,75 @@ The Keyboard Shortcuts dialog is `craft_menu::shortcuts`.
- `egui`: the egui side. Conversions to and from egui keys and modifiers; `KeyInput::from_egui`;
`egui::matches`, which accepts the shifted key egui reports for a Shift binding (`Shift+;`
matches `:`).
- `global`: `global::GlobalHotkeys`, chords that run a command while another application has the
keyboard, such as a record toggle pressed during a full-screen game. It registers them with
`RegisterHotKey` on Windows, a Carbon hotkey on macOS and a key grab on the X11 root window
on Linux and the BSDs. Not built for wasm32; on other systems (Android, iOS) `new` fails with
`GlobalError::Unsupported`.
```rust,ignore
let mut hotkeys = GlobalHotkeys::new()?;
hotkeys.set_waker(move || ctx.request_repaint());
let refused = hotkeys.replace(bindings); // (CommandRef, Chord) pairs
// Once a frame:
for event in hotkeys.poll() {
app.key(&event.command, event.state); // KeyState::Pressed or KeyState::Released
}
```
- One set is open per process at a time (`GlobalError::AlreadyOpen`). Create it on the UI
thread: on Windows that thread receives the hotkey messages, and on macOS it must be the main
thread.
- A chord needs Cmd, Ctrl or Alt unless its key is F1 to F35 (`GlobalError::TypingKey`). Keys
typed with Shift (`+`, `:`, `?`) have no key of their own (`GlobalError::Unbindable`). Off
macOS, `Cmd+K` and `Ctrl+K` are one hotkey (`GlobalError::Duplicate`). A chord another
application holds is `GlobalError::Taken`. Windows registers F1 to F24 and macOS F1 to F20.
On X11 the ISO key between left Shift and Z and `\` are one hotkey (`GlobalError::Duplicate`),
and `'` cannot be grabbed (`GlobalError::Unbindable`). On Windows a chord with Ctrl and Alt on
a letter, digit, symbol or Space key is refused (`GlobalError::AltGr`), since Windows reports AltGr
as Ctrl+Alt.
- On X11 a symbol chord is grabbed at the key that types the symbol in the current layout. A
symbol the layout types only with AltGr is refused (`GlobalError::Unbindable`): with German,
`Ctrl+[` would grab Ctrl+8. A symbol typed with Shift is written without Shift, as the keymap
matches punctuation: with AZERTY, `Ctrl+.` grabs Ctrl+Shift on the key that types `.`, and
`Ctrl+Shift+.` is refused (`GlobalError::Unbindable`). The Latin letters of a second layout
group count as that layout's own keys when the key types no letter, digit or symbol in the
first group, so with Russian and US `Ctrl+A` grabs the key that types A. With US and French,
`Ctrl+A` is refused (`GlobalError::Unbindable`), since the grab would go to the US Q key.
Symbols of a second group are refused like AltGr ones.
Two chords that land on one key and modifier set are one hotkey (`GlobalError::Duplicate`):
with AZERTY, `Ctrl+-` and `Ctrl+6`. So are two chords registered as the same hotkey on
different keys: `Ctrl+.` registered with AZERTY, then `Ctrl+Shift+.` after a switch to US.
- On X11, when a layout change moves a chord's key, `replace`, `unregister` and `clear`
release the key that was grabbed. A grab that no key of the current layout leads to stays
until a later change can release it, and its chord is refused meanwhile (`GlobalError::Taken`).
When the layout changes while a grab is released, a binding whose grab that release removed
is grabbed again, or leaves the set when it cannot be grabbed again.
When the keyboard mapping cannot be read, `replace` refuses every binding and keeps the set
as it is, except that an empty `replace` still clears the set. The grabs of the chords that
leave the set then stay until a later change can release them, and `unregister` returns the
error.
- On Windows and X11 a letter chord is grabbed at the key that types the letter, as the keymap
matches letters on a Latin layout. On macOS it is grabbed at the letter's position on a US
keyboard: with AZERTY, `Cmd+A` is the key that types Q.
- A held chord gives one `Pressed` and one `Released`. `replace` leaves a binding whose chord
and command do not change registered, so a held chord stays held. Unregistering a held chord,
or replacing its binding, gives its `Released` at the next `poll`; events the system sent
before the change go to the command the chord ran then. On Windows and macOS a press that
waits in the app's event queue while the bindings change goes to the new command. On Windows
the release of a chord unregistered while held is dropped when it arrives, so it does not end
a later hold of the same chord.
- At most 256 system events wait between polls (`MAX_QUEUED`); beyond that the oldest are
dropped, and after such a loss every chord that was down is released. When more than 256
events wait for `poll`, the oldest press whose release also waits is dropped with that
release, so every press the app gets has its release. Past 512 waiting events
(`MAX_PENDING`) the oldest press is dropped; a release is never dropped. At most 128 chords
are registered (`MAX_GLOBAL`).
- On X11 each `register` and `unregister` waits for the key-grab thread, which takes one
request every 50 ms. `replace` sends the chords it removes in one request and those it adds
in another, and adds them one at a time when the system refuses one of them; `clear` sends
one request. `new` fails with
`GlobalError::Os` when that thread has stopped (a display without the XKEYBOARD extension).
- A Wayland session is refused with `GlobalError::Wayland`, since an X11 grab there sees only
keys typed into X11 windows. Without an X11 display, `new` fails with
`GlobalError::NoDisplay`.
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -13,7 +13,9 @@
//! user's keyboard layout, for matching, recording and labels. [`editor`] is the model of a
//! shortcut editor: undo, a chord recorder, conflict queries and search. With the `egui` feature,
//! the `egui` module
//! converts to and from egui keys and matches key presses against bindings.
//! converts to and from egui keys and matches key presses against bindings. With the `global`
//! feature, the `global` module registers chords with the operating system so that they run
//! commands while another application has the keyboard.
//!
//! ```
//! use craft_keymap::{Chord, Platform};
@@ -143,6 +145,8 @@ mod commands;
pub mod editor;
#[cfg(feature = "egui")]
pub mod egui;
#[cfg(all(feature = "global", not(target_arch = "wasm32")))]
pub mod global;
pub mod import;
pub mod keymap;
pub mod layout;
+9
View File
@@ -208,6 +208,15 @@ Hide Others, Show All and Quit, where Quit asks the app first.
craft_menu::mac::install_app_menu(&cc.egui_ctx, "WordCraft")?;
```
Its labels are English. `mac::install_app_menu_with` takes a `LayoutOptions` instead, and its
`label` translates `About {app}`, `Services`, `Hide {app}`, `Hide Others`, `Show All` and
`Quit {app}`, the keys `mac_layout` uses for the same items.
```rust
#[cfg(target_os = "macos")]
craft_menu::mac::install_app_menu_with(&cc.egui_ctx, &LayoutOptions::new("WordCraft").label(&translate))?;
```
craft-menu owns the process's menu event handler (muda keeps the first one set, in craft-window), so the
crate sets it once and both `mac::install` and `mac::install_app_menu` use it; a later
`mac::install` replaces the minimal app menu, and a second `mac::install` returns `None`.
+1 -1
View File
@@ -99,7 +99,7 @@ impl<'a> LayoutOptions<'a> {
self
}
fn text(&self, english: &'static str) -> String {
pub(crate) fn text(&self, english: &'static str) -> String {
(self.label)(english).replace("{app}", self.app_name)
}
+2 -1
View File
@@ -64,7 +64,8 @@
//! [`LanguageMenu`] does for languages.
//!
//! The labels the layout writes itself are English unless the app passes its translations in
//! [`LayoutOptions::label`].
//! [`LayoutOptions::label`]. `mac::install_app_menu_with` takes the same translations for the
//! minimal app menu.
//!
//! **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key,
//! which would skip the app's own key rules (a focused text field keeps ⌘C, ⌘V and ⌘Z, dialogs
+27 -2
View File
@@ -39,6 +39,7 @@ use craft_ui::menu::Alternate;
use craft_ui::runtime::{frame, motion};
use craft_window::native_menu as native;
use crate::LayoutOptions;
use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok};
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
@@ -95,7 +96,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
/// Replace winit's default macOS app menu with a minimal one whose Quit (⌘Q) asks the app first,
/// for an app without a [`MenuBar`] of its own: About, Services, Hide, Hide Others, Show All and
/// Quit, labelled in English with `app_name` ("Quit WordCraft").
/// Quit, labeled in English with `app_name` ("Quit WordCraft"). [`install_app_menu_with`] takes
/// the app's translations.
///
/// winit's Quit ends the process without asking, so unsaved work is lost. This Quit has the id
/// [`craft_quit::QUIT_MENU_ID`] and runs [`craft_quit::on_menu_event`]: it asks the root window to
@@ -106,13 +108,36 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
/// platforms without an application menu bar. On error winit's menu stays: the app still runs, but
/// ⌘Q quits without asking.
pub fn install_app_menu(ctx: &egui::Context, app_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
install_app_menu_with(ctx, &LayoutOptions::new(app_name))
}
/// [`install_app_menu`] with the app's translations: the titles [`app_menu`] gives.
pub fn install_app_menu_with(ctx: &egui::Context, options: &LayoutOptions) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let ctx = ctx.clone();
let handler = Arc::new(move |id: &str, _: native::Chosen| {
craft_quit::on_menu_event(&ctx, id);
// Choosing an item is not window input, so nothing else wakes egui.
ctx.request_repaint();
});
native::install_app_menu(app_name, craft_quit::QUIT_MENU_ID, handler)
native::install_app_menu_with(&app_menu(options), craft_quit::QUIT_MENU_ID, handler)
}
/// The titles of the minimal app menu ([`install_app_menu_with`]). [`LayoutOptions::label`] names
/// the items through the keys [`crate::mac_layout`] uses for its app menu: `About {app}`,
/// `Services`, `Hide {app}`, `Hide Others`, `Show All` and `Quit {app}`, with `{app}` replaced by
/// [`LayoutOptions::app_name`], which also titles the menu. Services, Hide Others and Show All take
/// the system's localized titles when the app supplies no translation, as in [`crate::mac_layout`].
/// [`LayoutOptions::keys`] is not used.
pub fn app_menu(options: &LayoutOptions) -> native::AppMenu {
let mut menu = native::AppMenu::english(options.app_name);
let system = |english: &'static str| label_or_system(&options.text(english), english, native::system_title);
menu.about = options.text("About {app}");
menu.services = system(Standard::Services.english());
menu.hide = options.text("Hide {app}");
menu.hide_others = system("Hide Others");
menu.show_all = system(Standard::ShowAll.english());
menu.quit = options.text("Quit {app}");
menu
}
/// What each native item runs, by native id, for the handler.
+25 -1
View File
@@ -1,6 +1,6 @@
//! The Mac layout, its shortcut clashes, and the keys that decide rebuild against update in place.
use craft_menu::{Builtin, Document, Item, ItemKind, LayoutOptions, MenuBar, MenuRole, Node, mac_layout, structure_key, window_key};
use craft_menu::{Builtin, Document, Item, ItemKind, LayoutOptions, MenuBar, MenuRole, Node, mac, mac_layout, structure_key, window_key};
use craft_ui::testing::trial;
use crate::sample::{chord, cmd, ids, sample, titled};
@@ -41,6 +41,30 @@ fn the_app_menu_is_laid_out_the_mac_way() {
);
}
/// The minimal app menu names the app by default and takes the app's translations through the keys
/// the Mac layout uses for the same items.
#[trial]
fn the_minimal_app_menu_takes_the_apps_translations() {
let english = mac::app_menu(&LayoutOptions::new("Sample"));
assert_eq!(english.title, "Sample");
for label in [&english.about, &english.hide, &english.quit] {
assert!(label.contains("Sample"), "{label:?} names the app");
}
let german = |s: &'static str| match s {
"About {app}" => "Über {app}".to_string(),
"Services" => "Dienste".into(),
"Hide {app}" => "{app} ausblenden".into(),
"Hide Others" => "Andere ausblenden".into(),
"Show All" => "Alle einblenden".into(),
"Quit {app}" => "{app} beenden".into(),
other => panic!("no app menu label {other:?}"),
};
let m = mac::app_menu(&LayoutOptions::new("Sample").label(&german));
let got: [&str; 7] = [&m.title, &m.about, &m.services, &m.hide, &m.hide_others, &m.show_all, &m.quit];
assert_eq!(got, ["Sample", "Über Sample", "Dienste", "Sample ausblenden", "Andere ausblenden", "Alle einblenden", "Sample beenden"]);
}
/// App commands keep ⌘H, ⌘M, ⌘W and ⌘,: the system items give way, and each clash is reported.
#[trial]
fn clashes_are_resolved_in_the_apps_favour() {
+3
View File
@@ -86,5 +86,8 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H
rfd = { version = "0.17.2", default-features = false, optional = true }
wasm-bindgen-futures = { version = "0.4", optional = true }
[dev-dependencies]
craft-testkit = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
+12 -7
View File
@@ -494,7 +494,11 @@ mod tests {
use super::{ANIMATIONS_KEY, Answers, GNOME, KDE, KDE_MOTION_KEY, MOTION_KEY, STANDARD, decode, decode_motion};
use crate::appearance::is_gnome_session;
use crate::appearance::{Theme, Watcher};
use craft_testkit::deadline::with_deadline;
use std::time::Duration;
// A hang guard only: each wait under it ends at a message the worker sends, so a run that works
// never reaches the limit.
const HANG_GUARD: Duration = Duration::from_secs(60);
use zbus::zvariant::Value;
// The portal's, GNOME's and KDE's keys each decode to reduced or not; malformed values say
// nothing. Combined, any one asking for reduced motion wins, all answering otherwise is not
@@ -524,7 +528,7 @@ mod tests {
},
)
.ok_or("worker creation failed")?;
let shared = sent.recv_timeout(Duration::from_secs(2))?;
let shared = with_deadline(HANG_GUARD, "the source's shared state", move || sent.recv())?;
let mut answers = Answers { standard: None, gnome: None, motion: None, gnome_motion: None, kde_motion: None };
answers.apply(&shared, KDE, "SingleClick", &Value::F64(0.0));
answers.apply(&shared, KDE, KDE_MOTION_KEY, &Value::from("fast"));
@@ -618,7 +622,7 @@ mod tests {
},
)
.ok_or("worker creation failed")?;
finished.recv_timeout(Duration::from_secs(2))?;
with_deadline(HANG_GUARD, "the source's publishing", move || finished.recv())?;
assert_eq!(watcher.generation(), 4, "theme, contrast, motion and text scale each changed once");
assert_eq!((watcher.current(), watcher.contrast()), (Some(Theme::Dark), Some(Contrast::High)));
assert_eq!(watcher.text_scale(), Some(1.25));
@@ -656,18 +660,19 @@ mod tests {
},
)
.ok_or("worker creation failed")?;
ready.recv_timeout(Duration::from_secs(2))?;
with_deadline(HANG_GUARD, "the source's start", move || ready.recv())?;
let (dropped, drop_result) = std::sync::mpsc::channel();
let dropper = std::thread::spawn(move || {
drop(watcher);
let _ = dropped.send(());
});
let bounded = drop_result.recv_timeout(Duration::from_secs(1)).is_ok();
// Release before asserting, including when an unbounded implementation regresses.
// The source stays blocked until `release` drops, so a drop that waits for it never returns
// and the hang guard fails the test; unwinding from that failure drops `release`.
let returned = with_deadline(HANG_GUARD, "the watcher drop while its source is blocked", move || drop_result.recv());
drop(release);
exit.recv_timeout(Duration::from_secs(2))?;
with_deadline(HANG_GUARD, "the released source's exit", move || exit.recv())?;
assert!(dropper.join().is_ok(), "watcher drop panicked");
assert!(bounded, "watcher drop waited for a blocked synchronous poll");
assert!(returned.is_ok(), "watcher drop waited for a blocked synchronous poll");
Ok(())
}
}
+49 -54
View File
@@ -2,71 +2,66 @@
#![cfg(not(target_arch = "wasm32"))]
use craft_platform::{dialog_outcome::Outcome, dialogs::NativeDialogs};
use craft_testkit::deadline::with_deadline;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
mpsc,
};
use std::time::{Duration, Instant};
fn pump_until<R, T: Send + 'static>(
service: &mut NativeDialogs<R, T>,
mut create: impl FnMut(R) -> craft_platform::dialogs::DialogFuture<T>,
until: impl Fn() -> bool,
) {
let deadline = Instant::now() + Duration::from_secs(3);
while !until() {
assert!(Instant::now() < deadline, "worker did not settle");
service.pump(&mut create);
std::thread::yield_now();
}
}
use std::time::Duration;
// The service wakes the host once per request, once when its worker is ready for the picker and once
// when the picker has answered. The test pumps after each wake instead of polling against a clock.
#[test]
fn completion_between_pumps_cannot_reject_a_chained_request() -> Result<(), Box<dyn std::error::Error>> {
let wakes = Arc::new(AtomicUsize::new(0));
let count = wakes.clone();
let (client, mut service) = NativeDialogs::<u8, u8>::new(move || {
count.fetch_add(1, Ordering::SeqCst);
});
let first = client.request(1);
let (release, wait) = mpsc::channel();
let mut wait = Some(wait);
let created = Arc::new(AtomicUsize::new(0));
let count = created.clone();
pump_until(
&mut service,
move |value| {
fn completion_between_pumps_cannot_reject_a_chained_request() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// A hang guard only: every wait below ends at a wake, so a run that works never reaches the limit.
with_deadline(Duration::from_secs(60), "the dialog lifecycle", || {
let wakes = Arc::new(AtomicUsize::new(0));
let count = wakes.clone();
let (wake, woken) = mpsc::channel();
let (client, mut service) = NativeDialogs::<u8, u8>::new(move || {
count.fetch_add(1, Ordering::SeqCst);
let _ = wake.send(());
});
let first = client.request(1);
woken.recv()?;
let (release, wait) = mpsc::channel();
let mut wait = Some(wait);
let created = Arc::new(AtomicUsize::new(0));
let count = created.clone();
let mut create = move |value| -> craft_platform::dialogs::DialogFuture<u8> {
count.fetch_add(1, Ordering::SeqCst);
let wait = wait.take();
Box::pin(async move {
let _ = wait.map(|wait| wait.recv());
Outcome::Selected(value)
})
},
|| created.load(Ordering::SeqCst) == 1,
);
// Finish after the host's pump, before its app continuation polls the reply.
release.send(())?;
let deadline = Instant::now() + Duration::from_secs(3);
while wakes.load(Ordering::SeqCst) < 3 {
assert!(Instant::now() < deadline, "worker did not publish completion");
std::thread::yield_now();
}
assert!(matches!(first.try_recv(), Err(mpsc::TryRecvError::Empty)));
assert!(service.pending(), "an unpublished completion still retains the parent");
service.pump(|value| Box::pin(async move { Outcome::Selected(value) }));
assert_eq!(first.try_recv()?, Outcome::Selected(1));
assert!(!service.pending());
// The app can chain the next dialog immediately upon observing the first answer.
let second = client.request(2);
assert!(matches!(second.try_recv(), Err(mpsc::TryRecvError::Empty)));
let mut result = None;
while result.is_none() {
assert!(Instant::now() < deadline, "chained picker did not settle");
};
// The first pump starts the worker; the second, after its wake, opens the picker.
service.pump(&mut create);
woken.recv()?;
service.pump(&mut create);
assert_eq!(created.load(Ordering::SeqCst), 1, "worker did not settle");
// Finish after the host's pump, before its app continuation polls the reply.
release.send(())?;
woken.recv()?;
assert_eq!(wakes.load(Ordering::SeqCst), 3, "worker did not publish completion");
assert!(matches!(first.try_recv(), Err(mpsc::TryRecvError::Empty)));
assert!(service.pending(), "an unpublished completion still retains the parent");
service.pump(|value| Box::pin(async move { Outcome::Selected(value) }));
result = second.try_recv().ok();
std::thread::yield_now();
}
assert_eq!(result, Some(Outcome::Selected(2)));
assert!(!service.pending());
Ok(())
assert_eq!(first.try_recv()?, Outcome::Selected(1));
assert!(!service.pending());
// The app can chain the next dialog immediately upon observing the first answer.
let second = client.request(2);
assert!(matches!(second.try_recv(), Err(mpsc::TryRecvError::Empty)));
// The request's wake, the worker's and the picker's answer each lead to one pump.
for _ in 0..3 {
woken.recv()?;
service.pump(|value| Box::pin(async move { Outcome::Selected(value) }));
}
let result = second.try_recv().ok();
assert!(result.is_some(), "chained picker did not settle");
assert_eq!(result, Some(Outcome::Selected(2)));
assert!(!service.pending());
Ok(())
})
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "craft-raster3d"
description = "CPU rasterizer for prepared 3D scenes: clipping, depth-buffered triangles, metallic-roughness shading, shadow maps, box resolve and sRGB encoding"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
rayon = { workspace = true }
thiserror = { workspace = true }
+269
View File
@@ -0,0 +1,269 @@
# craft-raster3d
A CPU renderer for a prepared 3D scene. A `Scene` holds world-space triangles, their materials and
textures, lights, an optional environment light and shadow maps, as plain arrays. The crate clips,
rasterizes and shades the scene into premultiplied linear RGBA and camera depth, renders the shadow
maps of its lights, box-filters a supersampled result to output size and converts linear pixels to
the sRGB transfer curve. It has no UI, does no file or network I/O and has no `unsafe` code.
Building a scene from an app's document (layers, cameras, models, text) stays in the app.
- **Rendering.** `try_render(&scene, &limits)` returns a `Target` at the scene's raster size:
premultiplied linear RGBA and the camera-space depth of the nearest opaque surface, infinity where
no opaque surface is drawn. `Scene::clip` maps world to clip space with reversed depth (a larger
normalized device z is nearer); `Scene::view` maps world to camera space, and its third row gives
the depth. Rows are rasterized on several threads with rayon.
- **Clipping.** Triangles are clipped against the depth range `0 ≤ z ≤ w` before the perspective
divide, the clip volume WebGPU uses
(<https://www.w3.org/TR/webgpu/#coordinate-systems>), and against a guard band of
`GUARD_BAND × w` (1024) in x and y. A triangle inside the band is not clipped in x or y. When the
depth clip in `f32` overflows between far-apart corners, the triangle is clipped against every
plane in `f64` instead.
- **Coverage.** One sample at each pixel center. A pixel on an edge shared by two triangles belongs
to the triangle for which the edge is a top or left edge, the rule Direct3D documents
(<https://learn.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-rasterizer-stage-rules>).
Positions, normals, texture coordinates and tangents are interpolated with perspective-correct
weights (<https://www.w3.org/TR/webgpu/#coordinate-systems>).
- **Passes.** The first `Scene::opaque_count` indices are opaque triangles. Visibility is resolved
first and each pixel is shaded once; where the visible fragment is discarded (an alpha test or the
back face of a single-sided material), the nearest surviving fragment under the pixel is shaded
instead. The remaining indices are transparent triangles, which the caller sorts back to front.
Each is shaded per fragment, depth-tested against the opaque surfaces and blended over them. A
triangle whose material is shadows-only belongs in the transparent range; `try_render` returns an
error for one in the opaque range unless its material's `visible` is false.
Other visible materials for which `Material::transparent()` is true also belong in the
transparent range; `try_render` returns `BadMaterial` for one in the opaque range.
- **Facing.** A triangle whose screen-space winding is negative with y down
(counterclockwise on the screen) faces the camera. A material with `double_sided` false does not
draw back faces; a double-sided material shades a back face with its normal reversed.
- **Shading.** Direct light uses the Cook-Torrance BRDF with the GGX distribution, the
Smith-Schlick geometry term with `k = (roughness + 1)² / 8` and Schlick's Fresnel, with a Lambert
diffuse lobe weighted by `(1 − F)(1 − metallic)`, as in Karis, *Real Shading in Unreal Engine 4*
(SIGGRAPH 2013,
<https://de45xmedrsdbp.cloudfront.net/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf>).
Roughness is shaded as at least 0.03. Light colors are the irradiance on a surface facing the
light, so π is folded into the light intensity. Parallel, spot and point lights have no falloff,
a smooth falloff or a clamped inverse-square falloff. The environment light reads an irradiance
map for diffuse light and a chain of radiance levels by roughness for specular light, with
Karis's analytic environment BRDF for mobile
(<https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile>). Materials take a
base color, metallic-roughness, normal, occlusion and emissive texture, an alpha mode (opaque,
mask or blend), and weights for the diffuse lobe, the dielectric reflectance and the ambient light.
In mask mode a fragment whose material alpha (the base alpha times the base texture's) is below
the cutoff is discarded, and a fragment that passes is drawn with the layer's opacity alone, so
at an opacity of 1 it is fully opaque
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#alpha-coverage>). In blend mode the
alpha is the material alpha times the opacity.
- **Textures.** `Scene::texels` holds linear straight RGBA, row-major from the top row, and each
`TexInfo` gives a texture's offset, size and wrap modes (repeat, clamp or mirror). `sample` is a
bilinear lookup with texel centers at +0.5.
- **Shadow maps.** `try_shadow_maps(&mut scene, draft, &limits)` renders the light-space depth of
every triangle whose material casts shadows into one map per parallel or spot light, six per
point light and one orthographic map for the environment light's dominant direction, for every
light whose `shadow` is 0 or more. The shader compares each receiver with the nearest depth in the map
(<https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-11-shadow-map-antialiasing>)
over a jittered grid of 5 × 5 to 10 × 10 taps, each a bilinear comparison against the receiver's
plane. A spot or point light's maps hold casters at a light-space depth of 0.001 or more, and a
receiver at that depth or nearer is not shadowed. A spot light's map covers its outer cone's half
angle plus 0.05 radians. A spot light whose half angle with that margin is over 1.45 radians
(about 83°) gets six maps, as a point light does. A masked caster drops texels whose material alpha is below the
material's cutoff, as shading does. A blended caster drops texels whose alpha times the opacity
is below 0.5. A masked or blended caster without a base texture is tested the same way with its
material's alpha. An opaque-mode or masked caster with an opacity below 0.5 casts no shadow.
`shadow_map_size` gives one map texel per
raster pixel (supersampled pixels when `ssaa` is above 1, as EffectCraft sizes them) to a power
of two from 512 to 4096 (512 for a draft render), and
`shadow_point_face_size` caps a cube face at 2048. `shadow_sizes` keeps a scene within
`MAX_SHADOW_TEXELS` (26,000,000) by halving the largest map above its floor (512, or 128 for a
cube face), the earliest light first on ties, and then dropping the last lights' maps.
`try_env_shadow_map` builds the environment light's map. A second call of `try_shadow_maps`
replaces the maps of the first, and gives the same maps and marks. Its depth tests (one per
caster and map, plus each caster's bounding box in each map) are limited by `max_work`, and on
an error it leaves the scene as it was. The bounding boxes of casters that are skipped for their
material's alpha or opacity are not counted: a masked or blended caster without a base texture
whose alpha fails its test, a masked or blended caster with a base texture whose base alpha
times the opacity (the base alpha alone when masked) is 0 under a cutoff above 0, and an
opaque-mode or masked caster with an opacity below 0.5.
- **Resolve and encoding.** `try_resolve(&target, k)` averages each `k × k` block of premultiplied
pixels with equal weights, and takes the mean depth of the block's covered pixels, infinity where
none is covered; a pixel whose `f32` sums overflow, and every pixel when a block holds more than
2^24 subsamples, is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer
function of CSS Color 4 (<https://www.w3.org/TR/css-color-4/#color-conversion-code>), a linear
segment up to a magnitude of 0.0031308 and a 1/2.4 power above it, with a negative color keeping
its sign, multiplies by alpha again and leaves alpha linear. `srgb_to_linear` decodes a negative
value the same way. Pixels with alpha of 1e-6 or less are left as they are. `try_render_cpu` renders and
resolves by `Scene::ssaa`, and rejects a factor that does not divide the raster size before it
renders.
- **Limits.** `Limits` caps the raster pixels (2^24), the triangles of a scene (2^22), its vertices, used or not (3 × 2^22), the lights
(1024) and the coverage tests of the visibility, transparent and fallback passes (2^31). Preparation
counts every clipped triangle's bounding-box pixels plus one per triangle; fallback tests count
during rendering. `try_render`, `try_render_cpu` and
`try_shadow_maps` check the scene first and return a `RenderError` before they allocate a target
or a map: a zero side, a size over the limits, a side over 2^30, a buffer over `isize::MAX` bytes, a light whose shadow map does not
exist (`try_render`; a mark of −1 means no shadow), an index list that is not whole triangles, an index, material
or texture that does not exist, an environment light with no radiance level or with a level or
irradiance map that does not exist, a texture or shadow-map span past its array, a value that is
not finite, a material or texel alpha, a material opacity, metallic, roughness or occlusion
strength, a shadow darkness or an environment
light's key outside 0 to 1, a negative shadow diffusion or shadow-map radius, a parallel or spot light direction or an environment light direction
(other than zero) whose length differs from 1 by more than 0.001, a spot light whose inner cone
cosine is below its outer one, a light kind or falloff mode
or alpha mode other than 0 to 2, or a clip-space position past `f32`. `try_render` also returns
`ShadowsOnlyOpaque` for a triangle in the opaque range whose material is shadows-only and
visible, `BadMaterial` for any other visible transparent material in the opaque range, and
`BadPixel` when a rendered color or depth overflows `f32` (finite inputs near the top of its
range). `try_shadow_maps` also returns an error when a map's view or a caster's
light-space corners would not fit `f32` (vertices far from the origin).
`try_env_shadow_map` returns an error for inputs out of range and for a map that would hold a
value that is not finite. `try_resolve` and `try_encode` take no `Scene` and check only their
own inputs. `try_resolve` returns an error for a factor that is zero or does not divide both
sides and for buffers of the wrong length; a target with a zero side resolves to an empty image.
`try_encode` returns an error for an image whose buffer does not hold width × height pixels, a
pixel that is not finite, an alpha below 0 or above 1 (beyond 1e-4 of rounding), or a color whose
division by alpha overflows, and changes no pixel then; the error names the first such pixel. The renderer holds 40 bytes per raster
pixel (color, depth and visibility) and up to seven clipped triangles of about 140 bytes per
scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 29 bytes per pixel
(a discard flag and a candidate fragment) while its opaque pixels are shaded. The search for a
surviving fragment under discarded opaque pixels visits each opaque triangle's bounding box
once more, so it runs no more coverage tests than the visibility pass. Its tests count toward
`max_work`, and it can return `TooMuchWork` after the target is allocated.
## Origin
The renderer comes from EffectCraft's `crates/render/src/three_d/adv.rs` (`resolve`, `encode`,
`render_cpu`), `adv/raster.rs`, `adv/shade.rs` and the scene types of `adv/scene.rs`, at
`2f16feb12f`. `tests/it/differential.rs` runs a copy of EffectCraft's code with the alpha-mask
change of storytold/effectcraft#4075 applied on the scenes in that module, and for those scenes
every shadow texel, raster pixel, depth, resolved pixel and encoded pixel matches EffectCraft's bit
for bit. Each test prints the FNV-1a hashes of both sides' outputs. Other valid scenes can differ
through the changes listed below, for example where triangles leave the guard band or reach the
far plane, where depth-range crossings lie within 1/4096 of an edge from its inside corner, where
texture coordinates times the texture's width or height reach 2^23 in magnitude, where normals'
squared lengths, squared distances from fragments to point and spot lights, or casters'
light-space coordinates times a map's focal length overflow `f32`, where shadow-casting spot
lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 2^24
subsamples, where shadows-only materials do not receive shadows, where fragments under discarded
opaque pixels leave the depth range, where blended casters have no base texture, where
opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of
light-space depth of a spot or point light, where an encoded color is negative, and where a
texture is sampled between large finite texels of opposite signs. Halfway between red values of
`3e38` and `−3e38`, for example, the sampler here returns red 0 and EffectCraft's interpolation
overflows `f32`.
Changes from those files:
- Scenes, resolve factors and pixels are checked. `Limits` bounds sizes, triangles, lights and
coverage work. Scene and size checks precede target allocation. Preparation can allocate clipping
and triangle buffers before a work-limit error. EffectCraft panicked on an index or a material
reference that did not exist, an alpha-masked caster whose texture did not exist, an environment
level range that overflowed, a zero raster width and a resolve factor of 0. It returned a cropped
image for a factor that did not divide the size, NaN or infinite pixels for values that were not
finite, and black environment light for levels that did not exist.
- Triangles are clipped against the guard band, and clipped in `f64` when the depth clip in `f32`
overflows. EffectCraft clipped only the depth range, so a triangle with corners far past the
viewport that crossed the depth range could be dropped. Triangles leaving the band can shade
differently at their edges. A guard-band crossing is interpolated from the corner nearer the
plane, and a depth-range or spot-map near-plane crossing within 1/4096 of an edge from its
inside corner is interpolated from that corner. EffectCraft interpolated from the edge's first
corner, which put the crossing on the inside corner when the other corner was far away, and
dropped part of the triangle or the shadow caster.
- `try_shadow_maps` replaces the scene's maps and shadow texels, and reads any `shadow` of 0 or
more as a request, so the indices one call writes request the same maps from the next.
EffectCraft appended texels to those of an earlier call, which shifted every map's offset, and
read only 0 as a request, so a second call kept maps only for the light whose first map was
map 0.
- The search for a surviving fragment under a discarded opaque pixel visits the triangles in the
same order over their bounding boxes. EffectCraft searched every triangle of the pixel's band of
16 rows for each such pixel, which the work limit could not bound. The search takes only
fragments inside the depth range, as the visibility pass does; EffectCraft also took a fragment
whose interpolated depth rounded past 1.
- A shadows-only material that does not receive shadows draws nothing. EffectCraft drew the
shadows on it.
- A triangle in the opaque range whose material is shadows-only and visible is an error.
EffectCraft shaded it in the opaque pass, which wrote its shadow color and its depth and hid the
surfaces behind it. Its scene builder puts shadows-only triangles in the transparent range, so its scenes pass.
- A texture coordinate whose value times the texture's width or height reaches 2^23 is scaled to
texels in `f64`, after a repeated or mirrored axis reduces it by its period. EffectCraft scaled
it in `f32`, which dropped the half-texel shift there, and from 2^24 saturated the texel index,
which picked a texel off the wrap period. A shadow caster's texture coordinate whose
perspective interpolation overflows `f32` (a large coordinate times a corner's 1/depth) is
interpolated in `f64`; EffectCraft's was infinite, and its alpha test read a texel off the wrap
period.
- A negative color is encoded on the sRGB curve with its magnitude choosing the segment and its
sign kept, as CSS Color 4's conversion code does. EffectCraft put every negative value on the
linear segment, so red −0.25 encoded to −3.23 instead of about −0.537.
- A normal whose squared length overflows `f32`, and the direction to a point or spot light whose
squared distance overflows `f32`, are normalized in `f64`. EffectCraft divided them by an
infinite length, so the surface took no direct light.
- A caster corner or a receiver whose light-space coordinate times the map's focal length overflows
`f32` is projected in `f64`. EffectCraft's map coordinates for it were infinite.
- A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps,
as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest
of the cone were not shadowed.
- A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of
covered subsamples stopped at 2^24, which raised the mean depth.
- A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest
values) is projected in `f64` instead of dropping its triangle, and a drawn pixel whose camera
depth overflows is an error.
- A texture lookup computes its texel offset in `i128`, so `sample` on a texture whose sides
are near `u32::MAX` reads a missing texel as transparent black.
- A texture or shadow-map lookup at a coordinate past `i64` saturates instead of overflowing, and
a texture coordinate that is not finite is taken as the largest finite one, so the sample stays
finite. A channel whose bilinear interpolation between large finite
texels overflows `f32` is interpolated in `f64`.
- A receiver more than its filter reach plus one texel outside a shadow map is unshadowed before
the filter runs. EffectCraft's tap jitter scaled the map coordinate by 8, which overflowed past
`f32::MAX / 8` and made the pixel NaN.
- A masked fragment that passes its cutoff is drawn with the layer's opacity alone and writes its
depth in the opaque pass, and the cutoff tests the material's alpha without the opacity. In the
transparent pass such a fragment changes the color only and does not write camera depth. EffectCraft at
`2f16feb12f` kept the fragment's alpha below 1, so the clear color showed through a masked
surface in the opaque pass; storytold/effectcraft#4075 makes the same change there, and the copy
in `tests/it/reference/` carries it.
- A masked or blended caster without a base texture tests its material's alpha as a textured
caster tests a texel's, and an opaque-mode or masked caster with an opacity below 0.5 casts no
shadow. EffectCraft at `2f16feb12f` tested every textured caster against 0.5 and drew
untextured and opaque-mode casters whole, so a shadow could differ from the visible surface.
With storytold/effectcraft#4075, EffectCraft's masked casters use the material's cutoff, and
textured casters and untextured masked casters cast the same shadows as here. Two kinds of
caster still differ: an opaque-mode or masked caster with an opacity below 0.5, and an
untextured blended caster whose alpha times the opacity is below 0.5. EffectCraft draws both,
and here they cast no shadow.
- A spot light whose inner cone cosine is below its outer one is `BadLight`. EffectCraft's lights
always have the inner cosine at or above the outer one.
- A material whose metallic, roughness or occlusion strength is outside 0 to 1 is `BadMaterial`.
EffectCraft clamps these for its own materials and passes a glTF model's factors as the file
gives them, and the shader extrapolated past either end.
- A spot or point light's shadow maps clip casters at a light-space depth of 0.001, the depth
below which the shader does not shadow a receiver. EffectCraft clipped them at 1, so a caster
within 1 unit of the light cast no shadow and the receivers behind it were lit. A caster's
crossing with that plane takes the plane's depth exactly, so a caster crossing it with
far-apart corners stays in front of the light.
- A parallel or spot light's direction, and the environment light's direction when it is not
zero, must be unit length within 0.001. EffectCraft shaded with the direction as given and
normalized it for the shadow map, so a direction of another length scaled the light and changed
a spot light's cone without changing its shadow.
- A triangle on the far end of the depth range (normalized device z of 0) is drawn. EffectCraft
read a depth of 0 as an empty pixel and dropped it.
- `try_render` returns an error for a shadow mark that names a map that does not exist.
EffectCraft drew that light unshadowed. Its scene builder runs the shadow maps or sets every
mark to −1, so its scenes pass.
- A raster side over 2^30 is an error whatever the limits.
- A vertex that names a material that does not exist is an error. EffectCraft skipped its
triangle in the raster and panicked on it in the shadow pass.
- The environment light's map is built by `try_env_shadow_map`, which returns an error for inputs
that are out of range.
- A negative shadow diffusion on a light or the environment light is an error. EffectCraft
subtracted it from the penumbra, so a shadow edge could be narrower than its minimum width or
fall back to a reach of 2 texels.
- `render`, `setup`, `shadow_raster` and `shadow_maps` are split into smaller functions with the
same order of operations.
- The camera basis of the shadow maps is computed in this crate from the same operations as
EffectCraft's `camera::basis_view`.
## Migration
EffectCraft replaces `adv::raster::render` with `try_render`, `adv::resolve` with `try_resolve`,
`adv::encode` with `try_encode`, `adv::render_cpu` with `try_render_cpu`, and
`raster::shadow_maps` with `try_shadow_maps`, and maps a `RenderError` to a render failure. Its
scene builder fills `craft_raster3d::Scene`, whose fields are those of its `adv::scene::Scene`.
The BRDF and the environment BRDF stay as they are here until a separate change moves them to
`craft-pbr`, whose results differ (a roughness floor of 0.032 and a clamped environment BRDF).
+208
View File
@@ -0,0 +1,208 @@
//! # craft-raster3d
//!
//! A CPU renderer for a prepared 3D scene. A [`Scene`] holds world-space triangles, their
//! materials and textures, lights, an optional environment light and shadow maps, as plain
//! arrays. [`try_render`] clips, rasterizes and shades it into a [`Target`] of premultiplied
//! linear RGBA and camera depth; [`try_resolve`] box-filters a supersampled target down to an
//! [`Image`]; [`try_encode`] converts linear pixels to the sRGB transfer curve; and
//! [`try_render_cpu`] renders and resolves in one call. [`try_shadow_maps`] renders the depth maps
//! of the shadow-casting lights into the scene before it is rendered.
//!
//! - **Depth.** Reversed: a larger normalized device z is nearer. Triangles are clipped against
//! `0 ≤ z ≤ w` and against a guard band of `±GUARD_BAND × w` in x and y before the
//! perspective divide.
//! - **Coverage.** One sample at each pixel center, with the top-left rule on shared edges.
//! Attributes are interpolated with perspective-correct weights.
//! - **Passes.** The first [`Scene::opaque_count`] indices are opaque triangles: visibility is
//! resolved first and each pixel is shaded once. The rest are transparent triangles, which the
//! caller sorts back to front; they are shaded per fragment, depth-tested against the opaque
//! surfaces and blended over them. A visible transparent material in the opaque range returns
//! [`RenderError::BadMaterial`], or [`RenderError::ShadowsOnlyOpaque`] for a shadows-only material.
//! - **Facing.** A triangle whose screen-space winding is counterclockwise with y down is front
//! facing. A single-sided material does not draw back faces.
//! - **Textures.** [`Scene::texels`] holds linear straight RGBA, row-major from the top row;
//! [`TexInfo`] gives each texture's span and wrap modes.
//!
//! [`try_render`], [`try_render_cpu`] and [`try_shadow_maps`] check the scene against [`Limits`] and return a
//! [`RenderError`] before they allocate a target: malformed indices, references and spans,
//! values that are not finite, sizes, triangle counts, light counts and the coverage work of
//! setup. A light kind or falloff mode outside 0 to 2 returns [`RenderError::BadLight`].
//! A pass that runs over `max_work` while rendering also returns
//! [`RenderError::TooMuchWork`]. [`try_resolve`], [`try_encode`] and [`try_env_shadow_map`] check
//! their own inputs and sizes before they allocate. Rows run on several threads with rayon.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod raster;
mod resolve;
mod scene;
mod shade;
mod shadow;
pub use raster::{GUARD_BAND, Target, try_render};
pub use resolve::{Image, try_encode, try_render_cpu, try_resolve};
pub use scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo, Vertex};
pub use shade::{linear_to_srgb, sample, srgb_to_linear};
pub use shadow::{MAX_SHADOW_TEXELS, shadow_map_size, shadow_point_face_size, shadow_sizes, try_env_shadow_map, try_shadow_maps};
/// Why a scene could not be rendered, resolved or encoded.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum RenderError {
/// A side of the raster is zero.
#[error("raster size {0}x{1} has a zero side")]
BadSize(u32, u32),
/// The pixel count is over [`Limits::max_pixels`], a side is over 2^30, or a buffer would be
/// larger than `isize::MAX` bytes.
#[error("raster size {0}x{1} needs more pixels than the limits or the target allow")]
TooLarge(u32, u32),
/// The index list is not a whole number of triangles.
#[error("the scene holds {0} indices, which is not a multiple of 3")]
BadIndexCount(usize),
/// [`Scene::opaque_count`] is over the index count or not a multiple of 3.
#[error("the opaque count {opaque} does not split the {len} indices into whole triangles")]
BadOpaqueCount { opaque: u32, len: usize },
/// A triangle (by number) in the first [`Scene::opaque_count`] indices has a visible
/// shadows-only material, which is drawn only in the transparent pass. [`try_render`] returns
/// it.
#[error("triangle {0} is in the opaque range but its material draws only shadows")]
ShadowsOnlyOpaque(usize),
/// The triangle count is over [`Limits::max_triangles`].
#[error("the scene holds {count} triangles, over the limit of {limit}")]
TooManyTriangles { count: u64, limit: u64 },
/// The vertex count is over [`Limits::max_vertices`].
#[error("the scene holds {count} vertices, over the limit of {limit}")]
TooManyVertices { count: u64, limit: u64 },
/// An index names a vertex that does not exist.
#[error("index {position} names vertex {index}, which does not exist")]
BadIndex { position: usize, index: u32 },
/// A vertex has a value that is not finite or names a material that does not exist.
#[error("vertex {0} is not finite or names a material that does not exist")]
BadVertex(usize),
/// A vertex's clip-space position is not finite.
#[error("vertex {0} is outside the range the clip transform can hold")]
BadClipPosition(usize),
/// The clip or view transform, the eye or the camera direction is not finite.
#[error("the camera transform is not finite")]
BadTransform,
/// A material value is not finite or out of range (an alpha mode other than 0 to 2, or a
/// metallic, roughness or occlusion strength outside 0 to 1, for example), or names a texture
/// that does not exist. [`try_render`] also returns it for a visible transparent material
/// in the opaque range, except a shadows-only material returns [`RenderError::ShadowsOnlyOpaque`].
#[error("material {0} has a value that is not finite or out of range, or names a texture that does not exist")]
BadMaterial(usize),
/// A texture has a zero side, or its span runs past [`Scene::texels`].
#[error("texture {0} has a zero side or runs past the texels")]
BadTexture(usize),
/// A texel is not finite, or its alpha is outside 0 to 1.
#[error("texel {0} is not finite or has an alpha outside 0 to 1")]
BadTexel(usize),
/// A light has a kind or falloff mode other than 0 to 2, a value that is not finite, a cone cosine outside −1
/// to 1, (a spot light) an inner cone cosine below the outer one, a shadow darkness outside 0
/// to 1, or (a parallel or spot light) a direction whose length differs from 1 by more than
/// 0.001.
#[error(
"light {0} has an unknown kind or falloff mode, a value that is not finite, a cone cosine outside -1 to 1 or out of order, a shadow darkness outside 0 to 1 or a direction that is not unit length"
)]
BadLight(usize),
/// The light count is over [`Limits::max_lights`].
#[error("the scene holds {count} lights, over the limit of {limit}")]
TooManyLights { count: usize, limit: usize },
/// A light (by index) or the environment light (`None`) refers to a shadow map that is not in
/// [`Scene::shadows`]: [`try_render`] needs the maps [`try_shadow_maps`] makes, or the mark
/// −1 for no shadow.
#[error("a light refers to a shadow map that does not exist")]
MissingShadowMap(Option<usize>),
/// The environment light has a value that is not finite, a dominant direction that is neither
/// zero nor unit length (within 0.001), a key or shadow darkness outside 0 to 1, no radiance
/// level, or a radiance level or irradiance map that is not in [`Scene::textures`].
#[error(
"the environment light has a value that is not finite or out of range, a direction that is not unit length or names a texture that does not exist"
)]
BadEnvironment,
/// A shadow map has a zero size, a scale or transform that is not finite, a negative penumbra
/// radius, or a span that runs past [`Scene::shadow_texels`].
#[error("shadow map {0} has a bad size, scale, transform, radius or span")]
BadShadowMap(usize),
/// A shadow texel is NaN.
#[error("shadow texel {0} is NaN")]
BadShadowTexel(usize),
/// The inputs of a shadow map are out of range: a zero size, a radius that is not positive and
/// finite, a center that is not finite, a direction whose length differs from 1 by more than
/// 0.001, or inputs (a scene's vertices far from the origin, for one) whose map would hold a
/// value that is not finite in `f32`.
#[error("shadow map inputs are out of range")]
BadShadowInputs,
/// The shadow texels do not fit `u32` offsets.
#[error("the shadow texels do not fit 32-bit offsets")]
TooManyShadowTexels,
/// Rasterizing or rendering shadow maps would take more coverage or depth tests than
/// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. Fallback
/// and shadow-map work may be counted on several threads, within one triangle per thread, so `needed` is at least
/// `limit + 1` and may be below the scene's total.
#[error("the render needs at least {needed} tests, over the limit of {limit}")]
TooMuchWork { needed: u64, limit: u64 },
/// A resolve factor is zero or does not divide both sides of the target.
#[error("resolve factor {k} does not divide the target size {width}x{height}")]
BadFactor { k: u32, width: u32, height: u32 },
/// A buffer does not hold width × height values.
#[error("the buffer holds {found} values where {expected} are needed")]
BadDataLength { expected: usize, found: usize },
/// A pixel's color is not finite, or its alpha is negative or over 1. [`try_render`] returns
/// it for a rendered pixel whose color or depth overflowed `f32` (finite inputs near the top
/// of its range).
#[error("pixel {0} has a color that is not finite or an alpha out of range")]
BadPixel(usize),
}
/// Caps on sizes and work. Scene and size checks precede target allocation; fallback coverage
/// work is counted while rendering.
/// `#[non_exhaustive]`: start from [`Limits::default`] and set the fields you change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
/// Most raster pixels (width × height). Default 2^24.
pub max_pixels: u64,
/// Most triangles in a scene. Default 2^22.
pub max_triangles: u64,
/// Most vertices in a scene, used or not. Default 3 × 2^22.
pub max_vertices: u64,
/// Most lights in a scene. Default 1024.
pub max_lights: usize,
/// Most coverage tests of the visibility and transparent passes, plus tests under discarded
/// opaque pixels. Preparation counts every clipped triangle's bounding-box pixels plus one
/// per clipped triangle. Default 2^31.
pub max_work: u64,
}
impl Default for Limits {
fn default() -> Self {
Self { max_pixels: 1 << 24, max_triangles: 1 << 22, max_vertices: 3 << 22, max_lights: 1024, max_work: 1 << 31 }
}
}
/// The largest allocation in bytes that a `Vec` can make on the target.
const MAX_ALLOC_BYTES: u64 = isize::MAX as u64;
/// The longest raster side, whatever the limits: row and band arithmetic in `i32` has room
/// above it.
const MAX_SIDE: u32 = 1 << 30;
/// Bytes the renderer holds per raster pixel: color (16), depth (4) and visibility (20).
const BYTES_PER_PIXEL: u64 = 40;
impl Limits {
/// The pixel count of a `w × h` raster, or the error the limits give for that size.
/// Nothing is allocated.
pub fn check(&self, w: u32, h: u32) -> Result<usize, RenderError> {
if w == 0 || h == 0 {
return Err(RenderError::BadSize(w, h));
}
let pixels = u64::from(w) * u64::from(h);
let bytes = pixels.checked_mul(BYTES_PER_PIXEL).ok_or(RenderError::TooLarge(w, h))?;
if pixels > self.max_pixels || bytes > MAX_ALLOC_BYTES || w > MAX_SIDE || h > MAX_SIDE {
return Err(RenderError::TooLarge(w, h));
}
usize::try_from(pixels).map_err(|_| RenderError::TooLarge(w, h))
}
}
+636
View File
@@ -0,0 +1,636 @@
//! The triangle rasterizer.
//!
//! Triangles are clipped against the depth range (`0 ≤ z ≤ w`) and a guard band in x and y,
//! set up in screen space and scanned per band of rows in parallel with edge
//! functions (pixel centers, top-left fill rule) and perspective-correct barycentrics. Opaque
//! triangles resolve visibility first (reversed depth: larger ndc z is nearer) and each pixel is
//! shaded once; transparent triangles (already sorted back to front) are then shaded per
//! fragment and blended over, depth-tested against the opaque surfaces.
use std::sync::atomic::{AtomicU64, Ordering};
use rayon::prelude::*;
use crate::scene::{Scene, Vertex, validate, validate_passes, validate_shadow_refs};
use crate::shade::{Frag, shade};
use crate::{Limits, RenderError};
/// Half-width of the clip guard band in units of clip w: a triangle reaching past
/// `|x| > GUARD_BAND × w` or `|y| > GUARD_BAND × w` is clipped there before the perspective
/// divide, so screen coordinates stay within about 512 viewports of the raster. A triangle
/// inside the band is not clipped in x or y.
pub const GUARD_BAND: f64 = 1024.0;
/// A rendered target at raster size.
#[derive(Clone, Debug, PartialEq)]
pub struct Target {
pub width: u32,
pub height: u32,
/// Premultiplied linear RGBA, row-major from the top row.
pub color: Vec<[f32; 4]>,
/// Camera-space depth of the nearest opaque surface (∞ where empty).
pub depth: Vec<f32>,
}
/// A clipped triangle in screen space; `w` holds, per corner, its weights over the original
/// triangle's three vertices.
#[derive(Clone, Copy)]
struct STri {
p: [[f64; 2]; 3],
z: [f32; 3],
inv_w: [f64; 3],
wide: bool,
w: [[f32; 3]; 3],
tri: u32,
front: bool,
bbox: [i32; 4],
}
/// A polygon corner: clip coordinates and weights over the original triangle's vertices.
type Corner = ([f32; 4], [f32; 3]);
/// A screen-space corner: position, ndc z, 1/w and weights.
type ScreenCorner = ([f64; 2], f32, f64, [f32; 3]);
#[inline]
fn mat_mul(m: &[[f32; 4]; 4], p: [f32; 3]) -> [f32; 4] {
let mut o = [0.0; 4];
for r in 0..4 {
o[r] = m[r][0] * p[0] + m[r][1] * p[1] + m[r][2] * p[2] + m[r][3];
}
o
}
/// The signed distance of a clip-space point inside clip plane `plane`: 0 and 1 are the depth
/// range `0 ≤ z ≤ w`, 2 to 5 the guard band `|x| ≤ GUARD_BAND × w` and `|y| ≤ GUARD_BAND × w`.
fn plane_distance(c: &[f64; 4], plane: usize) -> f64 {
let g = GUARD_BAND * c[3];
match plane {
0 => c[2],
1 => c[3] - c[2],
2 => g + c[0],
3 => g - c[0],
4 => g + c[1],
_ => g - c[1],
}
}
/// The depth-range planes followed by the guard-band planes.
const ALL_PLANES: [usize; 6] = [0, 1, 2, 3, 4, 5];
/// The guard-band planes.
const GUARD_PLANES: [usize; 4] = [2, 3, 4, 5];
/// Clip a polygon against the guard band. A polygon inside the band is returned unchanged;
/// any other is clipped in `f64`.
fn clip_guard(poly: Vec<Corner>) -> Vec<Corner> {
if poly.iter().all(|(c, _)| GUARD_PLANES.iter().all(|&plane| plane_distance(&c.map(f64::from), plane) >= 0.0)) {
return poly;
}
clip_f64(&poly, &GUARD_PLANES)
}
/// The share of an edge's length within which an `f32` crossing is interpolated from the inside
/// corner instead of from the edge's first corner.
const NEAR_CORNER: f32 = 1.0 / 4096.0;
/// Where the edge from a corner at plane distance `da` to one at `db` crosses the plane, for an
/// `f32` clip: `(false, t)` for `a + (b − a) × t`, or `(true, t)` for `b + (a − b) × t` when the
/// crossing lies within [`NEAR_CORNER`] of the edge's length from `b` and `da` is finite. A
/// distance that overflowed keeps the first form, whose corner is then not finite. A difference
/// of finite distances that overflows `f32` is taken in `f64`.
pub(crate) fn f32_crossing(da: f32, db: f32) -> (bool, f32) {
let share = |p: f32, q: f32| {
let d = p - q;
if d.is_finite() || !p.is_finite() || !q.is_finite() { p / d } else { (f64::from(p) / (f64::from(p) - f64::from(q))) as f32 }
};
if da.is_finite() && db.abs() < da.abs() * NEAR_CORNER { (true, share(db, da)) } else { (false, share(da, db)) }
}
/// Clip a polygon against `planes` (see [`plane_distance`]), interpolating in `f64` from the
/// corner nearer the plane.
fn clip_f64(poly: &[Corner], planes: &[usize]) -> Vec<Corner> {
let mut p: Vec<([f64; 4], [f64; 3])> = poly.iter().map(|(c, w)| (c.map(f64::from), w.map(f64::from))).collect();
for &plane in planes {
if p.is_empty() {
break;
}
let d = |c: &[f64; 4]| plane_distance(c, plane);
let mut out = Vec::with_capacity(p.len() + 2);
for i in 0..p.len() {
let (a, b) = (p[i], p[(i + 1) % p.len()]);
let (da, db) = (d(&a.0), d(&b.0));
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) };
let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t);
let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t);
out.push((c, w));
}
}
p = out;
}
p.iter().map(|(c, w)| (c.map(|v| v as f32), w.map(|v| v as f32))).collect()
}
/// Clip a polygon (clip coords + original weights) against `0 ≤ z ≤ w`.
fn clip_poly(poly: Vec<Corner>) -> Vec<Corner> {
let mut p = poly;
for plane in 0..2 {
if p.is_empty() {
break;
}
let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] };
let mut out = Vec::with_capacity(p.len() + 2);
for i in 0..p.len() {
let (a, b) = (p[i], p[(i + 1) % p.len()]);
let (da, db) = (d(&a.0), d(&b.0));
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let (from_b, t) = f32_crossing(da, db);
let (p, q) = if from_b { (b, a) } else { (a, b) };
let mut c = [0.0; 4];
let mut w = [0.0; 3];
for k in 0..4 {
c[k] = p.0[k] + (q.0[k] - p.0[k]) * t;
}
for k in 0..3 {
w[k] = p.1[k] + (q.1[k] - p.1[k]) * t;
}
out.push((c, w));
}
}
p = out;
}
p
}
/// The ndc depth of a corner clipped to `0 ≤ z ≤ w`, moved back to the end of the range when the
/// division by `w` rounds past it by a few ulps (a corner on the near plane can give 1 + 2^-23). A
/// depth further out is kept, and the depth test rejects it.
#[inline]
fn ndc_z(z: f32) -> f32 {
const ROUNDING: f32 = 4.0 * f32::EPSILON;
if (1.0..=1.0 + ROUNDING).contains(&z) {
1.0
} else if (-ROUNDING..0.0).contains(&z) {
0.0
} else {
z
}
}
/// The clipped polygon of triangle `t` (the index of its first index) projected to the screen,
/// or `None` when nothing of it is left or a corner is not finite.
fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec<ScreenCorner>, bool)> {
let (w, h) = (s.width as f64, s.height as f64);
let ids = [s.indices[t] as usize, s.indices[t + 1] as usize, s.indices[t + 2] as usize];
let tri = vec![(clip[ids[0]], [1.0, 0.0, 0.0]), (clip[ids[1]], [0.0, 1.0, 0.0]), (clip[ids[2]], [0.0, 0.0, 1.0])];
let finite = |p: &[Corner]| p.iter().all(|(c, wt)| c.iter().chain(wt).all(|v| v.is_finite()));
// The depth range in f32; when that overflows between far-apart corners, every plane in f64.
let poly = clip_poly(tri.clone());
let poly = if finite(&poly) { clip_guard(poly) } else { clip_f64(&tri, &ALL_PLANES) };
if poly.len() < 3 || !finite(&poly) {
return None;
}
let scr: Vec<ScreenCorner> = poly
.iter()
.map(|(c, wt)| {
let iw = 1.0 / c[3];
let (nx, ny) = (c[0] * iw, c[1] * iw);
([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], ndc_z(c[2] * iw), f64::from(iw), *wt)
})
.collect();
let ok = |s: &ScreenCorner| s.0.iter().all(|v| v.is_finite()) && s.1.is_finite() && s.2.is_finite();
if scr.iter().all(ok) {
return Some((scr, false));
}
// A tiny w overflows 1/w in f32: project in f64, with 1/w scaled by a common factor so the
// largest is 1 (the interpolation weights use only their ratios). The scaled values stay in
// f64, since a ratio below the f32 range would round to 0 and drop the corner's weight.
let iw: Vec<f64> = poly.iter().map(|(c, _)| 1.0 / f64::from(c[3])).collect();
let top = iw.iter().fold(0.0f64, |a, &b| a.max(b));
let scr: Vec<ScreenCorner> = poly
.iter()
.zip(&iw)
.map(|((c, wt), &iw)| {
let (nx, ny) = (f64::from(c[0]) * iw, f64::from(c[1]) * iw);
([(nx + 1.0) * 0.5 * w, (1.0 - ny) * 0.5 * h], ndc_z((f64::from(c[2]) * iw) as f32), iw / top, *wt)
})
.collect();
scr.iter().all(ok).then_some((scr, true))
}
/// The screen triangles of a projected polygon, fanned from its first corner and clamped to the
/// viewport, appended to `out`.
fn fan(s: &Scene, scr: &[ScreenCorner], wide: bool, tri: u32, out: &mut Vec<STri>) {
// Facing from the polygon's screen-space winding (y down: negative = front).
let mut area = 0.0;
for i in 0..scr.len() {
let (a, b) = (scr[i].0, scr[(i + 1) % scr.len()].0);
area += a[0] * b[1] - b[0] * a[1];
}
if area == 0.0 || !area.is_finite() {
return;
}
let front = area < 0.0;
for k in 1..scr.len() - 1 {
let c = [scr[0], scr[k], scr[k + 1]];
let mut x0 = f64::INFINITY;
let mut y0 = f64::INFINITY;
let mut x1 = f64::NEG_INFINITY;
let mut y1 = f64::NEG_INFINITY;
for v in &c {
x0 = x0.min(v.0[0]);
y0 = y0.min(v.0[1]);
x1 = x1.max(v.0[0]);
y1 = y1.max(v.0[1]);
}
// Clamped on both sides to the viewport before narrowing to i32.
let (w, h) = (i64::from(s.width.min(i32::MAX as u32)), i64::from(s.height.min(i32::MAX as u32)));
let bbox = [
(x0.floor() as i64).clamp(0, w) as i32,
(y0.floor() as i64).clamp(0, h) as i32,
(x1.ceil() as i64).clamp(0, w) as i32,
(y1.ceil() as i64).clamp(0, h) as i32,
];
if bbox[0] >= bbox[2] || bbox[1] >= bbox[3] {
continue;
}
out.push(STri {
p: [c[0].0, c[1].0, c[2].0],
z: [c[0].1, c[1].1, c[2].1],
inv_w: [c[0].2, c[1].2, c[2].2],
wide,
w: [c[0].3, c[1].3, c[2].3],
tri,
front,
bbox,
});
}
}
/// Set up the screen triangles of index range `range`, adding each one's coverage tests (its
/// bounding-box pixels, plus one) to `work`. Stops with [`RenderError::TooMuchWork`] as soon as
/// `work` passes `limit`, before more triangles are kept.
fn setup(s: &Scene, clip: &[[f32; 4]], range: std::ops::Range<usize>, work: &mut u64, limit: u64) -> Result<Vec<STri>, RenderError> {
let mut out = vec![];
for t in range.step_by(3) {
let mat = s.vertices[s.indices[t] as usize].material as usize;
if !s.materials.get(mat).is_some_and(|m| m.visible) {
continue;
}
if let Some((scr, wide)) = project(s, clip, t) {
let first = out.len();
fan(s, &scr, wide, (t / 3) as u32, &mut out);
for st in &out[first..] {
let area = (st.bbox[2] - st.bbox[0]) as u64 * (st.bbox[3] - st.bbox[1]) as u64;
*work = work.saturating_add(area + 1);
}
if *work > limit {
return Err(RenderError::TooMuchWork { needed: *work, limit });
}
}
}
Ok(out)
}
/// Coverage of a pixel center: (ndc z, perspective-correct weights over the screen corners).
#[inline]
fn cover(t: &STri, px: f64, py: f64) -> Option<(f32, [f32; 3])> {
let [a, b, c] = t.p;
let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
// Orient so the area is positive.
let (b, c, swap) = if area < 0.0 { (c, b, true) } else { (b, c, false) };
let area = area.abs();
let edge = |p: [f64; 2], q: [f64; 2]| -> f64 { (q[0] - p[0]) * (py - p[1]) - (q[1] - p[1]) * (px - p[0]) };
let top_left = |p: [f64; 2], q: [f64; 2]| -> bool {
let (dx, dy) = (q[0] - p[0], q[1] - p[1]);
dy < 0.0 || (dy == 0.0 && dx > 0.0)
};
let e0 = edge(b, c); // opposite a
let e1 = edge(c, a); // opposite b
let e2 = edge(a, b); // opposite c
let inside = |e: f64, p: [f64; 2], q: [f64; 2]| e > 0.0 || (e == 0.0 && top_left(p, q));
if !(inside(e0, b, c) && inside(e1, c, a) && inside(e2, a, b)) {
return None;
}
let (l0, l1, l2) = (e0 / area, e1 / area, e2 / area);
// Back to the stored corner order.
let l = if swap { [l0, l2, l1] } else { [l0, l1, l2] };
let lf = l.map(|v| v as f32);
// The depth stays inside the corners' depth range, where rounding of the weights could carry
// it past (three corners at 1 can give 1 + 2^-23).
let (zlo, zhi) = (t.z[0].min(t.z[1]).min(t.z[2]), t.z[0].max(t.z[1]).max(t.z[2]));
let z = (lf[0] * t.z[0] + lf[1] * t.z[1] + lf[2] * t.z[2]).clamp(zlo, zhi);
if !t.wide {
let q = [0, 1, 2].map(|k| lf[k] * t.inv_w[k] as f32);
let sum = q[0] + q[1] + q[2];
if sum > 0.0 && sum.is_finite() {
return Some((z, [q[0] / sum, q[1] / sum, q[2] / sum]));
}
}
// A 1/w ratio below the f32 range rounds to 0: the weights are taken in f64.
let q = [0, 1, 2].map(|k| l[k] * t.inv_w[k]);
let sum = q[0] + q[1] + q[2];
if sum.is_nan() || sum <= 0.0 {
return None;
}
Some((z, [(q[0] / sum) as f32, (q[1] / sum) as f32, (q[2] / sum) as f32]))
}
/// Interpolate the original triangle's vertex attributes at screen-corner weights `l`.
fn frag(s: &Scene, t: &STri, l: [f32; 3]) -> Frag {
let base = t.tri as usize * 3;
let v: [&Vertex; 3] = [0, 1, 2].map(|k| &s.vertices[s.indices[base + k] as usize]);
// Weights over the original vertices.
let mut wv = [0.0f32; 3];
for c in 0..3 {
for k in 0..3 {
wv[k] += l[c] * t.w[c][k];
}
}
let mut f = Frag { pos: [0.0; 3], normal: [0.0; 3], uv: [0.0; 2], tangent: [0.0; 4], material: v[0].material, front: t.front };
for k in 0..3 {
let x = wv[k];
for i in 0..3 {
f.pos[i] += v[k].pos[i] * x;
f.normal[i] += v[k].normal[i] * x;
}
for i in 0..2 {
f.uv[i] += v[k].uv[i] * x;
}
for i in 0..4 {
f.tangent[i] += v[k].tangent[i] * x;
}
}
f.tangent[3] = v[0].tangent[3];
f
}
const BAND: i32 = 16;
/// The clip coordinates of every vertex, or the first vertex whose clip position is not finite.
fn clip_positions(s: &Scene) -> Result<Vec<[f32; 4]>, RenderError> {
s.vertices
.iter()
.enumerate()
.map(|(i, v)| {
let c = mat_mul(&s.clip, v.pos);
if c.iter().all(|x| x.is_finite()) { Ok(c) } else { Err(RenderError::BadClipPosition(i)) }
})
.collect()
}
/// The screen triangles of each band of `BAND` rows, by index into `ts`.
fn bin(ts: &[STri], bands: i32) -> Vec<Vec<u32>> {
let mut b = vec![vec![]; bands.max(0) as usize];
for (i, t) in ts.iter().enumerate() {
for band in (t.bbox[1] / BAND)..((t.bbox[3] + BAND - 1) / BAND).min(bands) {
b[band as usize].push(i as u32);
}
}
b
}
/// One band of rows being rendered: its first row, its row count and the raster width.
struct Band<'a> {
s: &'a Scene,
y0: i32,
rows: usize,
w: usize,
spent: &'a AtomicU64,
limit: u64,
}
/// The screen triangles of one pass and the indices of those in the current band.
#[derive(Clone, Copy)]
struct Pass<'a> {
tris: &'a [STri],
bins: &'a [u32],
}
/// Per pixel: (screen triangle, ndc z, weights); `u32::MAX` and [`EMPTY`] where no triangle
/// covers it.
type Visibility = Vec<(u32, f32, [f32; 3])>;
#[derive(Clone, Copy)]
struct FallbackFragment {
ndc_z: f32,
color: [f32; 4],
camera_depth: f32,
}
/// The visibility depth of a pixel with no opaque surface: below the far plane's 0, so a
/// fragment on the far plane is drawn.
const EMPTY: f32 = -1.0;
/// Whether ndc depth `z` is inside the depth range and nearer than `than`.
#[inline]
fn nearer(z: f32, than: f32) -> bool {
z > than && (0.0..=1.0).contains(&z)
}
impl Band<'_> {
/// Camera-space depth of a world point, NaN when it overflows `f32` (infinity marks an
/// empty pixel, and [`try_render`] rejects NaN).
fn cam_z(&self, p: [f32; 3]) -> f32 {
let view = self.s.view;
let z = view[2][0] * p[0] + view[2][1] * p[1] + view[2][2] * p[2] + view[2][3];
if z.is_finite() { z } else { f32::NAN }
}
/// The nearest opaque triangle covering each pixel of the band.
fn visibility(&self, opaque: Pass) -> Visibility {
let (w, y0, rows) = (self.w, self.y0, self.rows);
let mut vis: Visibility = vec![(u32::MAX, EMPTY, [0.0; 3]); rows * w];
for &ti in opaque.bins {
let t = &opaque.tris[ti as usize];
for y in t.bbox[1].max(y0)..t.bbox[3].min(y0 + rows as i32) {
let r = (y - y0) as usize * w;
for x in t.bbox[0]..t.bbox[2] {
if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5) {
let v = &mut vis[r + x as usize];
if nearer(z, v.1) {
*v = (ti, z, l);
}
}
}
}
}
vis
}
/// Shade each pixel's visible opaque fragment. A discarded fragment (alpha test, back face)
/// gives way to the nearest surviving fragment under the pixel, and the pixel's visibility
/// depth becomes that fragment's ([`EMPTY`] when none survives).
fn shade_opaque(&self, opaque: Pass, vis: &mut Visibility, crow: &mut [[f32; 4]], drow: &mut [f32]) -> Result<(), RenderError> {
let s = self.s;
let mut discarded = vec![false; self.rows * self.w];
for i in 0..self.rows * self.w {
let (ti, _, l) = vis[i];
if ti == u32::MAX {
continue;
}
let f = frag(s, &opaque.tris[ti as usize], l);
match shade(s, &f) {
Some(c) => {
crow[i] = c;
drow[i] = self.cam_z(f.pos);
}
None => discarded[i] = true,
}
}
if !discarded.contains(&true) {
return Ok(());
}
for (i, best) in self.fallback(opaque, vis, &discarded)?.into_iter().enumerate() {
if !discarded[i] {
continue;
}
match best {
Some(f) => {
crow[i] = f.color;
drow[i] = f.camera_depth;
vis[i].1 = f.ndc_z;
}
None => vis[i].1 = EMPTY,
}
}
Ok(())
}
/// For each discarded pixel of the band, the nearest surviving opaque fragment of a screen
/// triangle other than the pixel's visible one, inside the depth range as in
/// [`Band::visibility`]. Triangles are
/// visited in index order over their bounding boxes, and among fragments at equal depth the
/// first triangle's is kept. Coverage tests count toward [`Limits::max_work`].
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result<Vec<Option<FallbackFragment>>, RenderError> {
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
let mut best: Vec<Option<FallbackFragment>> = vec![None; rows * w];
for &tj in opaque.bins {
let t2 = &opaque.tris[tj as usize];
let mut tests = 0u64;
for y in t2.bbox[1].max(y0)..t2.bbox[3].min(y0 + rows as i32) {
let r = (y - y0) as usize * w;
for x in t2.bbox[0]..t2.bbox[2] {
let i = r + x as usize;
if !discarded[i] || vis[i].0 == tj {
continue;
}
tests += 1;
if let Some((z, l2)) = cover(t2, x as f64 + 0.5, y as f64 + 0.5)
&& nearer(z, best[i].map_or(EMPTY, |b| b.ndc_z))
{
let f2 = frag(s, t2, l2);
if let Some(c) = shade(s, &f2) {
best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos) });
}
}
}
}
let needed = self.spent.fetch_add(tests, Ordering::Relaxed).saturating_add(tests);
if needed > self.limit {
return Err(RenderError::TooMuchWork { needed, limit: self.limit });
}
}
Ok(best)
}
/// Transparent fragments in order, blended over the opaque result where they are nearer.
fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]]) {
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
for &ti in trans.bins {
let t = &trans.tris[ti as usize];
for y in t.bbox[1].max(y0)..t.bbox[3].min(y0 + rows as i32) {
let r = (y - y0) as usize * w;
for x in t.bbox[0]..t.bbox[2] {
let i = r + x as usize;
if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5)
&& nearer(z, vis[i].1)
&& let Some(c) = shade(s, &frag(s, t, l))
{
let d = crow[i];
let k = 1.0 - c[3];
crow[i] = [c[0] + d[0] * k, c[1] + d[1] * k, c[2] + d[2] * k, c[3] + d[3] * k];
}
}
}
}
}
}
/// Rasterize and shade set-up screen triangles into a target of `pixels` pixels.
fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, work: u64, limit: u64) -> Result<Target, RenderError> {
let (w, h) = (s.width as usize, s.height as usize);
let bands = (h as i32 + BAND - 1) / BAND;
let ob = bin(opaque, bands);
let tb = bin(trans, bands);
let mut color = vec![[0.0f32; 4]; pixels];
let mut depth = vec![f32::INFINITY; pixels];
let spent = AtomicU64::new(work);
color.par_chunks_mut(w * BAND as usize).zip(depth.par_chunks_mut(w * BAND as usize)).enumerate().try_for_each(|(band, (crow, drow))| {
let b = Band { s, y0: band as i32 * BAND, rows: crow.len() / w, w, spent: &spent, limit };
let (op, tp) = (Pass { tris: opaque, bins: &ob[band] }, Pass { tris: trans, bins: &tb[band] });
let mut vis = b.visibility(op);
b.shade_opaque(op, &mut vis, crow, drow)?;
b.blend_transparent(tp, &vis, crow);
Ok::<(), RenderError>(())
})?;
Ok(Target { width: s.width, height: s.height, color, depth })
}
/// Rasterize and shade the scene at its raster size.
///
/// The scene is checked first (see [`Limits`]); an empty scene gives a transparent target with
/// infinite depth. A triangle whose clipped polygon has zero area draws nothing.
pub fn try_render(s: &Scene, limits: &Limits) -> Result<Target, RenderError> {
let pixels = validate(s, limits)?;
validate_passes(s)?;
validate_shadow_refs(s)?;
let clip = clip_positions(s)?;
let mut work = 0;
let opaque = setup(s, &clip, 0..s.opaque_count as usize, &mut work, limits.max_work)?;
let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len(), &mut work, limits.max_work)?;
let t = raster(s, &opaque, &trans, pixels, work, limits.max_work)?;
// Finite inputs near the top of the f32 range can still overflow in shading.
if let Some(i) = t.color.iter().zip(&t.depth).position(|(c, d)| !c.iter().all(|v| v.is_finite()) || d.is_nan()) {
return Err(RenderError::BadPixel(i));
}
Ok(t)
}
#[cfg(test)]
mod tests {
use super::{cover, f32_crossing, fan, project};
use crate::scene::Scene;
#[test]
fn wide_projection_preserves_subnormal_weights_on_an_included_edge() {
let s = Scene { width: 8, height: 8, indices: vec![0, 1, 2], ..Scene::default() };
for (small, large) in [(1.0, 1.0), (f32::from_bits(1 << 21), 2097152.0)] {
let clip = [
[-0.875 * small, -0.125 * small, 0.5 * small, small],
[-0.875 * large, 0.875 * large, 0.5 * large, large],
[0.125 * large, 0.875 * large, 0.5 * large, large],
];
let (scr, wide) = project(&s, &clip, 0).unwrap();
let mut tris = Vec::new();
fan(&s, &scr, wide, 0, &mut tris);
assert_eq!(tris.len(), 1);
let (_, weights) = cover(&tris[0], 1.5, 0.5).unwrap();
assert_eq!(weights, [0.0, 0.75, 0.25]);
}
}
#[test]
fn a_crossing_whose_distance_difference_overflows_is_taken_in_f64() {
// −3e38 − 1e38 overflows f32; the plane lies three quarters of the way along the edge.
assert_eq!(f32_crossing(-3e38, 1e38), (false, 0.75));
assert_eq!(f32_crossing(1e38, -3e38), (false, 0.25));
}
}
+160
View File
@@ -0,0 +1,160 @@
//! The box resolve of a supersampled target and the sRGB encoding of its pixels.
use rayon::prelude::*;
use crate::raster::{Target, try_render};
use crate::scene::Scene;
use crate::shade::linear_to_srgb;
use crate::{Limits, RenderError};
/// An image of premultiplied RGBA pixels, row-major from the top row.
#[derive(Clone, Debug, PartialEq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub data: Vec<[f32; 4]>,
}
/// Alpha above 1 that [`try_encode`] accepts as rounding from blending.
const ALPHA_SLACK: f32 = 1e-4;
/// `w × h` as a length, when it fits `usize`.
fn area(w: u32, h: u32) -> Option<usize> {
usize::try_from(u64::from(w) * u64::from(h)).ok()
}
/// Box-filter a supersampled target down by `k` per side: each output pixel is the mean of its
/// `k × k` premultiplied colors, and its depth is the mean of the covered subsamples' depths
/// (infinity where none is covered). A pixel whose `f32` sums overflow, and every pixel when a
/// block holds more than 2^24 subsamples, is averaged in `f64`.
///
/// Returns [`RenderError::BadFactor`] when `k` is zero or does not divide both sides, and
/// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height
/// values.
pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError> {
if k == 0 || !t.width.is_multiple_of(k) || !t.height.is_multiple_of(k) {
return Err(RenderError::BadFactor { k, width: t.width, height: t.height });
}
let expected = area(t.width, t.height).ok_or(RenderError::TooLarge(t.width, t.height))?;
for found in [t.color.len(), t.depth.len()] {
if found != expected {
return Err(RenderError::BadDataLength { expected, found });
}
}
let (w, h) = (t.width / k, t.height / k);
// Fits: at most `expected`.
let out = area(w, h).unwrap_or(0);
let mut img = Image { width: w, height: h, data: vec![[0.0; 4]; out] };
let mut depth = vec![f32::INFINITY; out];
if out == 0 {
return Ok((img, depth));
}
let n = (u64::from(k) * u64::from(k)) as f32;
// An f32 count stops at 2^24, so a larger block is averaged in f64.
let wide = u64::from(k) * u64::from(k) > 1 << 24;
img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| {
for x in 0..w as usize {
if wide {
(row[x], drow[x]) = mean_f64(t, k as usize, x, y);
continue;
}
let mut acc = [0.0f32; 4];
let (mut dz, mut dn) = (0.0f32, 0.0f32);
for j in 0..k as usize {
for i in 0..k as usize {
let s = (y * k as usize + j) * t.width as usize + x * k as usize + i;
let c = t.color[s];
for q in 0..4 {
acc[q] += c[q];
}
if t.depth[s].is_finite() {
dz += t.depth[s];
dn += 1.0;
}
}
}
row[x] = acc.map(|v| v / n);
if dn > 0.0 {
drow[x] = dz / dn;
}
// Large finite samples can overflow the f32 sums; such a pixel is averaged in f64.
if !row[x].iter().all(|v| v.is_finite()) || drow[x].is_nan() || (dn > 0.0 && drow[x].is_infinite()) {
(row[x], drow[x]) = mean_f64(t, k as usize, x, y);
}
}
});
Ok((img, depth))
}
/// Output pixel (`x`, `y`) of a `k`-per-side resolve, summed in `f64`.
fn mean_f64(t: &Target, k: usize, x: usize, y: usize) -> ([f32; 4], f32) {
let (mut acc, mut dz, mut dn) = ([0.0f64; 4], 0.0f64, 0u64);
for j in 0..k {
for i in 0..k {
let s = (y * k + j) * t.width as usize + x * k + i;
for (a, c) in acc.iter_mut().zip(t.color[s]) {
*a += f64::from(c);
}
if t.depth[s].is_finite() {
dz += f64::from(t.depth[s]);
dn += 1;
}
}
}
let n = (k * k) as f64;
let depth = if dn > 0 { (dz / dn as f64) as f32 } else { f32::INFINITY };
(acc.map(|v| (v / n) as f32), depth)
}
/// Convert premultiplied linear pixels to premultiplied sRGB-encoded pixels in place: each
/// color channel is divided by alpha, encoded with [`linear_to_srgb`] and multiplied by alpha
/// again. Alpha stays linear, and pixels with alpha of 1e-6 or less are left as they are.
///
/// Every pixel is checked before any is changed. Returns [`RenderError::BadPixel`] with the first
/// pixel whose channels are not finite, whose alpha is negative or over 1 (beyond rounding), or
/// whose color divided by its alpha is not finite,
/// and [`RenderError::BadDataLength`] when the image does not hold width × height pixels.
pub fn try_encode(img: &mut Image) -> Result<(), RenderError> {
let expected = area(img.width, img.height).ok_or(RenderError::TooLarge(img.width, img.height))?;
if img.data.len() != expected {
return Err(RenderError::BadDataLength { expected, found: img.data.len() });
}
let bad = |p: &[f32; 4]| {
!p.iter().all(|c| c.is_finite()) || p[3] < 0.0 || p[3] > 1.0 + ALPHA_SLACK || (p[3] > 1e-6 && !p[..3].iter().all(|c| (c / p[3]).is_finite()))
};
// A pixel that fails the checks above is written as NaN, so the first invalid pixel is
// reported.
let encoded: Vec<[f32; 4]> = img
.data
.par_iter()
.map(|&p| {
if bad(&p) {
return [f32::NAN; 4];
}
let mut p = p;
let a = p[3];
if a > 1e-6 {
for c in &mut p[..3] {
*c = linear_to_srgb(*c / a) * a;
}
}
p
})
.collect();
if let Some(i) = encoded.iter().position(|p| !p.iter().all(|c| c.is_finite())) {
return Err(RenderError::BadPixel(i));
}
img.data = encoded;
Ok(())
}
/// Render a scene and resolve it by its supersampling factor ([`Scene::ssaa`], 0 read as 1):
/// the premultiplied linear image at output size and its depth. A factor that does not divide
/// the raster size is rejected before anything is rendered.
pub fn try_render_cpu(s: &Scene, limits: &Limits) -> Result<(Image, Vec<f32>), RenderError> {
let k = s.ssaa.max(1);
if !s.width.is_multiple_of(k) || !s.height.is_multiple_of(k) {
return Err(RenderError::BadFactor { k, width: s.width, height: s.height });
}
try_resolve(&try_render(s, limits)?, k)
}
+407
View File
@@ -0,0 +1,407 @@
//! The scene: everything the rasterizer needs, flattened into world-space triangles and plain
//! arrays, and the checks a scene passes before it is rendered.
use crate::shadow::cube_maps;
use crate::{Limits, RenderError};
/// One vertex in world space.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Vertex {
pub pos: [f32; 3],
pub normal: [f32; 3],
pub uv: [f32; 2],
/// Tangent and bitangent sign (`w`).
pub tangent: [f32; 4],
/// Index into [`Scene::materials`]. A triangle takes the material of its first vertex.
pub material: u32,
}
/// A material, resolved for shading.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material {
/// Linear RGBA factor.
pub base: [f32; 4],
/// 0 to 1.
pub metallic: f32,
/// 0 to 1.
pub roughness: f32,
pub emissive: [f32; 3],
pub normal_scale: f32,
/// 0 to 1.
pub occlusion_strength: f32,
/// 0 opaque, 1 mask, 2 blend.
pub alpha_mode: u32,
pub alpha_cutoff: f32,
/// Opacity of the whole surface (multiplies alpha).
pub opacity: f32,
/// Texture indices (negative = none).
pub tex_base: i32,
pub tex_mr: i32,
pub tex_normal: i32,
pub tex_occlusion: i32,
pub tex_emissive: i32,
pub double_sided: bool,
pub unlit: bool,
pub accepts_lights: bool,
pub receives_shadows: bool,
/// Draws only the shadows it receives, as black times their amount.
pub shadows_only: bool,
pub casts_shadows: bool,
/// Drawn (false for a surface that only casts shadows).
pub visible: bool,
/// Weights of the diffuse lobe, the dielectric specular reflectance and the ambient light.
pub diffuse_k: f32,
pub specular_k: f32,
pub ambient_k: f32,
}
impl Default for Material {
fn default() -> Self {
Material {
base: [1.0; 4],
metallic: 0.0,
roughness: 0.5,
emissive: [0.0; 3],
normal_scale: 1.0,
occlusion_strength: 1.0,
alpha_mode: 0,
alpha_cutoff: 0.5,
opacity: 1.0,
tex_base: -1,
tex_mr: -1,
tex_normal: -1,
tex_occlusion: -1,
tex_emissive: -1,
double_sided: false,
unlit: false,
accepts_lights: true,
receives_shadows: true,
shadows_only: false,
casts_shadows: false,
visible: true,
diffuse_k: 1.0,
specular_k: 1.0,
ambient_k: 1.0,
}
}
}
impl Material {
/// Drawn in the transparent (sorted, blended) pass.
pub fn transparent(&self) -> bool {
self.alpha_mode == 2 || self.opacity < 0.999 || self.shadows_only
}
}
/// A texture in [`Scene::texels`]: linear straight RGBA.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TexInfo {
pub offset: u32,
pub width: u32,
pub height: u32,
/// 0 repeat, 1 clamp, 2 mirror (other values repeat).
pub wrap_u: u32,
pub wrap_v: u32,
}
/// A light (ambient light is summed into [`Scene::ambient`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Light {
/// 0 parallel, 1 spot, 2 point.
pub kind: u32,
pub pos: [f32; 3],
/// Unit direction the light travels, for a parallel or spot light; a length that differs from
/// 1 by more than 0.001 is an error. A point light does not read it.
pub dir: [f32; 3],
/// Linear color times intensity.
pub color: [f32; 3],
/// Cosine of a spot light's full-intensity half angle, −1 to 1 and at least
/// [`Light::cos_outer`].
pub cos_inner: f32,
/// Cosine of a spot light's cone half angle, −1 to 1.
pub cos_outer: f32,
/// 0 none, 1 smooth, 2 inverse square clamped. Other values return [`RenderError::BadLight`].
pub falloff: u32,
pub radius: f32,
pub falloff_distance: f32,
/// First shadow map (point lights, and spot lights whose outer cone's half angle is over 1.40
/// radians, use six), −1 = none. [`crate::try_shadow_maps`] reads any
/// value of 0 or more as a request for maps.
pub shadow: i32,
/// Fraction of the light a full shadow removes, 0 to 1.
pub shadow_darkness: f32,
/// Penumbra widening in output pixels, 0 or more.
pub shadow_diffusion: f32,
}
/// A depth map seen from a light: `view` maps world → light space (+z forward); pixels
/// `u = focal·x/z + size/2` (perspective) or `focal·x + size/2` (orthographic); texels store
/// the light-space depth of the nearest caster. A perspective map holds the parts of casters at a
/// light-space depth of at least 0.001, and a receiver at that depth or nearer is not shadowed by
/// it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShadowMap {
pub view: [[f32; 4]; 3],
pub focal: f32,
pub ortho: bool,
pub size: u32,
/// First texel in [`Scene::shadow_texels`].
pub offset: u32,
/// Depth bias in texels (scaled by the texel footprint at the receiver).
pub bias: f32,
/// Penumbra width in output pixels; the shader converts it to a tap reach through the
/// receiver's texel footprint.
pub radius: f32,
}
/// The environment image: radiance levels `radiance..radiance + mips` and an irradiance map,
/// in [`Scene::textures`], equirect with the vertical axis along −y.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EnvInfo {
/// The texture index of the sharpest radiance level; levels `radiance..radiance + mips` go
/// from smooth to rough.
pub radiance: u32,
/// The radiance level count, at least 1.
pub mips: u32,
/// The texture index of the irradiance map.
pub irradiance: u32,
pub intensity: f32,
/// Radians about the vertical axis.
pub rotation: f32,
/// Unit direction from the scene toward the environment's dominant bright region, the
/// direction its shadow is cast from. `[0; 3]` when the image has no dominant direction: no
/// shadow. Any other length that differs from 1 by more than 0.001 is an error.
pub sun: [f32; 3],
/// The image's directional fraction, 0 to 1: 0 for a uniform image and near 1 for a single
/// bright spot. The shadow occludes only this fraction of the environment light.
pub key: f32,
/// Shadow map index into [`Scene::shadows`]: [`crate::try_shadow_maps`] reads any value of 0
/// or more as a request for a map; −1 casts no shadow.
pub shadow: i32,
/// Fraction of the occluded light a full shadow removes, 0 to 1.
pub shadow_darkness: f32,
/// Penumbra widening in output pixels, 0 or more.
pub shadow_diffusion: f32,
}
/// A prepared scene.
#[derive(Clone, Debug, Default)]
pub struct Scene {
/// Raster size (output × `ssaa`).
pub width: u32,
pub height: u32,
/// Supersampling factor per side; 0 is read as 1.
pub ssaa: u32,
/// World → clip (row-major; reversed depth: ndc z = near / camera z).
pub clip: [[f32; 4]; 4],
/// World → camera (row-major; camera z is the depth written to [`crate::Target::depth`]).
pub view: [[f32; 4]; 4],
pub eye: [f32; 3],
pub cam_fwd: [f32; 3],
pub ortho: bool,
pub vertices: Vec<Vertex>,
/// Triangles: the first `opaque_count` indices are opaque, the rest transparent, sorted
/// back to front. A visible material for which [`Material::transparent`] is true in the
/// opaque range returns [`RenderError::BadMaterial`], or [`RenderError::ShadowsOnlyOpaque`]
/// for a shadows-only material.
pub indices: Vec<u32>,
pub opaque_count: u32,
pub materials: Vec<Material>,
pub textures: Vec<TexInfo>,
pub texels: Vec<[f32; 4]>,
pub lights: Vec<Light>,
pub shadows: Vec<ShadowMap>,
pub shadow_texels: Vec<f32>,
pub env: Option<EnvInfo>,
pub ambient: [f32; 3],
/// Shading inputs and outputs are linear (no sRGB conversion needed).
pub linear_io: bool,
}
fn finite<const N: usize>(v: &[f32; N]) -> bool {
v.iter().all(|x| x.is_finite())
}
/// How far a direction's length may differ from 1.
const UNIT_TOLERANCE: f64 = 1e-3;
/// `v` is finite and its length is within [`UNIT_TOLERANCE`] of 1.
pub(crate) fn unit(v: &[f32; 3]) -> bool {
let len = v.iter().map(|&x| f64::from(x) * f64::from(x)).sum::<f64>().sqrt();
(len - 1.0).abs() <= UNIT_TOLERANCE
}
/// Checks a scene against `limits`: the raster size, the index list, every reference between the
/// arrays, texture and shadow spans, finite values and the triangle and light counts. Returns the
/// raster's pixel count.
pub(crate) fn validate(s: &Scene, limits: &Limits) -> Result<usize, RenderError> {
let pixels = limits.check(s.width, s.height)?;
if !s.clip.iter().all(finite) || !s.view.iter().all(finite) || !finite(&s.eye) || !finite(&s.cam_fwd) || !finite(&s.ambient) {
return Err(RenderError::BadTransform);
}
validate_indices(s, limits)?;
validate_materials(s)?;
validate_textures(s)?;
validate_lights(s, limits)?;
validate_shadows(s)?;
Ok(pixels)
}
fn validate_indices(s: &Scene, limits: &Limits) -> Result<(), RenderError> {
let len = s.indices.len();
if !len.is_multiple_of(3) {
return Err(RenderError::BadIndexCount(len));
}
let opaque = s.opaque_count as usize;
if opaque > len || !opaque.is_multiple_of(3) {
return Err(RenderError::BadOpaqueCount { opaque: s.opaque_count, len });
}
let count = (len / 3) as u64;
if count > limits.max_triangles {
return Err(RenderError::TooManyTriangles { count, limit: limits.max_triangles });
}
let vertices = s.vertices.len() as u64;
if vertices > limits.max_vertices {
return Err(RenderError::TooManyVertices { count: vertices, limit: limits.max_vertices });
}
if let Some((position, &index)) = s.indices.iter().enumerate().find(|(_, i)| **i as usize >= s.vertices.len()) {
return Err(RenderError::BadIndex { position, index });
}
let bad = |v: &Vertex| !finite(&v.pos) || !finite(&v.normal) || !finite(&v.uv) || !finite(&v.tangent) || v.material as usize >= s.materials.len();
if let Some(i) = s.vertices.iter().position(bad) {
return Err(RenderError::BadVertex(i));
}
Ok(())
}
fn validate_materials(s: &Scene) -> Result<(), RenderError> {
let tex_ok = |i: i32| i < 0 || (i as usize) < s.textures.len();
let ok = |m: &Material| {
finite(&m.base)
&& finite(&m.emissive)
&& finite(&[
m.metallic,
m.roughness,
m.normal_scale,
m.occlusion_strength,
m.alpha_cutoff,
m.opacity,
m.diffuse_k,
m.specular_k,
m.ambient_k,
])
&& (0.0..=1.0).contains(&m.base[3])
&& (0.0..=1.0).contains(&m.opacity)
&& (0.0..=1.0).contains(&m.metallic)
&& (0.0..=1.0).contains(&m.roughness)
&& (0.0..=1.0).contains(&m.occlusion_strength)
&& m.alpha_mode <= 2
&& [m.tex_base, m.tex_mr, m.tex_normal, m.tex_occlusion, m.tex_emissive].into_iter().all(tex_ok)
};
match s.materials.iter().position(|m| !ok(m)) {
Some(i) => Err(RenderError::BadMaterial(i)),
None => Ok(()),
}
}
fn validate_textures(s: &Scene) -> Result<(), RenderError> {
for (i, t) in s.textures.iter().enumerate() {
let end = u64::from(t.width).checked_mul(u64::from(t.height)).and_then(|n| n.checked_add(u64::from(t.offset)));
if t.width == 0 || t.height == 0 || end.is_none_or(|e| e > s.texels.len() as u64) {
return Err(RenderError::BadTexture(i));
}
}
match s.texels.iter().position(|t| !finite(t) || !(0.0..=1.0).contains(&t[3])) {
Some(i) => Err(RenderError::BadTexel(i)),
None => Ok(()),
}
}
fn validate_lights(s: &Scene, limits: &Limits) -> Result<(), RenderError> {
if s.lights.len() > limits.max_lights {
return Err(RenderError::TooManyLights { count: s.lights.len(), limit: limits.max_lights });
}
let ok = |l: &Light| {
l.kind <= 2
&& l.falloff <= 2
&& finite(&l.pos)
&& finite(&l.dir)
&& finite(&l.color)
&& finite(&[l.cos_inner, l.cos_outer, l.radius, l.falloff_distance, l.shadow_darkness, l.shadow_diffusion])
&& (-1.0..=1.0).contains(&l.cos_inner)
&& (-1.0..=1.0).contains(&l.cos_outer)
&& (l.kind != 1 || l.cos_inner >= l.cos_outer)
&& (0.0..=1.0).contains(&l.shadow_darkness)
&& l.shadow_diffusion >= 0.0
&& (l.kind == 2 || unit(&l.dir))
};
if let Some(i) = s.lights.iter().position(|l| !ok(l)) {
return Err(RenderError::BadLight(i));
}
if let Some(e) = &s.env {
let ok = finite(&e.sun)
&& (e.sun == [0.0; 3] || unit(&e.sun))
&& finite(&[e.intensity, e.rotation, e.key, e.shadow_darkness, e.shadow_diffusion])
&& (0.0..=1.0).contains(&e.key)
&& (0.0..=1.0).contains(&e.shadow_darkness)
&& e.shadow_diffusion >= 0.0
&& e.mips > 0
&& e.radiance.checked_add(e.mips).is_some_and(|end| end as usize <= s.textures.len())
&& (e.irradiance as usize) < s.textures.len();
if !ok {
return Err(RenderError::BadEnvironment);
}
}
Ok(())
}
/// Every light and the environment light either has no shadow (a negative mark) or refers to
/// maps in [`Scene::shadows`]: six from its mark for a point light or a spot light whose cone
/// one map does not cover, one otherwise.
/// Checks that no drawn triangle of the opaque range has a transparent material (its first
/// vertex's material, as the raster reads it; a material with `visible` false is not drawn). Run
/// after [`validate`].
pub(crate) fn validate_passes(s: &Scene) -> Result<(), RenderError> {
for (t, ids) in s.indices.get(..s.opaque_count as usize).unwrap_or_default().chunks(3).enumerate() {
if let Some(v) = s.vertices.get(ids[0] as usize)
&& let Some(m) = s.materials.get(v.material as usize)
&& m.visible
&& m.transparent()
{
return Err(if m.shadows_only { RenderError::ShadowsOnlyOpaque(t) } else { RenderError::BadMaterial(v.material as usize) });
}
}
Ok(())
}
pub(crate) fn validate_shadow_refs(s: &Scene) -> Result<(), RenderError> {
let exists = |first: i32, count: usize| first < 0 || (first as usize).checked_add(count).is_some_and(|end| end <= s.shadows.len());
if let Some(i) = s.lights.iter().position(|l| !exists(l.shadow, if cube_maps(l) { 6 } else { 1 })) {
return Err(RenderError::MissingShadowMap(Some(i)));
}
if s.env.is_some_and(|e| !exists(e.shadow, 1)) {
return Err(RenderError::MissingShadowMap(None));
}
Ok(())
}
fn validate_shadows(s: &Scene) -> Result<(), RenderError> {
for (i, m) in s.shadows.iter().enumerate() {
let end = u64::from(m.size).checked_mul(u64::from(m.size)).and_then(|n| n.checked_add(u64::from(m.offset)));
let ok = m.size > 0
&& m.view.iter().all(finite)
&& m.focal.is_finite()
&& m.focal > 0.0
&& finite(&[m.bias, m.radius])
&& m.radius >= 0.0
&& end.is_some_and(|e| e <= s.shadow_texels.len() as u64);
if !ok {
return Err(RenderError::BadShadowMap(i));
}
}
match s.shadow_texels.iter().position(|t| t.is_nan()) {
Some(i) => Err(RenderError::BadShadowTexel(i)),
None => Ok(()),
}
}
+798
View File
@@ -0,0 +1,798 @@
//! Physically based shading of one fragment.
//!
//! - Direct light: Cook–Torrance microfacet specular with the GGX/Trowbridge–Reitz normal
//! distribution, the Smith–Schlick-GGX geometry term (`k = (r + 1)² / 8`) and Schlick's
//! Fresnel (`F0` = 0.04 for dielectrics, the base color for metals), plus a Lambertian
//! diffuse lobe weighted by `(1 − F)(1 − metallic)` (Karis 2013, "Real Shading in Unreal
//! Engine 4"; the glTF 2.0 metallic-roughness model). Light colors are the irradiance on a
//! surface facing the light (a white 100% light shows a white diffuse surface at its base
//! color), so π is folded into the light intensity.
//! - Image-based light: a cosine-convolved irradiance map for diffuse, a mip chain of the
//! equirectangular environment sampled by roughness for specular, and the analytic split-sum
//! environment BRDF fit (Karis 2014, "Physically Based Shading on Mobile").
//! - Shadows: depth maps per light, percentage-closer filtered.
use crate::scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo};
use crate::shadow::{NEAR, cube_maps};
pub(crate) const PI: f32 = std::f32::consts::PI;
#[inline]
pub(crate) fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[inline]
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
#[inline]
fn norm(a: [f32; 3]) -> [f32; 3] {
let l = dot(a, a).sqrt();
// The squared length of a large finite vector overflows f32; such a vector is normalized in f64.
if l.is_infinite() && a.iter().all(|c| c.is_finite()) {
let a = a.map(f64::from);
let l = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt();
return a.map(|c| (c / l) as f32);
}
if l > 1e-20 { [a[0] / l, a[1] / l, a[2] / l] } else { [0.0, 0.0, -1.0] }
}
#[inline]
fn add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
#[inline]
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
/// `a − b` in f64, where the difference of finite `f32` positions cannot overflow.
#[inline]
fn sub_f64(a: [f32; 3], b: [f32; 3]) -> [f64; 3] {
[0, 1, 2].map(|i| f64::from(a[i]) - f64::from(b[i]))
}
/// The unit direction from `b` to `a`, taken in f64 when the f32 difference overflows.
#[inline]
fn norm_dir(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
let d = sub(a, b);
if d.iter().all(|c| c.is_finite()) || !a.iter().chain(&b).all(|c| c.is_finite()) {
return norm(d);
}
let d = sub_f64(a, b);
let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
d.map(|c| (c / l) as f32)
}
#[inline]
fn scale(a: [f32; 3], k: f32) -> [f32; 3] {
[a[0] * k, a[1] * k, a[2] * k]
}
#[inline]
fn mix(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
/// sRGB-encoded → linear light. The segment is chosen by magnitude and a negative value keeps
/// its sign, as in CSS Color 4's conversion code.
#[inline]
pub fn srgb_to_linear(c: f32) -> f32 {
let a = c.abs();
if a <= 0.04045 { c / 12.92 } else { ((a + 0.055) / 1.055).powf(2.4).copysign(c) }
}
/// Linear light → sRGB-encoded. Values above 1 continue the curve; the segment is chosen by
/// magnitude and a negative value keeps its sign, as in CSS Color 4's conversion code.
#[inline]
pub fn linear_to_srgb(c: f32) -> f32 {
let a = c.abs();
if a <= 0.0031308 { c * 12.92 } else { (1.055 * a.powf(1.0 / 2.4) - 0.055).copysign(c) }
}
/// GGX / Trowbridge–Reitz normal distribution, `a = roughness²`.
#[inline]
fn d_ggx(n_h: f32, a: f32) -> f32 {
let a2 = a * a;
let d = n_h * n_h * (a2 - 1.0) + 1.0;
a2 / (PI * d * d).max(1e-12)
}
/// Smith–Schlick-GGX geometry term for direct light (`k = (r + 1)² / 8`).
#[inline]
fn g_smith(n_v: f32, n_l: f32, rough: f32) -> f32 {
let k = (rough + 1.0) * (rough + 1.0) / 8.0;
let g1 = |x: f32| x / (x * (1.0 - k) + k);
g1(n_v) * g1(n_l)
}
/// Schlick's Fresnel approximation.
#[inline]
fn f_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] {
let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5);
[f0[0] + (1.0 - f0[0]) * k, f0[1] + (1.0 - f0[1]) * k, f0[2] + (1.0 - f0[2]) * k]
}
/// Surface parameters used by the direct-light BRDF after texture sampling.
#[derive(Clone, Copy)]
struct BrdfSurface {
base: [f32; 3],
metallic: f32,
roughness: f32,
specular: f32,
diffuse: f32,
}
/// Cook–Torrance BRDF × N·L × π for one light, the reflected fraction of the light's
/// irradiance per channel.
fn brdf(surface: BrdfSurface, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> [f32; 3] {
let BrdfSurface { base, metallic, roughness: rough, specular: spec_k, diffuse: diff_k } = surface;
let n_l = dot(n, l);
if n_l <= 0.0 {
return [0.0; 3];
}
let n_v = dot(n, v).max(1e-4);
let h = norm(add(v, l));
let n_h = dot(n, h).max(0.0);
let v_h = dot(v, h).max(0.0);
let r = rough.clamp(0.03, 1.0);
let f0 = [mix(0.04 * spec_k, base[0], metallic), mix(0.04 * spec_k, base[1], metallic), mix(0.04 * spec_k, base[2], metallic)];
let f = f_schlick(f0, v_h);
let d = d_ggx(n_h, r * r);
let g = g_smith(n_v, n_l, r);
let spec = d * g / (4.0 * n_v * n_l).max(1e-4);
let mut out = [0.0; 3];
for c in 0..3 {
let kd = (1.0 - f[c]) * (1.0 - metallic);
out[c] = (kd * base[c] / PI * diff_k + f[c] * spec) * n_l * PI;
}
out
}
/// Split-sum environment BRDF (scale, bias) for `F0·A + B` (analytic fit).
#[inline]
fn env_brdf(n_v: f32, rough: f32) -> (f32, f32) {
let c0 = [-1.0, -0.0275, -0.572, 0.022];
let c1 = [1.0, 0.0425, 1.04, -0.04];
let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]];
let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1];
(-1.04 * a004 + r[2], 1.04 * a004 + r[3])
}
/// Wrap a texel index.
#[inline]
fn wrap(i: i64, n: i64, mode: u32) -> i64 {
match mode {
1 => i.clamp(0, n - 1),
2 => {
let m = i.rem_euclid(2 * n);
if m >= n { 2 * n - 1 - m } else { m }
}
_ => i.rem_euclid(n),
}
}
/// The smallest `f32` magnitude whose neighbors are 1 apart (2^23): a scaled coordinate this
/// large loses the half-texel shift.
const UNIT_STEP: f32 = 8_388_608.0;
/// Bilinear texture sample at (u, v): 0..1 across the texture, texel centers at +0.5, wrapped
/// by the texture's modes. A texture with a zero side samples as white, and a texel past the
/// end of `texels` as transparent black.
pub fn sample(t: &TexInfo, texels: &[[f32; 4]], u: f32, v: f32) -> [f32; 4] {
let (w, h) = (t.width as i64, t.height as i64);
if w == 0 || h == 0 {
return [1.0; 4];
}
// The first texel index and the weight of the next one along an axis of `n` texels. A finite
// coordinate whose scaled value reaches 2^23 is scaled in f64, after a repeated axis is reduced
// by its period of 1 and a mirrored axis by its period of 2, so it keeps the half-texel shift
// and the texel index does not saturate. A coordinate that is not finite is taken as the
// largest finite one, so the weights below stay finite.
let axis = |c: f32, n: i64, mode: u32| -> (i64, f32) {
if c.is_finite() && (c * n as f32).abs() >= UNIT_STEP {
let c = f64::from(c);
let c = match mode {
1 => c,
2 => c.rem_euclid(2.0),
_ => c.rem_euclid(1.0),
};
let x = c * n as f64 - 0.5;
let x0 = x.floor();
return (x0 as i64, (x - x0) as f32);
}
let x = c * n as f32 - 0.5;
let x = if x.is_finite() { x } else { f32::MAX.copysign(x) };
let x0 = x.floor();
(x0 as i64, x - x0)
};
let ((x0, fx), (y0, fy)) = (axis(u, w, t.wrap_u), axis(v, h, t.wrap_v));
let get = |xi: i64, yi: i64| -> [f32; 4] {
let xi = wrap(xi, w, t.wrap_u);
let yi = wrap(yi, h, t.wrap_v);
// In i128, so a texture whose sides are near u32::MAX cannot overflow the offset.
let i = i128::from(t.offset) + i128::from(yi) * i128::from(w) + i128::from(xi);
usize::try_from(i).ok().and_then(|i| texels.get(i)).copied().unwrap_or([0.0; 4])
};
// A coordinate past i64 saturates; the next texel saturates too rather than overflowing.
let (x1, y1) = (x0.saturating_add(1), y0.saturating_add(1));
let (a, b, c, d) = (get(x0, y0), get(x1, y0), get(x0, y1), get(x1, y1));
let mut o = [0.0; 4];
for k in 0..4 {
let top = a[k] + (b[k] - a[k]) * fx;
let bot = c[k] + (d[k] - c[k]) * fx;
o[k] = top + (bot - top) * fy;
// Large finite texels of opposite signs overflow the differences; such a channel is
// interpolated in f64.
if !o[k].is_finite() {
let lerp = |p: f64, q: f64, t: f64| p + (q - p) * t;
let (fx, fy) = (f64::from(fx), f64::from(fy));
let top = lerp(f64::from(a[k]), f64::from(b[k]), fx);
let bot = lerp(f64::from(c[k]), f64::from(d[k]), fx);
o[k] = lerp(top, bot, fy).clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
}
}
o
}
/// Equirectangular coordinates of a world direction (+Y down; the environment's up is −Y),
/// rotated about the vertical axis by `rot` radians.
#[inline]
fn equirect_uv(d: [f32; 3], rot: f32) -> (f32, f32) {
let u = 0.5 + (d[0].atan2(d[2]) + rot) / (2.0 * PI);
let v = (-d[1]).clamp(-1.0, 1.0).acos() / PI;
(u - u.floor(), v)
}
/// `a` to `b` at `t`, returning an endpoint as is and mixing in f64 when the f32 difference
/// overflows.
#[inline]
fn mix_levels(a: f32, b: f32, t: f32) -> f32 {
let m = mix(a, b, t);
if m.is_finite() || !(a.is_finite() && b.is_finite()) {
return m;
}
if t == 0.0 {
return a;
}
if t == 1.0 {
return b;
}
let (a, b, t) = (f64::from(a), f64::from(b), f64::from(t));
(a + (b - a) * t) as f32
}
/// Diffuse (irradiance) and roughness-filtered specular radiance of the environment.
fn env_light(s: &Scene, e: &EnvInfo, n: [f32; 3], r: [f32; 3], rough: f32) -> ([f32; 3], [f32; 3]) {
let (u, v) = equirect_uv(n, e.rotation);
let irr = s.textures.get(e.irradiance as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let (u, v) = equirect_uv(r, e.rotation);
let lv = rough.clamp(0.0, 1.0) * (e.mips.saturating_sub(1)) as f32;
let l0 = lv.floor() as u32;
let l1 = (l0 + 1).min(e.mips.saturating_sub(1));
let f = lv - l0 as f32;
let a = s.textures.get((e.radiance + l0) as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let b = s.textures.get((e.radiance + l1) as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let spec = [mix_levels(a[0], b[0], f), mix_levels(a[1], b[1], f), mix_levels(a[2], b[2], f)];
(scale([irr[0], irr[1], irr[2]], e.intensity), scale(spec, e.intensity))
}
/// Light-space position (u, v in shadow-map pixels, depth) of a world point.
#[inline]
fn shadow_coord(m: &ShadowMap, p: [f32; 3]) -> Option<(f32, f32, f32)> {
let v = &m.view;
let q = [
v[0][0] * p[0] + v[0][1] * p[1] + v[0][2] * p[2] + v[0][3],
v[1][0] * p[0] + v[1][1] * p[1] + v[1][2] * p[2] + v[1][3],
v[2][0] * p[0] + v[2][1] * p[1] + v[2][2] * p[2] + v[2][3],
];
let c = m.size as f32 * 0.5;
// A finite coordinate whose product with the focal length overflows f32 is projected in f64.
let at = |x: f32, z: f32, fast: f32| {
if fast.is_finite() || !x.is_finite() { fast } else { (f64::from(x) * f64::from(m.focal) / f64::from(z) + f64::from(c)) as f32 }
};
if m.ortho {
Some((at(q[0], 1.0, q[0] * m.focal + c), at(q[1], 1.0, q[1] * m.focal + c), q[2]))
} else if q[2] > NEAR {
Some((at(q[0], q[2], q[0] * m.focal / q[2] + c), at(q[1], q[2], q[1] * m.focal / q[2] + c), q[2]))
} else {
None
}
}
/// Integer tap jitter hash: u32 bit math only, so a GPU backend can compute the same jitter
/// from the same inputs.
fn tap_hash(x: i32, y: i32) -> u32 {
let mut h = (x as u32).wrapping_mul(0x9E37_79B9) ^ (y as u32).wrapping_mul(0x85EB_CA6B);
h ^= h >> 16;
h = h.wrapping_mul(0x2545_F491);
h ^= h >> 15;
h
}
/// The jitter of tap (`i`, `j`), each axis in [−0.5, 0.5): [`tap_hash`] values at the four
/// corners of the receiver's 1/8-texel lattice cell (`cx`, `cy`), blended bilinearly by the
/// receiver's position in the cell (`wx`, `wy`). The jitter is continuous in the receiver's
/// map position.
fn tap_jitter(cx: i32, cy: i32, wx: f32, wy: f32, i: i32, j: i32) -> (f32, f32) {
let corner = |dx: i32, dy: i32| -> (f32, f32) {
let h = tap_hash(cx.wrapping_add(dx).wrapping_add(i.wrapping_mul(7919)), cy.wrapping_add(dy).wrapping_add(j.wrapping_mul(7919)));
(((h & 0xFFFF) as f32) * (1.0 / 65536.0) - 0.5, (((h >> 16) & 0xFFFF) as f32) * (1.0 / 65536.0) - 0.5)
};
let (c00, c10, c01, c11) = (corner(0, 0), corner(1, 0), corner(0, 1), corner(1, 1));
let ax = c00.0 + (c10.0 - c00.0) * wx;
let bx = c01.0 + (c11.0 - c01.0) * wx;
let ay = c00.1 + (c10.1 - c00.1) * wx;
let by = c01.1 + (c11.1 - c01.1) * wx;
(ax + (bx - ax) * wy, ay + (by - ay) * wy)
}
/// Upper bound of the PCF grid's taps per axis.
const PCF_MAX_TAPS: i32 = 10;
/// Steepest receiver-plane slope the PCF extrapolates, in texel footprints of depth per
/// texel (about 89°). Steeper planes are clamped to this slope.
const PLANE_SLOPE_MAX: f32 = 64.0;
/// Fraction of light reaching `p` through shadow map `m` (1 = lit). `ng` is the receiver's
/// geometric (not normal-mapped) normal facing the viewer.
///
/// PCF over an N×N tap grid (5 ≤ N ≤ `PCF_MAX_TAPS`) spread over a reach derived from `radius`
/// (the penumbra in output pixels) divided by the receiver's texel footprint, each tap jittered
/// by [`tap_jitter`] and comparing against the four nearest texel centers with bilinear weights.
/// Every texel is compared against the depth the receiver's own plane has at that texel's
/// center, not the receiver point's depth.
fn shadow_factor(m: &ShadowMap, texels: &[f32], p: [f32; 3], ng: [f32; 3], n_l: f32) -> f32 {
let Some((u, v, z)) = shadow_coord(m, p) else { return 1.0 };
let size = m.size as i64;
// Slope-scaled bias at texel scale (world units are pixels), steeper for grazing light.
let texel = if m.ortho { 1.0 / m.focal } else { z.abs() / m.focal };
let bias = m.bias * texel * (1.0 + 3.0 * (1.0 - n_l.clamp(0.0, 1.0)));
let at = |xi: i64, yi: i64| -> f32 {
if xi < 0 || yi < 0 || xi >= size || yi >= size {
return f32::INFINITY; // outside the map: nothing blocks the light there
}
texels.get(m.offset as usize + (yi * size + xi) as usize).copied().unwrap_or(f32::INFINITY)
};
// The receiver plane in light space as the slope of its depth across the map, in texel
// footprints per texel (`tx`, `ty`; depth grows along −t), clamped where the plane grazes the
// light. `den0` is the plane normal against the light ray through the receiver (the depth
// axis for an orthographic map), negative while it faces it.
let w = &m.view;
let nv = [0, 1, 2].map(|r| w[r][0] * ng[0] + w[r][1] * ng[1] + w[r][2] * ng[2]);
let c = m.size as f32 * 0.5;
let den0 = if m.ortho { nv[2] } else { nv[0] * ((u - c) / m.focal) + nv[1] * ((v - c) / m.focal) + nv[2] };
let (tx, ty) = if den0 < -1e-6 {
((nv[0] / den0).clamp(-PLANE_SLOPE_MAX, PLANE_SLOPE_MAX), (nv[1] / den0).clamp(-PLANE_SLOPE_MAX, PLANE_SLOPE_MAX))
} else {
(0.0, 0.0)
};
// 1 where texel (xi, yi) does not occlude the receiver plane at the texel's center. The
// perspective compare runs on 1/depth, which is linear across the map; a plane whose inverse
// depth reaches 0 is behind the light and cannot be occluded.
// When `focal * z` overflows, `iq` rounds to 0 and the plane would read as flat, so the f64
// compare runs instead.
let fz = m.focal * z;
let (iz, iq) = (1.0 / z, 1.0 / fz);
let open = |xi: i64, yi: i64| -> f32 {
let t = at(xi, yi);
if t == f32::INFINITY {
return 1.0;
}
let s = t + bias;
let g = tx * (xi as f32 + 0.5 - u) + ty * (yi as f32 + 0.5 - v);
let fast = if m.ortho {
(s.is_finite() && g.is_finite() && texel.is_finite()).then_some(z - g * texel <= s)
} else {
let inv = iz + g * iq;
(s.is_finite() && inv.is_finite() && fz.is_finite()).then_some(inv <= 0.0 || inv * s >= 1.0)
};
let lit = fast.unwrap_or_else(|| {
let z = if z.is_finite() {
f64::from(z)
} else {
f64::from(w[2][0]) * f64::from(p[0])
+ f64::from(w[2][1]) * f64::from(p[1])
+ f64::from(w[2][2]) * f64::from(p[2])
+ f64::from(w[2][3])
};
let focal = f64::from(m.focal);
let texel = if m.ortho { 1.0 / focal } else { z.abs() / focal };
let bias = f64::from(m.bias) * texel * (1.0 + 3.0 * (1.0 - f64::from(n_l.clamp(0.0, 1.0))));
let t = f64::from(t);
let g = f64::from(tx) * (xi as f64 + 0.5 - f64::from(u)) + f64::from(ty) * (yi as f64 + 0.5 - f64::from(v));
if t == f64::NEG_INFINITY {
!m.ortho && g <= -focal
} else if m.ortho {
z - t <= bias + g * texel
} else if g == 0.0 {
z - t <= bias
} else {
g <= -focal || z - t <= bias + g * (t / focal) + g * (bias / focal)
}
});
if lit { 1.0 } else { 0.0 }
};
// The penumbra in output pixels, converted through the receiver's texel footprint, and at
// least two texels.
let mut reach = (m.radius / texel).clamp(2.0, 256.0);
if !reach.is_finite() {
reach = 1.0;
}
// Every tap of a receiver more than `reach + 1` texels outside the map reads only texels
// outside it, so the light is unblocked there. Returning here also keeps the jitter
// lattice finite for map coordinates near `f32::MAX`.
let (lo, hi) = (-(reach + 1.0), size as f32 + reach + 1.0);
if !(u >= lo && u <= hi && v >= lo && v <= hi) {
return 1.0;
}
let n = (reach.ceil() as i32 + 1).clamp(5, PCF_MAX_TAPS);
let step = reach / (n - 1) as f32;
let half = (n - 1) as f32 * 0.5;
let (gu, gv) = (u * 8.0, v * 8.0);
let (cx, cy) = (gu.floor() as i32, gv.floor() as i32);
let (wx, wy) = (gu - gu.floor(), gv - gv.floor());
let mut lit = 0.0;
for j in 0..n {
for i in 0..n {
let (jx, jy) = tap_jitter(cx, cy, wx, wy, i, j);
let (su, sv) = (u + ((i as f32 - half) + jx) * step, v + ((j as f32 - half) + jy) * step);
// Texel (x, y) holds the depth at its center (x + 0.5, y + 0.5).
let (tu, tv) = (su - 0.5, sv - 0.5);
let (fx, fy) = (tu - tu.floor(), tv - tv.floor());
let (x0, y0) = (tu.floor() as i64, tv.floor() as i64);
let (x1, y1) = (x0.saturating_add(1), y0.saturating_add(1));
let (h00, h10, h01, h11) = (open(x0, y0), open(x1, y0), open(x0, y1), open(x1, y1));
let a = h00 + (h10 - h00) * fx;
let b = h01 + (h11 - h01) * fx;
lit += a + (b - a) * fy;
}
}
lit / (n * n) as f32
}
/// The visibility of light `l` at `p` (1 = unshadowed), darkened by its shadow darkness.
fn light_shadow(s: &Scene, l: &Light, p: [f32; 3], ng: [f32; 3], n_l: f32) -> f32 {
if l.shadow < 0 {
return 1.0;
}
let first = l.shadow as usize;
let m = if cube_maps(l) {
// Point light, or a spot light wider than one map: the cube face of the major axis of
// the light → point direction.
// In f64 when the f32 difference of far-apart positions overflows.
let d = sub(p, l.pos);
let d = if d.iter().all(|c| c.is_finite()) { d.map(f64::from) } else { sub_f64(p, l.pos) };
let (ax, ay, az) = (d[0].abs(), d[1].abs(), d[2].abs());
let face = if ax >= ay && ax >= az {
if d[0] > 0.0 { 0 } else { 1 }
} else if ay >= az {
if d[1] > 0.0 { 2 } else { 3 }
} else if d[2] > 0.0 {
4
} else {
5
};
s.shadows.get(first + face)
} else {
s.shadows.get(first)
};
let Some(m) = m else { return 1.0 };
let f = shadow_factor(m, &s.shadow_texels, p, ng, n_l);
1.0 - l.shadow_darkness * (1.0 - f)
}
/// The visibility of the environment light at `p` (1 = unshadowed), darkened by its shadow
/// darkness times the image's key fraction: the map occludes the dominant lobe, and the rest of
/// the environment keeps lighting the surface. An image without a dominant direction, or a
/// light without a map, shades unshadowed.
fn env_shadow(s: &Scene, e: &EnvInfo, p: [f32; 3], ng: [f32; 3], n: [f32; 3]) -> f32 {
if e.shadow < 0 || e.sun == [0.0; 3] {
return 1.0;
}
let Some(m) = s.shadows.get(e.shadow as usize) else { return 1.0 };
let n_l = dot(n, e.sun).clamp(0.0, 1.0);
let f = shadow_factor(m, &s.shadow_texels, p, ng, n_l);
1.0 - e.shadow_darkness * e.key * (1.0 - f)
}
/// Unit direction from `p` to light `l`, and the distance (infinite for a parallel light).
fn to_light(l: &Light, p: [f32; 3]) -> ([f32; 3], f32) {
if l.kind == 0 {
return (scale(l.dir, -1.0), f32::INFINITY);
}
let d = sub(l.pos, p);
let len = dot(d, d).sqrt();
// The squared distance to a far light, or the displacement itself, overflows f32; such a
// direction is taken in f64 from the original positions.
if len.is_infinite() && l.pos.iter().chain(&p).all(|c| c.is_finite()) {
let d = sub_f64(l.pos, p);
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
return (d.map(|c| (c / len) as f32), len as f32);
}
if len < 1e-6 { ([0.0, 0.0, -1.0], 0.0) } else { (scale(d, 1.0 / len), len) }
}
/// Distance attenuation × spot cone of a light at `p`.
fn attenuation(l: &Light, p: [f32; 3], to_l: [f32; 3], dist: f32) -> f32 {
let mut k = match l.falloff {
1 if l.kind != 0 => {
if dist <= l.radius {
1.0
} else if l.falloff_distance <= 0.0 {
0.0
} else {
let t = ((dist - l.radius) / l.falloff_distance).clamp(0.0, 1.0);
1.0 - t * t * (3.0 - 2.0 * t)
}
}
2 if l.kind != 0 => {
if dist <= l.radius || (l.radius <= 0.0 && dist <= 1.0) {
1.0
} else {
(l.radius.max(1.0) / dist).powi(2)
}
}
_ => 1.0,
};
let _ = p;
if l.kind == 1 {
let cos_a = dot(scale(to_l, -1.0), l.dir).clamp(-1.0, 1.0);
k *= if cos_a >= l.cos_inner {
1.0
} else if cos_a <= l.cos_outer {
0.0
} else {
// Smoothstep across the feather in angle.
let a = cos_a.acos();
let (ai, ao) = (l.cos_inner.acos(), l.cos_outer.acos());
let t = ((a - ai) / (ao - ai).max(1e-6)).clamp(0.0, 1.0);
1.0 - t * t * (3.0 - 2.0 * t)
};
}
k
}
/// Inputs of one fragment.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Frag {
pub pos: [f32; 3],
/// Interpolated (unnormalized) vertex normal.
pub normal: [f32; 3],
pub uv: [f32; 2],
pub tangent: [f32; 4],
pub material: u32,
pub front: bool,
}
/// Shade a fragment: premultiplied linear RGBA, or `None` when discarded (alpha test, back
/// face of a single-sided material).
pub(crate) fn shade(s: &Scene, f: &Frag) -> Option<[f32; 4]> {
let m: &Material = s.materials.get(f.material as usize)?;
if !f.front && !m.double_sided {
return None;
}
let tex = |i: i32| -> Option<[f32; 4]> { (i >= 0).then(|| s.textures.get(i as usize).map(|t| sample(t, &s.texels, f.uv[0], f.uv[1]))).flatten() };
let mut base = m.base;
if let Some(t) = tex(m.tex_base) {
for k in 0..4 {
base[k] *= t[k];
}
}
// Mask mode tests the material's alpha (factor times texture) against the cutoff, and a
// fragment that passes keeps only the layer's opacity. Blend mode multiplies the two.
if m.alpha_mode == 1 && base[3] < m.alpha_cutoff {
return None;
}
let blend = m.alpha_mode > 1;
let alpha = if blend { base[3] * m.opacity } else { m.opacity };
if blend && alpha <= 1e-5 {
return None;
}
let rgb = [base[0], base[1], base[2]];
let mut emissive = m.emissive;
if let Some(t) = tex(m.tex_emissive) {
emissive = [emissive[0] * t[0], emissive[1] * t[1], emissive[2] * t[2]];
}
if m.shadows_only {
return Some(shadow_only(s, m, f, alpha));
}
if m.unlit || !m.accepts_lights || (s.lights.is_empty() && s.env.is_none() && s.ambient == [0.0; 3]) {
let c = add(rgb, emissive);
return Some([c[0] * alpha, c[1] * alpha, c[2] * alpha, alpha]);
}
let (mut metallic, mut rough) = (m.metallic, m.roughness);
if let Some(t) = tex(m.tex_mr) {
rough *= t[1];
metallic *= t[2];
}
let mut n = norm(f.normal);
if !f.front {
n = scale(n, -1.0);
}
// Shadow lookups follow the geometric surface, not the normal map.
let ng = n;
if let Some(t) = tex(m.tex_normal) {
let tn = [(t[0] * 2.0 - 1.0) * m.normal_scale, (t[1] * 2.0 - 1.0) * m.normal_scale, t[2] * 2.0 - 1.0];
let tg = [f.tangent[0], f.tangent[1], f.tangent[2]];
// Gram-Schmidt against the shading normal.
let tg = norm(sub(tg, scale(n, dot(n, tg))));
let sign = if f.front { f.tangent[3] } else { -f.tangent[3] };
let bt = scale(cross(n, tg), sign);
n = norm(add(add(scale(tg, tn[0]), scale(bt, tn[1])), scale(n, tn[2])));
}
let ao = match tex(m.tex_occlusion) {
Some(t) => 1.0 + m.occlusion_strength * (t[0] - 1.0),
None => 1.0,
};
let v = if s.ortho { scale(s.cam_fwd, -1.0) } else { norm_dir(s.eye, f.pos) };
let mut out = [0.0f32; 3];
for l in &s.lights {
let (to_l, dist) = to_light(l, f.pos);
let k = attenuation(l, f.pos, to_l, dist);
if k <= 0.0 {
continue;
}
let n_l = dot(n, to_l);
if n_l <= 0.0 {
continue;
}
let sh = if m.receives_shadows { light_shadow(s, l, f.pos, ng, n_l) } else { 1.0 };
let b = brdf(BrdfSurface { base: rgb, metallic, roughness: rough, specular: m.specular_k, diffuse: m.diffuse_k }, n, v, to_l);
for c in 0..3 {
out[c] += b[c] * l.color[c] * k * sh;
}
}
for c in 0..3 {
out[c] += s.ambient[c] * rgb[c] * m.ambient_k * ao;
}
if let Some(e) = &s.env {
let n_v = dot(n, v).clamp(1e-4, 1.0);
let r = sub(scale(n, 2.0 * dot(n, v)), v);
let (irr, spec) = env_light(s, e, n, r, rough);
let f0 = [mix(0.04 * m.specular_k, rgb[0], metallic), mix(0.04 * m.specular_k, rgb[1], metallic), mix(0.04 * m.specular_k, rgb[2], metallic)];
let (a, b) = env_brdf(n_v, rough);
// The environment light's shadow darkens its own diffuse and specular.
let sh = if m.receives_shadows { env_shadow(s, e, f.pos, ng, n) } else { 1.0 };
for c in 0..3 {
let fs = f0[c] * a + b;
out[c] += (irr[c] * rgb[c] * (1.0 - fs) * (1.0 - metallic) * m.diffuse_k + spec[c] * fs) * ao * sh;
}
}
let c = add(out, emissive);
Some([c[0] * alpha, c[1] * alpha, c[2] * alpha, alpha])
}
/// A material that draws only the shadows it receives: black at the strongest shadow any light
/// casts on the fragment, nothing where it is unshadowed, takes no lights or receives no shadows.
fn shadow_only(s: &Scene, m: &Material, f: &Frag, alpha: f32) -> [f32; 4] {
if m.unlit || !m.accepts_lights || !m.receives_shadows {
return [0.0; 4];
}
let n = if f.front { norm(f.normal) } else { scale(norm(f.normal), -1.0) };
let mut amount = 0.0f32;
for l in &s.lights {
let (to_l, dist) = to_light(l, f.pos);
if attenuation(l, f.pos, to_l, dist) <= 0.0 {
continue;
}
let n_l = dot(n, to_l);
if n_l <= 0.0 {
continue;
}
amount = amount.max(1.0 - light_shadow(s, l, f.pos, n, n_l));
}
// The environment light's shadow counts too (it reaches every surface: no falloff).
if let Some(e) = &s.env {
amount = amount.max(1.0 - env_shadow(s, e, f.pos, n, n));
}
[0.0, 0.0, 0.0, alpha * amount]
}
#[cfg(test)]
mod tests {
use super::{mix_levels, norm_dir, shadow_coord, shadow_factor, sub_f64, to_light};
use crate::scene::{Light, ShadowMap};
#[test]
fn overflowing_perspective_compare_preserves_slope_at_equal_depths() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let m = ShadowMap { view, focal: 16.0, ortho: false, size: 8, offset: 0, bias: 0.0, radius: 0.0 };
let wide = ShadowMap { focal: 1e20, ..m };
for normal in [[1.0, 0.0, -1.0], [-1.0, 0.0, -1.0], [0.0, 0.0, -1.0]] {
let expected = shadow_factor(&m, &[1.0; 64], [0.0, 0.0, 1.0], normal, 1.0);
for depth in [1e20, 1.001e20] {
let actual = shadow_factor(&wide, &[depth; 64], [0.0, 0.0, depth], normal, 1.0);
assert_eq!(actual, expected, "normal {normal:?}, depth {depth}");
}
}
}
#[test]
fn overflowing_perspective_compare_preserves_bias_at_equal_depths() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let m = ShadowMap { view, focal: 16.0, ortho: false, size: 8, offset: 0, bias: 8.0, radius: 0.0 };
let wide = ShadowMap { focal: 1e20, ..m };
for normal in [[1.0, 0.0, -1.0], [-1.0, 0.0, -1.0], [0.0, 0.0, -1.0]] {
let expected = shadow_factor(&m, &[1.0; 64], [0.0, 0.0, 1.0], normal, 1.0);
for depth in [1e20, 1.001e20] {
let actual = shadow_factor(&wide, &[depth; 64], [0.0, 0.0, depth], normal, 1.0);
assert_eq!(actual, expected, "normal {normal:?}, depth {depth}");
}
}
}
#[test]
fn overflowing_light_space_depth_preserves_biased_sloped_receivers() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0]];
let m = ShadowMap { view, focal: 16.0, ortho: false, size: 8, offset: 0, bias: 32.0, radius: 0.0 };
let p = [0.0, 0.0, 2e38];
assert_eq!(shadow_coord(&m, p).unwrap().2, f32::INFINITY);
for normal in [[1.0, 0.0, -1.0], [-1.0, 0.0, -1.0]] {
let expected = shadow_factor(&m, &[1.0; 64], [0.0, 0.0, 1.0], normal, 1.0);
assert_eq!(expected, 1.0);
assert_eq!(shadow_factor(&m, &[2e38; 64], p, normal, 1.0), expected, "normal {normal:?}");
}
}
#[test]
fn wide_shadow_comparisons_preserve_negative_infinity_occlusion() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let texels = [f32::NEG_INFINITY; 64];
for ortho in [true, false] {
let m = ShadowMap { view, focal: 16.0, ortho, size: 8, offset: 0, bias: 0.0, radius: 0.0 };
let wide = ShadowMap { focal: if ortho { f32::from_bits(1 << 19) } else { 1e20 }, ..m };
let depth = if ortho { 1.0 } else { 1e20 };
for normal in [[1.0, 0.0, -1.0], [-1.0, 0.0, -1.0], [0.0, 0.0, -1.0]] {
let expected = shadow_factor(&m, &[0.5; 64], [0.0, 0.0, 1.0], normal, 1.0);
let actual = shadow_factor(&wide, &texels, [0.0, 0.0, depth], normal, 1.0);
assert_eq!(actual, expected, "ortho {ortho}, normal {normal:?}");
}
}
}
#[test]
fn overflowing_footprints_preserve_populated_shadow_comparisons() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
for ortho in [true, false] {
for depth in [0.5, 2.0] {
let m = ShadowMap { view, focal: 1.0, ortho, size: 8, offset: 0, bias: 0.0, radius: 0.0 };
let texels = vec![depth; 64];
let expected = shadow_factor(&m, &texels, [0.0, 0.0, 1.0], [0.0, 0.0, -1.0], 1.0);
let wide = ShadowMap { focal: f32::from_bits(1 << 19), ..m };
assert_eq!(shadow_factor(&wide, &texels, [0.0, 0.0, 1.0], [0.0, 0.0, -1.0], 1.0), expected, "ortho {ortho}, depth {depth}");
}
}
}
#[test]
fn a_receiver_whose_projection_overflows_f32_is_projected_in_f64() {
// 1e37 × 400 overflows f32; divided by the depth of 1e38 it is 40 texels from the center.
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let m = ShadowMap { view, focal: 400.0, ortho: false, size: 512, offset: 0, bias: 1.5, radius: 1.0 };
let (u, v, z) = shadow_coord(&m, [1e37, 0.0, 1e38]).unwrap_or((f32::NAN, f32::NAN, f32::NAN));
assert!((u - 296.0).abs() < 1e-3 && v == 256.0 && z == 1e38, "{u} {v} {z}");
}
#[test]
fn mip_levels_far_apart_mix_without_nan() {
assert_eq!(mix_levels(3e38, -3e38, 0.0), 3e38);
assert_eq!(mix_levels(3e38, -3e38, 1.0), -3e38);
assert_eq!(mix_levels(3e38, -3e38, 0.5), 0.0);
}
#[test]
fn directions_between_far_apart_points_are_taken_in_f64() {
let l = Light {
kind: 2,
pos: [2e38, 0.0, 0.0],
dir: [0.0, 0.0, 1.0],
color: [1.0; 3],
cos_inner: 1.0,
cos_outer: 1.0,
falloff: 0,
radius: 0.0,
falloff_distance: 0.0,
shadow: -1,
shadow_darkness: 1.0,
shadow_diffusion: 0.0,
};
assert_eq!(to_light(&l, [-2e38, 0.0, 0.0]), ([1.0, 0.0, 0.0], f32::INFINITY));
assert_eq!(norm_dir([0.0, 2e38, 0.0], [0.0, -2e38, 0.0]), [0.0, 1.0, 0.0]);
assert_eq!(sub_f64([-2e38, 0.0, 0.0], [2e38, 0.0, 0.0])[0], -2.0 * f64::from(2e38f32));
}
}
+662
View File
@@ -0,0 +1,662 @@
//! Shadow maps: per-light sizing within a scene-wide texel budget, the light-space depth
//! rasterizer and the environment light's orthographic map.
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use rayon::prelude::*;
use crate::raster::f32_crossing;
use crate::scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo, unit, validate};
use crate::shade::sample;
use crate::{Limits, RenderError};
/// Hard cap on the shadow depth texels (`f32`) of one scene, about 104 MB. It holds one point
/// light's full 2048-texel cube (6 × 2048² ≈ 25.2 M texels).
pub const MAX_SHADOW_TEXELS: u64 = 26_000_000;
fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn len3(a: [f64; 3]) -> f64 {
dot3(a, a).sqrt()
}
/// `a / |a|`, or `a` unchanged when its length is 0.
fn normalize3(a: [f64; 3]) -> [f64; 3] {
let l = len3(a);
if l > 0.0 { a.map(|v| v / l) } else { a }
}
fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn scale3(a: [f64; 3], k: f64) -> [f64; 3] {
a.map(|v| v * k)
}
/// The first three rows of the world → light transform looking from `eye` along `fwd`, with
/// `down` as the +y axis's hint: rows right, down and forward (orthonormal), applied after a
/// translation by −`eye`. A zero `fwd` looks along +z; a `down` along `fwd` is replaced by +y,
/// or by −z when `fwd` is near vertical.
fn basis(eye: [f64; 3], fwd: [f64; 3], down: [f64; 3]) -> [[f32; 4]; 3] {
let f = normalize3(fwd);
let f = if len3(f) == 0.0 { [0.0, 0.0, 1.0] } else { f };
let mut d = sub3(down, scale3(f, dot3(down, f)));
if len3(d) < 1e-9 {
d = if f[1].abs() < 0.99 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, -1.0] };
d = sub3(d, scale3(f, dot3(d, f)));
}
let d = normalize3(d);
let r = normalize3(cross3(d, f));
let rot = [[r[0], r[1], r[2], 0.0], [d[0], d[1], d[2], 0.0], [f[0], f[1], f[2], 0.0], [0.0, 0.0, 0.0, 1.0]];
let mut tr = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
tr[0][3] = -eye[0];
tr[1][3] = -eye[1];
tr[2][3] = -eye[2];
let mut m = [[0.0f64; 4]; 4];
for i in 0..4 {
for j in 0..4 {
m[i][j] = (0..4).map(|k| rot[i][k] * tr[k][j]).sum();
}
}
[0, 1, 2].map(|r| m[r].map(|v| v as f32))
}
/// Light-space near plane of a perspective shadow map. Casters are clipped against it, and the
/// shader does not shadow a receiver at this depth or nearer.
pub(crate) const NEAR: f32 = 1e-3;
/// A caster's corner in light space with its texture coordinates.
type LightCorner = ([f32; 3], [f32; 2]);
/// A corner on the map: (x, y), 1/z (1 for an orthographic map), depth and texture coordinates.
type MapCorner = ([f64; 2], f32, f32, [f32; 2]);
/// Triangle `t`'s corners in `m`'s light space, clipped against the near plane for a
/// perspective map.
fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec<LightCorner> {
let q: Vec<LightCorner> = ids
.iter()
.map(|&i| {
let p = s.vertices[i].pos;
let v = &m.view;
([0, 1, 2].map(|r| v[r][0] * p[0] + v[r][1] * p[1] + v[r][2] * p[2] + v[r][3]), s.vertices[i].uv)
})
.collect();
let mut poly = q;
if !m.ortho {
let mut out = vec![];
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
let (da, db) = (a.0[2] - NEAR, b.0[2] - NEAR);
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let (from_b, k) = f32_crossing(da, db);
let (p, q) = if from_b { (b, a) } else { (a, b) };
let lerp = |x: f32, y: f32| {
let d = y - x;
if d.is_finite() || !x.is_finite() || !y.is_finite() {
x + d * k
} else {
(f64::from(x) + (f64::from(y) - f64::from(x)) * f64::from(k)) as f32
}
};
// The crossing lies on the near plane; its depth is set to it, since the lerp of
// far-apart depths can round to 0 or below.
out.push(([lerp(p.0[0], q.0[0]), lerp(p.0[1], q.0[1]), NEAR], [lerp(p.1[0], q.1[0]), lerp(p.1[1], q.1[1])]));
}
}
poly = out;
}
poly
}
/// The light-space polygon on `m`'s texels.
fn map_corners(m: &ShadowMap, poly: &[LightCorner]) -> Vec<MapCorner> {
let c = m.size as f32 * 0.5;
// A finite coordinate whose product with the focal length overflows f32 is projected in f64.
let at = |x: f32, z: f32, fast: f32| {
if fast.is_finite() || !x.is_finite() { f64::from(fast) } else { f64::from(x) * f64::from(m.focal) / f64::from(z) + f64::from(c) }
};
poly.iter()
.map(|(p, uv)| {
if m.ortho {
([at(p[0], 1.0, p[0] * m.focal + c), at(p[1], 1.0, p[1] * m.focal + c)], 1.0, p[2], *uv)
} else {
let iz = 1.0 / p[2];
([at(p[0], p[2], p[0] * m.focal * iz + c), at(p[1], p[2], p[1] * m.focal * iz + c)], iz, p[2], *uv)
}
})
.collect()
}
/// A caster's alpha test: the base texture and the factor its alpha is multiplied by (the
/// material's base alpha times the opacity, or the base alpha alone for a masked caster). A texel
/// is skipped when its alpha is below `cutoff`.
struct AlphaTest<'a> {
tex: &'a TexInfo,
factor: f32,
cutoff: f32,
}
/// The opacity a caster's material alpha is multiplied by and the cutoff it is tested against: a
/// masked caster tests the material's alpha against its cutoff, as shading does; a blended one
/// tests its alpha times the opacity against 0.5.
fn caster_alpha(mat: &Material) -> (f32, f32) {
if mat.alpha_mode == 1 { (1.0, mat.alpha_cutoff) } else { (mat.opacity, 0.5) }
}
/// Whether a caster of material `mat` casts nothing whatever its texels: a masked or blended
/// caster without a base texture has one alpha, tested as a texel's alpha is; a masked or blended
/// caster with a base texture and a factor of 0 fails a cutoff above 0 at every texel; and an
/// opaque-mode or masked caster draws with its opacity alone, tested as a blended caster's alpha
/// is.
fn casts_nothing(mat: &Material) -> bool {
let (opacity, cutoff) = caster_alpha(mat);
let factor = mat.base[3] * opacity;
let alpha_fails = if mat.tex_base < 0 { factor < cutoff } else { factor == 0.0 && cutoff > 0.0 };
(mat.alpha_mode != 0 && alpha_fails) || (mat.alpha_mode != 2 && mat.opacity < 0.5)
}
/// Texture coordinate `i` at the barycentric weights `l` of map triangle `tri`, perspective
/// correct with depth `z` on a perspective map. A sum that overflows `f32` (a large coordinate
/// times a corner's 1/depth) is taken in `f64` and kept within `f32`'s range, so the sample
/// reduces it by its wrap period.
fn caster_uv(tri: &[MapCorner; 3], l: [f32; 3], z: f32, i: usize, ortho: bool) -> f32 {
let u = if ortho {
l[0] * tri[0].3[i] + l[1] * tri[1].3[i] + l[2] * tri[2].3[i]
} else {
(l[0] * tri[0].3[i] * tri[0].1 + l[1] * tri[1].3[i] * tri[1].1 + l[2] * tri[2].3[i] * tri[2].1) * z
};
if u.is_finite() {
return u;
}
let (iz, z) = if ortho { ([1.0; 3], 1.0) } else { ([tri[0].1, tri[1].1, tri[2].1].map(f64::from), f64::from(z)) };
let sum: f64 = (0..3).map(|k| f64::from(l[k]) * f64::from(tri[k].3[i]) * iz[k]).sum();
(sum * z).clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
}
impl AlphaTest<'_> {
fn discards(&self, a: f32) -> bool {
a < self.cutoff
}
}
/// A map triangle's signed area and the texels of `m` inside its bounding box (`x0..x1`,
/// `y0..y1`), or `None` when its area is too small to rasterize.
fn texel_bounds(m: &ShadowMap, tri: &[MapCorner; 3]) -> Option<(f64, [usize; 4])> {
let n = m.size as usize;
let (a, b, cc) = (tri[0].0, tri[1].0, tri[2].0);
let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]);
if area.abs() < 1e-12 {
return None;
}
let x0 = a[0].min(b[0]).min(cc[0]).floor().max(0.0) as usize;
let x1 = (a[0].max(b[0]).max(cc[0]).ceil().max(0.0) as usize).min(n);
let y0 = a[1].min(b[1]).min(cc[1]).floor().max(0.0) as usize;
let y1 = (a[1].max(b[1]).max(cc[1]).ceil().max(0.0) as usize).min(n);
Some((area, [x0, x1, y0, y1]))
}
/// Rasterize one map triangle's nearest depth into `d` (`n × n` texels).
fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option<&AlphaTest>, d: &mut [f32]) {
let n = m.size as usize;
let (a, b, cc) = (tri[0].0, tri[1].0, tri[2].0);
let Some((area, [x0, x1, y0, y1])) = texel_bounds(m, &tri) else { return };
let wide_depth = !m.ortho && tri.iter().any(|c| c.1.is_subnormal());
for y in y0..y1 {
for x in x0..x1 {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let e0 = ((cc[0] - b[0]) * (py - b[1]) - (cc[1] - b[1]) * (px - b[0])) / area;
let e1 = ((a[0] - cc[0]) * (py - cc[1]) - (a[1] - cc[1]) * (px - cc[0])) / area;
let e2 = 1.0 - e0 - e1;
if e0 < 0.0 || e1 < 0.0 || e2 < 0.0 {
continue;
}
let l = [e0 as f32, e1 as f32, e2 as f32];
let z = if m.ortho {
l[0] * tri[0].2 + l[1] * tri[1].2 + l[2] * tri[2].2
} else if wide_depth {
(1.0 / (e0 / f64::from(tri[0].2) + e1 / f64::from(tri[1].2) + e2 / f64::from(tri[2].2))) as f32
} else {
1.0 / (l[0] * tri[0].1 + l[1] * tri[1].1 + l[2] * tri[2].1)
};
let px = &mut d[y * n + x];
if z >= *px {
continue;
}
let uv = [0, 1].map(|i| caster_uv(&tri, l, z, i, m.ortho));
if let Some(t) = alpha
&& t.discards(sample(t.tex, &s.texels, uv[0], uv[1])[3] * t.factor)
{
continue;
}
*px = z;
}
}
}
/// The texels of `m` inside a map triangle's bounding box, as [`raster_triangle`] visits them.
fn triangle_texels(m: &ShadowMap, tri: [MapCorner; 3]) -> u64 {
let Some((_, [x0, x1, y0, y1])) = texel_bounds(m, &tri) else { return 0 };
(x1.saturating_sub(x0) as u64).saturating_mul(y1.saturating_sub(y0) as u64)
}
/// The depth tests rendering `maps` takes: one per caster and map, plus each map triangle's
/// bounding-box texels. When the casters times the maps already exceed `limit`, that product.
/// The maps are counted on several threads into one total, and each stops at the first caster
/// after the total passes `limit`. Returns [`RenderError::BadShadowInputs`] when the total stays
/// within `limit` and a caster's corners in a map are not finite, since the rasterizer would skip
/// that caster.
fn shadow_work(s: &Scene, maps: &[ShadowMap], casters: &[usize], limit: u64) -> Result<u64, RenderError> {
let pairs = (maps.len() as u64).saturating_mul(casters.len() as u64);
if pairs > limit {
return Ok(pairs);
}
let finite = |c: &MapCorner| c.0.iter().all(|v| v.is_finite()) && c.1.is_finite() && c.2.is_finite();
let total = AtomicU64::new(0);
let not_finite = AtomicBool::new(false);
maps.par_iter().for_each(|m| {
for &t in casters {
if total.load(Ordering::Relaxed) > limit {
return;
}
let ids = [s.indices[3 * t] as usize, s.indices[3 * t + 1] as usize, s.indices[3 * t + 2] as usize];
// A caster that casts nothing is not projected, as the rasterizer skips it.
let poly = if casts_nothing(&s.materials[s.vertices[ids[0]].material as usize]) { Vec::new() } else { light_poly(s, m, ids) };
let mut cost = 1u64;
if poly.len() >= 3 {
let scr = map_corners(m, &poly);
if scr.iter().all(finite) {
cost = (1..scr.len() - 1).fold(cost, |acc, k| acc.saturating_add(triangle_texels(m, [scr[0], scr[k], scr[k + 1]])));
} else {
not_finite.store(true, Ordering::Relaxed);
}
}
let mut seen = total.load(Ordering::Relaxed);
while let Err(now) = total.compare_exchange_weak(seen, seen.saturating_add(cost), Ordering::Relaxed, Ordering::Relaxed) {
seen = now;
}
}
});
let total = total.into_inner();
if total <= limit && not_finite.into_inner() { Err(RenderError::BadShadowInputs) } else { Ok(total) }
}
/// Rasterize the shadow-casting triangles' light-space depth into `m`'s texels.
fn shadow_raster(s: &Scene, m: &ShadowMap, casters: &[usize]) -> Vec<f32> {
let n = m.size as usize;
let mut d = vec![f32::INFINITY; n * n];
for &t in casters {
let ids = [s.indices[3 * t] as usize, s.indices[3 * t + 1] as usize, s.indices[3 * t + 2] as usize];
let mat = &s.materials[s.vertices[ids[0]].material as usize];
if casts_nothing(mat) {
continue;
}
let (opacity, cutoff) = caster_alpha(mat);
let alpha = (mat.alpha_mode != 0 && mat.tex_base >= 0).then(|| AlphaTest {
tex: &s.textures[mat.tex_base as usize],
factor: mat.base[3] * opacity,
cutoff,
});
let poly = light_poly(s, m, ids);
if poly.len() < 3 {
continue;
}
let scr = map_corners(m, &poly);
for k in 1..scr.len() - 1 {
raster_triangle(s, m, [scr[0], scr[k], scr[k + 1]], alpha.as_ref(), &mut d);
}
}
d
}
/// Long side of a quality shadow map: one map texel per pixel of the `width × height` raster
/// (the supersampled size when the scene is supersampled), to a power of two,
/// clamped to 512..4096. Draft renders keep a flat 512.
pub fn shadow_map_size(width: u32, height: u32, draft: bool) -> u32 {
if draft {
return 512;
}
let side = width.max(height).clamp(512, 4096);
let mut size = 512u32;
while size < side {
size *= 2;
}
size
}
/// Per-face size of a point light's cube map: the full map size, capped at 2048 so one cube fits
/// [`MAX_SHADOW_TEXELS`]. Draft renders take half the map size.
pub fn shadow_point_face_size(size: u32, draft: bool) -> u32 {
if draft { (size / 2).max(1) } else { size.min(2048) }
}
/// Per-light map sizes (`None` = this light gets no shadow map). `kinds`: 0 = no shadows (costs
/// nothing), 1 = single map (spot or parallel), 2 = cube (a point light, or a spot light wider
/// than one map; budgeted as its six faces).
/// Lights start at their full size; while the scene exceeds [`MAX_SHADOW_TEXELS`] the largest
/// map above its floor (512, or 128 for a cube face) is halved, the earliest light first on
/// ties, and once every light is at its floor the last lights lose their shadows. Deterministic,
/// and O(n log n) in the light count.
pub fn shadow_sizes(width: u32, height: u32, draft: bool, kinds: &[u32]) -> Vec<Option<u32>> {
let base = shadow_map_size(width, height, draft);
let faces = |k: u32| -> u64 { if k == 2 { 6 } else { 1 } };
let floor = |k: u32| -> u32 { if k == 2 { 128 } else { 512 } };
let mut sizes: Vec<u32> = kinds
.iter()
.map(|&k| match k {
0 => 0,
2 => shadow_point_face_size(base, draft),
_ => base,
})
.collect();
let cost = |z: u32, k: u32| -> u64 { (z as u64) * (z as u64) * faces(k) };
let mut total: u64 = sizes.iter().zip(kinds).map(|(&z, &k)| cost(z, k)).sum();
// Largest size first, then the lowest index.
let mut heap: BinaryHeap<(u32, Reverse<usize>)> =
sizes.iter().zip(kinds).enumerate().filter(|(_, (z, k))| **z > floor(**k)).map(|(i, (&z, _))| (z, Reverse(i))).collect();
while total > MAX_SHADOW_TEXELS {
let Some((z, Reverse(i))) = heap.pop() else { break };
let k = kinds[i];
total -= cost(z, k) - cost(z / 2, k);
sizes[i] = z / 2;
if z / 2 > floor(k) {
heap.push((z / 2, Reverse(i)));
}
}
for i in (0..sizes.len()).rev() {
if total <= MAX_SHADOW_TEXELS {
break;
}
total -= cost(sizes[i], kinds[i]);
sizes[i] = 0;
}
sizes.into_iter().map(|z| (z > 0).then_some(z)).collect()
}
/// The environment light's shadow map: one orthographic map of `size` texels over the sphere at
/// `centre` with `radius`, seen from the environment's dominant direction `e.sun` (the light
/// travels from the bright region into the scene). Its penumbra is at least eight output
/// pixels, or four map texels where those are coarser, plus half the light's shadow diffusion
/// up to 24 pixels.
///
/// Returns [`RenderError::BadShadowInputs`] for a zero size, a radius that is not positive and
/// finite, a center that is not finite, a direction whose length differs from 1 by more than
/// 0.001, a shadow diffusion that is negative or not finite, or inputs whose map would hold a
/// value that is not finite in `f32`.
pub fn try_env_shadow_map(e: EnvInfo, centre: [f64; 3], radius: f64, size: u32) -> Result<ShadowMap, RenderError> {
let ok = size > 0
&& radius.is_finite()
&& radius > 0.0
&& centre.iter().all(|v| v.is_finite())
&& unit(&e.sun)
&& e.shadow_diffusion.is_finite()
&& e.shadow_diffusion >= 0.0;
if !ok {
return Err(RenderError::BadShadowInputs);
}
let m = env_shadow_map(e, centre, radius, size);
if !(m.focal.is_finite() && m.focal > 0.0 && m.radius.is_finite() && m.view.iter().flatten().all(|v| v.is_finite())) {
return Err(RenderError::BadShadowInputs);
}
Ok(m)
}
fn env_shadow_map(e: EnvInfo, centre: [f64; 3], radius: f64, size: u32) -> ShadowMap {
let texel = 2.0 * radius / size as f64;
let soft = (4.0 * texel).max(8.0) + (e.shadow_diffusion as f64 * 0.5).min(24.0);
let sun = e.sun.map(|v| v as f64);
let dir = [-sun[0], -sun[1], -sun[2]];
let eye = [centre[0] + sun[0] * radius * 2.0, centre[1] + sun[1] * radius * 2.0, centre[2] + sun[2] * radius * 2.0];
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
let focal = (size as f64 * 0.5 / radius) as f32;
ShadowMap { view: basis(eye, dir, hint), focal, ortho: true, size, offset: 0, bias: 1.5, radius: soft as f32 }
}
/// The triangles whose material casts shadows.
fn caster_list(s: &Scene) -> Vec<usize> {
(0..s.indices.len() / 3)
.filter(|&t| s.materials.get(s.vertices[s.indices[3 * t] as usize].material as usize).is_some_and(|m| m.casts_shadows))
.collect()
}
/// The bounding sphere of the scene's vertices: (center, radius + 1).
fn bounding_sphere(s: &Scene) -> ([f64; 3], f64) {
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for v in &s.vertices {
for k in 0..3 {
lo[k] = lo[k].min(v.pos[k] as f64);
hi[k] = hi[k].max(v.pos[k] as f64);
}
}
let centre = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
(centre, radius)
}
/// The widest half angle, in radians, that one spot light map covers (about 83°).
const MAX_SPOT_HALF_ANGLE: f64 = 1.45;
/// The half angle a spot light's map covers: the outer cone's half angle plus 0.05 radians.
fn spot_half_angle(l: &Light) -> f64 {
l.cos_outer.clamp(-1.0, 1.0).acos() as f64 + 0.05
}
/// Whether light `l` has a cube of six maps instead of one map: a point light, or a spot light
/// whose cone with its margin is wider than one map covers.
pub(crate) fn cube_maps(l: &Light) -> bool {
l.kind == 2 || (l.kind == 1 && spot_half_angle(l) > MAX_SPOT_HALF_ANGLE)
}
/// The maps of light `li` at `size`, appended to `maps`.
fn light_maps(s: &Scene, li: usize, size: u32, sphere: ([f64; 3], f64), maps: &mut Vec<ShadowMap>) {
let (centre, radius) = sphere;
let l = s.lights[li];
// Penumbra width in output pixels; the sampling bias is independent of it.
let soft = 1.0 + (l.shadow_diffusion * 0.5).min(24.0);
let pos = l.pos.map(|v| v as f64);
let dir = l.dir.map(|v| v as f64);
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
match l.kind {
0 => {
let eye = [centre[0] - dir[0] * radius * 2.0, centre[1] - dir[1] * radius * 2.0, centre[2] - dir[2] * radius * 2.0];
let focal = (size as f64 * 0.5 / radius) as f32;
maps.push(ShadowMap { view: basis(eye, dir, hint), focal, ortho: true, size, offset: 0, bias: 1.5, radius: soft });
}
1 if !cube_maps(&l) => {
let half = spot_half_angle(&l);
let focal = (size as f64 * 0.5 / half.tan()) as f32;
maps.push(ShadowMap { view: basis(pos, dir, hint), focal, ortho: false, size, offset: 0, bias: 1.5, radius: soft });
}
_ => {
let fs = size;
for (f, d) in [
([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
] {
maps.push(ShadowMap { view: basis(pos, f, d), focal: fs as f32 * 0.5, ortho: false, size: fs, offset: 0, bias: 1.5, radius: soft });
}
}
}
}
/// Render the shadow maps of every shadow-casting light (lights whose `shadow` is 0 or more),
/// and of the environment light when it casts shadows and has a dominant direction
/// (`env.shadow` 0 or more, `env.sun != [0; 3]`): one orthographic map from that direction over
/// the scene's bounding sphere, after the lights' maps. Map sizes come from [`shadow_sizes`] at
/// the scene's raster size. Each light's `shadow` becomes the index of its first map, or −1 when
/// it gets none; with no shadow-casting triangle, every mark is cleared.
///
/// [`Scene::shadows`] and [`Scene::shadow_texels`] are replaced, and the indices a call writes
/// request the same maps again, so a second call gives the same maps and marks. The scene is
/// checked first, as for [`crate::try_render`], and the depth tests the maps take (one per
/// caster and map, plus each caster's bounding box in each map) are limited by
/// [`Limits::max_work`]. On an error the scene is left as it was.
pub fn try_shadow_maps(s: &mut Scene, draft: bool, limits: &Limits) -> Result<(), RenderError> {
validate(s, limits)?;
let marks = (s.lights.clone(), s.env);
let result = shadow_maps_checked(s, draft, limits);
if result.is_err() {
(s.lights, s.env) = marks;
}
result
}
fn shadow_maps_checked(s: &mut Scene, draft: bool, limits: &Limits) -> Result<(), RenderError> {
let casters = caster_list(s);
// The environment light casts a shadow when marked and its image has a dominant direction;
// with nothing to cast one, its mark is cleared either way.
let env_shadow = !casters.is_empty() && s.env.is_some_and(|e| e.shadow >= 0 && e.sun != [0.0; 3]);
if !env_shadow && let Some(e) = &mut s.env {
e.shadow = -1;
}
if casters.is_empty() {
for l in &mut s.lights {
l.shadow = -1;
}
s.shadows.clear();
s.shadow_texels.clear();
return Ok(());
}
let sphere = bounding_sphere(s);
let kinds: Vec<u32> = s
.lights
.iter()
.map(|l| {
if l.shadow < 0 {
0
} else if cube_maps(l) {
2
} else {
1
}
})
// The environment light's map is a single orthographic one.
.chain(std::iter::once(if env_shadow { 1 } else { 0 }))
.collect();
let sizes = shadow_sizes(s.width, s.height, draft, &kinds);
let mut maps: Vec<ShadowMap> = vec![];
for li in 0..s.lights.len() {
let Some(size) = sizes.get(li).copied().flatten() else {
s.lights[li].shadow = -1;
continue;
};
if s.lights[li].shadow < 0 {
s.lights[li].shadow = -1;
continue;
}
let first = maps.len() as i32;
light_maps(s, li, size, sphere, &mut maps);
s.lights[li].shadow = first;
}
if env_shadow && let Some(e) = s.env {
match sizes.get(s.lights.len()).copied().flatten() {
Some(size) => {
let first = maps.len() as i32;
maps.push(env_shadow_map(e, sphere.0, sphere.1, size));
if let Some(e) = &mut s.env {
e.shadow = first;
}
}
// The texel budget dropped it.
None => {
if let Some(e) = &mut s.env {
e.shadow = -1;
}
}
}
}
// Finite vertices far from the origin can still give a view that does not fit f32.
let usable = |m: &ShadowMap| m.focal.is_finite() && m.focal > 0.0 && m.radius.is_finite() && m.view.iter().flatten().all(|v| v.is_finite());
if !maps.iter().all(usable) {
return Err(RenderError::BadShadowInputs);
}
let needed = shadow_work(s, &maps, &casters, limits.max_work)?;
if needed > limits.max_work {
return Err(RenderError::TooMuchWork { needed, limit: limits.max_work });
}
let texels: Vec<Vec<f32>> = maps.par_iter().map(|m| shadow_raster(s, m, &casters)).collect();
let mut all = Vec::with_capacity(texels.iter().map(Vec::len).sum());
for (m, t) in maps.iter_mut().zip(texels) {
m.offset = u32::try_from(all.len()).map_err(|_| RenderError::TooManyShadowTexels)?;
all.extend(t);
}
s.shadows = maps;
s.shadow_texels = all;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{NEAR, light_poly, shadow_raster};
use crate::{Material, Scene, ShadowMap, TexInfo, Vertex};
fn perspective_map() -> ShadowMap {
ShadowMap {
view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
focal: 4.0,
ortho: false,
size: 8,
offset: 0,
bias: 0.0,
radius: 0.0,
}
}
#[test]
fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() {
for z in [1e38, f32::MAX] {
let s = Scene {
vertices: [[-0.25 * z, -0.25 * z, z], [0.25 * z, -0.25 * z, z], [0.0, 0.25 * z, z]]
.map(|pos| Vertex { pos, ..Vertex::default() })
.to_vec(),
indices: vec![0, 1, 2],
materials: vec![Material::default()],
..Scene::default()
};
let depths = shadow_raster(&s, &perspective_map(), &[0]);
assert!(depths[3 * 8 + 3].is_finite(), "caster depth {z}");
assert!(depths.iter().filter(|d| d.is_finite()).all(|&d| d == z));
}
}
#[test]
fn clipped_caster_uvs_with_overflowing_differences_keep_the_alpha_test() {
let covered = |u: f32, alphas: [f32; 2], indices: Vec<u32>| {
let s = Scene {
vertices: [([-NEAR, 0.0, 0.0], u), ([NEAR, -NEAR, 2.0 * NEAR], -u), ([NEAR, NEAR, 2.0 * NEAR], -u)]
.map(|(pos, u)| Vertex { pos, uv: [u, 0.5], ..Vertex::default() })
.to_vec(),
indices,
materials: vec![Material { alpha_mode: 1, tex_base: 0, ..Material::default() }],
textures: vec![TexInfo { width: 2, height: 1, wrap_u: 1, wrap_v: 1, ..TexInfo::default() }],
texels: alphas.map(|a| [1.0, 1.0, 1.0, a]).to_vec(),
..Scene::default()
};
let map = perspective_map();
let ids = [s.indices[0] as usize, s.indices[1] as usize, s.indices[2] as usize];
assert!(light_poly(&s, &map, ids).iter().all(|(_, uv)| uv.iter().all(|u| u.is_finite())));
shadow_raster(&s, &map, &[0]).iter().filter(|d| d.is_finite()).count()
};
for indices in [vec![0, 1, 2], vec![0, 2, 1]] {
assert!(covered(f32::MAX, [1.0; 2], indices.clone()) > 0);
assert_eq!(covered(1e20, [0.0, 1.0], indices.clone()), 0);
assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0);
}
}
}
File diff suppressed because it is too large. Load diff
+118
View File
@@ -0,0 +1,118 @@
//! This crate against the app's previous code (`crate::reference`), on the same scenes. For the
//! scenes in this module, every shadow texel, raster pixel, depth, resolved pixel and encoded
//! pixel matches bit for bit; the README's Origin section lists the scenes that differ. Each test
//! prints the 64-bit FNV-1a hash of each output from both sides.
use craft_raster3d::{Limits, Scene, try_encode, try_render, try_render_cpu, try_resolve, try_shadow_maps};
use crate::reference::effectcraft as ec;
use crate::{bits, bits4, fnv, lit_scene, quad_scene};
/// Runs both sides on `scene`: shadow maps (when `shadows`), the raster, the resolve and the
/// encoding, and asserts that every output matches bit for bit.
fn compare(name: &str, scene: &Scene, shadows: Option<bool>) {
let (mut ours, mut theirs) = (scene.clone(), scene.clone());
if let Some(draft) = shadows {
try_shadow_maps(&mut ours, draft, &Limits::default()).unwrap();
ec::raster::shadow_maps(&mut theirs, draft);
assert_eq!(ours.shadows, theirs.shadows, "{name}: shadow maps");
assert_eq!(bits(&ours.shadow_texels), bits(&theirs.shadow_texels), "{name}: shadow texels");
assert_eq!(ours.lights, theirs.lights, "{name}: light marks");
assert_eq!(ours.env, theirs.env, "{name}: environment mark");
println!("{name} shadow texels: ours {:016x} theirs {:016x}", fnv(&[], &ours.shadow_texels), fnv(&[], &theirs.shadow_texels));
}
let t = try_render(&ours, &Limits::default()).unwrap();
let r = ec::raster::render(&theirs);
assert_eq!((t.width, t.height), (r.width, r.height));
assert_eq!(bits4(&t.color), bits4(&r.color), "{name}: raster color");
assert_eq!(bits(&t.depth), bits(&r.depth), "{name}: raster depth");
println!("{name} raster: ours {:016x} theirs {:016x}", fnv(&t.color, &t.depth), fnv(&r.color, &r.depth));
let k = ours.ssaa.max(1);
let (img, depth) = try_resolve(&t, k).unwrap();
let (rimg, rdepth) = ec::resolve(&r, k);
assert_eq!((img.width, img.height), (rimg.width, rimg.height));
assert_eq!(bits4(&img.data), bits4(&rimg.data), "{name}: resolved color");
assert_eq!(bits(&depth), bits(&rdepth), "{name}: resolved depth");
let (cpu, cpu_depth) = try_render_cpu(&ours, &Limits::default()).unwrap();
let (rcpu, rcpu_depth) = ec::render_cpu(&theirs);
assert_eq!(bits4(&cpu.data), bits4(&rcpu.data), "{name}: render_cpu color");
assert_eq!(bits(&cpu_depth), bits(&rcpu_depth), "{name}: render_cpu depth");
println!("{name} resolved: ours {:016x} theirs {:016x}", fnv(&img.data, &depth), fnv(&rimg.data, &rdepth));
let (mut enc, mut renc) = (img, rimg);
try_encode(&mut enc).unwrap();
ec::encode(&mut renc);
assert_eq!(bits4(&enc.data), bits4(&renc.data), "{name}: encoded");
println!("{name} encoded: ours {:016x} theirs {:016x}", fnv(&enc.data, &[]), fnv(&renc.data, &[]));
}
#[test]
fn quad_scenes_match_the_previous_renderer() {
let red = [1.0, 0.0, 0.0, 1.0];
let blue = [0.0, 0.0, 1.0, 1.0];
compare("overlap", &quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)]), None);
compare("half-alpha quad", &quad_scene(32, 32, &[([4.0, 4.0, 20.0, 12.0], 10.0, [1.0, 1.0, 1.0, 0.5])]), None);
compare(
"two transparent layers",
&quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], 50.0, [0.0, 0.0, 1.0, 0.5])]),
None,
);
// Quads reaching past the viewport (inside the guard band) and one off it.
compare(
"past the edges",
&quad_scene(
24,
16,
&[([-30.0, -5.0, 10.0, 40.0], 300.0, red), ([5.0, 3.0, 90.0, 12.0], 200.0, [0.0, 1.0, 0.0, 0.5]), ([30.0, 0.0, 40.0, 8.0], 1.0, blue)],
),
None,
);
}
/// The lit scene covers over a quarter of the pixels in more than 100 colors, with shadow-map texels covered by
/// casters, so a match is not a match of empty outputs.
fn assert_drawn(s: &Scene, draft: bool) {
let mut s = s.clone();
try_shadow_maps(&mut s, draft, &Limits::default()).unwrap();
assert!(s.shadow_texels.iter().filter(|t| t.is_finite()).count() > 1000);
let t = try_render(&s, &Limits::default()).unwrap();
let covered = t.color.iter().filter(|c| c[3] > 0.0).count();
assert!(covered * 4 > t.color.len(), "covered {covered} of {}", t.color.len());
let mut colors: Vec<[u32; 4]> = bits4(&t.color);
colors.sort_unstable();
colors.dedup();
assert!(colors.len() > 100, "{} colors", colors.len());
}
#[test]
fn lit_perspective_scene_matches_the_previous_renderer() {
assert_drawn(&lit_scene((48, 36), 1, false), false);
compare("lit perspective", &lit_scene((48, 36), 1, false), Some(false));
}
#[test]
fn lit_supersampled_scene_matches_the_previous_renderer() {
compare("lit perspective 2x2", &lit_scene((32, 24), 2, false), Some(false));
}
#[test]
fn lit_orthographic_draft_scene_matches_the_previous_renderer() {
assert_drawn(&lit_scene((40, 30), 1, true), true);
compare("lit orthographic draft", &lit_scene((40, 30), 1, true), Some(true));
}
#[test]
fn lit_scene_without_shadow_maps_matches_the_previous_renderer() {
// No maps: every mark is −1, as the app sets them when shadows are off.
let mut s = lit_scene((40, 30), 1, false);
s.env.as_mut().unwrap().shadow = -1;
for l in &mut s.lights {
l.shadow = -1;
}
compare("lit without maps", &s, None);
for m in &mut s.materials {
m.casts_shadows = false;
}
// No casters, with every light and the environment light marked 0: every mark is cleared.
let s = Scene { materials: s.materials, ..lit_scene((40, 30), 1, false) };
compare("lit without casters", &s, Some(false));
}
+229
View File
@@ -0,0 +1,229 @@
//! Integration tests: one test binary for the crate, one module per area.
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod bounds;
mod differential;
mod moved;
/// A verbatim copy of the app's previous code, run by `differential`.
mod reference {
pub mod effectcraft;
}
use craft_raster3d::{EnvInfo, Light, Limits, Material, Scene, TexInfo, Vertex};
/// The default limits with `f` applied.
pub fn limits(f: impl FnOnce(&mut Limits)) -> Limits {
let mut l = Limits::default();
f(&mut l);
l
}
/// A scene of axis-aligned quads (z = camera depth) seen by an orthographic identity camera
/// mapping world x/y straight to raster pixels.
pub fn quad_scene(w: u32, h: u32, quads: &[([f32; 4], f32, [f32; 4])]) -> Scene {
let mut s = Scene { width: w, height: h, ssaa: 1, linear_io: true, ..Scene::default() };
// clip: x → 2x/w − 1, y → 1 − 2y/h, z: depth 0..1000 → 1..0 (nearer = larger).
s.clip = [[2.0 / w as f32, 0.0, 0.0, -1.0], [0.0, -2.0 / h as f32, 0.0, 1.0], [0.0, 0.0, -0.001, 1.0], [0.0, 0.0, 0.0, 1.0]];
s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
s.ortho = true;
s.cam_fwd = [0.0, 0.0, 1.0];
for (rect, z, color) in quads {
let m = s.materials.len() as u32;
s.materials.push(Material {
base: *color,
unlit: true,
double_sided: true,
alpha_mode: if color[3] < 1.0 { 2 } else { 0 },
..Material::default()
});
let b = s.vertices.len() as u32;
for (x, y) in [(rect[0], rect[1]), (rect[2], rect[1]), (rect[2], rect[3]), (rect[0], rect[3])] {
s.vertices.push(Vertex { pos: [x, y, *z], normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m });
}
s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]);
}
// Opaque first, transparent (in given order) after.
let tris: Vec<[u32; 3]> = s.indices.chunks(3).map(|t| [t[0], t[1], t[2]]).collect();
let (o, t): (Vec<_>, Vec<_>) = tris.into_iter().partition(|t| !s.materials[s.vertices[t[0] as usize].material as usize].transparent());
s.opaque_count = 3 * o.len() as u32;
s.indices = o.into_iter().chain(t).flatten().collect();
s
}
/// Builds a lit scene quad by quad, opaque and transparent triangles kept apart.
struct Builder {
s: Scene,
opaque: Vec<u32>,
trans: Vec<u32>,
}
impl Builder {
/// A quad through corners `c` (in order around it) with material `m`, and its two triangles.
fn quad(&mut self, c: [[f32; 3]; 4], normal: [f32; 3], m: u32) {
let b = self.s.vertices.len() as u32;
let uv = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
for (p, uv) in c.into_iter().zip(uv) {
self.s.vertices.push(Vertex { pos: p, normal, uv, tangent: [1.0, 0.0, 0.0, 1.0], material: m });
}
let list = if self.s.materials[m as usize].transparent() { &mut self.trans } else { &mut self.opaque };
list.extend([b, b + 1, b + 2, b, b + 2, b + 3]);
}
/// A triangle with material `m`.
fn tri(&mut self, c: [[f32; 3]; 3], normal: [f32; 3], m: u32) {
let b = self.s.vertices.len() as u32;
for (p, uv) in c.into_iter().zip([[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]]) {
self.s.vertices.push(Vertex { pos: p, normal, uv, tangent: [0.0, 1.0, 0.0, -1.0], material: m });
}
let list = if self.s.materials[m as usize].transparent() { &mut self.trans } else { &mut self.opaque };
list.extend([b, b + 1, b + 2]);
}
fn finish(mut self) -> Scene {
self.s.opaque_count = self.opaque.len() as u32;
self.s.indices = self.opaque.into_iter().chain(self.trans).collect();
self.s
}
}
/// Appends a `w × h` texture made by `f(x, y)` and returns its index.
fn texture(s: &mut Scene, w: u32, h: u32, wrap: (u32, u32), f: impl Fn(u32, u32) -> [f32; 4]) -> i32 {
let offset = s.texels.len() as u32;
for y in 0..h {
for x in 0..w {
s.texels.push(f(x, y));
}
}
s.textures.push(TexInfo { offset, width: w, height: h, wrap_u: wrap.0, wrap_v: wrap.1 });
s.textures.len() as i32 - 1
}
fn norm(v: [f32; 3]) -> [f32; 3] {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
v.map(|x| x / l)
}
/// A lit scene at `out` pixels times `ssaa`, seen in perspective from (0, 0, −500) along +z
/// (+y down), or orthographically: a floor that crosses the near plane and reaches past the
/// viewport, a textured, normal-mapped box face and top, an alpha-masked card, a transparent card,
/// a card that draws only shadows, two single-sided triangles of opposite winding, an unlit
/// emissive triangle, three shadow-casting lights (parallel, spot, point), an environment light
/// with a dominant direction and ambient light. Shadow maps are not rendered yet.
pub fn lit_scene(out: (u32, u32), ssaa: u32, ortho: bool) -> Scene {
let (w, h) = (out.0 * ssaa, out.1 * ssaa);
let mut s = Scene { width: w, height: h, ssaa, ..Scene::default() };
s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 500.0], [0.0, 0.0, 0.0, 1.0]];
s.eye = [0.0, 0.0, -500.0];
s.cam_fwd = [0.0, 0.0, 1.0];
if ortho {
s.ortho = true;
s.clip = [[2.0 / 400.0, 0.0, 0.0, 0.0], [0.0, -2.0 / 300.0, 0.0, 0.0], [0.0, 0.0, -0.001, 0.5], [0.0, 0.0, 0.0, 1.0]];
} else {
let f = 0.8 * w as f32;
s.clip = [[2.0 * f / w as f32, 0.0, 0.0, 0.0], [0.0, -2.0 * f / h as f32, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 500.0]];
}
// Environment: three radiance levels and an irradiance map, brighter toward −y (up).
let sky = |x: u32, y: u32, w: u32, h: u32| {
let v = 1.0 - (y as f32 + 0.5) / h as f32;
let u = (x as f32 + 0.5) / w as f32;
[0.2 + 1.5 * v * v, 0.25 + 1.2 * v, 0.3 + 0.4 * u, 1.0]
};
texture(&mut s, 8, 4, (0, 1), |x, y| sky(x, y, 8, 4));
texture(&mut s, 4, 2, (0, 1), |x, y| sky(x, y, 4, 2));
texture(&mut s, 2, 1, (0, 1), |x, y| sky(x, y, 2, 1));
texture(&mut s, 4, 2, (0, 1), |x, y| sky(x, y, 4, 2).map(|c| c * 0.6));
let mask = texture(&mut s, 2, 2, (0, 0), |x, y| [1.0, 0.9, 0.8, if (x + y) % 2 == 0 { 1.0 } else { 0.0 }]);
let color = texture(&mut s, 2, 2, (2, 2), |x, y| [0.6 + 0.3 * x as f32, 0.5, 0.4 + 0.4 * y as f32, 1.0]);
let normal = texture(&mut s, 2, 2, (1, 1), |x, y| [0.5 + 0.2 * x as f32, 0.5 - 0.15 * y as f32, 0.95, 1.0]);
let mr = texture(&mut s, 2, 2, (0, 0), |x, _| [1.0, 0.6 + 0.3 * x as f32, 0.5, 1.0]);
let occlusion = texture(&mut s, 1, 1, (0, 0), |_, _| [0.7, 0.7, 0.7, 1.0]);
s.env = Some(EnvInfo {
radiance: 0,
mips: 3,
irradiance: 3,
intensity: 0.7,
rotation: 0.4,
sun: norm([0.2, -0.9, 0.3]),
key: 0.6,
shadow: 0,
shadow_darkness: 0.8,
shadow_diffusion: 6.0,
});
s.ambient = [0.05, 0.05, 0.06];
let light = |kind: u32, pos: [f32; 3], dir: [f32; 3], color: [f32; 3]| Light {
kind,
pos,
dir: norm(dir),
color,
cos_inner: 0.95,
cos_outer: 0.85,
falloff: kind.min(2),
radius: 150.0,
falloff_distance: 900.0,
shadow: 0,
shadow_darkness: 0.9,
shadow_diffusion: 4.0,
};
s.lights = vec![
light(0, [0.0; 3], [0.3, 0.8, 0.5], [0.9, 0.85, 0.8]),
light(1, [-150.0, -300.0, -100.0], [150.0, 400.0, 200.0], [1.2, 1.0, 0.7]),
light(2, [150.0, -150.0, 0.0], [0.0, 1.0, 0.0], [0.6, 0.7, 1.0]),
];
let mats = [
Material { base: [0.8, 0.8, 0.8, 1.0], roughness: 0.7, double_sided: true, ..Material::default() },
Material {
base: [0.9, 0.3, 0.2, 1.0],
metallic: 0.3,
roughness: 0.35,
tex_base: color,
tex_normal: normal,
tex_mr: mr,
tex_occlusion: occlusion,
casts_shadows: true,
double_sided: true,
specular_k: 1.2,
..Material::default()
},
Material { alpha_mode: 1, tex_base: mask, emissive: [0.1, 0.0, 0.0], casts_shadows: true, double_sided: true, ..Material::default() },
Material { base: [0.2, 0.4, 1.0, 0.5], alpha_mode: 2, roughness: 0.2, double_sided: true, ..Material::default() },
Material { base: [0.3, 0.9, 0.3, 1.0], ..Material::default() },
Material { shadows_only: true, double_sided: true, ..Material::default() },
Material { base: [0.1, 0.1, 0.1, 1.0], emissive: [0.9, 0.8, 0.2], unlit: true, ..Material::default() },
];
s.materials = mats.to_vec();
let mut b = Builder { s, opaque: vec![], trans: vec![] };
let up = [0.0, -1.0, 0.0];
b.quad([[-400.0, 100.0, -800.0], [400.0, 100.0, -800.0], [400.0, 100.0, 600.0], [-400.0, 100.0, 600.0]], up, 0);
b.quad([[-60.0, 100.0, 50.0], [-60.0, -20.0, 50.0], [60.0, -20.0, 50.0], [60.0, 100.0, 50.0]], [0.0, 0.0, -1.0], 1);
b.quad([[-60.0, -20.0, 50.0], [-60.0, -20.0, 170.0], [60.0, -20.0, 170.0], [60.0, -20.0, 50.0]], up, 1);
b.quad([[80.0, 100.0, 0.0], [80.0, -60.0, 0.0], [160.0, -60.0, 60.0], [160.0, 100.0, 60.0]], norm([-0.6, 0.0, -0.8]), 2);
b.tri([[-180.0, 0.0, -50.0], [-120.0, 0.0, -50.0], [-150.0, -60.0, -50.0]], [0.0, 0.0, -1.0], 4);
b.tri([[-180.0, 40.0, -50.0], [-150.0, -20.0, -50.0], [-120.0, 40.0, -50.0]], [0.0, 0.0, -1.0], 4);
b.tri([[100.0, -100.0, 300.0], [180.0, -100.0, 300.0], [140.0, -160.0, 300.0]], [0.0, 0.0, -1.0], 6);
// Transparent, back to front.
b.quad([[-200.0, 100.0, 250.0], [-200.0, -40.0, 250.0], [-80.0, -40.0, 250.0], [-80.0, 100.0, 250.0]], [0.0, 0.0, -1.0], 5);
b.quad([[-100.0, 60.0, -20.0], [-100.0, -80.0, -20.0], [20.0, -80.0, -20.0], [20.0, 60.0, -20.0]], [0.0, 0.0, -1.0], 3);
b.finish()
}
/// The bit patterns of a pixel list, for exact comparison.
pub fn bits4(v: &[[f32; 4]]) -> Vec<[u32; 4]> {
v.iter().map(|p| p.map(f32::to_bits)).collect()
}
/// The bit patterns of a value list, for exact comparison.
pub fn bits(v: &[f32]) -> Vec<u32> {
v.iter().map(|x| x.to_bits()).collect()
}
/// 64-bit FNV-1a of the bit patterns of `pixels` and then `values`.
pub fn fnv(pixels: &[[f32; 4]], values: &[f32]) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for b in pixels.iter().flatten().chain(values).flat_map(|x| x.to_bits().to_le_bytes()) {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
+158
View File
@@ -0,0 +1,158 @@
//! The rasterizer, sampler and shadow-sizing tests of EffectCraft's
//! `crates/render/src/three_d/adv/tests.rs`, on this crate's API.
use craft_raster3d::{Limits, MAX_SHADOW_TEXELS, TexInfo, sample, shadow_map_size, shadow_point_face_size, shadow_sizes, try_render};
use crate::quad_scene;
#[test]
fn depth_buffer_keeps_the_nearest_surface() {
let red = [1.0, 0.0, 0.0, 1.0];
let blue = [0.0, 0.0, 1.0, 1.0];
// Blue is listed first but is farther away.
let s = quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)]);
let t = try_render(&s, &Limits::default()).unwrap();
let px = |x: usize, y: usize| t.color[y * 40 + x];
assert_eq!(px(5, 5), blue);
assert_eq!(px(15, 15), red, "overlap: the nearer quad wins");
assert_eq!(px(35, 25), red);
assert_eq!(px(35, 5), [0.0; 4]);
assert_eq!(t.depth[15 * 40 + 15], 100.0);
assert!(t.depth[5 * 40 + 35].is_infinite());
}
#[test]
fn coverage_is_exact_for_pixel_aligned_quads() {
// Shared diagonal edges are filled once (top-left rule): exact pixel counts.
let s = quad_scene(32, 32, &[([4.0, 4.0, 20.0, 12.0], 10.0, [1.0, 1.0, 1.0, 0.5])]);
let t = try_render(&s, &Limits::default()).unwrap();
let covered = t.color.iter().filter(|c| c[3] > 0.0).count();
assert_eq!(covered, 16 * 8);
// Blended once (no double coverage along the diagonal).
assert!(t.color.iter().all(|c| c[3] == 0.0 || (c[3] - 0.5).abs() < 1e-6));
// Two transparent layers composite in order.
let s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], 50.0, [0.0, 0.0, 1.0, 0.5])]);
let c = try_render(&s, &Limits::default()).unwrap().color[0];
assert!((c[0] - 0.25).abs() < 1e-6 && (c[2] - 0.5).abs() < 1e-6 && (c[3] - 0.75).abs() < 1e-6, "{c:?}");
}
#[test]
fn textures_sample_bilinear_with_wrap_modes() {
let t = TexInfo { offset: 0, width: 2, height: 1, wrap_u: 0, wrap_v: 1 };
let texels = vec![[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]];
assert_eq!(sample(&t, &texels, 0.25, 0.5)[0], 0.0);
assert_eq!(sample(&t, &texels, 0.5, 0.5)[0], 0.5);
// Repeat wraps the right edge back to texel 0.
assert!((sample(&t, &texels, 1.0, 0.5)[0] - 0.5).abs() < 1e-6);
let c = TexInfo { wrap_u: 1, ..t };
assert_eq!(sample(&c, &texels, 1.0, 0.5)[0], 1.0);
}
#[test]
fn shadow_map_size_tracks_raster_resolution() {
assert_eq!(shadow_map_size(640, 360, false), 1024);
assert_eq!(shadow_map_size(1920, 1080, false), 2048);
assert_eq!(shadow_map_size(3840, 2160, false), 4096);
// Clamped to the pow2 range: small or absurd rasters stay inside 512..4096.
assert_eq!(shadow_map_size(64, 64, false), 512);
assert_eq!(shadow_map_size(0, 0, false), 512);
assert_eq!(shadow_map_size(u32::MAX, u32::MAX, false), 4096);
assert_eq!(shadow_map_size(7, 100000, false), 4096);
// The draft budget stays at 512 regardless.
assert_eq!(shadow_map_size(3840, 2160, true), 512);
assert_eq!(shadow_map_size(0, 0, true), 512);
}
#[test]
fn shadow_point_faces_are_capped() {
// Cube faces take the full map size up to 2048 (one 2048 cube ≈ 25 M f32 texels).
assert_eq!(shadow_point_face_size(4096, false), 2048);
assert_eq!(shadow_point_face_size(2048, false), 2048);
assert_eq!(shadow_point_face_size(1024, false), 1024);
assert_eq!(shadow_point_face_size(512, false), 512);
// Draft keeps the half-size face.
assert_eq!(shadow_point_face_size(512, true), 256);
}
fn budget_texels(sizes: &[Option<u32>], kinds: &[u32]) -> u64 {
sizes.iter().zip(kinds).map(|(s, &k)| s.map(|z| (z as u64) * (z as u64) * if k == 2 { 6 } else { 1 }).unwrap_or(0)).sum()
}
#[test]
fn shadow_sizes_stay_within_the_scene_budget() {
// Within budget a light gets its full size: one 4K point cube keeps 2048 faces.
assert_eq!(shadow_sizes(4096, 2160, false, &[2]), vec![Some(2048)]);
// Several cubes overflow: deterministically halved (largest first, earliest light
// on ties) until inside: three or four settle at 1024, five push two to 512.
assert_eq!(shadow_sizes(4096, 2160, false, &[2; 3]), vec![Some(1024); 3]);
assert_eq!(shadow_sizes(4096, 2160, false, &[2; 4]), vec![Some(1024); 4]);
let sizes = shadow_sizes(4096, 2160, false, &[2; 5]);
assert_eq!(sizes, vec![Some(512), Some(512), Some(1024), Some(1024), Some(1024)]);
assert!(budget_texels(&sizes, &[2; 5]) <= MAX_SHADOW_TEXELS);
// A hostile light count can never break the cap; sizes only shrink or drop to None.
let many = vec![2u32; 1000];
let sizes = shadow_sizes(3840, 2160, false, &many);
assert_eq!(sizes.len(), 1000);
assert!(budget_texels(&sizes, &many) <= MAX_SHADOW_TEXELS);
assert!(sizes.iter().flatten().all(|&z| (128..=2048).contains(&z)));
// Deterministic: same inputs, same plan.
assert_eq!(sizes, shadow_sizes(3840, 2160, false, &many));
// Non-point lights and a modest scene keep full quality sizes.
assert_eq!(shadow_sizes(1920, 1080, false, &[1; 2]), vec![Some(2048), Some(2048)]);
// A light that casts nothing costs nothing: it stays None and leaves its
// full-size budget to the lights that do cast.
assert_eq!(shadow_sizes(640, 360, false, &[0, 1]), vec![None, Some(1024)]);
assert!(shadow_sizes(640, 360, false, &[0; 500]).iter().all(Option::is_none));
}
#[test]
fn shadow_sizes_match_the_halve_largest_rule_and_scale_to_many_lights() {
// The specification `shadow_sizes` implements, step by step: halve the largest map
// above its floor (earliest light on ties) until the scene fits, then drop maps
// from the last light.
let spec = |w: u32, h: u32, draft: bool, kinds: &[u32]| -> Vec<Option<u32>> {
let base = shadow_map_size(w, h, draft);
let mut sizes: Vec<u32> = kinds
.iter()
.map(|&k| {
if k == 0 {
0
} else if k == 2 {
shadow_point_face_size(base, draft)
} else {
base
}
})
.collect();
let total = |s: &[u32]| -> u64 { s.iter().zip(kinds).map(|(&z, &k)| (z as u64) * (z as u64) * if k == 2 { 6 } else { 1 }).sum() };
while total(&sizes) > MAX_SHADOW_TEXELS {
let pick =
(0..sizes.len()).filter(|&i| sizes[i] > if kinds[i] == 2 { 128 } else { 512 }).max_by_key(|&i| (sizes[i], std::cmp::Reverse(i)));
match pick {
Some(i) => sizes[i] /= 2,
None => match sizes.iter().rposition(|&z| z > 0) {
Some(i) => sizes[i] = 0,
None => break,
},
}
}
sizes.into_iter().map(|z| (z > 0).then_some(z)).collect()
};
let mut seed = 0x2545_F491u32;
for case in 0..300 {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let n = (seed >> 8) as usize % 40;
let kinds: Vec<u32> = (0..n)
.map(|_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 16) % 3
})
.collect();
let (w, h, draft) = ([640, 1920, 3840, 8000][case % 4], [360, 1080, 2160, 100][case % 4], case % 7 == 0);
assert_eq!(shadow_sizes(w, h, draft, &kinds), spec(w, h, draft, &kinds), "case {case}: {kinds:?}");
}
// A hostile light count stays fast (n log n) and inside the budget.
let many = vec![2u32; 100_000];
let sizes = shadow_sizes(3840, 2160, false, &many);
assert!(budget_texels(&sizes, &many) <= MAX_SHADOW_TEXELS);
}
@@ -0,0 +1,178 @@
//! EffectCraft's Advanced 3D renderer at 2f16feb12f (`crates/render/src/three_d/adv.rs`,
//! `adv/raster.rs` and `adv/shade.rs`; `adv/raster.rs` and `adv/shade.rs` are unchanged since
//! 8fc2bc99), for the differential tests, with the alpha-mask change of storytold/effectcraft#4075
//! applied to `shade::shade` and `raster::shadow_raster`: a masked fragment that passes the
//! cutoff keeps only the layer's opacity, and a masked caster tests the material's alpha against
//! its cutoff. `resolve`, `encode` and `render_cpu` are copied from
//! `adv.rs` with `Image` defined here; `encode`'s channel loop iterates over the channels
//! instead of indexing them, which clippy asks for. `geom` holds the parts of `effectcraft_geom`
//! and `camera::basis_view` that the shadow maps use.
pub mod raster;
pub mod shade;
use rayon::prelude::*;
use craft_raster3d::Scene;
use raster::Target;
pub struct Image {
pub width: u32,
pub height: u32,
pub data: Vec<[f32; 4]>,
}
impl Image {
pub fn new(width: u32, height: u32) -> Self {
Image { width, height, data: vec![[0.0; 4]; (width * height) as usize] }
}
}
pub fn resolve(t: &Target, k: u32) -> (Image, Vec<f32>) {
let (w, h) = (t.width / k, t.height / k);
let mut img = Image::new(w, h);
let mut depth = vec![f32::INFINITY; (w * h) as usize];
let n = (k * k) as f32;
img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| {
for x in 0..w as usize {
let mut acc = [0.0f32; 4];
let (mut dz, mut dn) = (0.0f32, 0.0f32);
for j in 0..k as usize {
for i in 0..k as usize {
let s = (y * k as usize + j) * t.width as usize + x * k as usize + i;
let c = t.color[s];
for q in 0..4 {
acc[q] += c[q];
}
if t.depth[s].is_finite() {
dz += t.depth[s];
dn += 1.0;
}
}
}
row[x] = acc.map(|v| v / n);
if dn > 0.0 {
drow[x] = dz / dn;
}
}
});
(img, depth)
}
pub fn encode(img: &mut Image) {
img.data.par_iter_mut().for_each(|p| {
let a = p[3];
if a > 1e-6 {
for c in &mut p[..3] {
*c = shade::linear_to_srgb(*c / a) * a;
}
}
});
}
pub fn render_cpu(s: &Scene) -> (Image, Vec<f32>) {
resolve(&raster::render(s), s.ssaa.max(1))
}
/// `effectcraft_geom`'s `Vec3` and `Mat4` operations and `camera::basis_view`.
pub mod geom {
use std::ops::{Add, Div, Mul, Neg, Sub};
#[derive(Clone, Copy, Debug)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
pub const fn vec3(x: f64, y: f64, z: f64) -> Vec3 {
Vec3 { x, y, z }
}
impl Vec3 {
pub fn dot(self, o: Vec3) -> f64 {
self.x * o.x + self.y * o.y + self.z * o.z
}
pub fn cross(self, o: Vec3) -> Vec3 {
vec3(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x)
}
pub fn length(self) -> f64 {
self.dot(self).sqrt()
}
pub fn normalize(self) -> Vec3 {
let l = self.length();
if l > 0.0 { self / l } else { self }
}
}
impl Add for Vec3 {
type Output = Vec3;
fn add(self, o: Vec3) -> Vec3 {
Vec3 { x: self.x + o.x, y: self.y + o.y, z: self.z + o.z }
}
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, o: Vec3) -> Vec3 {
Vec3 { x: self.x - o.x, y: self.y - o.y, z: self.z - o.z }
}
}
impl Mul<f64> for Vec3 {
type Output = Vec3;
fn mul(self, k: f64) -> Vec3 {
Vec3 { x: self.x * k, y: self.y * k, z: self.z * k }
}
}
impl Div<f64> for Vec3 {
type Output = Vec3;
fn div(self, k: f64) -> Vec3 {
Vec3 { x: self.x / k, y: self.y / k, z: self.z / k }
}
}
impl Neg for Vec3 {
type Output = Vec3;
fn neg(self) -> Vec3 {
Vec3 { x: -self.x, y: -self.y, z: -self.z }
}
}
#[derive(Clone, Copy, Debug)]
pub struct Mat4(pub [[f64; 4]; 4]);
impl Mat4 {
pub const IDENTITY: Mat4 = Mat4([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]);
pub fn translate(t: Vec3) -> Mat4 {
let mut m = Mat4::IDENTITY;
m.0[0][3] = t.x;
m.0[1][3] = t.y;
m.0[2][3] = t.z;
m
}
}
impl Mul for Mat4 {
type Output = Mat4;
fn mul(self, o: Mat4) -> Mat4 {
let mut r = [[0.0; 4]; 4];
for i in 0..4 {
for j in 0..4 {
r[i][j] = (0..4).map(|k| self.0[i][k] * o.0[k][j]).sum();
}
}
Mat4(r)
}
}
pub fn basis_view(eye: Vec3, forward: Vec3, down_hint: Vec3) -> Mat4 {
let f = forward.normalize();
let f = if f.length() == 0.0 { vec3(0.0, 0.0, 1.0) } else { f };
let mut d = down_hint - f * down_hint.dot(f);
if d.length() < 1e-9 {
d = if f.y.abs() < 0.99 { vec3(0.0, 1.0, 0.0) } else { vec3(0.0, 0.0, -1.0) };
d = d - f * d.dot(f);
}
let d = d.normalize();
let r = d.cross(f).normalize();
Mat4([[r.x, r.y, r.z, 0.0], [d.x, d.y, d.z, 0.0], [f.x, f.y, f.z, 0.0], [0.0, 0.0, 0.0, 1.0]]) * Mat4::translate(-eye)
}
}
@@ -0,0 +1,583 @@
//! EffectCraft's `crates/render/src/three_d/adv/raster.rs`. Changes: the imports (the scene
//! types come from this crate, `basis_view` and `vec3` from `super::geom`), `pub` in place of
//! `pub(crate)`, comments removed, and two expressions broken over lines as rustfmt asks.
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use rayon::prelude::*;
use super::shade::{Frag, sample, shade};
use craft_raster3d::{EnvInfo, Scene, ShadowMap, Vertex};
pub struct Target {
pub width: u32,
pub height: u32,
pub color: Vec<[f32; 4]>,
pub depth: Vec<f32>,
}
#[derive(Clone, Copy)]
struct STri {
p: [[f64; 2]; 3],
z: [f32; 3],
inv_w: [f32; 3],
w: [[f32; 3]; 3],
tri: u32,
front: bool,
bbox: [i32; 4],
}
#[inline]
fn mat_mul(m: &[[f32; 4]; 4], p: [f32; 3]) -> [f32; 4] {
let mut o = [0.0; 4];
for r in 0..4 {
o[r] = m[r][0] * p[0] + m[r][1] * p[1] + m[r][2] * p[2] + m[r][3];
}
o
}
fn clip_poly(poly: Vec<([f32; 4], [f32; 3])>) -> Vec<([f32; 4], [f32; 3])> {
let mut p = poly;
for plane in 0..2 {
if p.is_empty() {
break;
}
let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] };
let mut out = Vec::with_capacity(p.len() + 2);
for i in 0..p.len() {
let (a, b) = (p[i], p[(i + 1) % p.len()]);
let (da, db) = (d(&a.0), d(&b.0));
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let t = da / (da - db);
let mut c = [0.0; 4];
let mut w = [0.0; 3];
for k in 0..4 {
c[k] = a.0[k] + (b.0[k] - a.0[k]) * t;
}
for k in 0..3 {
w[k] = a.1[k] + (b.1[k] - a.1[k]) * t;
}
out.push((c, w));
}
}
p = out;
}
p
}
fn setup(s: &Scene, clip: &[[f32; 4]], range: std::ops::Range<usize>) -> Vec<STri> {
let (w, h) = (s.width as f64, s.height as f64);
let mut out = vec![];
for t in range.step_by(3) {
let ids = [s.indices[t] as usize, s.indices[t + 1] as usize, s.indices[t + 2] as usize];
let mat = s.vertices[ids[0]].material as usize;
if !s.materials.get(mat).is_some_and(|m| m.visible) {
continue;
}
let poly = vec![(clip[ids[0]], [1.0, 0.0, 0.0]), (clip[ids[1]], [0.0, 1.0, 0.0]), (clip[ids[2]], [0.0, 0.0, 1.0])];
let poly = clip_poly(poly);
if poly.len() < 3 {
continue;
}
let scr: Vec<([f64; 2], f32, f32, [f32; 3])> = poly
.iter()
.map(|(c, wt)| {
let iw = 1.0 / c[3];
let (nx, ny) = (c[0] * iw, c[1] * iw);
([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], c[2] * iw, iw, *wt)
})
.collect();
let mut area = 0.0;
for i in 0..scr.len() {
let (a, b) = (scr[i].0, scr[(i + 1) % scr.len()].0);
area += a[0] * b[1] - b[0] * a[1];
}
if area == 0.0 || !area.is_finite() {
continue;
}
let front = area < 0.0;
for k in 1..scr.len() - 1 {
let c = [scr[0], scr[k], scr[k + 1]];
let mut x0 = f64::INFINITY;
let mut y0 = f64::INFINITY;
let mut x1 = f64::NEG_INFINITY;
let mut y1 = f64::NEG_INFINITY;
for v in &c {
x0 = x0.min(v.0[0]);
y0 = y0.min(v.0[1]);
x1 = x1.max(v.0[0]);
y1 = y1.max(v.0[1]);
}
let (w, h) = (i64::from(s.width.min(i32::MAX as u32)), i64::from(s.height.min(i32::MAX as u32)));
let bbox = [
(x0.floor() as i64).clamp(0, w) as i32,
(y0.floor() as i64).clamp(0, h) as i32,
(x1.ceil() as i64).clamp(0, w) as i32,
(y1.ceil() as i64).clamp(0, h) as i32,
];
if bbox[0] >= bbox[2] || bbox[1] >= bbox[3] {
continue;
}
out.push(STri {
p: [c[0].0, c[1].0, c[2].0],
z: [c[0].1, c[1].1, c[2].1],
inv_w: [c[0].2, c[1].2, c[2].2],
w: [c[0].3, c[1].3, c[2].3],
tri: (t / 3) as u32,
front,
bbox,
});
}
}
out
}
#[inline]
fn cover(t: &STri, px: f64, py: f64) -> Option<(f32, [f32; 3])> {
let [a, b, c] = t.p;
let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
let (b, c, swap) = if area < 0.0 { (c, b, true) } else { (b, c, false) };
let area = area.abs();
let edge = |p: [f64; 2], q: [f64; 2]| -> f64 { (q[0] - p[0]) * (py - p[1]) - (q[1] - p[1]) * (px - p[0]) };
let top_left = |p: [f64; 2], q: [f64; 2]| -> bool {
let (dx, dy) = (q[0] - p[0], q[1] - p[1]);
dy < 0.0 || (dy == 0.0 && dx > 0.0)
};
let e0 = edge(b, c);
let e1 = edge(c, a);
let e2 = edge(a, b);
let inside = |e: f64, p: [f64; 2], q: [f64; 2]| e > 0.0 || (e == 0.0 && top_left(p, q));
if !(inside(e0, b, c) && inside(e1, c, a) && inside(e2, a, b)) {
return None;
}
let (l0, l1, l2) = ((e0 / area) as f32, (e1 / area) as f32, (e2 / area) as f32);
let l = if swap { [l0, l2, l1] } else { [l0, l1, l2] };
let z = l[0] * t.z[0] + l[1] * t.z[1] + l[2] * t.z[2];
let q = [l[0] * t.inv_w[0], l[1] * t.inv_w[1], l[2] * t.inv_w[2]];
let sum = q[0] + q[1] + q[2];
if sum <= 0.0 {
return None;
}
Some((z, [q[0] / sum, q[1] / sum, q[2] / sum]))
}
fn frag(s: &Scene, t: &STri, l: [f32; 3]) -> Frag {
let base = t.tri as usize * 3;
let v: [&Vertex; 3] = [0, 1, 2].map(|k| &s.vertices[s.indices[base + k] as usize]);
let mut wv = [0.0f32; 3];
for c in 0..3 {
for k in 0..3 {
wv[k] += l[c] * t.w[c][k];
}
}
let mut f = Frag { pos: [0.0; 3], normal: [0.0; 3], uv: [0.0; 2], tangent: [0.0; 4], material: v[0].material, front: t.front };
for k in 0..3 {
let x = wv[k];
for i in 0..3 {
f.pos[i] += v[k].pos[i] * x;
f.normal[i] += v[k].normal[i] * x;
}
for i in 0..2 {
f.uv[i] += v[k].uv[i] * x;
}
for i in 0..4 {
f.tangent[i] += v[k].tangent[i] * x;
}
}
f.tangent[3] = v[0].tangent[3];
f
}
const BAND: i32 = 16;
pub fn render(s: &Scene) -> Target {
let (w, h) = (s.width as usize, s.height as usize);
let clip: Vec<[f32; 4]> = s.vertices.iter().map(|v| mat_mul(&s.clip, v.pos)).collect();
let opaque = setup(s, &clip, 0..s.opaque_count as usize);
let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len());
let bands = (h as i32 + BAND - 1) / BAND;
let bin = |ts: &[STri]| -> Vec<Vec<u32>> {
let mut b = vec![vec![]; bands.max(0) as usize];
for (i, t) in ts.iter().enumerate() {
for band in (t.bbox[1] / BAND)..((t.bbox[3] + BAND - 1) / BAND).min(bands) {
b[band as usize].push(i as u32);
}
}
b
};
let ob = bin(&opaque);
let tb = bin(&trans);
let view = s.view;
let cam_z = |p: [f32; 3]| view[2][0] * p[0] + view[2][1] * p[1] + view[2][2] * p[2] + view[2][3];
let mut color = vec![[0.0f32; 4]; w * h];
let mut depth = vec![f32::INFINITY; w * h];
color.par_chunks_mut(w * BAND as usize).zip(depth.par_chunks_mut(w * BAND as usize)).enumerate().for_each(|(band, (crow, drow))| {
let y0 = band as i32 * BAND;
let rows = crow.len() / w;
let mut vis: Vec<(u32, f32, [f32; 3])> = vec![(u32::MAX, 0.0, [0.0; 3]); rows * w];
for &ti in &ob[band] {
let t = &opaque[ti as usize];
for y in t.bbox[1].max(y0)..t.bbox[3].min(y0 + rows as i32) {
let r = (y - y0) as usize * w;
for x in t.bbox[0]..t.bbox[2] {
if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5) {
let v = &mut vis[r + x as usize];
if z > v.1 && z <= 1.0 {
*v = (ti, z, l);
}
}
}
}
}
for i in 0..rows * w {
let (ti, _, l) = vis[i];
if ti == u32::MAX {
continue;
}
let t = &opaque[ti as usize];
let f = frag(s, t, l);
match shade(s, &f) {
Some(c) => {
crow[i] = c;
drow[i] = cam_z(f.pos);
}
None => {
let (x, y) = ((i % w) as f64 + 0.5, (y0 as usize + i / w) as f64 + 0.5);
let mut best: Option<(f32, [f32; 4], f32)> = None;
for &tj in &ob[band] {
if tj == ti {
continue;
}
let t2 = &opaque[tj as usize];
if (x as i32) < t2.bbox[0] || (x as i32) >= t2.bbox[2] || (y as i32) < t2.bbox[1] || (y as i32) >= t2.bbox[3] {
continue;
}
if let Some((z, l2)) = cover(t2, x, y)
&& best.is_none_or(|b| z > b.0)
{
let f2 = frag(s, t2, l2);
if let Some(c) = shade(s, &f2) {
best = Some((z, c, cam_z(f2.pos)));
}
}
}
if let Some((z, c, d)) = best {
crow[i] = c;
drow[i] = d;
vis[i].1 = z;
} else {
vis[i].1 = 0.0;
}
}
}
}
for &ti in &tb[band] {
let t = &trans[ti as usize];
for y in t.bbox[1].max(y0)..t.bbox[3].min(y0 + rows as i32) {
let r = (y - y0) as usize * w;
for x in t.bbox[0]..t.bbox[2] {
let i = r + x as usize;
if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5)
&& z > vis[i].1
&& z <= 1.0
&& let Some(c) = shade(s, &frag(s, t, l))
{
let d = crow[i];
let k = 1.0 - c[3];
crow[i] = [c[0] + d[0] * k, c[1] + d[1] * k, c[2] + d[2] * k, c[3] + d[3] * k];
}
}
}
}
});
Target { width: s.width, height: s.height, color, depth }
}
fn basis(eye: [f64; 3], fwd: [f64; 3], down: [f64; 3]) -> [[f32; 4]; 3] {
use super::geom::vec3;
let m = super::geom::basis_view(vec3(eye[0], eye[1], eye[2]), vec3(fwd[0], fwd[1], fwd[2]), vec3(down[0], down[1], down[2]));
[0, 1, 2].map(|r| m.0[r].map(|v| v as f32))
}
fn shadow_raster(s: &Scene, m: &ShadowMap, casters: &[usize]) -> Vec<f32> {
let n = m.size as usize;
let mut d = vec![f32::INFINITY; n * n];
let c = n as f32 * 0.5;
const NEAR: f32 = 1.0;
for &t in casters {
let ids = [s.indices[3 * t] as usize, s.indices[3 * t + 1] as usize, s.indices[3 * t + 2] as usize];
let mat = &s.materials[s.vertices[ids[0]].material as usize];
// Mask mode casts where the material's alpha passes its cutoff (as `shade` draws it);
// blend mode casts where its alpha times the layer's opacity reaches one half.
let (alpha_k, cutoff) = if mat.alpha_mode == 1 { (mat.base[3], mat.alpha_cutoff) } else { (mat.base[3] * mat.opacity, 0.5) };
let alpha_tex = if mat.alpha_mode != 0 && mat.tex_base >= 0 { s.textures.get(mat.tex_base as usize) } else { None };
if mat.alpha_mode == 1 && alpha_tex.is_none() && alpha_k < cutoff {
continue;
}
let q: Vec<([f32; 3], [f32; 2])> = ids
.iter()
.map(|&i| {
let p = s.vertices[i].pos;
let v = &m.view;
([0, 1, 2].map(|r| v[r][0] * p[0] + v[r][1] * p[1] + v[r][2] * p[2] + v[r][3]), s.vertices[i].uv)
})
.collect();
let mut poly = q;
if !m.ortho {
let mut out = vec![];
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
let (da, db) = (a.0[2] - NEAR, b.0[2] - NEAR);
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let k = da / (da - db);
let lerp = |x: f32, y: f32| x + (y - x) * k;
out.push(([lerp(a.0[0], b.0[0]), lerp(a.0[1], b.0[1]), lerp(a.0[2], b.0[2])], [lerp(a.1[0], b.1[0]), lerp(a.1[1], b.1[1])]));
}
}
poly = out;
}
if poly.len() < 3 {
continue;
}
let scr: Vec<([f64; 2], f32, f32, [f32; 2])> = poly
.iter()
.map(|(p, uv)| {
if m.ortho {
([(p[0] * m.focal + c) as f64, (p[1] * m.focal + c) as f64], 1.0, p[2], *uv)
} else {
let iz = 1.0 / p[2];
([(p[0] * m.focal * iz + c) as f64, (p[1] * m.focal * iz + c) as f64], iz, p[2], *uv)
}
})
.collect();
for k in 1..scr.len() - 1 {
let tri = [scr[0], scr[k], scr[k + 1]];
let (a, b, cc) = (tri[0].0, tri[1].0, tri[2].0);
let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]);
if area.abs() < 1e-12 {
continue;
}
let x0 = a[0].min(b[0]).min(cc[0]).floor().max(0.0) as usize;
let x1 = (a[0].max(b[0]).max(cc[0]).ceil().max(0.0) as usize).min(n);
let y0 = a[1].min(b[1]).min(cc[1]).floor().max(0.0) as usize;
let y1 = (a[1].max(b[1]).max(cc[1]).ceil().max(0.0) as usize).min(n);
for y in y0..y1 {
for x in x0..x1 {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let e0 = ((cc[0] - b[0]) * (py - b[1]) - (cc[1] - b[1]) * (px - b[0])) / area;
let e1 = ((a[0] - cc[0]) * (py - cc[1]) - (a[1] - cc[1]) * (px - cc[0])) / area;
let e2 = 1.0 - e0 - e1;
if e0 < 0.0 || e1 < 0.0 || e2 < 0.0 {
continue;
}
let l = [e0 as f32, e1 as f32, e2 as f32];
let (z, uv) = if m.ortho {
(
l[0] * tri[0].2 + l[1] * tri[1].2 + l[2] * tri[2].2,
[0, 1].map(|i| l[0] * tri[0].3[i] + l[1] * tri[1].3[i] + l[2] * tri[2].3[i]),
)
} else {
let iz = l[0] * tri[0].1 + l[1] * tri[1].1 + l[2] * tri[2].1;
let z = 1.0 / iz;
(z, [0, 1].map(|i| (l[0] * tri[0].3[i] * tri[0].1 + l[1] * tri[1].3[i] * tri[1].1 + l[2] * tri[2].3[i] * tri[2].1) * z))
};
let px = &mut d[y * n + x];
if z >= *px {
continue;
}
if let Some(t) = alpha_tex
&& sample(t, &s.texels, uv[0], uv[1])[3] * alpha_k < cutoff
{
continue;
}
*px = z;
}
}
}
}
d
}
pub const MAX_SHADOW_TEXELS: u64 = 26_000_000;
pub fn shadow_map_size(width: u32, height: u32, draft: bool) -> u32 {
if draft {
return 512;
}
let side = width.max(height).clamp(512, 4096);
let mut size = 512u32;
while size < side {
size *= 2;
}
size
}
pub fn shadow_point_face_size(size: u32, draft: bool) -> u32 {
if draft { (size / 2).max(1) } else { size.min(2048) }
}
pub fn shadow_sizes(width: u32, height: u32, draft: bool, kinds: &[u32]) -> Vec<Option<u32>> {
let base = shadow_map_size(width, height, draft);
let faces = |k: u32| -> u64 { if k == 2 { 6 } else { 1 } };
let floor = |k: u32| -> u32 { if k == 2 { 128 } else { 512 } };
let mut sizes: Vec<u32> = kinds
.iter()
.map(|&k| match k {
0 => 0,
2 => shadow_point_face_size(base, draft),
_ => base,
})
.collect();
let cost = |z: u32, k: u32| -> u64 { (z as u64) * (z as u64) * faces(k) };
let mut total: u64 = sizes.iter().zip(kinds).map(|(&z, &k)| cost(z, k)).sum();
let mut heap: BinaryHeap<(u32, Reverse<usize>)> =
sizes.iter().zip(kinds).enumerate().filter(|(_, (z, k))| **z > floor(**k)).map(|(i, (&z, _))| (z, Reverse(i))).collect();
while total > MAX_SHADOW_TEXELS {
let Some((z, Reverse(i))) = heap.pop() else { break };
let k = kinds[i];
total -= cost(z, k) - cost(z / 2, k);
sizes[i] = z / 2;
if z / 2 > floor(k) {
heap.push((z / 2, Reverse(i)));
}
}
for i in (0..sizes.len()).rev() {
if total <= MAX_SHADOW_TEXELS {
break;
}
total -= cost(sizes[i], kinds[i]);
sizes[i] = 0;
}
sizes.into_iter().map(|z| (z > 0).then_some(z)).collect()
}
pub fn env_shadow_map(e: EnvInfo, centre: [f64; 3], radius: f64, size: u32) -> ShadowMap {
let texel = 2.0 * radius / size as f64;
let soft = (4.0 * texel).max(8.0) + (e.shadow_diffusion as f64 * 0.5).min(24.0);
let sun = e.sun.map(|v| v as f64);
let dir = [-sun[0], -sun[1], -sun[2]];
let eye = [centre[0] + sun[0] * radius * 2.0, centre[1] + sun[1] * radius * 2.0, centre[2] + sun[2] * radius * 2.0];
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
let focal = (size as f64 * 0.5 / radius) as f32;
ShadowMap { view: basis(eye, dir, hint), focal, ortho: true, size, offset: 0, bias: 1.5, radius: soft as f32 }
}
pub fn shadow_maps(s: &mut Scene, draft: bool) {
let casters: Vec<usize> = (0..s.indices.len() / 3)
.filter(|&t| s.materials.get(s.vertices[s.indices[3 * t] as usize].material as usize).is_some_and(|m| m.casts_shadows))
.collect();
let env_shadow = !casters.is_empty() && s.env.is_some_and(|e| e.shadow == 0 && e.sun != [0.0; 3]);
if !env_shadow && let Some(e) = &mut s.env {
e.shadow = -1;
}
if casters.is_empty() {
for l in &mut s.lights {
l.shadow = -1;
}
return;
}
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for v in &s.vertices {
for k in 0..3 {
lo[k] = lo[k].min(v.pos[k] as f64);
hi[k] = hi[k].max(v.pos[k] as f64);
}
}
let centre = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
let kinds: Vec<u32> = s
.lights
.iter()
.map(|l| {
if l.shadow != 0 {
0
} else if l.kind > 1 {
2
} else {
1
}
})
.chain(std::iter::once(if env_shadow { 1 } else { 0 }))
.collect();
let sizes = shadow_sizes(s.width, s.height, draft, &kinds);
let mut maps: Vec<ShadowMap> = vec![];
for li in 0..s.lights.len() {
let Some(size) = sizes.get(li).copied().flatten() else {
s.lights[li].shadow = -1;
continue;
};
if s.lights[li].shadow != 0 {
s.lights[li].shadow = -1;
continue;
}
let l = s.lights[li];
let first = maps.len() as i32;
let soft = 1.0 + (l.shadow_diffusion * 0.5).min(24.0);
let pos = l.pos.map(|v| v as f64);
let dir = l.dir.map(|v| v as f64);
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
match l.kind {
0 => {
let eye = [centre[0] - dir[0] * radius * 2.0, centre[1] - dir[1] * radius * 2.0, centre[2] - dir[2] * radius * 2.0];
let focal = (size as f64 * 0.5 / radius) as f32;
maps.push(ShadowMap { view: basis(eye, dir, hint), focal, ortho: true, size, offset: 0, bias: 1.5, radius: soft });
}
1 => {
let half = (l.cos_outer.clamp(-1.0, 1.0).acos() as f64 + 0.05).min(1.45);
let focal = (size as f64 * 0.5 / half.tan()) as f32;
maps.push(ShadowMap { view: basis(pos, dir, hint), focal, ortho: false, size, offset: 0, bias: 1.5, radius: soft });
}
_ => {
let fs = size;
for (f, d) in [
([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
] {
maps.push(ShadowMap {
view: basis(pos, f, d),
focal: fs as f32 * 0.5,
ortho: false,
size: fs,
offset: 0,
bias: 1.5,
radius: soft,
});
}
}
}
s.lights[li].shadow = first;
}
if env_shadow && let Some(e) = s.env {
match sizes.get(s.lights.len()).copied().flatten() {
Some(size) => {
let first = maps.len() as i32;
maps.push(env_shadow_map(e, centre, radius, size));
if let Some(e) = &mut s.env {
e.shadow = first;
}
}
None => {
if let Some(e) = &mut s.env {
e.shadow = -1;
}
}
}
}
let texels: Vec<Vec<f32>> = maps.par_iter().map(|m| shadow_raster(s, m, &casters)).collect();
for (m, t) in maps.iter_mut().zip(texels) {
m.offset = s.shadow_texels.len() as u32;
s.shadow_texels.extend(t);
}
s.shadows = maps;
}
@@ -0,0 +1,473 @@
//! EffectCraft's `crates/render/src/three_d/adv/shade.rs`. Changes: the import of the scene
//! types (from this crate), `equirect_dir` and `srgb_to_linear` left out (the renderer does not
//! call them), and comments removed.
use craft_raster3d::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo};
pub const PI: f32 = std::f32::consts::PI;
#[inline]
pub fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[inline]
pub fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
#[inline]
pub fn norm(a: [f32; 3]) -> [f32; 3] {
let l = dot(a, a).sqrt();
if l > 1e-20 { [a[0] / l, a[1] / l, a[2] / l] } else { [0.0, 0.0, -1.0] }
}
#[inline]
fn add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
#[inline]
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
#[inline]
fn scale(a: [f32; 3], k: f32) -> [f32; 3] {
[a[0] * k, a[1] * k, a[2] * k]
}
#[inline]
fn mix(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
#[inline]
pub fn linear_to_srgb(c: f32) -> f32 {
if c <= 0.0031308 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
}
#[inline]
pub fn d_ggx(n_h: f32, a: f32) -> f32 {
let a2 = a * a;
let d = n_h * n_h * (a2 - 1.0) + 1.0;
a2 / (PI * d * d).max(1e-12)
}
#[inline]
pub fn g_smith(n_v: f32, n_l: f32, rough: f32) -> f32 {
let k = (rough + 1.0) * (rough + 1.0) / 8.0;
let g1 = |x: f32| x / (x * (1.0 - k) + k);
g1(n_v) * g1(n_l)
}
#[inline]
pub fn f_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] {
let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5);
[f0[0] + (1.0 - f0[0]) * k, f0[1] + (1.0 - f0[1]) * k, f0[2] + (1.0 - f0[2]) * k]
}
#[derive(Clone, Copy)]
pub struct BrdfSurface {
pub base: [f32; 3],
pub metallic: f32,
pub roughness: f32,
pub specular: f32,
pub diffuse: f32,
}
pub fn brdf(surface: BrdfSurface, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> [f32; 3] {
let BrdfSurface { base, metallic, roughness: rough, specular: spec_k, diffuse: diff_k } = surface;
let n_l = dot(n, l);
if n_l <= 0.0 {
return [0.0; 3];
}
let n_v = dot(n, v).max(1e-4);
let h = norm(add(v, l));
let n_h = dot(n, h).max(0.0);
let v_h = dot(v, h).max(0.0);
let r = rough.clamp(0.03, 1.0);
let f0 = [mix(0.04 * spec_k, base[0], metallic), mix(0.04 * spec_k, base[1], metallic), mix(0.04 * spec_k, base[2], metallic)];
let f = f_schlick(f0, v_h);
let d = d_ggx(n_h, r * r);
let g = g_smith(n_v, n_l, r);
let spec = d * g / (4.0 * n_v * n_l).max(1e-4);
let mut out = [0.0; 3];
for c in 0..3 {
let kd = (1.0 - f[c]) * (1.0 - metallic);
out[c] = (kd * base[c] / PI * diff_k + f[c] * spec) * n_l * PI;
}
out
}
#[inline]
pub fn env_brdf(n_v: f32, rough: f32) -> (f32, f32) {
let c0 = [-1.0, -0.0275, -0.572, 0.022];
let c1 = [1.0, 0.0425, 1.04, -0.04];
let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]];
let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1];
(-1.04 * a004 + r[2], 1.04 * a004 + r[3])
}
#[inline]
fn wrap(i: i64, n: i64, mode: u32) -> i64 {
match mode {
1 => i.clamp(0, n - 1),
2 => {
let m = i.rem_euclid(2 * n);
if m >= n { 2 * n - 1 - m } else { m }
}
_ => i.rem_euclid(n),
}
}
pub fn sample(t: &TexInfo, texels: &[[f32; 4]], u: f32, v: f32) -> [f32; 4] {
let (w, h) = (t.width as i64, t.height as i64);
if w == 0 || h == 0 {
return [1.0; 4];
}
let x = u * w as f32 - 0.5;
let y = v * h as f32 - 0.5;
let (x0, y0) = (x.floor(), y.floor());
let (fx, fy) = (x - x0, y - y0);
let (x0, y0) = (x0 as i64, y0 as i64);
let get = |xi: i64, yi: i64| -> [f32; 4] {
let xi = wrap(xi, w, t.wrap_u);
let yi = wrap(yi, h, t.wrap_v);
texels.get(t.offset as usize + (yi * w + xi) as usize).copied().unwrap_or([0.0; 4])
};
let (a, b, c, d) = (get(x0, y0), get(x0 + 1, y0), get(x0, y0 + 1), get(x0 + 1, y0 + 1));
let mut o = [0.0; 4];
for k in 0..4 {
let top = a[k] + (b[k] - a[k]) * fx;
let bot = c[k] + (d[k] - c[k]) * fx;
o[k] = top + (bot - top) * fy;
}
o
}
#[inline]
pub fn equirect_uv(d: [f32; 3], rot: f32) -> (f32, f32) {
let u = 0.5 + (d[0].atan2(d[2]) + rot) / (2.0 * PI);
let v = (-d[1]).clamp(-1.0, 1.0).acos() / PI;
(u - u.floor(), v)
}
pub fn env_light(s: &Scene, e: &EnvInfo, n: [f32; 3], r: [f32; 3], rough: f32) -> ([f32; 3], [f32; 3]) {
let (u, v) = equirect_uv(n, e.rotation);
let irr = s.textures.get(e.irradiance as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let (u, v) = equirect_uv(r, e.rotation);
let lv = rough.clamp(0.0, 1.0) * (e.mips.saturating_sub(1)) as f32;
let l0 = lv.floor() as u32;
let l1 = (l0 + 1).min(e.mips.saturating_sub(1));
let f = lv - l0 as f32;
let a = s.textures.get((e.radiance + l0) as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let b = s.textures.get((e.radiance + l1) as usize).map_or([0.0; 4], |t| sample(t, &s.texels, u, v));
let spec = [mix(a[0], b[0], f), mix(a[1], b[1], f), mix(a[2], b[2], f)];
(scale([irr[0], irr[1], irr[2]], e.intensity), scale(spec, e.intensity))
}
#[inline]
pub fn shadow_coord(m: &ShadowMap, p: [f32; 3]) -> Option<(f32, f32, f32)> {
let v = &m.view;
let q = [
v[0][0] * p[0] + v[0][1] * p[1] + v[0][2] * p[2] + v[0][3],
v[1][0] * p[0] + v[1][1] * p[1] + v[1][2] * p[2] + v[1][3],
v[2][0] * p[0] + v[2][1] * p[1] + v[2][2] * p[2] + v[2][3],
];
let c = m.size as f32 * 0.5;
if m.ortho {
Some((q[0] * m.focal + c, q[1] * m.focal + c, q[2]))
} else if q[2] > 1e-3 {
Some((q[0] * m.focal / q[2] + c, q[1] * m.focal / q[2] + c, q[2]))
} else {
None
}
}
fn tap_hash(x: i32, y: i32) -> u32 {
let mut h = (x as u32).wrapping_mul(0x9E37_79B9) ^ (y as u32).wrapping_mul(0x85EB_CA6B);
h ^= h >> 16;
h = h.wrapping_mul(0x2545_F491);
h ^= h >> 15;
h
}
fn tap_jitter(cx: i32, cy: i32, wx: f32, wy: f32, i: i32, j: i32) -> (f32, f32) {
let corner = |dx: i32, dy: i32| -> (f32, f32) {
let h = tap_hash(cx.wrapping_add(dx).wrapping_add(i.wrapping_mul(7919)), cy.wrapping_add(dy).wrapping_add(j.wrapping_mul(7919)));
(((h & 0xFFFF) as f32) * (1.0 / 65536.0) - 0.5, (((h >> 16) & 0xFFFF) as f32) * (1.0 / 65536.0) - 0.5)
};
let (c00, c10, c01, c11) = (corner(0, 0), corner(1, 0), corner(0, 1), corner(1, 1));
let ax = c00.0 + (c10.0 - c00.0) * wx;
let bx = c01.0 + (c11.0 - c01.0) * wx;
let ay = c00.1 + (c10.1 - c00.1) * wx;
let by = c01.1 + (c11.1 - c01.1) * wx;
(ax + (bx - ax) * wy, ay + (by - ay) * wy)
}
const PCF_MAX_TAPS: i32 = 10;
const PLANE_SLOPE_MAX: f32 = 64.0;
pub fn shadow_factor(m: &ShadowMap, texels: &[f32], p: [f32; 3], ng: [f32; 3], n_l: f32) -> f32 {
let Some((u, v, z)) = shadow_coord(m, p) else { return 1.0 };
let size = m.size as i64;
let texel = if m.ortho { 1.0 / m.focal } else { z.abs() / m.focal };
let bias = m.bias * texel * (1.0 + 3.0 * (1.0 - n_l.clamp(0.0, 1.0)));
let at = |xi: i64, yi: i64| -> f32 {
if xi < 0 || yi < 0 || xi >= size || yi >= size {
return f32::INFINITY;
}
texels.get(m.offset as usize + (yi * size + xi) as usize).copied().unwrap_or(f32::INFINITY)
};
let w = &m.view;
let nv = [0, 1, 2].map(|r| w[r][0] * ng[0] + w[r][1] * ng[1] + w[r][2] * ng[2]);
let c = m.size as f32 * 0.5;
let den0 = if m.ortho { nv[2] } else { nv[0] * ((u - c) / m.focal) + nv[1] * ((v - c) / m.focal) + nv[2] };
let (tx, ty) = if den0 < -1e-6 {
((nv[0] / den0).clamp(-PLANE_SLOPE_MAX, PLANE_SLOPE_MAX), (nv[1] / den0).clamp(-PLANE_SLOPE_MAX, PLANE_SLOPE_MAX))
} else {
(0.0, 0.0)
};
let (iz, iq) = (1.0 / z, 1.0 / (m.focal * z));
let open = |xi: i64, yi: i64| -> f32 {
let s = at(xi, yi) + bias;
let g = tx * (xi as f32 + 0.5 - u) + ty * (yi as f32 + 0.5 - v);
let lit = if m.ortho {
z - g * texel <= s
} else {
let inv = iz + g * iq;
inv <= 0.0 || inv * s >= 1.0
};
if lit { 1.0 } else { 0.0 }
};
let mut reach = (m.radius / texel).clamp(2.0, 256.0);
if !reach.is_finite() {
reach = 1.0;
}
let n = (reach.ceil() as i32 + 1).clamp(5, PCF_MAX_TAPS);
let step = reach / (n - 1) as f32;
let half = (n - 1) as f32 * 0.5;
let (gu, gv) = (u * 8.0, v * 8.0);
let (cx, cy) = (gu.floor() as i32, gv.floor() as i32);
let (wx, wy) = (gu - gu.floor(), gv - gv.floor());
let mut lit = 0.0;
for j in 0..n {
for i in 0..n {
let (jx, jy) = tap_jitter(cx, cy, wx, wy, i, j);
let (su, sv) = (u + ((i as f32 - half) + jx) * step, v + ((j as f32 - half) + jy) * step);
let (tu, tv) = (su - 0.5, sv - 0.5);
let (fx, fy) = (tu - tu.floor(), tv - tv.floor());
let (x0, y0) = (tu.floor() as i64, tv.floor() as i64);
let (h00, h10, h01, h11) = (open(x0, y0), open(x0 + 1, y0), open(x0, y0 + 1), open(x0 + 1, y0 + 1));
let a = h00 + (h10 - h00) * fx;
let b = h01 + (h11 - h01) * fx;
lit += a + (b - a) * fy;
}
}
lit / (n * n) as f32
}
pub fn light_shadow(s: &Scene, l: &Light, p: [f32; 3], ng: [f32; 3], n_l: f32) -> f32 {
if l.shadow < 0 {
return 1.0;
}
let first = l.shadow as usize;
let m = if l.kind == 2 {
let d = sub(p, l.pos);
let (ax, ay, az) = (d[0].abs(), d[1].abs(), d[2].abs());
let face = if ax >= ay && ax >= az {
if d[0] > 0.0 { 0 } else { 1 }
} else if ay >= az {
if d[1] > 0.0 { 2 } else { 3 }
} else if d[2] > 0.0 {
4
} else {
5
};
s.shadows.get(first + face)
} else {
s.shadows.get(first)
};
let Some(m) = m else { return 1.0 };
let f = shadow_factor(m, &s.shadow_texels, p, ng, n_l);
1.0 - l.shadow_darkness * (1.0 - f)
}
pub fn env_shadow(s: &Scene, e: &EnvInfo, p: [f32; 3], ng: [f32; 3], n: [f32; 3]) -> f32 {
if e.shadow < 0 || e.sun == [0.0; 3] {
return 1.0;
}
let Some(m) = s.shadows.get(e.shadow as usize) else { return 1.0 };
let n_l = dot(n, e.sun).clamp(0.0, 1.0);
let f = shadow_factor(m, &s.shadow_texels, p, ng, n_l);
1.0 - e.shadow_darkness * e.key * (1.0 - f)
}
fn to_light(l: &Light, p: [f32; 3]) -> ([f32; 3], f32) {
if l.kind == 0 {
return (scale(l.dir, -1.0), f32::INFINITY);
}
let d = sub(l.pos, p);
let len = dot(d, d).sqrt();
if len < 1e-6 { ([0.0, 0.0, -1.0], 0.0) } else { (scale(d, 1.0 / len), len) }
}
pub fn attenuation(l: &Light, p: [f32; 3], to_l: [f32; 3], dist: f32) -> f32 {
let mut k = match l.falloff {
1 if l.kind != 0 => {
if dist <= l.radius {
1.0
} else if l.falloff_distance <= 0.0 {
0.0
} else {
let t = ((dist - l.radius) / l.falloff_distance).clamp(0.0, 1.0);
1.0 - t * t * (3.0 - 2.0 * t)
}
}
2 if l.kind != 0 => {
if dist <= l.radius || (l.radius <= 0.0 && dist <= 1.0) {
1.0
} else {
(l.radius.max(1.0) / dist).powi(2)
}
}
_ => 1.0,
};
let _ = p;
if l.kind == 1 {
let cos_a = dot(scale(to_l, -1.0), l.dir).clamp(-1.0, 1.0);
k *= if cos_a >= l.cos_inner {
1.0
} else if cos_a <= l.cos_outer {
0.0
} else {
let a = cos_a.acos();
let (ai, ao) = (l.cos_inner.acos(), l.cos_outer.acos());
let t = ((a - ai) / (ao - ai).max(1e-6)).clamp(0.0, 1.0);
1.0 - t * t * (3.0 - 2.0 * t)
};
}
k
}
#[derive(Clone, Copy, Debug)]
pub struct Frag {
pub pos: [f32; 3],
pub normal: [f32; 3],
pub uv: [f32; 2],
pub tangent: [f32; 4],
pub material: u32,
pub front: bool,
}
pub fn shade(s: &Scene, f: &Frag) -> Option<[f32; 4]> {
let m: &Material = s.materials.get(f.material as usize)?;
if !f.front && !m.double_sided {
return None;
}
let tex = |i: i32| -> Option<[f32; 4]> { (i >= 0).then(|| s.textures.get(i as usize).map(|t| sample(t, &s.texels, f.uv[0], f.uv[1]))).flatten() };
let mut base = m.base;
if let Some(t) = tex(m.tex_base) {
for k in 0..4 {
base[k] *= t[k];
}
}
// Mask mode tests the material's alpha (factor × texture) against the cutoff, and a
// fragment that passes keeps only the layer's opacity. Blend mode multiplies the two.
if m.alpha_mode == 1 && base[3] < m.alpha_cutoff {
return None;
}
let blend = m.alpha_mode > 1;
let alpha = if blend { base[3] * m.opacity } else { m.opacity };
if blend && alpha <= 1e-5 {
return None;
}
let rgb = [base[0], base[1], base[2]];
let mut emissive = m.emissive;
if let Some(t) = tex(m.tex_emissive) {
emissive = [emissive[0] * t[0], emissive[1] * t[1], emissive[2] * t[2]];
}
if m.shadows_only {
return Some(shadow_only(s, m, f, alpha));
}
if m.unlit || !m.accepts_lights || (s.lights.is_empty() && s.env.is_none() && s.ambient == [0.0; 3]) {
let c = add(rgb, emissive);
return Some([c[0] * alpha, c[1] * alpha, c[2] * alpha, alpha]);
}
let (mut metallic, mut rough) = (m.metallic, m.roughness);
if let Some(t) = tex(m.tex_mr) {
rough *= t[1];
metallic *= t[2];
}
let mut n = norm(f.normal);
if !f.front {
n = scale(n, -1.0);
}
let ng = n;
if let Some(t) = tex(m.tex_normal) {
let tn = [(t[0] * 2.0 - 1.0) * m.normal_scale, (t[1] * 2.0 - 1.0) * m.normal_scale, t[2] * 2.0 - 1.0];
let tg = [f.tangent[0], f.tangent[1], f.tangent[2]];
let tg = norm(sub(tg, scale(n, dot(n, tg))));
let sign = if f.front { f.tangent[3] } else { -f.tangent[3] };
let bt = scale(cross(n, tg), sign);
n = norm(add(add(scale(tg, tn[0]), scale(bt, tn[1])), scale(n, tn[2])));
}
let ao = match tex(m.tex_occlusion) {
Some(t) => 1.0 + m.occlusion_strength * (t[0] - 1.0),
None => 1.0,
};
let v = if s.ortho { scale(s.cam_fwd, -1.0) } else { norm(sub(s.eye, f.pos)) };
let mut out = [0.0f32; 3];
for l in &s.lights {
let (to_l, dist) = to_light(l, f.pos);
let k = attenuation(l, f.pos, to_l, dist);
if k <= 0.0 {
continue;
}
let n_l = dot(n, to_l);
if n_l <= 0.0 {
continue;
}
let sh = if m.receives_shadows { light_shadow(s, l, f.pos, ng, n_l) } else { 1.0 };
let b = brdf(BrdfSurface { base: rgb, metallic, roughness: rough, specular: m.specular_k, diffuse: m.diffuse_k }, n, v, to_l);
for c in 0..3 {
out[c] += b[c] * l.color[c] * k * sh;
}
}
for c in 0..3 {
out[c] += s.ambient[c] * rgb[c] * m.ambient_k * ao;
}
if let Some(e) = &s.env {
let n_v = dot(n, v).clamp(1e-4, 1.0);
let r = sub(scale(n, 2.0 * dot(n, v)), v);
let (irr, spec) = env_light(s, e, n, r, rough);
let f0 = [mix(0.04 * m.specular_k, rgb[0], metallic), mix(0.04 * m.specular_k, rgb[1], metallic), mix(0.04 * m.specular_k, rgb[2], metallic)];
let (a, b) = env_brdf(n_v, rough);
let sh = if m.receives_shadows { env_shadow(s, e, f.pos, ng, n) } else { 1.0 };
for c in 0..3 {
let fs = f0[c] * a + b;
out[c] += (irr[c] * rgb[c] * (1.0 - fs) * (1.0 - metallic) * m.diffuse_k + spec[c] * fs) * ao * sh;
}
}
let c = add(out, emissive);
Some([c[0] * alpha, c[1] * alpha, c[2] * alpha, alpha])
}
fn shadow_only(s: &Scene, m: &Material, f: &Frag, alpha: f32) -> [f32; 4] {
if m.unlit || !m.accepts_lights {
return [0.0; 4];
}
let n = if f.front { norm(f.normal) } else { scale(norm(f.normal), -1.0) };
let mut amount = 0.0f32;
for l in &s.lights {
let (to_l, dist) = to_light(l, f.pos);
if attenuation(l, f.pos, to_l, dist) <= 0.0 {
continue;
}
let n_l = dot(n, to_l);
if n_l <= 0.0 {
continue;
}
amount = amount.max(1.0 - light_shadow(s, l, f.pos, n, n_l));
}
if let Some(e) = &s.env {
amount = amount.max(1.0 - env_shadow(s, e, f.pos, n, n));
}
[0.0, 0.0, 0.0, alpha * amount]
}
+1
View File
@@ -25,6 +25,7 @@ sha2 = { version = "0.10", default-features = false, features = ["std"], optiona
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
skrifa = { workspace = true, optional = true }
tempfile = "3.20"
toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] }
serde_json = { workspace = true, optional = true }
+27
View File
@@ -258,6 +258,15 @@ Changes from `craft-media-testkit`'s `hammer`:
- `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data
moved or shared with an `Arc`.
## temp
`TempDir::new(tag)` makes a new, empty folder `craft-testkit-<tag>-<random characters>` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; removal on drop is best effort, and `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix `new` asks for mode 0o700 (the umask can remove more bits), and returns an error when the folder it made is a link, is open to other users or is owned by another user. It returns `PermissionDenied` when the mode lacks owner read, write or search permission. The check reads mode bits only. It does not read POSIX or NFSv4 access control lists, so an entry that grants another user access is not detected. On Windows the folder gets the inheritable access entries of the temporary directory (the user's own `%LOCALAPPDATA%\Temp` by default) and is not checked. When `TMP` or `TEMP` names a shared folder, other users may be able to open the new folder, depending on that folder's access entries. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder. On every platform, `new(tag)` and `file(name)` return `InvalidInput` for an empty tag or name, `.`, `..`, or a tag or name with `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*`, NUL or a control character U+0001 to U+001F. The module is not built for `wasm32`.
```rust
let dir = craft_testkit::TempDir::new("export")?;
std::fs::write(dir.file("out.png")?, &png)?;
```
## `image` feature
`craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18.
@@ -494,6 +503,15 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|---|---|---|---|
| `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` |
### temp
| Code | Repository | Path | SHA |
|---|---|---|---|
| `temp_dir`, `TempDir` | storytold/vectorcraft | `crates/testkit/src/lib.rs` | `bada8e1710` |
| `ScratchDir` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` | `92e2071199` |
| `private_dir` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` |
| `TempDir` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e69890223` |
### image
| Code | Source |
@@ -591,6 +609,15 @@ An adoption keeps the variable name the app uses today.
CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which
cases change, and keep the test names.
### temp
| Consumer | Code it replaces | State |
|---|---|---|
| VectorCraft | `temp_dir` and `TempDir` in `crates/testkit/src/lib.rs` | Pending. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. |
| PdfCraft | `ScratchDir` in `crates/testkit/src/scratch.rs` (#6124) | Pending. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. |
| CADCraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | Pending. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. |
| `craft-media-testkit` | `private_dir()` in `crates/media-testkit/src/lib.rs` | Pending. `private_dir()` is unchanged. |
### image
| Consumer | Today | State |
+9
View File
@@ -43,6 +43,11 @@
//! for GPU tests. Every GPU test in a process must take this lock, because a test that takes a
//! different lock can run at the same time as one that takes this one.
//!
//! On targets other than `wasm32`, `temp::TempDir` is a new test folder, private to the user on
//! Unix, that is removed with its contents when dropped, also when the test panics. Removal on drop
//! is best effort; `temp::TempDir::close` returns the error. The Unix privacy check reads the mode
//! bits only; it does not read POSIX or NFSv4 access control lists.
//!
//! `skip` decides what a test does when something it needs is missing (a program, a corpus,
//! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the
//! variable the caller names is `1`. A value other than unset, empty or `1` fails the test as a
@@ -92,6 +97,8 @@ pub mod sample_damage;
pub mod serial;
#[cfg(not(target_arch = "wasm32"))]
pub mod skip;
#[cfg(not(target_arch = "wasm32"))]
pub mod temp;
#[cfg(not(target_arch = "wasm32"))]
pub use deadline::{DeadlineLimit, Signal, wait_until, with_deadline};
@@ -99,3 +106,5 @@ pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float
#[cfg(not(target_arch = "wasm32"))]
pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits};
#[cfg(not(target_arch = "wasm32"))]
pub use temp::TempDir;
+475
View File
@@ -0,0 +1,475 @@
//! Test folders that are removed with their contents when the test that made them ends.
//!
//! [`TempDir::new`] makes a new, empty folder in the system temporary directory with
//! [`tempfile::Builder`]: the name is `craft-testkit-<tag>-` followed by random characters, and a
//! name that is already taken is skipped. A folder this module did not make is never emptied or
//! reused. On Unix the folder is made with mode 0o700, and before [`TempDir::new`] returns it checks
//! that the folder is a real folder, not a link, with no access for other users, and owned by the
//! user running the test. The access check reads the mode bits only; it does not read POSIX or NFSv4
//! access control lists, so an entry that grants another user access is not detected. The checks apply to the created folder only, so a temporary directory
//! reached through a link (`/var` on macOS links to `/private/var`) works. On Windows the folder
//! gets the inheritable access entries of the temporary directory, which is the user's own
//! `%LOCALAPPDATA%\Temp` by default, and no access check is made. When `TMP` or `TEMP` names a
//! shared folder, other users may be able to open the new folder, depending on that folder's
//! access entries.
//!
//! [`TempDir::path`] returns the canonical path of the folder: `/private/var/...` on macOS, and a
//! `\\?\` path on Windows. Compare it with another canonical path, not with a join of
//! [`std::env::temp_dir`].
//!
//! Dropping a [`TempDir`], also while a test panics, removes the folder with everything in it. A
//! link inside the folder is removed, not followed. Removal on drop is best effort: a file another
//! process holds open can stop it on Windows. [`TempDir::close`] removes the folder and returns the
//! error. A process that is killed or aborts leaves its folders behind, and later calls skip them.
//!
//! The checks read the folder once, after it is made. They do not protect against a process of the
//! same user that replaces the folder after the check.
use std::io;
use std::path::{Path, PathBuf};
/// How many random characters follow the tag in a folder name.
const RANDOM_CHARS: usize = 10;
/// The file [`TempDir::new`] makes, reads and removes in a new folder on Unix to learn which user
/// owns the files this process makes.
#[cfg(unix)]
const OWNER_PROBE: &str = ".craft-testkit-owner";
/// A new, empty folder in the system temporary directory, removed with its contents when dropped,
/// also when the test panics.
///
/// Bind it to a variable that lives as long as the folder is needed. Used as a temporary, as in
/// `TempDir::new("x")?.file("a.png")`, it is dropped, and the folder removed, at the end of that
/// statement.
#[derive(Debug)]
pub struct TempDir {
/// The canonical path of the folder.
path: PathBuf,
/// Removes the folder when dropped.
dir: tempfile::TempDir,
}
impl TempDir {
/// Makes a new folder named `craft-testkit-<tag>-<random characters>` in
/// [`std::env::temp_dir`]. Each call makes a folder of its own, also for calls with the same
/// tag at the same time.
///
/// # Errors
///
/// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`,
/// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform.
/// The error from the file system when the folder cannot be made. An error when the folder that
/// was made is a link or another kind of entry, is open to other users, or is owned by another
/// user; such a folder is left in place. On Unix, `PermissionDenied` when the mode lacks owner
/// read, write or search permission; such a folder is also left in place.
pub fn new(tag: &str) -> io::Result<Self> {
Self::new_in(tag, &std::env::temp_dir(), RANDOM_CHARS)
}
/// Makes the folder in `root`, with `random` random characters after the tag.
fn new_in(tag: &str, root: &Path, random: usize) -> io::Result<Self> {
one_name("tag", tag)?;
let prefix = format!("craft-testkit-{tag}-");
let mut builder = tempfile::Builder::new();
builder.prefix(&prefix).rand_bytes(random);
#[cfg(unix)]
builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
Self::guard(builder.tempdir_in(std::fs::canonicalize(root)?)?)
}
/// Checks the folder `dir` made and returns it with its canonical path. A folder that fails the
/// check is left in place, since it may not be the one `dir` made.
fn guard(mut dir: tempfile::TempDir) -> io::Result<Self> {
if let Err(e) = verify(dir.path()) {
dir.disable_cleanup(true);
return Err(e);
}
let path = std::fs::canonicalize(dir.path())?;
Ok(Self { path, dir })
}
/// The canonical, absolute path of the folder.
pub fn path(&self) -> &Path {
&self.path
}
/// The path of `name` in the folder. The file is not made.
///
/// # Errors
///
/// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`,
/// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform.
pub fn file(&self, name: &str) -> io::Result<PathBuf> {
one_name("file name", name)?;
Ok(self.path.join(name))
}
/// Removes the folder with everything in it.
///
/// # Errors
///
/// The error from the file system when the folder or something in it cannot be removed.
pub fn close(self) -> io::Result<()> {
self.dir.close()
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
&self.path
}
}
/// Returns `InvalidInput` unless `name` is one path component on every platform.
fn one_name(what: &str, name: &str) -> io::Result<()> {
if name.is_empty()
|| name == "."
|| name == ".."
|| name.contains(['/', '\\', ':', '<', '>', '"', '|', '?', '*'])
|| name.chars().any(|c| c <= '\u{1f}')
{
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{what} {name:?} is not a single file name")));
}
Ok(())
}
/// What [`verify`] reads about a folder, without following a link.
#[derive(Debug, Clone, Copy)]
struct Entry {
is_dir: bool,
is_symlink: bool,
/// The permission bits, on Unix.
mode: Option<u32>,
/// The user id of the owner, on Unix.
owner: Option<u32>,
}
/// Checks that `path` is a folder this process made, as [`check`] describes.
fn verify(path: &Path) -> io::Result<()> {
let meta = std::fs::symlink_metadata(path)?;
#[cfg(unix)]
let (mode, owner) = (Some(std::os::unix::fs::PermissionsExt::mode(&meta.permissions())), Some(std::os::unix::fs::MetadataExt::uid(&meta)));
#[cfg(not(unix))]
let (mode, owner) = (None, None);
let entry = Entry { is_dir: meta.is_dir(), is_symlink: meta.file_type().is_symlink(), mode, owner };
check(path, entry, || my_uid(path))
}
/// Returns an error unless `entry` is a real folder, not a link, with no access for group or other
/// users, with owner read, write and search permission on Unix, owned by the user `me` returns.
/// `me` runs only after the other checks pass.
fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result<Option<u32>>) -> io::Result<()> {
if entry.is_symlink || !entry.is_dir {
return Err(io::Error::other(format!("{}: a link or another kind of entry is in place of the new folder", path.display())));
}
if entry.mode.is_some_and(|mode| mode & 0o077 != 0) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is open to other users", path.display())));
}
if entry.mode.is_some_and(|mode| mode & 0o700 != 0o700) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the owner cannot use the new folder", path.display())));
}
if entry.owner != me()? {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is owned by another user", path.display())));
}
Ok(())
}
/// The user id that owns a file this process makes, read from a probe file made new in `dir` and
/// removed again.
#[cfg(unix)]
fn my_uid(dir: &Path) -> io::Result<Option<u32>> {
let probe = dir.join(OWNER_PROBE);
let meta = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?.metadata();
std::fs::remove_file(&probe)?;
Ok(Some(std::os::unix::fs::MetadataExt::uid(&meta?)))
}
/// Files have no Unix owner here.
#[cfg(not(unix))]
fn my_uid(_dir: &Path) -> io::Result<Option<u32>> {
Ok(None)
}
#[cfg(test)]
mod tests {
use super::*;
fn entries(dir: &Path) -> usize {
std::fs::read_dir(dir).unwrap().count()
}
#[test]
fn a_test_dir_is_removed_with_its_contents_when_dropped() {
let dir = TempDir::new("dropped").unwrap();
let path = dir.path().to_path_buf();
std::fs::create_dir_all(path.join("nested")).unwrap();
std::fs::write(path.join("nested").join("a.txt"), b"a").unwrap();
drop(dir);
assert!(!path.exists(), "{} is left", path.display());
}
#[test]
fn a_test_dir_is_removed_when_its_test_panics() {
let mut path = None;
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let dir = TempDir::new("panicked").unwrap();
std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap();
path = Some(dir.path().to_path_buf());
panic!("the test fails");
}));
assert_eq!(r.err().and_then(|p| p.downcast_ref::<&str>().copied()), Some("the test fails"));
let path = path.unwrap();
assert!(!path.exists(), "{} is left", path.display());
}
#[test]
fn test_dirs_with_one_tag_are_separate_and_private() {
let (a, b) = (TempDir::new("shared-tag").unwrap(), TempDir::new("shared-tag").unwrap());
assert_ne!(a.path(), b.path());
std::fs::write(a.file("a.txt").unwrap(), b"a").unwrap();
assert_eq!(entries(b.path()), 0, "one test's files are not in another's directory");
#[cfg(unix)]
assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(a.path()).unwrap().permissions()) & 0o777, 0o700);
drop(a);
assert!(b.path().is_dir(), "dropping one leaves the other");
}
#[test]
fn a_scratch_dir_is_removed_with_its_contents_when_dropped() {
let dir = TempDir::new("testkit-scratch").unwrap();
let path = dir.path().to_path_buf();
assert!(path.is_dir(), "{path:?} exists while the test holds it");
assert_eq!(entries(&path), 0, "and starts empty");
std::fs::create_dir_all(path.join("nested")).unwrap();
std::fs::write(path.join("nested").join("a.pdf"), b"%PDF").unwrap();
drop(dir);
assert!(!path.exists(), "{path:?} is gone, contents and all");
}
#[test]
fn scratch_dirs_with_the_same_name_are_separate_folders() {
let (a, b) = (TempDir::new("testkit-same").unwrap(), TempDir::new("testkit-same").unwrap());
assert_ne!(a.path(), b.path());
std::fs::write(a.file("x").unwrap(), b"a").unwrap();
drop(b);
assert_eq!(std::fs::read(a.file("x").unwrap()).unwrap(), b"a", "dropping one leaves the other's files");
}
/// With one random character there are 62 names, and every one but `7` is taken: the new folder
/// is `7`, and the folders that were there keep their files.
#[test]
fn a_taken_name_is_skipped_and_its_folder_left_alone() {
let root = TempDir::new("taken-root").unwrap();
let free = '7';
let mut planted = Vec::new();
for c in ('a'..='z').chain('A'..='Z').chain('0'..='9').filter(|&c| c != free) {
let folder = root.path().join(format!("craft-testkit-taken-{c}"));
// On a file system that ignores case, `A` is the folder `a` made.
match std::fs::create_dir(&folder) {
Ok(()) => std::fs::write(folder.join("theirs.pdf"), b"%PDF").unwrap(),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("{}: {e}", folder.display()),
}
planted.push(folder);
}
let dir = TempDir::new_in("taken", root.path(), 1).unwrap();
assert_eq!(dir.path().file_name().and_then(|n| n.to_str()), Some("craft-testkit-taken-7"));
assert_eq!(entries(dir.path()), 0, "and starts empty");
drop(dir);
for folder in &planted {
assert_eq!(std::fs::read(folder.join("theirs.pdf")).unwrap(), b"%PDF", "{folder:?} kept its file");
}
}
#[test]
fn existing_folder_is_never_reused() {
let root = TempDir::new("reuse-root").unwrap();
let theirs = root.path().join("craft-testkit-reuse-");
std::fs::create_dir(&theirs).unwrap();
std::fs::write(theirs.join("theirs.txt"), b"theirs").unwrap();
// With no random characters the one name tried is the folder above.
let err = TempDir::new_in("reuse", root.path(), 0).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read(theirs.join("theirs.txt")).unwrap(), b"theirs");
assert_eq!(entries(&theirs), 1);
}
#[test]
fn creation_failure_returns_error() {
let root = TempDir::new("failure-root").unwrap();
let file = root.file("a-file").unwrap();
std::fs::write(&file, b"not a folder").unwrap();
assert!(TempDir::new_in("x", &file, RANDOM_CHARS).is_err(), "a file as the root");
assert!(TempDir::new_in("x", &root.path().join("missing"), RANDOM_CHARS).is_err(), "a missing root");
}
#[test]
fn tag_rejects_empty_and_separators() {
for tag in ["", ".", "..", "a/b", "a\\b", "../x", "..\\x", "/x", "C:\\x", "C:x", "a\0b"] {
let err = TempDir::new(tag).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{tag:?}");
}
for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') {
let tag = format!("a{c}b");
assert_eq!(TempDir::new(&tag).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{tag:?}");
}
}
#[test]
fn file_rejects_absolute_parent_and_separators() {
let root = TempDir::new("file-root").unwrap();
let dir = TempDir::new_in("file", root.path(), RANDOM_CHARS).unwrap();
for name in ["", ".", "..", "a/b", "a\\b", "../outside.txt", "..\\outside.txt", "/x", "\\x", "C:\\x", "C:x", "a:stream", "a\0b"] {
let err = dir.file(name).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{name:?}");
}
for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') {
let name = format!("report{c}.txt");
assert_eq!(dir.file(&name).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{name:?}");
}
let a = dir.file("a.txt").unwrap();
assert_eq!(a, dir.path().join("a.txt"));
assert!(!a.exists(), "file does not make the file");
drop(dir);
assert_eq!(entries(root.path()), 0, "nothing was written next to the folder");
}
#[test]
fn path_is_canonical() {
let dir = TempDir::new("canonical").unwrap();
assert!(dir.path().is_absolute());
assert_eq!(dir.path(), std::fs::canonicalize(dir.path()).unwrap());
assert_eq!(dir.path().parent().map(Path::to_path_buf), Some(std::fs::canonicalize(std::env::temp_dir()).unwrap()));
}
#[cfg(windows)]
#[test]
fn windows_path_is_verbatim() {
let dir = TempDir::new("verbatim").unwrap();
assert!(dir.path().to_string_lossy().starts_with(r"\\?\"), "{:?}", dir.path());
}
#[test]
fn same_tag_concurrent_creation_is_unique() {
let barrier = std::sync::Arc::new(std::sync::Barrier::new(16));
let threads: Vec<_> = (0..16)
.map(|_| {
let barrier = std::sync::Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
TempDir::new("concurrent")
})
})
.collect();
let dirs: Vec<TempDir> = threads.into_iter().map(|t| t.join().unwrap().unwrap()).collect();
let paths: std::collections::BTreeSet<&Path> = dirs.iter().map(TempDir::path).collect();
assert_eq!(paths.len(), 16);
assert!(dirs.iter().all(|d| entries(d.path()) == 0), "each starts empty");
}
#[test]
fn close_removes_the_folder() {
let dir = TempDir::new("close").unwrap();
let path = dir.path().to_path_buf();
std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap();
dir.close().unwrap();
assert!(!path.exists());
}
#[test]
fn close_reports_cleanup_failure() {
let dir = TempDir::new("close-failure").unwrap();
std::fs::remove_dir(dir.path()).unwrap();
assert!(dir.close().is_err(), "a folder that is already gone cannot be removed");
}
#[test]
fn wrong_owner_or_public_mode_is_rejected() {
let path = Path::new("folder");
let private = Entry { is_dir: true, is_symlink: false, mode: Some(0o40700), owner: Some(1000) };
assert!(check(path, private, || Ok(Some(1000))).is_ok());
for mode in [0o40750, 0o40705, 0o40777] {
let err = check(path, Entry { mode: Some(mode), ..private }, || Ok(Some(1000))).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}");
}
for mode in [0o40300, 0o40500, 0o40600] {
let err = check(path, Entry { mode: Some(mode), ..private }, || panic!("no probe without owner access")).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}");
}
let err = check(path, private, || Ok(Some(1001))).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
assert!(check(path, Entry { is_symlink: true, ..private }, || panic!("no probe through a link")).is_err());
assert!(check(path, Entry { is_dir: false, ..private }, || panic!("no probe in a file")).is_err());
let open = Entry { mode: Some(0o40777), ..private };
assert!(check(path, open, || panic!("no probe in an open folder")).is_err());
}
#[cfg(unix)]
#[test]
fn new_dir_is_owner_private() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let dir = TempDir::new("private").unwrap();
let meta = std::fs::symlink_metadata(dir.path()).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o700);
let mine = dir.file("mine.txt").unwrap();
std::fs::write(&mine, b"a").unwrap();
assert_eq!(meta.uid(), std::fs::metadata(&mine).unwrap().uid());
std::fs::remove_file(&mine).unwrap();
assert_eq!(entries(dir.path()), 0, "the owner probe is removed");
}
#[cfg(unix)]
#[test]
fn created_folder_symlink_is_rejected() {
let root = TempDir::new("link-root").unwrap();
let real = root.path().join("real");
std::fs::create_dir(&real).unwrap();
std::fs::write(real.join("theirs.txt"), b"theirs").unwrap();
let made = tempfile::Builder::new().prefix("craft-testkit-link-").tempdir_in(root.path()).unwrap();
let link = made.path().to_path_buf();
std::fs::remove_dir(&link).unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
assert!(TempDir::guard(made).is_err());
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is left in place");
assert_eq!(std::fs::read(real.join("theirs.txt")).unwrap(), b"theirs");
assert_eq!(entries(&real), 1, "no probe was made through the link");
}
#[cfg(unix)]
#[test]
fn temp_root_reached_through_symlink_works() {
let root = TempDir::new("symlink-root").unwrap();
let real = root.path().join("real");
std::fs::create_dir(&real).unwrap();
let link = root.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let dir = TempDir::new_in("through-link", &link, RANDOM_CHARS).unwrap();
assert_eq!(dir.path().parent(), Some(real.as_path()), "the path is canonical");
assert!(dir.path().is_dir());
let path = dir.path().to_path_buf();
let other = root.path().join("other");
std::fs::create_dir_all(other.join(path.file_name().unwrap())).unwrap();
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&other, &link).unwrap();
drop(dir);
assert!(!path.exists(), "the folder that was made is removed after the link changes");
assert!(other.join(path.file_name().unwrap()).is_dir(), "a folder with the same name under the new target stays");
assert!(real.is_dir() && link.is_symlink(), "the root and the link stay");
}
#[cfg(unix)]
#[test]
fn drop_does_not_follow_inner_symlink() {
let root = TempDir::new("inner-link-root").unwrap();
let outside = root.path().join("outside");
std::fs::create_dir(&outside).unwrap();
std::fs::write(outside.join("keep.txt"), b"keep").unwrap();
let dir = TempDir::new_in("inner-link", root.path(), RANDOM_CHARS).unwrap();
std::os::unix::fs::symlink(&outside, dir.file("link").unwrap()).unwrap();
let path = dir.path().to_path_buf();
drop(dir);
assert!(!path.exists());
assert_eq!(std::fs::read(outside.join("keep.txt")).unwrap(), b"keep");
}
}
+1
View File
@@ -49,6 +49,7 @@ chrono = { workspace = true }
semver = { version = "1", features = ["serde"] }
[dev-dependencies]
craft-testkit = { workspace = true }
craft-ui = { workspace = true, features = ["suite"] }
flate2 = "1"
+13 -17
View File
@@ -806,24 +806,25 @@ pub(crate) mod macos_checks {
/// Runs `hdiutil` with `args` (the caller holds its [`macos::disk_image_turn`]). The disk-image
/// helper can turn a request away with EAGAIN ("Resource temporarily unavailable") while it
/// is busy elsewhere, as on shared CI runners; that reply alone is retried, up to five
/// attempts over about eight seconds. Any other result returns at once.
/// is busy elsewhere, as on shared CI runners; that reply alone is retried, until the helper
/// gives another answer. A helper that stays busy for a minute fails the test.
fn hdiutil(args: &[&std::ffi::OsStr]) -> std::process::Output {
let mut output = std::process::Command::new("hdiutil").args(args).output().unwrap();
for wait_ms in [500, 1000, 2000, 4000] {
// Only stops a test that a busy helper holds up. The retries stop with it, on this thread,
// before the caller's turn and folders are released.
let hang_guard = std::time::Instant::now();
loop {
let output = std::process::Command::new("hdiutil").args(args).output().unwrap();
if output.status.success() || !busy(&output.stderr) {
break;
return output;
}
std::thread::sleep(std::time::Duration::from_millis(wait_ms));
output = std::process::Command::new("hdiutil").args(args).output().unwrap();
let reason = String::from_utf8_lossy(&output.stderr);
assert!(hang_guard.elapsed() < std::time::Duration::from_secs(60), "the disk-image helper stayed busy for a minute: {}", reason.trim());
}
output
}
/// A release-style disk image holding a `PhotoCraft.app` that reports `version`. The tests,
/// in this process and in others, ask the disk-image helper one at a time; when a program
/// that is not one of these tests keeps it busy, the test fails with what `hdiutil create`
/// said.
/// in this process and in others, ask the disk-image helper one at a time; while a program
/// that is not one of these tests keeps it busy, [`hdiutil`] asks again.
fn dmg(dir: &Path, version: &str) -> PathBuf {
let src = dir.join(format!("src-{version}"));
bundle(&src, version);
@@ -1020,8 +1021,7 @@ pub(crate) mod macos_checks {
let mount = paths.cache.join(format!("mount-photocraft-{pid}-1"));
std::fs::create_dir_all(&mount).unwrap();
// One request at a time, as in `dmg`. A detach elsewhere can still keep the disk-image
// helper busy, and it turns the attach away; the attach is tried a few times, as
// `install_dmg` does.
// helper busy, and it turns the attach away; the test's `hdiutil` helper then asks again.
let output = {
let _one_at_a_time = macos::disk_image_turn();
hdiutil(&[
@@ -1036,10 +1036,6 @@ pub(crate) mod macos_checks {
])
};
let _attached = Attached(mount.clone());
if !output.status.success() && busy(&output.stderr) {
eprintln!("skipped: the disk-image helper stayed busy: {}", String::from_utf8_lossy(&output.stderr).trim());
return;
}
assert!(output.status.success(), "hdiutil attach failed: {}", String::from_utf8_lossy(&output.stderr).trim());
let staging = apps.join(format!(".artcraft-launcher-staging-{pid}-Ab12Cd"));
bundle(&staging, "0.6.0");
+88 -25
View File
@@ -727,19 +727,36 @@ pub(crate) mod inherited_pipe_tests {
/// Runs a helper while polling cancellation and draining its bounded output.
#[cfg(target_os = "linux")]
pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<(), String>) -> Result<std::process::Output, String> {
pub(crate) fn cancellable_output(cmd: Command, check: impl Fn() -> Result<(), String>) -> Result<std::process::Output, String> {
let (mut helper_start, mut output_start) = (None, None);
cancellable_output_until(cmd, check, move |pending| {
let (start, limit) = match pending {
Pending::Helper => (*helper_start.get_or_insert_with(Instant::now), Duration::from_secs(60 * 60)),
Pending::Output => (*output_start.get_or_insert_with(Instant::now), Duration::from_secs(5)),
};
let more = within(start, Instant::now(), limit);
if more {
std::thread::sleep(Duration::from_millis(25));
}
more
})
}
/// [`cancellable_output`], asking `keep_waiting` each time the run finds the helper or its output
/// unfinished. `keep_waiting` returns `false` when the time limit for the helper (one hour) or for
/// its output to close after it exits (five seconds) has passed.
#[cfg(target_os = "linux")]
fn cancellable_output_until(
mut cmd: Command,
check: impl Fn() -> Result<(), String>,
mut keep_waiting: impl FnMut(Pending) -> bool,
) -> Result<std::process::Output, String> {
check()?;
let mut child =
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("couldn't run flatpak ({e})"))?;
let stdout = read_all(child.stdout.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?;
let stderr = read_all(child.stderr.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?;
let started = Instant::now();
let status = loop {
if started.elapsed() >= Duration::from_secs(60 * 60) {
let _ = child.kill();
let _ = child.wait();
return Err("Flatpak did not finish within one hour".into());
}
if let Err(e) = check() {
let _ = child.kill();
let _ = child.wait();
@@ -747,7 +764,12 @@ pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<()
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => std::thread::sleep(Duration::from_millis(25)),
Ok(None) if keep_waiting(Pending::Helper) => {}
Ok(None) => {
let _ = child.kill();
let _ = child.wait();
return Err("Flatpak did not finish within one hour".into());
}
Err(e) => {
let _ = child.kill();
let _ = child.wait();
@@ -755,13 +777,11 @@ pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<()
}
}
};
let deadline = Instant::now();
while !stdout.is_finished() || !stderr.is_finished() {
check()?;
if deadline.elapsed() > Duration::from_secs(5) {
if !keep_waiting(Pending::Output) {
return Err("Flatpak output did not close after completion".into());
}
std::thread::sleep(Duration::from_millis(25));
}
Ok(std::process::Output { status, stdout: stdout.join().unwrap_or_default(), stderr: stderr.join().unwrap_or_default() })
}
@@ -770,28 +790,71 @@ pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<()
#[cfg(target_os = "linux")]
pub(crate) mod update_cancel_tests {
use super::*;
use craft_testkit::deadline::with_deadline;
use craft_ui::testing::trial;
/// Stops a broken test: a run that waits for a helper that never exits on its own, or for
/// output that a descendant never closes.
const HANG_GUARD: Duration = Duration::from_secs(60);
/// The first check runs before the helper starts, and the second finds it running. The helper
/// never exits on its own, so the run returns only by stopping it.
#[trial]
fn cancels_a_running_helper_promptly() {
let mut cmd = command("sleep");
cmd.arg("30");
let start = Instant::now();
let result = cancellable_output(cmd, || if start.elapsed() >= Duration::from_millis(100) { Err("cancelled".into()) } else { Ok(()) });
assert_eq!(result.unwrap_err(), "cancelled");
assert!(start.elapsed() < Duration::from_secs(5));
with_deadline(HANG_GUARD, "a canceled helper run", || {
let mut cmd = command("sleep");
cmd.arg("86400");
let checks = std::cell::Cell::new(0);
let result = cancellable_output(cmd, || {
checks.set(checks.get() + 1);
if checks.get() >= 2 { Err("cancelled".into()) } else { Ok(()) }
});
assert_eq!(result.unwrap_err(), "cancelled");
assert_eq!(checks.get(), 2, "the run kept checking after it was canceled");
});
}
/// A descendant that outlives the helper keeps the pipes open; the caller gets an error at
/// the deadline instead of waiting for it.
/// Stops the process whose id the file at this path holds, when dropped.
struct Descendant(std::path::PathBuf);
impl Drop for Descendant {
fn drop(&mut self) {
if let Ok(pid) = std::fs::read_to_string(&self.0) {
let _ = command("kill").arg(pid.trim()).status();
}
}
}
/// A descendant that outlives the helper keeps the pipes open; the caller gets an error when
/// the time limit for the output passes instead of waiting for the descendant.
#[trial]
fn output_held_open_by_a_descendant_fails_at_the_deadline() {
let mut cmd = command("sh");
cmd.args(["-c", "sleep 8 &"]);
let start = Instant::now();
let err = cancellable_output(cmd, || Ok(())).expect_err("a descendant holding the pipes should time out");
assert!(err.contains("did not close after completion"), "{err}");
assert!(start.elapsed() < Duration::from_secs(8), "{:?}", start.elapsed());
with_deadline(HANG_GUARD, "a run whose output a descendant holds open", || {
let dir = tempfile::tempdir().unwrap();
let descendant = Descendant(dir.path().join("descendant"));
let mut cmd = command("sh");
cmd.args(["-c", "sleep 86400 & echo $! > \"$1\"", "sh"]).arg(&descendant.0);
let mut output_asked = false;
let result = cancellable_output_until(
cmd,
|| Ok(()),
|pending| match pending {
Pending::Helper => {
std::thread::yield_now();
true
}
// The helper has exited and the descendant holds its pipes: the time limit passes.
Pending::Output => {
assert!(!output_asked, "the run kept waiting after its time limit passed");
output_asked = true;
false
}
},
);
let err = result.expect_err("a descendant holding the pipes should time out");
assert!(err.contains("did not close after completion"), "{err}");
assert!(output_asked, "the run didn't wait for the output");
});
}
#[trial]
+21 -6
View File
@@ -25,6 +25,8 @@ use crate::updater::Status;
#[cfg(feature = "suite")]
pub(crate) mod stories;
#[cfg(test)]
pub(crate) mod tests;
const PROMPT_KEY: &str = "updateDialog.prompt";
const CHECK_KEY: &str = "updateDialog.check";
@@ -69,6 +71,8 @@ craft_ui::words! {
/// A ready update on macOS and Linux, already in place ([`crate::updater::READY_TEXT`]).
ready_installed: template "updateDialog.readyInstalled" = "The update is installed. Close {app} to finish; it restarts by itself.";
managed: template "updateDialog.managed" = "{app} {running} follows the version chosen in the launcher, so it does not update itself.";
/// A requested check while the app has turned update checks off ([`crate::updater::Status::Off`]).
off: template "updateDialog.off" = "Update checks are turned off in {app}.";
updated: template "updateDialog.updated" = "{app} updated to {version}.";
install_failed: template "updateDialog.installFailed" = "The update could not be installed: {reason}";
}
@@ -456,20 +460,26 @@ impl UpdateCheckDialog {
self.chosen = Some(choice);
}
/// The release the available state shows. While checks are off ([`Status::Off`]) the dialog
/// shows that message with OK instead, even when the updater still holds a release.
fn shown_release(&self) -> Option<&Release> {
self.available.as_ref().filter(|_| self.status != Status::Off)
}
/// The release page the available state links to, when it is a safe web link.
fn notes_url(&self) -> Option<&str> {
self.available.as_ref().map(|release| release.html_url.as_str()).filter(|url| safe_web_link(url))
self.shown_release().map(|release| release.html_url.as_str()).filter(|url| safe_web_link(url))
}
/// The choices the current state offers with their roles, the default first.
fn offered(&self, self_updating: bool) -> Vec<(CheckChoice, DialogRole)> {
if self.available.is_some() {
if self.shown_release().is_some() {
let install = if self_updating { CheckChoice::Update } else { CheckChoice::Download };
return vec![(install, DialogRole::Accept), (CheckChoice::CheckAgain, DialogRole::Other)];
}
match self.status {
Status::Idle => vec![(CheckChoice::CheckNow, DialogRole::Accept)],
Status::Checking | Status::Installing | Status::Updated(_) => vec![(CheckChoice::Close, DialogRole::Accept)],
Status::Checking | Status::Installing | Status::Updated(_) | Status::Off => vec![(CheckChoice::Close, DialogRole::Accept)],
Status::Ready => vec![(CheckChoice::Close, DialogRole::Accept), (CheckChoice::RestartToUpdate, DialogRole::Other)],
Status::UpToDate | Status::Managed | Status::Failed(_) | Status::RateLimited | Status::InstallFailed(_) => {
vec![(CheckChoice::Close, DialogRole::Accept), (CheckChoice::CheckAgain, DialogRole::Other)]
@@ -479,7 +489,9 @@ impl UpdateCheckDialog {
/// Whether `choice` can be answered now: the available state's buttons wait for a running install.
fn answerable(&self, choice: CheckChoice) -> bool {
!(self.installing && self.available.is_some() && matches!(choice, CheckChoice::Update | CheckChoice::Download | CheckChoice::CheckAgain))
!(self.installing
&& self.shown_release().is_some()
&& matches!(choice, CheckChoice::Update | CheckChoice::Download | CheckChoice::CheckAgain))
}
/// Shows one pass. The choices are the footer buttons' meanings, in the order of the dialog's `picked`.
@@ -489,7 +501,7 @@ impl UpdateCheckDialog {
let ok = env.words::<CommonWords>().ok.clone();
let subject = Subject::of(&env);
let self_updating = *self.self_updating.get_or_insert_with(|| subject.app.is_some_and(self_update::is_self_updating));
self.release_installs = match (subject.app, &self.available) {
self.release_installs = match (subject.app, self.shown_release()) {
(Some(app), Some(release)) => self_update::release_installs(app, release),
_ => true,
};
@@ -513,7 +525,7 @@ impl UpdateCheckDialog {
let enter = offered.first().is_some_and(|(choice, _)| self.answerable(*choice));
let initial = if enter { Initial::Default } else { Initial::Keep };
let notes = self.notes_url().map(str::to_owned);
let version = self.available.as_ref().map(Release::version_label);
let version = self.shown_release().map(Release::version_label);
let (status, running, message, installing, icon) = (&self.status, &self.running_version, &self.message, self.installing, &self.icon);
let installing_label = words.installing.clone();
// What the last update came to is a notice that leaves the app usable behind it.
@@ -572,6 +584,9 @@ impl UpdateCheckDialog {
Status::Managed => {
Text::new(words.managed.fill(&[("app", subject.name), ("running", running)])).shade(Shade::Muted).show(ui);
}
Status::Off => {
Text::new(words.off.fill(&[("app", subject.name)])).shade(Shade::Muted).show(ui);
}
Status::Updated(version) => {
Text::new(words.updated.fill(&[("app", subject.name), ("version", version)])).show(ui);
}
+23
View File
@@ -0,0 +1,23 @@
//! The check dialog's choices in each state.
use super::*;
use craft_ui::testing::trial;
fn release() -> Release {
Release { tag: "v2.0.0".into(), html_url: "https://example.org/releases/v2.0.0".into(), ..Release::default() }
}
/// A release the updater still holds after checks were turned off does not hide the Off
/// message: the dialog offers OK alone, with no release notes link.
#[trial]
fn checks_off_shows_the_off_state_over_a_held_release() {
let mut dialog = UpdateCheckDialog::new("1.0.0").with_self_updating(true);
dialog.set_available(Some(release()));
assert_eq!(dialog.offered(true), vec![(CheckChoice::Update, DialogRole::Accept), (CheckChoice::CheckAgain, DialogRole::Other)]);
dialog.set_status(Status::Off);
assert_eq!(dialog.offered(true), vec![(CheckChoice::Close, DialogRole::Accept)]);
assert!(dialog.notes_url().is_none());
dialog.set_installing(true);
assert!(dialog.answerable(CheckChoice::Close));
assert_eq!(dialog.confirm(&Context::default()), Some(CheckChoice::Close));
}
+95 -2
View File
@@ -12,6 +12,7 @@
//! reports what came of it: [`Status::Updated`] or [`Status::InstallFailed`].
use std::path::PathBuf;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::mpsc::{Receiver, SendError, Sender, TryRecvError, channel};
use std::sync::{Arc, Mutex, PoisonError};
@@ -81,6 +82,9 @@ pub enum Status {
/// A requested check found that the launcher keeps this app on a version of its choosing
/// ([`Updater::managed`]), so it does not update itself.
Managed,
/// A check was requested while the app has turned update checks off
/// ([`Updater::set_checks_enabled`]), so it did not run.
Off,
/// This start follows an update that installed this version.
Updated(String),
/// The last update could not be installed, for this reason.
@@ -120,6 +124,16 @@ type Found = Result<Option<(Release, bool)>, CheckError>;
/// Says whether this copy can install a release itself (tests stand in for the files with one).
type InstallProbe = Arc<dyn Fn(&'static App, &Release) -> bool + Send + Sync>;
/// Runs on the check's thread just before it starts its request (tests).
type BeforeAsk = Arc<dyn Fn() + Send + Sync>;
/// The check's thread has not started its request.
const CHECK_WAITING: u8 = 0;
/// The check's thread has started its request.
const CHECK_ASKING: u8 = 1;
/// Checks were turned off before the check's thread started its request: it asks nothing.
const CHECK_DROPPED: u8 = 2;
/// Whether this copy can install `release` itself. It reads the installed files, which can take
/// long on slow storage, so the check's thread and the offer's thread call it, never a pass.
fn can_install_itself(app: &'static App, release: &Release) -> bool {
@@ -241,7 +255,16 @@ pub struct Updater {
started: bool,
/// The last update's outcome record was read ([`Updater::read_last_update`]).
outcome_read: bool,
/// Checks may ask the network ([`Self::set_checks_enabled`]).
checks_enabled: bool,
check: Option<Receiver<Found>>,
/// Whether `check`'s thread has started its request ([`CHECK_ASKING`]), or checks were turned
/// off before it did ([`CHECK_DROPPED`]). The thread moves it from [`CHECK_WAITING`] to
/// [`CHECK_ASKING`] in one step as it begins its request, so it either begins the request
/// before checks are turned off or asks nothing.
check_state: Arc<AtomicU8>,
/// Runs on the check's thread just before it starts its request (tests).
before_ask: Option<BeforeAsk>,
/// A release the app offered ([`Self::offer`]) while its thread reads whether this copy can
/// install it itself; `tick` opens the prompt with the answer.
offered: Option<Receiver<(Release, bool)>>,
@@ -304,7 +327,10 @@ impl Updater {
requested: false,
started: false,
outcome_read: false,
checks_enabled: true,
check: None,
check_state: Arc::new(AtomicU8::new(CHECK_WAITING)),
before_ask: None,
offered: None,
next_offer: None,
offer_outdated: false,
@@ -358,6 +384,44 @@ impl Updater {
}
}
/// Turns update checks on or off, as [`Self::set_checks_enabled`] does.
#[must_use]
pub fn with_checks_enabled(mut self, enabled: bool) -> Self {
self.set_checks_enabled(enabled);
self
}
/// Turns update checks on or off, for a session that must not reach the network (a test, a
/// scripted run, a user who turned checks off). While they are off, [`Self::check_at_start`]
/// reads only what the last update came to, and [`Self::check_now`] reports [`Status::Off`]
/// without asking the network or the launcher's file. Turning checks off drops the answer of
/// a check that is running; its thread skips the request when it has not begun it yet, and a
/// request already under way finishes unread. A requested check then reports [`Status::Off`].
/// A check at start that was skipped does not run when checks are turned on again;
/// [`Self::check_now`] does. Turning checks on again sets a [`Status::Off`] back to
/// [`Status::Idle`]. An update that is installing or ready carries on, and
/// [`Self::offer`] still opens the prompt for a release the app found itself. Checks are on
/// by default.
pub fn set_checks_enabled(&mut self, enabled: bool) {
self.checks_enabled = enabled;
// A result that says checks are off is no longer true; the check dialog offers Check Now.
if enabled && self.status == Status::Off {
self.status = Status::Idle;
}
if !enabled && self.check.take().is_some() {
self.check_state.store(CHECK_DROPPED, Ordering::SeqCst);
// A requested check answers as `finish_check` would while an update installs or is ready.
if std::mem::take(&mut self.requested) {
self.status = if self.install.is_some() || self.installed { self.pending_status() } else { Status::Off };
}
}
}
/// Whether update checks are on ([`Self::set_checks_enabled`]).
pub fn checks_enabled(&self) -> bool {
self.checks_enabled
}
/// Replaces the built-in check with `source`, which takes no arguments. [`Self::with_check`]
/// sets one that is passed the app and version.
pub fn with_source(self, source: CheckSource) -> Self {
@@ -380,6 +444,13 @@ impl Updater {
self
}
/// Runs `hook` on the check's thread just before it starts its request (tests).
#[cfg(test)]
fn with_before_ask(mut self, hook: BeforeAsk) -> Self {
self.before_ask = Some(hook);
self
}
/// Reads and writes the update's outcome records under `paths` instead of the app's own
/// folders (tests).
pub fn with_paths(mut self, paths: Paths) -> Self {
@@ -457,7 +528,9 @@ impl Updater {
/// Help ▸ Check for Updates: a check whose outcome [`Self::status`] reports. A check already
/// running becomes a requested one. While an update installs or waits for the app to close,
/// nothing starts and the status says so ([`Status::Installing`], [`Status::Ready`]).
/// nothing starts and the status says so ([`Status::Installing`], [`Status::Ready`]). While
/// checks are off ([`Self::set_checks_enabled`]), nothing starts and the status is
/// [`Status::Off`].
pub fn check_now(&mut self) {
self.started = true;
self.begin(true);
@@ -579,6 +652,14 @@ impl Updater {
}
return;
}
if !self.checks_enabled {
if requested {
self.status = Status::Off;
} else {
log::info!("{} skips the update check: checks are off", self.app.name);
}
return;
}
if requested {
self.requested = true;
self.status = Status::Checking;
@@ -592,9 +673,21 @@ impl Updater {
return;
}
let (tx, rx) = channel();
let (source, probe, app, version) = (self.source.clone(), self.probe.clone(), self.app, self.version.clone());
self.check_state = Arc::new(AtomicU8::new(CHECK_WAITING));
let state = self.check_state.clone();
let (source, probe, before_ask, app, version) =
(self.source.clone(), self.probe.clone(), self.before_ask.clone(), self.app, self.version.clone());
let spawned = std::thread::Builder::new().name("update-check".into()).spawn(move || {
let ask = || -> Found {
if let Some(hook) = &before_ask {
hook();
}
// This exchange is where the request begins. Once `set_checks_enabled(false)` has
// stored `CHECK_DROPPED`, it fails and the thread asks nothing; a thread that
// passed it first has begun its request, which finishes unread.
if state.compare_exchange(CHECK_WAITING, CHECK_ASKING, Ordering::SeqCst, Ordering::SeqCst).is_err() {
return Ok(None);
}
let check = CheckContext { app, version };
let checked: Checked = match source {
Some(ask) => ask(&check),
+127
View File
@@ -354,6 +354,133 @@ fn a_check_answering_during_an_update_reports_the_update() {
}
}
#[trial]
fn checks_turned_off_never_ask_the_network() {
let ctx = egui::Context::default();
let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = asked.clone();
let mut u = Updater::new(&PHOTOCRAFT, "0.1.0")
.with_source(Arc::new(move || {
count.fetch_add(1, Ordering::SeqCst);
Ok(Some(newer()))
}))
.with_pins_path(no_pins())
.with_checks_enabled(false);
assert!(!u.checks_enabled());
u.check_at_start();
assert!(u.check.is_none());
assert_eq!(u.status(), &Status::Idle);
u.check_now();
assert!(u.check.is_none());
assert_eq!(u.status(), &Status::Off);
u.tick(&ctx);
assert!(!u.prompt_open());
assert_eq!(asked.load(Ordering::SeqCst), 0);
// Turned on again, the status no longer says checks are off, and a requested check asks.
u.set_checks_enabled(true);
assert_eq!(u.status(), &Status::Idle);
u.check_now();
u.settle_for_tests(&ctx);
assert!(u.prompt_open());
assert_eq!(asked.load(Ordering::SeqCst), 1);
}
/// The first check's request is under way when checks are turned off: the test waits until its
/// thread is inside the source, turns checks off, lets the source answer with a release and waits
/// for the thread to finish before checking that the release was not offered.
#[trial]
fn turning_checks_off_drops_a_running_check() {
let ctx = egui::Context::default();
let (entered_tx, entered) = channel();
let (release, release_rx) = channel::<()>();
let (entered_tx, release_rx) = (Mutex::new(entered_tx), Mutex::new(release_rx));
let mut u = Updater::new(&PHOTOCRAFT, "0.1.0")
.with_source(Arc::new(move || {
let _ = entered_tx.lock().unwrap_or_else(PoisonError::into_inner).send(());
let _ = release_rx.lock().unwrap_or_else(PoisonError::into_inner).recv();
Ok(Some(newer()))
}))
.with_pins_path(no_pins());
u.check_now();
assert_eq!(u.status(), &Status::Checking);
entered.recv().expect("the check's thread enters the source");
// The test keeps the thread's channel to learn when it has finished; the updater drops a stand-in.
let answer = u.check.take().expect("the check is running");
let (_stand_in_tx, stand_in) = channel();
u.check = Some(stand_in);
u.set_checks_enabled(false);
assert!(u.check.is_none());
assert_eq!(u.status(), &Status::Off);
release.send(()).expect("the source waits");
assert!(matches!(answer.recv(), Ok(Ok(Some(_)))), "the request finishes with a release");
u.tick(&ctx);
assert!(!u.prompt_open());
assert_eq!(u.status(), &Status::Off);
// The dropped check's thread is told to ask nothing more; the next check gets its own flag.
let mut u = updater(Ok(None));
u.check_now();
let state = u.check_state.clone();
assert_ne!(state.load(Ordering::SeqCst), CHECK_DROPPED);
u.set_checks_enabled(false);
assert_eq!(state.load(Ordering::SeqCst), CHECK_DROPPED);
u.set_checks_enabled(true);
u.check_now();
assert_ne!(u.check_state.load(Ordering::SeqCst), CHECK_DROPPED);
u.settle_for_tests(&ctx);
assert_eq!(u.status(), &Status::UpToDate);
// A check at start that is running stops quietly.
let mut u = updater(Ok(Some(newer())));
u.check_at_start();
u.set_checks_enabled(false);
assert!(u.check.is_none());
u.tick(&ctx);
assert!(!u.prompt_open());
assert_eq!(u.status(), &Status::Idle);
// A requested check dropped while an update installs reports the installation.
let mut u = updater(Ok(None));
u.check_now();
let (_tx, rx) = channel();
u.install = Some((rx, newer()));
u.set_checks_enabled(false);
assert_eq!(u.status(), &Status::Installing);
}
/// The check's thread stops just before its request while the test turns checks off; once it
/// goes on, it does not start the request.
#[trial]
fn checks_turned_off_before_the_request_starts_skip_it() {
let (reached_tx, reached) = channel();
let (go, go_rx) = channel::<()>();
let (reached_tx, go_rx) = (Mutex::new(reached_tx), Mutex::new(go_rx));
let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = asked.clone();
let mut u = Updater::new(&PHOTOCRAFT, "0.1.0")
.with_source(Arc::new(move || {
count.fetch_add(1, Ordering::SeqCst);
Ok(Some(newer()))
}))
.with_pins_path(no_pins())
.with_before_ask(Arc::new(move || {
let _ = reached_tx.lock().unwrap_or_else(PoisonError::into_inner).send(());
let _ = go_rx.lock().unwrap_or_else(PoisonError::into_inner).recv();
}));
u.check_now();
reached.recv().expect("the check's thread reaches its request");
// The test keeps the thread's channel to learn when it has finished; the updater drops a stand-in.
let answer = u.check.take().expect("the check is running");
let (_stand_in_tx, stand_in) = channel();
u.check = Some(stand_in);
u.set_checks_enabled(false);
go.send(()).expect("the check's thread waits");
assert!(matches!(answer.recv(), Ok(Ok(None))), "the thread answers without a release");
assert_eq!(asked.load(Ordering::SeqCst), 0);
assert_eq!(u.status(), &Status::Off);
}
/// A failed installation closes a result window showing it; the prompt says why.
#[trial]
fn a_failed_install_ends_the_installing_status() {
+8
View File
@@ -172,6 +172,14 @@ fn the_check_dialog_words_a_rate_limit_itself_and_passes_other_reasons_through()
assert!(check_dialog_shows(Status::Failed("offline".into()), "offline"));
}
/// A requested check while checks are off says so, and offers no second check.
#[trial]
fn the_check_dialog_says_checks_are_off() {
assert!(check_dialog_shows(Status::Off, "Update checks are turned off in PhotoCraft."));
let words = UpdateWords::default();
assert!(!check_dialog_shows(Status::Off, words.check_again.as_str()));
}
#[trial]
fn a_panicking_check_is_an_error_not_a_hang() {
let ctx = ctx();
+2 -1
View File
@@ -146,7 +146,8 @@ application's menu bar, `NativeBar::apply` keeps it in step (a changed `structur
`windows` key rebuilds only the Windows menu, anything else updates in place; `NativeBar::failed` reports a
rebuild that failed and left the menus as they were), and the `Handler` set with
`NativeBar::set_handler` receives each chosen item's `id`, the modifiers held and whether a key press chose it.
`install_app_menu` installs a minimal app menu whose Quit reports to a handler. Off macOS (and without the
`install_app_menu` installs a minimal app menu whose Quit reports to a handler, with English titles;
`install_app_menu_with` takes the titles as an `AppMenu`. Off macOS (and without the
feature) every call does nothing, so callers need no platform check. craft-menu lowers its menu model to
this description.
+38 -2
View File
@@ -33,7 +33,7 @@ mod other;
#[cfg(not(all(target_os = "macos", feature = "appkit")))]
use other as imp;
pub use imp::{hide_app, hide_other_apps, install_app_menu, system_title};
pub use imp::{hide_app, hide_other_apps, install_app_menu, install_app_menu_with, system_title};
/// Called when an item is chosen: the item's `id` and how it was chosen ([`Chosen`]: key press or
/// click, and the modifiers held either way). The platform calls it between frames from the event
@@ -166,7 +166,7 @@ pub enum Node {
Platform {
/// Which one.
kind: Platform,
/// The title.
/// The title. `&` is literal.
title: String,
},
/// An item the app handles.
@@ -254,6 +254,42 @@ impl Options {
}
}
/// The titles of the minimal application menu ([`install_app_menu_with`]). `&` is literal.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AppMenu {
/// The menu's title.
pub title: String,
/// About.
pub about: String,
/// The Services submenu.
pub services: String,
/// Hide.
pub hide: String,
/// Hide Others.
pub hide_others: String,
/// Show All.
pub show_all: String,
/// Quit.
pub quit: String,
}
impl AppMenu {
/// English titles with `app_name`: the menu is titled `app_name`, and About, Hide and Quit
/// name it ("Quit WordCraft").
pub fn english(app_name: &str) -> AppMenu {
AppMenu {
title: app_name.to_owned(),
about: format!("About {app_name}"),
services: "Services".to_owned(),
hide: format!("Hide {app_name}"),
hide_others: "Hide Others".to_owned(),
show_all: "Show All".to_owned(),
quit: format!("Quit {app_name}"),
}
}
}
/// Whether a menu is open. Safe from any thread; false where there is no application menu bar.
pub fn menu_tracking() -> bool {
imp::menu_tracking()
+14 -8
View File
@@ -30,7 +30,7 @@ use objc2::{MainThreadMarker, sel};
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType};
use objc2_foundation::{NSBundle, NSLocale, NSObjectProtocol, NSString};
use super::{Bar, Chosen, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut, Wake};
use super::{AppMenu, Bar, Chosen, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut, Wake};
/// Set by [`Installed::install`]: there is one full menu bar per process.
static INSTALLED: AtomicBool = AtomicBool::new(false);
@@ -118,22 +118,27 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
///
/// Does nothing when this menu or a full menu bar ([`Installed::install`]) is already installed.
pub fn install_app_menu(app_name: &str, quit_id: &str, handler: Handler) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
install_app_menu_with(&AppMenu::english(app_name), quit_id, handler)
}
/// [`install_app_menu`] with the titles `menu`, for an app that translates them.
pub fn install_app_menu_with(menu: &AppMenu, quit_id: &str, handler: Handler) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if MainThreadMarker::new().is_none() {
return Err("the application menu is installed on the main thread".into());
}
if INSTALLED.load(Ordering::SeqCst) || APP_MENU.with_borrow(Option::is_some) {
return Ok(());
}
let quit = MenuItem::with_id(quit_id, format!("Quit {app_name}"), true, Some(Accelerator::new(Modifiers::META, Code::KeyQ)));
let app_menu = Submenu::new(app_name, true);
let quit = MenuItem::with_id(quit_id, escape(&menu.quit), true, Some(Accelerator::new(Modifiers::META, Code::KeyQ)));
let app_menu = Submenu::new(escape(&menu.title), true);
app_menu.append_items(&[
&PredefinedMenuItem::about(Some(&format!("About {app_name}")), None),
&PredefinedMenuItem::about(Some(&escape(&menu.about)), None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::services(None),
&PredefinedMenuItem::services(Some(&escape(&menu.services))),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::hide(Some(&format!("Hide {app_name}"))),
&PredefinedMenuItem::hide_others(None),
&PredefinedMenuItem::show_all(None),
&PredefinedMenuItem::hide(Some(&escape(&menu.hide))),
&PredefinedMenuItem::hide_others(Some(&escape(&menu.hide_others))),
&PredefinedMenuItem::show_all(Some(&escape(&menu.show_all))),
&PredefinedMenuItem::separator(),
&quit,
])?;
@@ -407,6 +412,7 @@ fn append(entries: &mut Entries, sub: &Submenu, nodes: &[Node]) -> muda::Result<
sub.append(&s)?;
}
Node::Platform { kind, title } => {
let title = escape(title);
let text = Some(title.as_str());
let p = match kind {
Platform::Services => PredefinedMenuItem::services(text),
+6 -1
View File
@@ -2,7 +2,7 @@
use std::convert::Infallible;
use super::{Bar, Handler, Options, Wake};
use super::{AppMenu, Bar, Handler, Options, Wake};
/// No menu bar here, so no menu is ever open.
pub(super) fn menu_tracking() -> bool {
@@ -52,6 +52,11 @@ pub fn install_app_menu(_app_name: &str, _quit_id: &str, _handler: Handler) -> R
Ok(())
}
/// [`install_app_menu`] with the titles `menu`. Does nothing here.
pub fn install_app_menu_with(_menu: &AppMenu, _quit_id: &str, _handler: Handler) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
Ok(())
}
/// The platform's own title for the English menu title `english`; `english` here.
pub fn system_title(english: &str) -> String {
english.to_owned()
+3 -1
View File
@@ -5,7 +5,7 @@ edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, the asset attribution check, an optional slot lock shared across processes, a per-step JSON report, the workspace version command, and .ico and .icns packing"
description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, the asset attribution check, an optional slot lock shared across processes, a per-step JSON report, a check of pinned dependencies, the workspace version command, and .ico and .icns packing"
[lints]
workspace = true
@@ -16,6 +16,8 @@ default = []
lock = ["dep:libc"]
# The per-step JSON report, replaced atomically.
report = ["dep:serde_json", "dep:craft-atomic"]
# Pinned dependencies and forbidden packages, checked in `cargo metadata` (`cargo xtask pdf-deps`).
pins = ["dep:serde_json"]
# Downloads named in a pinned list, checked against SHA-256, and bounded tar extraction.
fetch = ["dep:craft-atomic", "dep:flate2", "dep:sha2", "dep:tar", "dep:unicode-normalization"]
# `cargo xtask stats`: files, lines and tests of Rust per workspace crate, read from `cargo metadata`.
+76 -2
View File
@@ -11,13 +11,14 @@ The crate is native only and is a dependency of an app's `xtask` package only.
| `names` | always | `Policy`, `Input`, `scan`, `scan_source`, `literals`, `test_path`: the display-name scanner, which looks for the words an app lists in its string literals, `Cargo.toml` descriptions and text files |
| `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses |
| `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` |
| `pins` | `pins` | `run`, `check`, `check_commits`: the version, source and features of pinned dependencies, packages the app forbids, and one commit per git repository, read from `cargo metadata`; `run_target_features`: one target's features, read from `cargo tree`; `host_target`: the host target, read from `rustc -vV`; each command's output is read within size limits |
| `fetch` | `fetch` | `fetch_pinned`, `fetch_archive`, `extract`, `sha256_hex`: files of a pinned list downloaded over HTTPS and checked against SHA-256, and tar archives extracted under entry and size limits |
| `stats` | `stats` | `run`, `collect` and `write_table`: files, lines and tests of Rust per workspace crate (`cargo xtask stats`) |
| `icon` | always | `ico::pack`, `icns::pack`, `png_size`, `png_info`, `read_pngs`, `Limits`, and `ico::read_file` and `icns::read_file` for an app's test of its committed icons |
| `version` | `version` | `run`, `run_with`, `Limits`, `lock_dirs`, `read`, `replace`, `validate`: `cargo xtask version [set X.Y.Z[-pre]]` on the root `Cargo.toml` |
No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `stats` adds
`serde_json`. `fetch` adds `craft-atomic`, `sha2`, `tar`, `flate2` and
No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `pins` and `stats` each
add `serde_json`. `fetch` adds `craft-atomic`, `sha2`, `tar`, `flate2` and
`unicode-normalization`, and runs the system `curl`. `version` adds `craft-atomic` and `toml_edit` and
turns on `lock`.
@@ -284,6 +285,73 @@ cancel while waiting) runs no step and writes no report. The report looks like t
so a reader never sees a partial report, and a failed write leaves the previous report in place.
Machine, GPU, corpus and skip details stay in the app's own report.
## Pins
`cargo xtask pdf-deps` checks that pinned dependencies resolve to the pinned version and source, with
the allowed features, and that packages the app forbids are not in the graph. The app enables the
`pins` feature, keeps its own table and passes it with a function that builds its `cargo` command:
```rust
use craft_xtask::pins::{FeatureRule, Forbidden, Name, Pin, Policy, Scope};
const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef";
Some("pdf-deps") => {
let source = craft_xtask::pins::git_source("https://github.com/storytold/craft-libs", REV);
let pins = [Pin { name: "craft-pdf", version: "0.1.0", source: &source, features: FeatureRule::Exactly(&["read"]) }];
let forbidden = [Forbidden { name: Name::Exact("krilla"), scope: Scope::Active }];
craft_xtask::pins::run(cargo, &Policy { pins: &pins, forbidden: &forbidden }, &Default::default())
.map_err(|e| e.to_string())
}
```
- `run` runs `cargo metadata --locked --format-version 1` and passes the JSON to `check`.
- Each `Pin` name has exactly one package, with the pinned `version` and `source`. `git_source(url, rev)`
gives the source Cargo writes for a git dependency pinned to a full commit hash, and `CRATES_IO` the
source for crates.io. `git_source` and `check_commits` write a git URL as Cargo does: the `.` and
`..` segments of the path resolved (`https://github.com/o/./r` becomes `https://github.com/o/r`),
and for `http` and `https` the scheme and host in lowercase, a port written as its number, and
without the default port (`https://github.com:0443/o/r` becomes `https://github.com/o/r`).
- `FeatureRule::Contains` requires the listed features and allows others. `FeatureRule::Exactly`
requires every listed feature and allows no others. Both read the package's node in `resolve.nodes`.
- `Scope::Active` rejects a forbidden package that has a resolved node, development dependencies
included. `Scope::ProductionFrom(root)` rejects a forbidden package reached from `root` over normal
or build edges; one reached only through development edges is allowed. `Name::Family("hayro")`
matches `hayro` and every `hayro-*` name.
- Packages the policy does not name are allowed. An empty policy sets no rule on the packages, but
the metadata must still be within `metadata_bytes`, parse, and have a `packages` list with a `name`
for each package.
- `check_commits` reads the same JSON against `OneCommit` rules. Every package whose source is the
rule's git repository must resolve from one commit, the text after the source's `#`. An `Extra`
names a package allowed at its own commit, for a dependency the app declares at a second revision
(DesignCraft's `craft-xml-dtd = { package = "craft-xml", … }`). A violation lists each commit with
the packages resolved from it:
```rust
let json = craft_xtask::pins::metadata(cargo, &limits)?;
let rule = OneCommit { url: "https://github.com/storytold/craft-libs", extra: &[Extra { name: "craft-xml", rev: DTD_REV }] };
craft_xtask::pins::check_commits(&json, &[rule], &limits)?;
```
- JSON that does not parse, or lacks a field a rule needs (`resolve.nodes`, a package `id`, a node's
`features` or `deps`, an edge's `dep_kinds`), is an error.
- Cargo merges every target's features into one metadata result. `run_target_features` runs
`cargo tree --target <target>` from a root package and checks that each line for one package has
exactly the given features; `host_target` reads the host target from `rustc -vV`.
- `Limits` bounds each command's output. More standard output than the limit stops the command and
returns an error, and so does standard output that a process the command started keeps open for 2
seconds after the command exits. Standard error is read to its end, and its first `stderr_bytes`
are kept for the error message; after a failing exit it is read for at most 2 seconds more:
| Limit | Default |
|---|---|
| `metadata_bytes`: the `cargo metadata` JSON, also for JSON passed to `check` | 64 MiB |
| `tree_bytes`: one `cargo tree` output | 64 MiB |
| `version_bytes`: the `rustc -vV` output | 64 KiB |
| `stderr_bytes`: standard error kept for a message | 64 KiB |
- `pins::Error` tells apart a command that could not start, could not be read, exited without
success or printed too much; output that is not valid; and a `Violation` of the policy.
## Fetch
| Function | What it does |
@@ -499,6 +567,11 @@ fn version(rest: &[&str]) -> Result<(), String> {
| `assets`: folder-only extensions and the tests in `assets::tests::gridcraft` | GridCraft `xtask/src/assets.rs` at [f204433](https://github.com/storytold/gridcraft/blob/f2044337c7e195bdf6bec1b3914937a3dd386749/xtask/src/assets.rs) |
| `assets`: first-cell rows, folder patterns, forbidden extensions and names, the license column and the tests in `assets::tests::lightcraft` | LightCraft `xtask/src/assets.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/assets.rs) |
| `assets`: the policy checks, the cell parser, bad-entry and near-row reports, the size limits, UTF-8 names, skipped folders and the regular-file test | written here |
| `pins`: exact feature sets, the production walk over normal and build edges, the per-target `cargo tree` feature check, and their five tests | DeckCraft `xtask/src/pdf_deps.rs` at `aa3a1baa01` |
| `pins`: one package per name with an exact version and source, and its three tests | VectorCraft `xtask/src/pdf_deps.rs` at `34627134fa` |
| `pins`: required features that allow others, and its five tests | DesignCraft `xtask/src/pdf_deps.rs` at `18246dddd2` |
| `pins`: packages forbidden when resolved, and its five tests | EffectCraft `xtask/src/pdf_deps.rs` at `f31a6b0aef` |
| `pins`: the output size limits, an empty feature list in `cargo tree`, and the errors for missing fields, features that are not strings, edges without a kind and packages without a name | written here |
| `fetch`: a list of name, address and SHA-256; a file with another SHA-256 is deleted so the next run downloads it again | LightCraft `xtask/src/corpus.rs` (`fetch_pinned`) at [6b2b7e6](https://github.com/storytold/lightcraft/blob/6b2b7e6d1117e683a1701568e56f979d061e4699/xtask/src/corpus.rs) |
| `fetch`: HTTPS-only `curl` arguments, a regular-file check before reuse, a per-file byte limit, and a download staged beside its destination and renamed after its check | VectorCraft `xtask/src/pngsuite.rs` at [ed96a12](https://github.com/storytold/vectorcraft/blob/ed96a1219620b5b6ab13e25369f7b55cddd664f6/xtask/src/pngsuite.rs) |
| `fetch`: the archive limits (1 MiB archive, 1000 entries, 16 MiB extracted) | DesignCraft `xtask/src/main.rs` (PngSuite download) at [f5087ea](https://github.com/storytold/designcraft/blob/f5087eae963c6f8474abb45669ce2b7275761e6d/xtask/src/main.rs) |
@@ -514,6 +587,7 @@ No app uses this crate yet.
| AniCraft, CADCraft, DeckCraft, FigCraft, GridCraft, LightCraft, PhotoCraft, WordCraft | Planned: the lexer and matcher of `display_names.rs` move to `names`, with `MatchCase::Exact`. `BANNED`, `ALLOWED`, `ROOTS`, the prefix exceptions (LightCraft, WordCraft), PhotoCraft's catalog test and the tests named after them stay in the app. |
| VectorCraft | Planned: `cargo xtask brands` calls `names::scan` with `MatchCase::AsciiInsensitive`, byte and C strings, `brand-ok` and its desktop entry as `Input::text_mark_above`. The word list, the file selection from `git ls-files` and the message stay in the app. |
| LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. |
| DeckCraft, DesignCraft, EffectCraft, VectorCraft | Planned: `xtask/src/pdf_deps.rs` moves to `pins`. Each app keeps its `pdf-deps` command and its table, and runs `cargo xtask pdf-deps` before and after the switch. |
| DeckCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. |
| CADCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. |
| craft-launcher | Planned: `xtask/src/ico.rs` and `icns.rs` move to `icon`. The `ico` and `icns` commands stay in the app. |
+4
View File
@@ -17,6 +17,8 @@
//! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so
//! that gate runs in several checkouts of one machine take turns.
//! - `report` (feature `report`): the per-step JSON report, replaced atomically.
//! - `pins` (feature `pins`): the version, source and features of pinned dependencies, and packages
//! an app forbids, read from `cargo metadata` (`cargo xtask pdf-deps`).
//! - `fetch` (feature `fetch`): files named in a pinned list, each checked against its SHA-256 before
//! it is written in place, and tar archives extracted under entry and size limits.
//! - `stats` (feature `stats`): files, lines and tests of Rust per workspace crate (`cargo xtask stats`).
@@ -56,6 +58,8 @@ pub mod icon;
#[cfg(feature = "lock")]
pub mod lock;
pub mod names;
#[cfg(feature = "pins")]
pub mod pins;
#[cfg(feature = "report")]
pub mod report;
pub mod runner;
File diff suppressed because it is too large. Load diff