diff --git a/.gitignore b/.gitignore index 5a324f98..e08783f7 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,7 @@ __pycache__/ # Zola build output of the user documentation (site/) /site/public/ + +# Local editor settings and CMake build trees (e.g. from the oracle scripts) +/.vscode/ +/build/ diff --git a/Cargo.lock b/Cargo.lock index 63847d32..839b409b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1077,7 +1077,7 @@ dependencies = [ [[package]] name = "moho" version = "0.1.0" -source = "git+https://github.com/doubleailes/Moho?rev=8163843d896f161d167a761dcae9b14a8bd21f7b#8163843d896f161d167a761dcae9b14a8bd21f7b" +source = "git+https://github.com/doubleailes/Moho?rev=4d63d411c368883ea27c5c0542876d805a7d60b6#4d63d411c368883ea27c5c0542876d805a7d60b6" dependencies = [ "openusd", "openusd-schemas", diff --git a/Cargo.toml b/Cargo.toml index da37ad68..4185f4f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,7 +89,7 @@ ocio = "0.2.0" # families `media`, `physics`, `proc`, `semantics`, `skel`, `ui` (`geom`, `lux`, # `render`, `shade`, `vol` are always on). Bump order: Moho, then crust-render, # then Mantle. -moho = { git = "https://github.com/doubleailes/Moho", rev = "8163843d896f161d167a761dcae9b14a8bd21f7b" } +moho = { git = "https://github.com/doubleailes/Moho", rev = "4d63d411c368883ea27c5c0542876d805a7d60b6" } # The hot loops are spread across crates: the integrator in `crust-core` # calls the kernel in `crust-rt`, which calls `glam`'s SIMD vector ops. diff --git a/crates/crust-core/src/scene/hydra/assets.rs b/crates/crust-core/src/scene/hydra/assets.rs index 14c23ca8..f09849cb 100644 --- a/crates/crust-core/src/scene/hydra/assets.rs +++ b/crates/crust-core/src/scene/hydra/assets.rs @@ -149,22 +149,24 @@ pub(in crate::scene) fn load_ptex( loaded } -/// An asset value as a path: openusd's `resolved_path` when it has one, else -/// the authored string, a relative one anchored against the directory of the -/// layer that authors it (`layer_dir`, the host's -/// `HostFacts::authoring_layer_dir`), the root layer's when that is unknown. +/// An asset value as a path, from the index alone: the value's +/// `resolved_path` when it has one, else the authored string, an absolute +/// one as it is and a relative one against the directory of `stage_path`. /// -/// openusd's value resolution anchors an `asset` value on its authoring layer -/// and records where it resolves even when no file is there (a `` set, -/// a missing texture), and the scene index carries that value, so an asset -/// authored in a sublayer or a reference (ALab's look layers, five directories -/// below `entry.usda`) reaches the host from its own layer's directory. A -/// path authored as a `string` carries no resolution: `layer_dir` anchors it -/// (`tests/asset_anchoring.rs`). +/// The index anchors an `asset` value on the layer that authors it and +/// records where it resolves even when no file is there (a `` set, a +/// missing texture; Moho anchors what openusd leaves unresolved), so an asset +/// authored in a sublayer or a reference (ALab's look layers, five +/// directories below `entry.usda`) reaches the host from its own layer's +/// directory. A path authored as a `string` is text, which USD does not +/// anchor: a relative one resolves against the stage's directory and raises +/// `asset.string_path`, naming `attribute`, the property that authors it +/// (`tests/asset_anchoring.rs`). No answer about the host's stage is asked: +/// the image depends on the index alone. pub(in crate::scene) fn asset_value_path( value: &sdf::Value, stage_path: &Path, - layer_dir: &dyn Fn() -> Option, + attribute: &dyn Fn() -> Option, ) -> Option { let (authored, resolved) = match value { sdf::Value::AssetPath(p) => (p.as_str().to_string(), p.resolved_path()), @@ -183,11 +185,21 @@ pub(in crate::scene) fn asset_value_path( if candidate.is_absolute() { return Some(candidate.to_path_buf()); } - let dir = layer_dir().unwrap_or_else(|| { - stage_path - .parent() - .unwrap_or_else(|| Path::new(".")) - .to_path_buf() - }); - Some(dir.join(candidate)) + let dir = stage_path.parent().unwrap_or_else(|| Path::new(".")); + let resolved = dir.join(candidate); + if matches!(value, sdf::Value::String(_)) { + let attribute = attribute(); + let prim = attribute + .as_ref() + .map_or_else(String::new, |a| a.prim_path().to_string()); + let named = attribute.map_or_else(|| "an attribute".to_owned(), |a| a.to_string()); + crate::warning!( + AssetStringPath, + at = prim, + "{named} authors the relative path \"{authored}\" as a string, which USD does not \ + anchor on its layer; it resolves against the stage's directory, to {}", + resolved.display() + ); + } + Some(resolved) } diff --git a/crates/crust-core/src/scene/hydra/camera.rs b/crates/crust-core/src/scene/hydra/camera.rs index 1b4f06c3..df7eec24 100644 --- a/crates/crust-core/src/scene/hydra/camera.rs +++ b/crates/crust-core/src/scene/hydra/camera.rs @@ -415,7 +415,6 @@ impl RenderCamera { /// camera on `stage`. pub(in crate::scene) fn build_camera( scene: &dyn SceneIndex, - host: &dyn super::index::host::HostFacts, path: &sdf::Path, settings: &RenderSettings, framing: Framing, @@ -423,7 +422,7 @@ pub(in crate::scene) fn build_camera( let cam = camera_at(scene, path)?; let world = super::xform::world(&cam); let frame = CameraFrame::read(&cam, world, settings, framing); - let (camera, refused_meters_per_unit) = lens_camera(&cam, host, &frame, settings); + let (camera, refused_meters_per_unit) = lens_camera(&cam, scene, &frame, settings); let clip = clipping(&cam); let camera = camera.with_clipping(clip.near, clip.far, &clip.planes); let read = lens(&cam, &frame); @@ -570,10 +569,18 @@ const FALLBACK_METERS_PER_UNIT: f64 = 0.01; /// The stage's authored `metersPerUnit` (C++ `UsdGeomGetStageMetersPerUnit`, /// which reads only the root and session layers), `None` when no layer -/// authors it: a host fact, read off the stage (design D4: Hydra carries no -/// unit). Unchecked: [`lens_diameter`] refuses a value that is not a length. -fn authored_meters_per_unit(host: &dyn super::index::host::HostFacts) -> Option { - host.meters_per_unit() +/// authors it: Moho's `__usdMetersPerUnit/metersPerUnit` on the index's +/// absolute root, there only when authored (Hydra itself carries no unit). +/// Unchecked: [`lens_diameter`] refuses a value that is not a length. +fn authored_meters_per_unit(scene: &dyn SceneIndex) -> Option { + use moho::tokens::usd_meters_per_unit as t; + match PrimData::at(scene, &sdf::Path::abs_root()) + .locate([t::USD_METERS_PER_UNIT, t::METERS_PER_UNIT])? + .value()? + { + sdf::Value::Double(m) => Some(m), + _ => None, + } } /// The lens diameter in scene units: `focalLength / fStop` millimetres, @@ -584,7 +591,7 @@ fn authored_meters_per_unit(host: &dyn super::index::host::HostFacts) -> Option< /// that is not finite, not positive, or so small that the diameter overflows /// `f32` is refused and reads as the fallback. fn lens_diameter( - host: &dyn super::index::host::HostFacts, + scene: &dyn SceneIndex, focal_length: f32, f_stop: f32, depth_of_field: bool, @@ -595,7 +602,7 @@ fn lens_diameter( let diameter = |meters_per_unit: f64| { (f64::from(focal_length) / f64::from(f_stop) * 0.001 / meters_per_unit) as f32 }; - match authored_meters_per_unit(host) { + match authored_meters_per_unit(scene) { // A unit so small that the diameter overflows `f32` is no length // either: the lens would offset every ray to infinity. Some(m) if m.is_finite() && m > 0.0 && diameter(m).is_finite() => (diameter(m), None), @@ -608,7 +615,7 @@ fn lens_diameter( /// the stage unit its lens refused. fn lens_camera( cam: &PrimData, - host: &dyn super::index::host::HostFacts, + scene: &dyn SceneIndex, frame: &CameraFrame, settings: &RenderSettings, ) -> (Camera, Option) { @@ -641,7 +648,7 @@ fn lens_camera( let vfov_deg = 2.0 * frame.tan_half_vfov().atan().to_degrees(); let (aperture, refused_meters_per_unit) = - lens_diameter(host, frame.focal_length, f_stop, settings.depth_of_field()); + lens_diameter(scene, frame.focal_length, f_stop, settings.depth_of_field()); // A pinhole has no focus plane, and USD's `focusDistance = 0` (what // GfCamera writes, and a DCC camera with focus off) would put the image // plane on the eye: every ray would have no direction. A pinhole's rays @@ -797,7 +804,6 @@ mod tests { use crate::scene::hydra::settings::CameraChoice; use crate::scene::usd_import::prim_at; use crate::scene::usd_import::stage_builder; - use crate::scene::usd_import::stage_facts::StageFacts; use moho::openusd::usd::InitialLoadSet; use moho::openusd::usd::{Prim, Stage}; @@ -814,13 +820,7 @@ mod tests { framing: Framing, ) -> Option { let scene = scene_of(stage); - super::build_camera( - scene.chain.as_ref(), - &StageFacts::of(stage), - prim.path(), - settings, - framing, - ) + super::build_camera(scene.chain.as_ref(), prim.path(), settings, framing) } fn camera_lens( @@ -844,7 +844,7 @@ mod tests { } fn authored_meters_per_unit(stage: &Stage) -> Option { - super::authored_meters_per_unit(&StageFacts::of(stage)) + super::authored_meters_per_unit(scene_of(stage).chain.as_ref()) } /// A stage on a `.usda` holding `metadata` and nothing else. diff --git a/crates/crust-core/src/scene/hydra/commit.rs b/crates/crust-core/src/scene/hydra/commit.rs index 96a83232..663339f3 100644 --- a/crates/crust-core/src/scene/hydra/commit.rs +++ b/crates/crust-core/src/scene/hydra/commit.rs @@ -445,7 +445,7 @@ fn visit_camera( // named. let is_first = ctx.first_camera_path.as_ref() == Some(path); if ctx.camera.is_none() && (is_named || is_first) { - match build_camera(index, ctx.caches.host, path, &ctx.settings, ctx.framing) { + match build_camera(index, path, &ctx.settings, ctx.framing) { Some(c) if is_named || named.is_none() => { debug!("Imported USD camera at {}", path); ctx.camera = Some((c, path.clone())); diff --git a/crates/crust-core/src/scene/hydra/index/host.rs b/crates/crust-core/src/scene/hydra/index/host.rs index cc2ef3a9..e5ac1718 100644 --- a/crates/crust-core/src/scene/hydra/index/host.rs +++ b/crates/crust-core/src/scene/hydra/index/host.rs @@ -34,8 +34,6 @@ pub trait HostFacts { fn layer_stack(&self) -> Vec; /// How many prims the strongest layer hides with an `over`. fn invisible_overrides(&self) -> Option; - /// The stage's `metersPerUnit`, when a layer authors it. - fn meters_per_unit(&self) -> Option; /// Why the prim at `pass` is no `RenderPass`, for the host's error. fn not_a_pass(&self, pass: &sdf::Path) -> String; /// The `.mtlx` document (and the material in it) the material at @@ -49,9 +47,6 @@ pub trait HostFacts { /// Whether the prim at `path` is an instance whose prototype the stage /// does not compose. fn instance_without_prototype(&self, path: &sdf::Path) -> bool; - /// The directory of the layer authoring the value of the attribute at - /// `attr`, where a relative asset path in it is anchored. - fn authoring_layer_dir(&self, attr: &sdf::Path) -> Option; } /// A host with no stage to ask: every fact absent. @@ -70,9 +65,6 @@ impl HostFacts for NoHostFacts { fn invisible_overrides(&self) -> Option { None } - fn meters_per_unit(&self) -> Option { - None - } fn not_a_pass(&self, _: &sdf::Path) -> String { "the host has no stage to say why".to_string() } @@ -91,7 +83,4 @@ impl HostFacts for NoHostFacts { fn instance_without_prototype(&self, _: &sdf::Path) -> bool { false } - fn authoring_layer_dir(&self, _: &sdf::Path) -> Option { - None - } } diff --git a/crates/crust-core/src/scene/hydra/lights.rs b/crates/crust-core/src/scene/hydra/lights.rs index 0d4b253c..eed66619 100644 --- a/crates/crust-core/src/scene/hydra/lights.rs +++ b/crates/crust-core/src/scene/hydra/lights.rs @@ -201,7 +201,7 @@ fn lux_shaping( let ies_file = lp(prim).value("shaping:ies:file").and_then(|v| { asset_value_path(&v, caches.stage_path, &|| { - caches.layer_dir(prim.path(), "inputs:shaping:ies:file") + prim.path().append_property("inputs:shaping:ies:file").ok() }) }); if let Some(path) = ies_file { @@ -505,7 +505,7 @@ fn rect_light_texture( let file = "inputs:texture:file"; let path = lp(prim).value("texture:file").and_then(|v| { asset_value_path(&v, caches.stage_path, &|| { - caches.layer_dir(prim.path(), file) + prim.path().append_property(file).ok() }) })?; let space = texture_color_space(prim, caches.working); @@ -796,11 +796,12 @@ pub(in crate::scene) fn emit_dome_light( ) { // The authoring layer anchors the path, not the root layer: the Moana // island's lights author `../textures/islandsun.exr` relative to - // `usd/island.usda` (see `asset_value_path`). + // `usd/island.usda`, an `asset` the index resolves on that layer (see + // `asset_value_path`). let file = "inputs:texture:file"; let texture_path = lp(prim).value("texture:file").and_then(|v| { asset_value_path(&v, ctx.stage_path, &|| { - ctx.caches.layer_dir(prim.path(), file) + prim.path().append_property(file).ok() }) }); let (lights, assets) = (&mut ctx.lights, ctx.assets); diff --git a/crates/crust-core/src/scene/hydra/materials.rs b/crates/crust-core/src/scene/hydra/materials.rs index 7ae96dbf..9ff67098 100644 --- a/crates/crust-core/src/scene/hydra/materials.rs +++ b/crates/crust-core/src/scene/hydra/materials.rs @@ -563,7 +563,7 @@ fn pxr_displacement( .and_then(|v| { asset_value_path(v, caches.stage_path, &|| { node.as_ref() - .and_then(|n| src.layer_dir(n, "inputs:filename")) + .and_then(|n| n.append_property("inputs:filename").ok()) }) })?; maps.push(crate::PtexRef(load_ptex( @@ -788,7 +788,6 @@ fn inline_mtlx_material( let mat_path = &src.path; let net = super::mtlx_network::translate( caches.stage_path, - &|p, name| src.layer_dir(p, name), &caches.materials.library, surface, volume, @@ -822,27 +821,18 @@ fn inline_mtlx_material( } /// A material as the index readers read it: its prim and its networks -/// ([`super::index::network`]) in the scene index the import reads, and the -/// nodes' prims, for what a shader input authors itself. -pub(in crate::scene) struct MatSource<'h> { +/// ([`super::index::network`]) in the scene index the import reads. +pub(in crate::scene) struct MatSource { /// The material's path, in the namespace it is bound in. pub(in crate::scene) path: sdf::Path, pub(in crate::scene) prim: super::index::data::PrimData, pub(in crate::scene) networks: std::collections::BTreeMap, - index: moho::scene_index::SceneIndexHandle, - /// For a material inside a re-rooted prototype, `(the path the - /// instancing chain holds it at, its name)`: its prims are read there - /// and named here ([`super::index::data::PrimData::rebased`]). - rebase: Option<(sdf::Path, sdf::Path)>, - /// The host, for what only it knows: the layer an asset value is - /// authored in ([`MatSource::layer_dir`]). - host: &'h dyn super::index::host::HostFacts, } -impl<'h> MatSource<'h> { +impl MatSource { /// The material at `mat_path`. - pub(in crate::scene) fn new(mat_path: &sdf::Path, caches: &ImportCaches<'h>) -> Self { + pub(in crate::scene) fn new(mat_path: &sdf::Path, caches: &ImportCaches<'_>) -> Self { use super::index::data::PrimData; // A material bound inside a re-rooted prototype: read in the // instancing chain, at the path the binding names (Moho's M11). @@ -855,9 +845,6 @@ impl<'h> MatSource<'h> { path: mat_path.clone(), networks: super::index::network::networks(&prim), prim, - index: inst.clone(), - rebase: Some((data.clone(), name.clone())), - host: caches.host, }; } // Read at the top of the import's chain, after the material-node @@ -870,38 +857,6 @@ impl<'h> MatSource<'h> { path: mat_path.clone(), networks: super::index::network::networks(&prim), prim, - index, - rebase: None, - host: caches.host, - } - } - - /// The directory of the layer authoring the value of attribute `name` of - /// the prim at `path` (read as the material is, so named by its USD - /// path): where a relative asset path in it is anchored. - pub(in crate::scene) fn layer_dir( - &self, - path: &sdf::Path, - name: &str, - ) -> Option { - let attr = self.at(path).path().append_property(name).ok()?; - self.host.authoring_layer_dir(&attr) - } - - /// The prim at `path`, read as the material is. - pub(in crate::scene) fn at(&self, path: &sdf::Path) -> super::index::data::PrimData { - use super::index::data::PrimData; - match &self.rebase { - Some((data, name)) => { - let at = path - .as_str() - .strip_prefix(name.as_str()) - .filter(|rest| rest.is_empty() || rest.starts_with('/')) - .and_then(|rest| sdf::Path::new(format!("{data}{rest}").as_str()).ok()) - .unwrap_or_else(|| path.clone()); - PrimData::rebased(&self.index, &at, data, name) - } - None => PrimData::in_index(&self.index, path), } } @@ -1203,7 +1158,7 @@ pub(in crate::scene) fn material_ptex( let node_path = network.path(name)?; let value = network.nodes.get(name)?.value(file)?; let path = asset_value_path(&value, caches.stage_path, &|| { - src.layer_dir(&node_path, &format!("inputs:{file}")) + node_path.append_property(format!("inputs:{file}")).ok() })?; let space = crate::ColorSpace::new(Space::G22_REC709, caches.working); diff --git a/crates/crust-core/src/scene/hydra/mod.rs b/crates/crust-core/src/scene/hydra/mod.rs index e1c9c957..e9f4fa1a 100644 --- a/crates/crust-core/src/scene/hydra/mod.rs +++ b/crates/crust-core/src/scene/hydra/mod.rs @@ -822,7 +822,7 @@ pub(in crate::scene) fn read_index( let mut settings = import_render_settings(scene, pass); // The products the render writes. The first one's camera and resolution // are the render's: the settings' own unless that product overrides them. - let products = import_render_products(scene, Some((path, host)), pass); + let products = import_render_products(scene, Some(path), pass); if let Some((w, h)) = products.resolution { settings = settings.with_resolution(w, h); } @@ -1418,14 +1418,6 @@ impl<'a> ImportCaches<'a> { } } - /// The directory of the layer authoring attribute `name` of the prim at - /// `path`, as the host answers it: where a relative asset path in it is - /// anchored ([`assets::asset_value_path`]). - fn layer_dir(&self, path: &sdf::Path, name: &str) -> Option { - self.host - .authoring_layer_dir(&path.append_property(name).ok()?) - } - /// The prim at `path` of the index being committed. fn prim_data(&self, path: &sdf::Path) -> index::data::PrimData { match &self.scene { diff --git a/crates/crust-core/src/scene/hydra/mtlx_network.rs b/crates/crust-core/src/scene/hydra/mtlx_network.rs index d5cab902..dc18d1c6 100644 --- a/crates/crust-core/src/scene/hydra/mtlx_network.rs +++ b/crates/crust-core/src/scene/hydra/mtlx_network.rs @@ -55,14 +55,12 @@ pub(in crate::scene) fn is_mtlx_id(id: &str, library: &Library) -> bool { /// render contexts the terminals resolved in) into one document. pub(in crate::scene) fn translate( stage_path: &Path, - layer_dir: &LayerDir<'_>, library: &Library, surface: Option<(&Shading, &str)>, volume: Option<(&Shading, &str)>, ) -> Network { let mut b = Builder { stage_path, - layer_dir, library, nodes: Vec::new(), names: HashMap::new(), @@ -81,15 +79,8 @@ pub(in crate::scene) fn translate( } } -/// The directory of the layer authoring attribute `name` of the node prim at -/// `path` (a network path): where a relative `filename` it holds is anchored -/// ([`asset_value_path`]). -pub(in crate::scene) type LayerDir<'a> = - dyn Fn(&sdf::Path, &str) -> Option + 'a; - struct Builder<'s> { stage_path: &'s Path, - layer_dir: &'s LayerDir<'s>, library: &'s Library, nodes: Vec, /// Shader prim path → its node's name (the path itself), once translated. @@ -118,7 +109,6 @@ pub(in crate::scene) struct ValueNetwork { /// network, so it is refused. pub(in crate::scene) fn translate_value_graph( stage_path: &Path, - layer_dir: &LayerDir<'_>, graph: &sdf::Path, outputs: &[(String, &Shading, shading::Connection)], ) -> ValueNetwork { @@ -127,7 +117,6 @@ pub(in crate::scene) fn translate_value_graph( let library = Library::default(); let mut b = Builder { stage_path, - layer_dir, library: &library, nodes: Vec::new(), names: HashMap::new(), @@ -353,12 +342,7 @@ impl Builder<'_> { sdf::Value::String(s) => s.clone(), sdf::Value::Token(t) => t.as_str().to_string(), sdf::Value::AssetPath(_) if mtype == "filename" => { - let layer_dir = || { - let attr = sdf::Path::new(at).ok()?; - let (prim, name) = attr.split_property()?; - (self.layer_dir)(&prim, name) - }; - asset_value_path(value, self.stage_path, &layer_dir)? + asset_value_path(value, self.stage_path, &|| sdf::Path::new(at).ok())? .to_string_lossy() .into_owned() } @@ -613,7 +597,7 @@ mod tests { .into(), ..Default::default() }; - let net = translate(&path, &|_, _| None, &library, Some((&network, "/S")), None); + let net = translate(&path, &library, Some((&network, "/S")), None); assert!(net.doc.reported.is_empty(), "{:?}", net.doc.reported); let c = net .doc diff --git a/crates/crust-core/src/scene/hydra/precomp.rs b/crates/crust-core/src/scene/hydra/precomp.rs index 967a4ec1..bd3c6b84 100644 --- a/crates/crust-core/src/scene/hydra/precomp.rs +++ b/crates/crust-core/src/scene/hydra/precomp.rs @@ -36,7 +36,6 @@ use super::attrs::{decode_f32, decode_i32, decode_text, decode_vec3}; use super::index::data::PrimData; use super::index::fields::Fields; use super::index::network::{self, Connection, Network, Node}; -use super::mtlx_network::LayerDir; use super::mtlx_network::translate_value_graph; use super::products::FilterTarget; @@ -63,7 +62,6 @@ const OUT: &str = "out"; pub(in crate::scene) fn import_precomp( scene: &dyn moho::scene_index::SceneIndex, stage_path: &Path, - layer_dir: &LayerDir<'_>, settings: &sdf::Path, request: &mut AovRequest, targets: &HashMap, @@ -90,7 +88,7 @@ pub(in crate::scene) fn import_precomp( // The sample filters' graphs first: a var reading one needs its outputs. let graphs: Vec = sample_paths .iter() - .map(|p| Graph::read(scene, stage_path, layer_dir, p)) + .map(|p| Graph::read(scene, stage_path, p)) .collect(); drop_unresolved(request, targets, &graphs, &display_paths); let vars = Vars::of(request); @@ -105,7 +103,6 @@ pub(in crate::scene) fn import_precomp( let filter = read_display( scene, stage_path, - layer_dir, path, index as u16, &display_paths, @@ -179,7 +176,6 @@ impl Graph { fn read( scene: &dyn moho::scene_index::SceneIndex, stage_path: &Path, - layer_dir: &LayerDir<'_>, path: &sdf::Path, ) -> Graph { let networks = networks(scene, path); @@ -196,7 +192,7 @@ impl Graph { terminals.push((name.clone(), net, c.clone())); } } - let network = translate_value_graph(stage_path, layer_dir, path, &terminals); + let network = translate_value_graph(stage_path, path, &terminals); let roots: Vec<(&str, Option<&str>)> = network .outputs .iter() @@ -457,7 +453,6 @@ fn beauty_var() -> AovVar { fn read_display( scene: &dyn moho::scene_index::SceneIndex, stage_path: &Path, - layer_dir: &LayerDir<'_>, path: &sdf::Path, index: u16, paths: &[sdf::Path], @@ -490,7 +485,9 @@ fn read_display( "crust:convolve" => Operation::Convolve { input: image("in"), kernel_path: prim.value("kernel").and_then(|v| { - asset_value_path(&v, stage_path, &|| layer_dir(&node_path, "inputs:kernel")) + asset_value_path(&v, stage_path, &|| { + node_path.append_property("inputs:kernel").ok() + }) }), kernel: None, scale: prim.f32("kernelScale").unwrap_or(1.0), diff --git a/crates/crust-core/src/scene/hydra/preview.rs b/crates/crust-core/src/scene/hydra/preview.rs index 30064a24..e1f6afda 100644 --- a/crates/crust-core/src/scene/hydra/preview.rs +++ b/crates/crust-core/src/scene/hydra/preview.rs @@ -376,7 +376,7 @@ fn preview_uv_input( let file = value(tk::FILE).and_then(|v| { asset_value_path(&v, caches.stage_path, &|| { - src.layer_dir(&tex_path, "inputs:file") + tex_path.append_property("inputs:file").ok() }) }); let Some(file) = file else { diff --git a/crates/crust-core/src/scene/hydra/products.rs b/crates/crust-core/src/scene/hydra/products.rs index 1851fe11..b6e3ec35 100644 --- a/crates/crust-core/src/scene/hydra/products.rs +++ b/crates/crust-core/src/scene/hydra/products.rs @@ -456,13 +456,13 @@ impl PrimvarKeep { /// settings prim or the prim authors no `products` — the "write the single /// beauty EXR" case. /// -/// The precomp is read too when `stage_path` is given: the stage's file and -/// the host's facts, which its kernel asset paths resolve against (a relative -/// one on the layer authoring it); a reader that only wants the products' -/// camera and framing (`crust ls`) passes `None`. +/// The precomp is read too when `stage_path` is given: the stage's file, +/// which a relative kernel path the index leaves unresolved resolves against +/// ([`super::assets::asset_value_path`]); a reader that only wants the +/// products' camera and framing (`crust ls`) passes `None`. pub(in crate::scene) fn import_render_products( scene: &dyn SceneIndex, - stage_path: Option<(&std::path::Path, &dyn super::index::host::HostFacts)>, + stage_path: Option<&std::path::Path>, pass: Option<&sdf::Path>, ) -> RenderProducts { let Some(path) = render_settings_path(scene, pass) else { @@ -473,15 +473,10 @@ pub(in crate::scene) fn import_render_products( return RenderProducts::default(); } let mut out = read_products(scene, &settings); - if let Some((stage_path, host)) = stage_path { - let layer_dir = |prim: &sdf::Path, name: &str| { - let attr = prim.append_property(name).ok()?; - host.authoring_layer_dir(&attr) - }; + if let Some(stage_path) = stage_path { out.request.precomp = super::precomp::import_precomp( scene, stage_path, - &layer_dir, &path, &mut out.request, &out.filter_targets, @@ -1351,14 +1346,7 @@ mod tests { .expect("stage opens"); let scope = crate::WarningScope::enter(); let scene = crate::scene::usd_import::input_chain(stage.clone(), None); - let products = import_render_products( - scene.chain.as_ref(), - Some(( - &path, - &crate::scene::usd_import::stage_facts::StageFacts::of(&stage), - )), - None, - ); + let products = import_render_products(scene.chain.as_ref(), Some(&path), None); (products, scope.finish()) } diff --git a/crates/crust-core/src/scene/hydra/update.rs b/crates/crust-core/src/scene/hydra/update.rs index 80120fe0..b0c4f42f 100644 --- a/crates/crust-core/src/scene/hydra/update.rs +++ b/crates/crust-core/src/scene/hydra/update.rs @@ -1293,7 +1293,6 @@ fn refresh_settings( let camera = camera.as_str(); let rc = build_camera( at.index.as_ref(), - at.facts, &target, &read.settings, read.products.framing, diff --git a/crates/crust-core/src/scene/usd_import/stage_facts.rs b/crates/crust-core/src/scene/usd_import/stage_facts.rs index 89de94f9..03c842c0 100644 --- a/crates/crust-core/src/scene/usd_import/stage_facts.rs +++ b/crates/crust-core/src/scene/usd_import/stage_facts.rs @@ -54,23 +54,6 @@ pub(in crate::scene) fn time_range(stage: &Stage, index: &dyn SceneIndex) -> Opt )) } -/// The stage's authored `metersPerUnit` (C++ `UsdGeomGetStageMetersPerUnit` -/// reads the root and session layers), `None` when no layer authors it. A -/// host fact: Hydra carries no stage unit (design D4). -pub(in crate::scene) fn meters_per_unit(stage: &Stage) -> Option { - if !stage - .has_authored_stage_metadata("metersPerUnit") - .unwrap_or(false) - { - return None; - } - match stage.stage_metadata("metersPerUnit").ok().flatten()? { - sdf::Value::Double(m) => Some(m), - sdf::Value::Float(m) => Some(f64::from(m)), - _ => None, - } -} - /// The files behind layer `identifiers`, sorted and without repeats: a layer /// inside a package is the package file, a relative identifier is anchored /// to the root layer `root`'s directory, file format arguments are dropped, @@ -334,31 +317,6 @@ pub(in crate::scene) fn instance_without_prototype(stage: &Stage, path: &sdf::Pa prim.is_instance().unwrap_or(false) && !matches!(prim.prototype(), Ok(Some(_))) } -/// The directory of the layer that authors the value of the attribute at -/// `attr` (following its connections to an interface input that supplies -/// it): where a relative asset path the value holds is anchored, as USD -/// anchors an asset path on its layer. Which layer authors an opinion is a -/// fact of the layer stack, not scene description (design D7). `None` when -/// the stage holds no such opinion. -pub(in crate::scene) fn authoring_layer_dir( - stage: &Stage, - attr: &sdf::Path, -) -> Option { - let mut at = attr.clone(); - // An interface chain is short; the bound keeps a cycle from looping. - for _ in 0..16 { - let (prim, name) = at.split_property()?; - let attribute = super::prim_at(stage, prim).attribute(name); - if attribute.has_authored_value().unwrap_or(false) { - let site = attribute.property_stack().ok()?.into_iter().next()?; - let dir = Path::new(&site.layer).parent()?.to_path_buf(); - return (!dir.as_os_str().is_empty()).then_some(dir); - } - at = attribute.connections().ok()?.into_iter().next()?; - } - None -} - /// Geometry and volume renderer attributes, by the name after `crust:`, that /// are constant primvars now (design D5). const GEOMETRY_ATTRIBUTES: &[&str] = &[ @@ -580,9 +538,6 @@ impl HostFacts for StageFacts { fn invisible_overrides(&self) -> Option { Some(invisible_overrides(&self.stage)) } - fn meters_per_unit(&self) -> Option { - meters_per_unit(&self.stage) - } fn not_a_pass(&self, pass: &sdf::Path) -> String { not_a_pass(&self.stage, pass) } @@ -598,7 +553,4 @@ impl HostFacts for StageFacts { fn instance_without_prototype(&self, path: &sdf::Path) -> bool { instance_without_prototype(&self.stage, path) } - fn authoring_layer_dir(&self, attr: &sdf::Path) -> Option { - authoring_layer_dir(&self.stage, attr) - } } diff --git a/crates/crust-core/src/warnings.rs b/crates/crust-core/src/warnings.rs index 3cfd6315..af2a6353 100644 --- a/crates/crust-core/src/warnings.rs +++ b/crates/crust-core/src/warnings.rs @@ -420,6 +420,8 @@ warning_codes! { // Assets AssetUnsupportedByHost => "asset.unsupported_by_host", Skipped, Each, "The host's asset loader does not decode this type of asset."; + AssetStringPath => "asset.string_path", Approximated, Each, + "A relative file path authored as a string resolves against the stage's directory, not its layer's."; TextureUnreadable => "texture.unreadable", Skipped, Each, "A texture could not be loaded; the input reads its fallback."; TextureUdimTileMissing => "texture.udim_tile_missing", Skipped, Each, diff --git a/crates/crust-core/tests/asset_anchoring.rs b/crates/crust-core/tests/asset_anchoring.rs index 3fd14ede..5fd160bb 100644 --- a/crates/crust-core/tests/asset_anchoring.rs +++ b/crates/crust-core/tests/asset_anchoring.rs @@ -159,11 +159,40 @@ fn relative_assets_in_a_referenced_layer_anchor_on_that_layer() { ); } +/// The textures the host is asked for whose name holds `needle`, with `root` +/// written as `$DIR` and every separator as `/`. +fn asked(assets: &Recording, root: &Path, needle: &str) -> Vec { + let root = root.display().to_string(); + assets + .0 + .lock() + .unwrap() + .iter() + .map(|p| { + p.display() + .to_string() + .replacen(&root, "$DIR", 1) + .replace('\\', "/") + }) + .filter(|p| p.contains(needle)) + .collect() +} + +/// How many `asset.string_path` warnings `scene` raised. +fn string_path_warnings(scene: &Scene) -> usize { + scene + .warnings + .iter() + .filter(|w| w.code == crust_core::WarningCode::AssetStringPath) + .count() +} + /// A texture file authored as a `string`, not an `asset`: USD does not -/// resolve it, and the importer anchors it on its authoring layer all the -/// same, as the direct importer did. +/// anchor text on its layer, and the index carries no resolution for it, so +/// it resolves against the stage's directory and says so +/// (`hydra-only-renders`, design D1). #[test] -fn a_string_typed_texture_path_anchors_on_its_layer_too() { +fn a_string_typed_texture_path_resolves_against_the_stage_and_warns() { let dir = std::env::temp_dir().join("crust_asset_anchoring_string"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("assets/deep")).unwrap(); @@ -174,15 +203,45 @@ fn a_string_typed_texture_path_anchors_on_its_layer_too() { std::fs::write(dir.join("assets/deep/asset.usda"), asset).unwrap(); std::fs::write(dir.join("root.usda"), ROOT).unwrap(); let assets = Recording::default(); - Scene::from_usd_with_assets(&dir.join("root.usda"), &assets).expect("imports"); - let root = dir.display().to_string(); + let scene = Scene::from_usd_with_assets(&dir.join("root.usda"), &assets).expect("imports"); + assert_eq!(asked(&assets, &dir, "rough"), ["$DIR/textures/rough.png"]); + assert!(string_path_warnings(&scene) >= 1, "{:?}", scene.warnings); + let message = &scene + .warnings + .iter() + .find(|w| w.code == crust_core::WarningCode::AssetStringPath) + .unwrap() + .message; + assert!( + message.contains("which USD does not anchor on its layer") && !message.contains(" "), + "{message:?}" + ); +} + +/// An absolute path authored as a `string` is read as it is, silently. +#[test] +fn an_absolute_string_texture_path_is_read_as_it_is() { + let dir = std::env::temp_dir().join("crust_asset_anchoring_absolute"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("assets/deep")).unwrap(); + let absolute = dir.join("elsewhere/rough.png"); + let literal = absolute.display().to_string().replace('\\', "/"); + let asset = ASSET.replace( + "asset inputs:file = @textures/rough.png@", + &format!("string inputs:file = \"{literal}\""), + ); + std::fs::write(dir.join("assets/deep/asset.usda"), asset).unwrap(); + std::fs::write(dir.join("root.usda"), ROOT).unwrap(); + let assets = Recording::default(); + let scene = Scene::from_usd_with_assets(&dir.join("root.usda"), &assets).expect("imports"); let asked: Vec = assets .0 .lock() .unwrap() .iter() - .map(|p| p.display().to_string().replacen(&root, "$DIR", 1)) + .map(|p| p.display().to_string().replace('\\', "/")) .filter(|p| p.contains("rough")) .collect(); - assert_eq!(asked, ["$DIR/assets/deep/textures/rough.png"]); + assert_eq!(asked, [literal]); + assert_eq!(string_path_warnings(&scene), 0, "{:?}", scene.warnings); } diff --git a/crates/crust-core/tests/lens_units_from_index.rs b/crates/crust-core/tests/lens_units_from_index.rs new file mode 100644 index 00000000..dc06ed02 --- /dev/null +++ b/crates/crust-core/tests/lens_units_from_index.rs @@ -0,0 +1,94 @@ +//! `hydra-only-renders` "The unit from the index": the lens converts its +//! millimetres through the stage unit the index carries +//! (`__usdMetersPerUnit/metersPerUnit`, Moho), so a host that answers no +//! facts about its stage commits the same lens as one that does. + +use std::path::Path; +use std::sync::Arc; + +use crust_core::{HostFacts, NoHostFacts, Scene, SceneDelegate, StageHostFacts, UsdImportOptions}; +use moho::openusd::usd::{InitialLoadSet, Stage}; +use moho::stage::StageSceneIndex; + +const METRE_LENS: &str = r#"#usda 1.0 +( + defaultPrim = "World" + metersPerUnit = 1 + upAxis = "Y" +) + +def Xform "World" +{ + def Camera "cam" + { + float focalLength = 50 + float fStop = 2 + float focusDistance = 5 + } + + def Sphere "ball" + { + double radius = 1 + double3 xformOp:translate = (0, 0, -5) + uniform token[] xformOpOrder = ["xformOp:translate"] + } +} +"#; + +/// The scene a fresh delegate commits over the stage at `path`, with +/// `facts` built from the stage when `stage_facts` is set, else none. +fn commit(path: &Path, stage_facts: bool) -> Scene { + let stage = Stage::builder() + .schema_registry(crust_core::usd_schema_registry()) + .load(InitialLoadSet::LoadAll) + .open(path.to_str().unwrap()) + .unwrap(); + let index = StageSceneIndex::new(); + index.set_stage(stage.clone()); + let chain = moho::chain::standard(index); + let facts: Box = if stage_facts { + Box::new(StageHostFacts::new(&stage, path, Some(chain.clone()))) + } else { + Box::new(NoHostFacts) + }; + let mut delegate = SceneDelegate::new( + chain, + path, + UsdImportOptions::default(), + Arc::new(crust_core::NoAssets), + ); + delegate.update(facts.as_ref(), None).unwrap().scene +} + +/// The distance between two opposite lens samples through the frame centre: +/// the lens diameter, in scene units. +fn lens_diameter(scene: &Scene) -> f32 { + let a = scene.camera.get_ray(0.5, 0.5, [0.0, 0.5], 0.0); + let b = scene.camera.get_ray(0.5, 0.5, [1.0, 0.5], 0.0); + a.origin().distance(b.origin()) +} + +#[test] +fn a_metre_stage_has_the_same_lens_without_host_facts() { + let dir = std::env::temp_dir().join("crust_lens_units_from_index"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("metre_lens.usda"); + std::fs::write(&path, METRE_LENS).unwrap(); + + let with = commit(&path, true); + let without = commit(&path, false); + // 50 mm at f/2 is 25 mm: 0.025 units on a metre stage (2.5 on the + // centimetre fallback, had the unit been lost). + assert!( + (lens_diameter(&with) - 0.025).abs() < 1e-7, + "{}", + lens_diameter(&with) + ); + assert_eq!( + lens_diameter(&with).to_bits(), + lens_diameter(&without).to_bits(), + "with host facts {}, without {}", + lens_diameter(&with), + lens_diameter(&without) + ); +} diff --git a/crates/crust-render/tests/host_facts.rs b/crates/crust-render/tests/host_facts.rs new file mode 100644 index 00000000..c0982dba --- /dev/null +++ b/crates/crust-render/tests/host_facts.rs @@ -0,0 +1,123 @@ +//! `hydra-only-renders`: the image depends on the scene index alone. Every +//! sample that references no `.mtlx` document renders bit-identically when +//! its delegate is told nothing about the stage (`NoHostFacts`) and when it +//! is told everything (`StageHostFacts`): what the host knows of its stage +//! only informs warnings, reports and provenance. The one listed exception, +//! a material referencing a `.mtlx` document (which openusd does not +//! compose), is checked to differ, so the list cannot hide a regression. +#![allow(clippy::unwrap_used)] + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crust_assets::FileAssets; +use crust_core::{ + HostFacts, NoHostFacts, Renderer, Scene, SceneDelegate, StageHostFacts, UsdImportOptions, +}; +use moho::openusd::usd::{InitialLoadSet, Stage}; +use moho::stage::StageSceneIndex; + +/// The samples whose materials reference a `.mtlx` document: the one fact +/// still asked of the host (`HostFacts::mtlx_reference`) until +/// `mtlx-format-plugin` composes them into the stage. +const MTLX_REFERENCING: &[&str] = &[ + "displacement", + "hair", + "hair_variation", + "materialx_basic", + "materialx_cutout", + "materialx_emissive", + "materialx_subsurface", + "materialx_surfaces", + "thin_window", +]; + +/// The resolution every sample is rendered at: small enough for an +/// unoptimized test build, large enough to see every texture. Both sides of +/// a comparison render at it, so the frame's own aspect does not matter. +const RESOLUTION: (usize, usize) = (24, 16); + +fn samples() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../samples") +} + +/// The scene a fresh delegate commits over `path`, told about the stage when +/// `stage_facts` is set, loading assets from disk. +fn commit(path: &Path, stage_facts: bool) -> Scene { + let stage = Stage::builder() + .schema_registry(crust_core::usd_schema_registry()) + .load(InitialLoadSet::LoadAll) + .open(path.to_str().unwrap()) + .unwrap(); + let index = StageSceneIndex::new(); + index.set_stage(stage.clone()); + let chain = moho::chain::standard(index); + let facts: Box = if stage_facts { + Box::new(StageHostFacts::new(&stage, path, Some(chain.clone()))) + } else { + Box::new(NoHostFacts) + }; + let mut delegate = SceneDelegate::new( + chain, + path, + UsdImportOptions::default(), + Arc::new(FileAssets::new()), + ); + delegate.update(facts.as_ref(), None).unwrap().scene +} + +/// The scene rendered at 16 spp and [`RESOLUTION`], as bits. +fn bits(scene: Scene) -> Vec { + let settings = scene + .settings + .with_samples_per_pixel(16) + .with_resolution(RESOLUTION.0, RESOLUTION.1); + let renderer = Renderer::new(scene.camera, scene.world, scene.lights, settings) + .with_volumes(scene.volumes); + let (image, _) = renderer.render_with_stats(true, &|_, _| {}); + let (w, h) = image.size(); + (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .flat_map(|(x, y)| { + let (r, g, b) = image.get_rgb(x, y); + [r.to_bits(), g.to_bits(), b.to_bits()] + }) + .collect() +} + +fn same_without_host_facts(path: &Path) -> bool { + bits(commit(path, true)) == bits(commit(path, false)) +} + +#[test] +fn no_host_facts_render_the_same_image() { + let mut checked = Vec::new(); + let mut differ = Vec::new(); + let mut entries: Vec = std::fs::read_dir(samples()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|e| e == "usda")) + .collect(); + entries.sort(); + for path in entries { + let name = path.file_stem().unwrap().to_string_lossy().into_owned(); + if MTLX_REFERENCING.contains(&name.as_str()) { + continue; + } + if !same_without_host_facts(&path) { + differ.push(name.clone()); + } + checked.push(name); + } + assert!(checked.len() > 30, "{checked:?}"); + assert!(differ.is_empty(), "differ without host facts: {differ:?}"); +} + +/// The listed exception: without the host, a `.mtlx`-referenced material +/// composes empty and renders otherwise. +#[test] +fn a_mtlx_reference_still_needs_the_host() { + assert!(!same_without_host_facts( + &samples().join("materialx_basic.usda") + )); +} diff --git a/docs/architecture.md b/docs/architecture.md index f377a27d..13833f69 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -176,7 +176,7 @@ both sides must keep; the contract lives in the doc comment at the definition. | `Light`, `LightShape` | `crust-core/src/light/` (`mod.rs`, `shape.rs`) | `AreaLight`, `DistantLight`, `DomeLight`; sphere / rect / affine shapes | NEE and the bounce side must compute the same density for the same point | | `ProgressCallback` | `crust-core/src/tracer/mod.rs` | the CLI's `indicatif` bar | called with `(done, total)`; the engine never prints | | `RenderControl`, `RenderOutcome` | `crust-core/src/tracer/control.rs` | the CLI (Ctrl-C, `--checkpoint`), a kept `Delegate`'s renders (polled through its `RenderHandle`) | one per render, owned by the host, `Sync`: `cancel` from any thread is sticky; `snapshot` is `None` before the first publish, then the region-sized beauty (the precomp's displayed output, its display chain run on read over the units published so far, when `crust:display` is authored; `beauty_snapshot` is always the beauty) at a monotonic `generation`; `samples_reached` is the first sweep's last completed stage, `max_samples_reached` the most any pass has reached (a new pass, such as a guided render's next training pass, resets the first, not the second); a cancelled render returns what it traced and `Cancelled` | -| `HostFacts` | `crust-core/src/scene/hydra/index/host.rs` | `StageHostFacts` (the batch host), `NoHostFacts`, Mantle | what is not scene description (layers, `invisible` overrides, `metersPerUnit`, a `.mtlx` reference, transform facts, an asset's authoring layer), answered by the host that opened the stage; the delegate names no stage | +| `HostFacts` | `crust-core/src/scene/hydra/index/host.rs` | `StageHostFacts` (the batch host), `NoHostFacts`, Mantle | what is not scene description (layers, `invisible` overrides, a `.mtlx` reference, transform facts), answered by the host that opened the stage; the delegate names no stage, and only the `.mtlx` reference changes the image (`crust-render/tests/host_facts.rs`) | | `SceneDelegate`, `Delegate` | `crust-core/src/scene/hydra/delegate.rs`, `crust-render/src/delegate/` | the CLI (`load_scene`), Mantle's IPR | a host hands a Moho standard chain and drives `update` from the thread that owns it; an update reports its `UpdateClass` and is bitwise a fresh commit | | `RenderStats`, `profile::Section` | `crust-core/src/stats.rs`, `profile.rs` | — | counters always on, timers per phase; `--profile` sections compile away when off | diff --git a/openspec/changes/hydra-only-renders/.openspec.yaml b/openspec/changes/hydra-only-renders/.openspec.yaml new file mode 100644 index 00000000..5c99d6d7 --- /dev/null +++ b/openspec/changes/hydra-only-renders/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-29 diff --git a/openspec/changes/hydra-only-renders/design.md b/openspec/changes/hydra-only-renders/design.md new file mode 100644 index 00000000..fc979c2f --- /dev/null +++ b/openspec/changes/hydra-only-renders/design.md @@ -0,0 +1,108 @@ +## Context + +`HostFacts` (`scene/hydra/index/host.rs`) is what the delegate asks its host +about the stage. The batch host and Mantle answer it with `StageHostFacts` +(`usd_import/stage_facts.rs`); `NoHostFacts` answers nothing. Of its eleven +questions, three change the committed scene: + +- `authoring_layer_dir`, called through `asset_value_path` + (`scene/hydra/assets.rs`) at every file-reading site: `UsdUVTexture` and + Ptex files, MaterialX `filename`s, rect/dome light textures, IES profiles, + the precomp kernel. `asset_value_path` takes the index value's + `resolved_path` first. Moho resolves every relative `asset` value on its + authoring layer (`stage/attribute.rs`, `anchor`), so the layer directory is + only reached for a value authored as a `string`, or an asset Moho could not + anchor (an anonymous layer). `0bebb347` added the string case to match the + direct importer. +- `meters_per_unit`, read by `camera.rs` for the lens diameter. +- `mtlx_reference`, the `.mtlx` a material references, which + `mtlx-format-plugin` replaces with composition. + +`time_range` reads its values from the index already; only "is a range +authored" is the host's, and it only gates a warning. + +## Goals / Non-Goals + +**Goals:** +- With `NoHostFacts`, the delegate commits the same scene as with + `StageHostFacts`, except a `.mtlx`-referenced material. +- That is checked by a test, not claimed. + +**Non-Goals:** +- Removing the diagnostic facts. Hydra does not carry them, and a host that + cannot answer them loses warnings, not pixels. +- MaterialX references: `mtlx-format-plugin` owns their removal. +- Changing the `HostFacts` trait's shape beyond removing two methods. + +## Decisions + +**D1. A `string` path resolves against the stage path's directory, with a +warning.** USD anchors `asset` values only; a `string` is text. The +delegate has one directory it may use without a stage: the one beside the +stage path its host gave (the root layer's, for the batch host). +`asset_value_path` loses its `layer_dir` argument and keeps its other +order: the resolved path, an absolute authored path, then the stage +directory. A relative `string` raises `asset.string_path` (`Approximated`, +logged each time the import reads it, as `texture.unreadable` counts each +reference to a file) naming the attribute and the resolved path, so a scene +that relied on layer anchoring says why its texture moved. +*Alternatives:* keep `authoring_layer_dir` as a declared exception (keeps a +non-USD behaviour that needs a stage); ask Moho to anchor `string` inputs +(non-USD in Moho, and every consumer would inherit it); refuse the path +(louder, but a string path beside the root layer works today and would +break needlessly). + +**D2. The unit from `__usdMetersPerUnit/metersPerUnit`.** `camera.rs`'s +`authored_meters_per_unit` reads the index root (absent → `None`, the +existing "unauthored" warning and centimetre fallback). Bump Moho to the +merge of `stage-meters-per-unit` first. The value is read at each commit, as +the host fact was; Moho notifies nothing for a root metadata edit, which is +no worse than today (an in-place update did not re-ask the host either). + +**D3. The guard renders through the delegate with both facts.** A test in +`crust-render` (it owns the delegate and the batch host's chain) opens each +`samples/*.usda` that references no `.mtlx`, builds the chain, commits once +with `StageHostFacts` and once with `NoHostFacts` on two delegates, renders +each at 16 spp at a reduced resolution (a `-r`-style override, so all +samples fit in the test budget), and compares RGBA bitwise. The stage path +given to both is the sample's, so D1's directory is the same. The `.mtlx` +samples (nine today) are listed by name, so a new one is excluded only on +purpose; `mtlx-format-plugin` empties the list. +*Alternative:* compare committed scenes structurally. Pixels are what the +requirement promises, and a structural diff would need an equality Crust +does not have. + +**D4. `tests/asset_anchoring.rs`'s string case is rewritten, not deleted.** +It asserts D1: the file beside the root layer and the warning. The +`asset` cases keep their layer-anchored expectations, now met by the index +alone. + +## Risks / Trade-offs + +- [Production content authors texture paths as `string`] → Measured before + merging: `crust check` on ALab and Moana counts `asset.string_path`. If + either relies on it, this is the user's call before implementation goes + further. +- [Mantle's mirror has no file, so its stage path is a fixed path under the + current directory] → Mantle's LOPs author absolute paths; a `string` path + there resolves under the current directory and warns, as any host + without a layer. +- [The guard is slow] → Reduced resolution and the existing 16 spp pin; it + renders each sample twice, once per facts. + +## Migration Plan + +1. Moho `stage-meters-per-unit` merged; bump Moho here. +2. D2, then D1 with its warning and test rewrite, then the guard (D3). +3. Docs: warnings page, design records, architecture. +4. Mantle bumps crust-render afterwards; it needs no code change. + +## Open Questions + +None left. Whether ALab or Moana author relative `string` paths (the first +risk) was measured on 2026-10-30 with a temporary count in +`asset_value_path` under `crust check`: ALab 2.3.0 (`entry.usda`, frame +1004) and the Moana island (`island.usda`) reach the layer directory zero +times, for `string` paths and for `asset` values Moho left unresolved +alike. The count fired on a sublayered `string inputs:file`, so a zero is a +real zero. diff --git a/openspec/changes/hydra-only-renders/proposal.md b/openspec/changes/hydra-only-renders/proposal.md new file mode 100644 index 00000000..48df9ae0 --- /dev/null +++ b/openspec/changes/hydra-only-renders/proposal.md @@ -0,0 +1,70 @@ +## Why + +Crust's delegate reads only Hydra schemas (`tests/hydra_only.rs`), but three +answers it takes from the host's stage, through `HostFacts`, still change the +image: the directory of the layer that authors an asset value +(`authoring_layer_dir`), the stage's `metersPerUnit` (depth of field), and a +material's `.mtlx` reference. Under a host with no stage (`NoHostFacts`), a +relative texture authored as a `string`, a metre-unit scene's lens and a +`.mtlx`-referenced material render differently. A Hydra 2.0 delegate should +render from its index alone; the stage should only explain what it rendered. + +## What Changes + +- **Asset paths come from the index.** `HostFacts::authoring_layer_dir` is + removed. An `asset` value already arrives resolved (Moho anchors it on its + authoring layer, as UsdImaging does), and is used as it does today. A + relative path authored as a `string`, which USD never anchors, resolves + against the stage path's directory, as when no layer is known today, and + raises a new warning, `asset.string_path`. **BREAKING (behaviour)**: such a + path in a sublayer or reference in another directory no longer finds its + file beside that layer (it did since `0bebb347`); authoring it as an + `asset` restores it. +- **`metersPerUnit` comes from the index.** Depth of field reads + `__usdMetersPerUnit/metersPerUnit` on the index root (Moho's + `stage-meters-per-unit`, a prerequisite), and `HostFacts::meters_per_unit` + is removed. Its warnings (unauthored, refused) are unchanged. +- **MaterialX references stay a host fact, until `mtlx-format-plugin`.** + `mtlx_reference` is the one render-affecting fact left; the in-flight + `mtlx-format-plugin` change removes it by composing `.mtlx` documents into + the stage. This change records it as the only exception. +- **A guard.** Each sample that references no `.mtlx` renders bit-identically + at 16 spp with `NoHostFacts` and with `StageHostFacts`. +- The remaining facts stay: they feed warnings, `crust check` and provenance + only. `time_range` among them: its values already come from the index's + `sceneGlobals`, and only whether the stage authors a range (Hydra gives `0` + when it does not) is asked of the host, for the frame-outside-range + warning. Likewise `layers`, `layer_stack`, `invisible_overrides`, + `not_a_pass`, `foreign_spec_paths`, `xform_facts` and + `instance_without_prototype`. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `render-delegate`: a requirement that the delegate's image depends on the + scene index alone, host facts informing diagnostics only, with + `.mtlx` references the one listed exception. +- `usd-scene-import`: a relative asset path authored as a `string` resolves + against the stage's directory with an `asset.string_path` warning, rather + than on its authoring layer. + +## Impact + +- `crust-core`: `scene/hydra/index/host.rs` (two methods removed), + `usd_import/stage_facts.rs`, `scene/hydra/{assets,lights,materials,products, + camera,mod}.rs` and `precomp`, `warnings.rs` (one code), + `tests/asset_anchoring.rs` (the string case rewritten), a new guard test. +- Moho pin: bumped to the merge of `stage-meters-per-unit`. +- Docs: `site/content/docs/reference/warnings.md`, the `usd-scene-import` and + `render-delegate` design records, `docs/architecture.md` (the delegate's + host facts). +- Hosts: Mantle and the batch host keep passing `StageHostFacts`; nothing + they call changes. Mantle's mirror stage has no file, so a `string` path + there resolves against its fixed path; Mantle's LOPs author absolute paths. +- Performance: none expected; the index reads replace stage reads once per + commit. diff --git a/openspec/changes/hydra-only-renders/specs/render-delegate/spec.md b/openspec/changes/hydra-only-renders/specs/render-delegate/spec.md new file mode 100644 index 00000000..c0490222 --- /dev/null +++ b/openspec/changes/hydra-only-renders/specs/render-delegate/spec.md @@ -0,0 +1,37 @@ +## ADDED Requirements + +### Requirement: The image depends on the scene index alone + +The scene the delegate commits, and so the image it renders, SHALL depend only +on the scene index the host gave it and on the host's render settings for the +delegate (samples, region). What the delegate asks its host about the stage +(`HostFacts`) SHALL only inform warnings, `crust check` reports and +provenance, with one exception: the `.mtlx` document a material references, +which openusd does not compose (removed by `mtlx-format-plugin`). + +In particular, the delegate SHALL read from the index: +- every asset path, as the index's `asset` value gives it (resolved, or + authored); a relative path the index leaves unresolved resolves against the + directory of the stage path the host gave; +- the stage's unit, from the absolute root's `__usdMetersPerUnit/metersPerUnit`, + unauthored when absent. + +#### Scenario: No host facts, the same image + +- **WHEN** a sample that references no `.mtlx` document is rendered at 16 + spp once with `NoHostFacts` and once with the stage's `StageHostFacts` +- **THEN** the two images are bit-identical + +#### Scenario: The unit from the index + +- **WHEN** a stage authors `metersPerUnit = 1`, its render camera authors + depth of field, and the delegate is updated with `NoHostFacts` +- **THEN** the lens is the one the existing depth-of-field requirement gives + for `metersPerUnit = 1` + +#### Scenario: The listed exception + +- **WHEN** a material's only opinion is a reference into a `.mtlx` document + and the delegate is updated with `NoHostFacts` +- **THEN** the material renders as an empty material, and with + `StageHostFacts` it renders through the referenced document diff --git a/openspec/changes/hydra-only-renders/specs/usd-scene-import/spec.md b/openspec/changes/hydra-only-renders/specs/usd-scene-import/spec.md new file mode 100644 index 00000000..c117b31c --- /dev/null +++ b/openspec/changes/hydra-only-renders/specs/usd-scene-import/spec.md @@ -0,0 +1,29 @@ +## ADDED Requirements + +### Requirement: Relative asset paths resolve as the index gives them + +A file named by an `asset`-typed value (a texture, a Ptex file, a MaterialX +`filename`, a light texture, an IES profile, the precomp kernel) SHALL be the +path the index's value resolves to, which is anchored on the layer that +authors it. A relative path authored as a `string`, which USD does not +anchor, SHALL resolve against the directory of the stage path the host gave, +and SHALL raise the `asset.string_path` warning, naming the attribute and the +path it resolved to, each time the import reads it (as `texture.unreadable` +counts each reference to a file). + +#### Scenario: An asset in a referenced layer + +- **WHEN** a layer two directories below the root layer authors + `asset inputs:file = @textures/rough.png@` +- **THEN** the texture read is `textures/rough.png` beside that layer + +#### Scenario: A string in a referenced layer + +- **WHEN** the same layer authors `string inputs:file = "textures/rough.png"` +- **THEN** the texture read is `textures/rough.png` beside the root layer, and + `asset.string_path` names the attribute and that path + +#### Scenario: An absolute string + +- **WHEN** a layer authors a `string` file path that is absolute +- **THEN** that path is read and no warning is raised diff --git a/openspec/changes/hydra-only-renders/tasks.md b/openspec/changes/hydra-only-renders/tasks.md new file mode 100644 index 00000000..22cbe17d --- /dev/null +++ b/openspec/changes/hydra-only-renders/tasks.md @@ -0,0 +1,33 @@ +## 0. Before starting + +- [x] 0.1 Run `crust check --json -` on ALab and Moana and count relative paths authored as `string` at the file-reading sites (a temporary debug count, not committed); record the counts in design.md's open question, and stop for the user's decision if either is non-zero + +## 1. The unit from the index (design D2) + +- [x] 1.1 Bump Moho to the merge of `stage-meters-per-unit` (`[workspace.dependencies]`), `cargo update -p moho`; verify `cargo tree -i openusd` shows one copy +- [x] 1.2 `camera.rs`: read `__usdMetersPerUnit/metersPerUnit` from the index root instead of `HostFacts::meters_per_unit`; remove the method from `HostFacts`, `NoHostFacts` and `StageFacts`; the existing depth-of-field and refused-unit tests pass unchanged +- [x] 1.3 Add a test: a `metersPerUnit = 1` stage with depth of field commits the same lens with `NoHostFacts` as with `StageHostFacts` (spec "The unit from the index") + +## 2. Asset paths from the index (design D1, D4) + +- [x] 2.1 Add `WarningCode::AssetStringPath` (`asset.string_path`, `Approximated`, each read) and its row in `site/content/docs/reference/warnings.md`; the warnings-in-step test passes +- [x] 2.2 `asset_value_path` drops its `layer_dir` argument: resolved path, absolute authored path, then the stage path's directory, raising `asset.string_path` for a relative `string`; update its call sites in `lights.rs`, `materials.rs`, `products.rs`/precomp and `mod.rs`, and remove `layer_dir` helpers +- [x] 2.3 Remove `HostFacts::authoring_layer_dir` and `stage_facts::authoring_layer_dir` +- [x] 2.4 Rewrite `tests/asset_anchoring.rs`'s string case to D1 (the file beside the root layer, the warning raised), add an absolute-string case without warning; verify every `asset` case passes unchanged + +## 3. The guard (design D3) + +- [x] 3.1 Add `crates/crust-render/tests/host_facts.rs` (feature `delegate`): every `samples/*.usda` not on a named `.mtlx` list, committed through two delegates (`StageHostFacts`, `NoHostFacts`), rendered at 16 spp at a reduced resolution, compared bitwise (spec "No host facts, the same image") +- [x] 3.2 In the same file, the listed exception: a `.mtlx`-referencing sample differs with `NoHostFacts` (spec "The listed exception"), so the list cannot hide a regression silently +- [x] 3.3 Run `scripts/check_images.sh check` against goldens recorded before 1.2 (16 spp, `--indirect-clamp 0` on both sides); verify no sample's image changed + +## 4. Documentation and gate + +- [x] 4.1 `openspec/specs/render-delegate/design.md` and `usd-scene-import/design.md`: host facts are diagnostics only, with the `.mtlx` exception; the string-path anchoring history and its reversal; `docs/architecture.md`'s delegate section likewise +- [x] 4.2 `site/`: the asset-path page states that `string` paths resolve against the stage's directory; `zola build` passes +- [x] 4.3 Run `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo clippy -p crust-render --features delegate --all-targets -- -D warnings` and `cargo test --workspace --no-fail-fast`; verify all pass + +## Workflow follow-up + +- Mantle bumps crust-render to this change's merge; no Mantle code changes. +- `mtlx-format-plugin` empties the guard's `.mtlx` list and removes `mtlx_reference`. diff --git a/openspec/specs/render-delegate/design.md b/openspec/specs/render-delegate/design.md index bc65c0d9..a93dc653 100644 --- a/openspec/specs/render-delegate/design.md +++ b/openspec/specs/render-delegate/design.md @@ -46,6 +46,31 @@ and a prim factory, flushed in `Update`. Moho ports the three (`PrimTypeNoticeBatchingSceneIndex`, `PrimManagingObserver`, `PrimFactory`), so the delegate's code is the same over Moho as over a later FFI `SceneIndex`. +## What the host is asked, and what the image depends on + +A Hydra delegate is handed a terminal scene index and nothing else: UsdImaging +resolves asset paths before they reach it, and it never sees a stage. Crust's delegate +also asks its host a few questions about the stage (`HostFacts`), because some facts +are not scene description: which layers composed, whether a time range is authored, +the transform facts behind `xform.uncomposable`. Since `hydra-only-renders` those +answers inform warnings, `crust check` and provenance only: the committed scene, and +so the image, depends on the index alone. The one exception is a material that +references a `.mtlx` document, which openusd does not compose, so Crust reads the +file itself through `HostFacts::mtlx_reference` until `mtlx-format-plugin` composes +it into the stage. + +Two facts that used to change the image moved onto the index. The stage unit, which +the lens converts its millimetres through, is Moho's `__usdMetersPerUnit` on the +absolute root (Hydra carries no unit; UsdImaging's camera scales lens values by a +fixed 0.1). Asset paths are the index's `asset` values, which Moho resolves on their +authoring layer as UsdImaging does; only a path authored as a `string` lost its layer +anchoring, and it now resolves against the stage's directory with `asset.string_path`. + +The guard is `crust-render/tests/host_facts.rs`: every sample that references no +`.mtlx` renders bit-identically at 16 spp with `NoHostFacts` and with +`StageHostFacts`, and a `.mtlx`-referencing one is checked to differ, so the list of +exceptions cannot hide a regression. + ## Panics are contained where the host unwinds hdCrust built under an unwinding profile and caught a panic at every boundary diff --git a/openspec/specs/usd-scene-import/design.md b/openspec/specs/usd-scene-import/design.md index 3573cf8d..f8766487 100644 --- a/openspec/specs/usd-scene-import/design.md +++ b/openspec/specs/usd-scene-import/design.md @@ -1196,7 +1196,9 @@ same point. authored (what `crust ls camera --json` reports); only `lens_camera` derives the diameter. Only a lens reads the unit: one that is not finite, not positive, or so small that the diameter overflows `f32` (a lens offsetting every ray to infinity) is - refused as `camera.invalid_meters_per_unit` and reads as 0.01, raised like the + refused as `camera.invalid_meters_per_unit` and reads as 0.01 (the unit is read from + the index root's `__usdMetersPerUnit/metersPerUnit`, Moho's, absent when unauthored), + raised like the exposure check, for the camera rendered through only (`RenderCamera::warn_lens_units`), so a fallback candidate the traversal built and dropped says nothing. `metersPerUnit` is read for the lens only: light units, displacement bounds and edge lengths still @@ -1687,12 +1689,26 @@ machinery are gone, and the goldens are the guard. the USD type, applied API schemas and a native instance's prototype. `primOrigin/scenePath` names a prototype prim by its USD source. - **Host facts.** What is not scene description comes through the public `HostFacts` - trait (`hydra/index/host.rs`): the time range, the layers and layer stack, - layer-spec `invisible` overrides, `metersPerUnit`, a `.mtlx` reference, a + trait (`hydra/index/host.rs`): whether the stage authors a time range, the layers + and layer stack, layer-spec `invisible` overrides, a `.mtlx` reference, a material's foreign spec paths for provenance, the transform facts behind - `xform.uncomposable`, an instance without a prototype, and an asset's authoring - layer directory. The batch host answers from its stage (`usd_import/stage_facts.rs`, - public as `StageHostFacts`). A host with no stage answers nothing (`NoHostFacts`). + `xform.uncomposable`, and an instance without a prototype. The batch host answers + from its stage (`usd_import/stage_facts.rs`, public as `StageHostFacts`). A host + with no stage answers nothing (`NoHostFacts`). +- **The image depends on the index alone** (`hydra-only-renders`). Of the host facts, + only the `.mtlx` reference changes the committed scene, until `mtlx-format-plugin` + composes `.mtlx` documents into the stage; the others inform warnings, `crust + check` and provenance. `crust-render/tests/host_facts.rs` pins it: every sample + that references no `.mtlx` renders bit-identically at 16 spp with `NoHostFacts` + and with `StageHostFacts`. Two facts moved onto the index for it. The stage unit + is Moho's `__usdMetersPerUnit/metersPerUnit` on the absolute root (Moho + `stage-meters-per-unit`). An asset path is the index's `asset` value, which Moho + resolves on the layer that authors it; a relative path authored as a `string`, + which USD never anchors, resolves against the stage path's directory and raises + `asset.string_path`. From `0bebb347` until this change a `string` path anchored + on its authoring layer through a host fact (`authoring_layer_dir`), as the + direct importer had; measured on 2026-10-30, ALab 2.3.0 and the Moana island + author no such path. The `crust check`-only stage checks (`time.default_and_samples`, `settings.path_across_arc`, …) are a host-side walk that no render pays for. `crust ls` lists the render's index by Hydra type. diff --git a/site/content/docs/reference/warnings.md b/site/content/docs/reference/warnings.md index 8ed7e558..c11d639e 100644 --- a/site/content/docs/reference/warnings.md +++ b/site/content/docs/reference/warnings.md @@ -271,6 +271,7 @@ Sample and display filters ([render settings](@/docs/usd/render-settings.md#prec | code | kind | meaning | what to do | |------|------|---------|------------| | `asset.unsupported_by_host` | skipped | The host's asset loader does not decode this type of asset. | Use a host that decodes assets (the `crust` CLI does). | +| `asset.string_path` | approximated | A relative file path authored as a string resolves against the stage's directory, not its layer's. | Author the path as an `asset` (`@path@`), which USD anchors on the layer that authors it. | | `texture.unreadable` | skipped | A texture could not be loaded; the input reads its fallback. | Check the file path and format; the message gives the loader's reason. | | `texture.udim_tile_missing` | skipped | A tile of a UDIM set does not decode; the set is used without it. | Fix or remove the tile the message names. | | `texture.tx_stale` | approximated | A .tx's modification time is not its source's; it is used anyway. | Rerun with `--auto-tx` to reconvert. | diff --git a/site/content/docs/usd/materials.md b/site/content/docs/usd/materials.md index bdc4417c..e37706a6 100644 --- a/site/content/docs/usd/materials.md +++ b/site/content/docs/usd/materials.md @@ -655,6 +655,21 @@ seam. `CRUST_DISPLACE=0` turns displacement off for an A/B; see [environment variables](@/docs/reference/environment-variables.md#crust-displace). +## Texture file paths + +A file path authored as an `asset` (`@textures/rough.png@`) is resolved as USD resolves +it: a relative path against the directory of the layer that authors it, so a texture +beside a referenced or sublayered file is found there, whichever file the render +opens. This holds for every file crust reads: `UsdUVTexture` and Ptex files, +MaterialX `filename` inputs, light textures, IES profiles and the precomp kernel. + +A path authored as a `string` (`string inputs:file = "textures/rough.png"`) is text, +which USD does not resolve. An absolute one is read as it is. A relative one resolves +against the directory of the file the render opened, wherever the layer that authors +it lives, and raises the +[`asset.string_path`](@/docs/reference/warnings.md) warning. Author the path as an +`asset` to have it found beside its own layer. + ## Texture colour spaces Textures are converted to linear light in the