From 0fc4cd27473910c5ff6c9df7acd6f9148fa2647b Mon Sep 17 00:00:00 2001 From: austin62jake Date: Wed, 4 Nov 2026 06:11:09 +0000 Subject: [PATCH] Agents and scripts: the render stage commands (Ground, Backdrop, Clear) describe their exact parameters and reply (#11455) (#11456) * claim: #11455 Co-Authored-By: Claude Opus 5.5 * Render stage: input and output schemas for Ground, Backdrop and Clear (#11455) The three handlers' strict parameter types move to schema/render_stage.rs as GroundParams, BackdropParams and ClearParams, with descriptions and JsonSchema, and become the contracts; the handlers read the same types. The handlers build the shared StageSaved reply instead of json! literals, and the saved setup is serialized with an error instead of json!'s panic path. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude --- crates/engine/src/cmd/render.rs | 12 +- crates/engine/src/cmd/render/staging.rs | 120 ++++++--------- crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/render_stage.rs | 145 ++++++++++++++++++ .../engine/src/schema/render_stage_tests.rs | 99 ++++++++++++ crates/engine/src/schema/unconverted.txt | 3 - 6 files changed, 299 insertions(+), 81 deletions(-) create mode 100644 crates/engine/src/schema/render_stage.rs create mode 100644 crates/engine/src/schema/render_stage_tests.rs diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 64001d6c0..150734229 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -91,11 +91,17 @@ CommandSpec::new("render.library.preview", "Inspect Original Surface Map", libra .params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."), CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only() .params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."), -CommandSpec::new("render.stage.ground", "Save Render Ground", staging::ground).icon("render_scene") +CommandSpec::new("render.stage.ground", "Save Render Ground", crate::checked!("render.stage.ground", staging::ground)).icon("render_scene") + .contract(&staging::GROUND_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: typed raytrace setup, set?: setup patch, margin_fraction?:0.25, gap_mm?:0.1, reflectance_linear?:[0.18,0.18,0.18], replace_stage?:false. Fits one finite passive ground below the visible product once and saves its physical transforms in one undo. Product AABB separation is rechecked on every render."), -CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", staging::backdrop).icon("render_scene").doc_only() +CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", crate::checked!("render.stage.backdrop", staging::backdrop)).icon("render_scene").doc_only() + .contract(&staging::BACKDROP_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: typed raytrace setup, set?: setup patch, kind: floor_wall or cyclorama, reflectance_linear?: [0.18,0.18,0.18], expected_revision: reviewed revision, replace_stage?:false. Fits a finite floor/wall or a 24-strip polygonal cyclorama behind the visible subject using the saved camera azimuth; world +Z up and a minimum one-mm stage envelope. Preserves subject geometry, lighting, output, pose and engineering materials; one undo and rechecked product separation. Not an infinite/analytically smooth/terrain background."), -CommandSpec::new("render.stage.clear", "Remove Render Stage", staging::clear).icon("render_scene").doc_only() +CommandSpec::new("render.stage.clear", "Remove Render Stage", crate::checked!("render.stage.clear", staging::clear)).icon("render_scene").doc_only() + .contract(&staging::CLEAR_CONTRACT) + .output(crate::schema::output_schema_for::) .params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."), CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance") .params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."), diff --git a/crates/engine/src/cmd/render/staging.rs b/crates/engine/src/cmd/render/staging.rs index 586434e23..4130f3576 100644 --- a/crates/engine/src/cmd/render/staging.rs +++ b/crates/engine/src/cmd/render/staging.rs @@ -1,7 +1,8 @@ //! Explicit saved render-only ground. Does not add engineering bodies or material cards. +use crate::schema::TypedContract; +use crate::schema::render_stage::{BackdropKind, BackdropParams, ClearParams, GroundParams, StageSaved}; use crate::{Result, Session, params::bad}; -use serde::Deserialize; -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_doc::render_settings::{RenderJob, RenderSetup}; use solidcraft_render::{ ProductScene, @@ -9,49 +10,41 @@ use solidcraft_render::{ stage::{Stage, StagePanel}, }; use std::sync::Arc; -fn patch() -> Value { - json!({}) -} -fn margin() -> f64 { - 0.25 -} -fn gap() -> f64 { - 0.1 -} -fn reflectance() -> [f64; 3] { - [0.18; 3] -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Ground { - name: String, - #[serde(default = "patch")] - set: Value, - #[serde(default = "margin")] - margin_fraction: f64, - #[serde(default = "gap")] - gap_mm: f64, - #[serde(default = "reflectance")] - reflectance_linear: [f64; 3], - #[serde(default)] - replace_stage: bool, -} + +pub(super) const GROUND_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const BACKDROP_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const CLEAR_CONTRACT: TypedContract = TypedContract::new(); + pub(super) fn apply(scene: &mut ProductScene, setup: &RenderSetup, command: &str) -> Result<()> { setup.stage.append_to(scene, &CancelToken::default()).map_err(|e| bad(command, e.to_string())) } -fn save(s: &mut Session, name: String, setup: RenderSetup, command: &str) -> Result { +fn save(s: &mut Session, name: String, setup: RenderSetup, command: &str) -> Result { let mut settings = (*s.doc.render).clone(); settings.setups.insert(name.clone(), setup.clone()); settings.validate().map_err(|e| bad(command, e.to_string()))?; + let setup = serde_json::to_value(&setup).map_err(|e| bad(command, e.to_string()))?; if settings != *s.doc.render { s.doc_mut().render = Arc::new(settings); } - Ok(json!({"name":name,"setup":setup,"engineering_geometry_unchanged":true,"stage_only":true, - "clearance":"conservative product AABB separation; not a B-rep collision proof"})) + Ok(StageSaved { + name, + setup, + engineering_geometry_unchanged: true, + stage_only: true, + clearance: "conservative product AABB separation; not a B-rep collision proof".into(), + geometry_kind: None, + light_transport: None, + camera_preserved: None, + limitations: None, + param_warnings: Vec::new(), + }) +} +fn reply(command: &str, saved: StageSaved) -> Result { + serde_json::to_value(saved).map_err(|e| bad(command, e.to_string())) } pub(super) fn ground(s: &mut Session, params: &Value) -> Result { let command = "render.stage.ground"; - let input: Ground = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: GroundParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if !input.margin_fraction.is_finite() || !(0.0..=10.0).contains(&input.margin_fraction) || !input.gap_mm.is_finite() @@ -88,48 +81,22 @@ pub(super) fn ground(s: &mut Session, params: &Value) -> Result { }]) .map_err(|e| bad(command, e.to_string()))?; apply(&mut scene, &setup, command)?; - save(s, input.name, setup, command) -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Clear { - name: String, - #[serde(default = "patch")] - set: Value, + reply(command, save(s, input.name, setup, command)?) } pub(super) fn clear(s: &mut Session, params: &Value) -> Result { let command = "render.stage.clear"; - let input: Clear = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: ClearParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; setup.stage = Stage::default(); - save(s, input.name, setup, command) + reply(command, save(s, input.name, setup, command)?) } -#[derive(Clone, Copy, Debug, Deserialize)] -#[serde(rename_all = "snake_case")] -enum BackdropKind { - FloorWall, - Cyclorama, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct BackdropInput { - name: String, - #[serde(default = "patch")] - set: Value, - kind: BackdropKind, - #[serde(default = "reflectance")] - reflectance_linear: [f64; 3], - #[serde(default)] - replace_stage: bool, - expected_revision: u64, -} /// Original world-space stage derived from captured subject bounds and the chosen /// camera azimuth. Twenty-four explicit planar strips approximate the round cove; /// it is not an analytic smooth surface, terrain or engineering model operation. pub(super) fn backdrop(s: &mut Session, params: &Value) -> Result { let command = "render.stage.backdrop"; - let input: BackdropInput = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: BackdropParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.expected_revision != s.revision { return Err(bad(command, "the design changed; review the stage again")); } @@ -204,17 +171,20 @@ pub(super) fn backdrop(s: &mut Session, params: &Value) -> Result { setup.stage = Stage::new(panels).map_err(|e| bad(command, e.to_string()))?; apply(&mut scene, &setup, command)?; let mut result = save(s, input.name, setup, command)?; - result["geometry_kind"] = json!(match input.kind { - BackdropKind::FloorWall => "finite_floor_and_wall", - BackdropKind::Cyclorama => "24_segment_polygonal_cyclorama", - }); - result["light_transport"] = - json!("nonemissive world-space stage; receives native lighting and casts reflections/shadows supported by the selected executor"); - result["camera_preserved"] = json!(true); - result["limitations"] = json!([ - "Finite background, not an infinite floor or a terrain mesh.", - "Cyclorama is an explicit 24-strip polygonal approximation, not a smooth CAD face.", - "No change to HDR, light energy, subject optics, pose or engineering properties." + result.geometry_kind = Some( + match input.kind { + BackdropKind::FloorWall => "finite_floor_and_wall", + BackdropKind::Cyclorama => "24_segment_polygonal_cyclorama", + } + .into(), + ); + result.light_transport = + Some("nonemissive world-space stage; receives native lighting and casts reflections/shadows supported by the selected executor".into()); + result.camera_preserved = Some(true); + result.limitations = Some(vec![ + "Finite background, not an infinite floor or a terrain mesh.".into(), + "Cyclorama is an explicit 24-strip polygonal approximation, not a smooth CAD face.".into(), + "No change to HDR, light energy, subject optics, pose or engineering properties.".into(), ]); - Ok(result) + reply(command, result) } diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index a065bd650..79dd9a7ea 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -76,6 +76,7 @@ pub mod panels; pub mod print_face; pub mod render; pub mod render_lights; +pub mod render_stage; pub mod render_ui; pub mod section; pub mod sheet; diff --git a/crates/engine/src/schema/render_stage.rs b/crates/engine/src/schema/render_stage.rs new file mode 100644 index 000000000..269382028 --- /dev/null +++ b/crates/engine/src/schema/render_stage.rs @@ -0,0 +1,145 @@ +//! Contracts and result type for the render stage commands in `cmd/render/staging.rs` (#11455). +//! A stage is a set of render-only panels saved with a render setup. The handlers read these +//! same parameter types, so each contract is exactly what its handler takes; like the handlers, +//! a contract refuses unknown keys. + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +fn patch() -> Value { + serde_json::json!({}) +} + +fn set_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "object", "maxProperties": 13, "default": {}}) +} + +fn margin() -> f64 { + 0.25 +} + +fn gap() -> f64 { + 0.1 +} + +fn reflectance() -> [f64; 3] { + [0.18; 3] +} + +/// Fit one ground panel under the visible product, a little below its lowest point, and save +/// it with a render setup in one undo step. The setup must render with the CPU raytracer or the +/// GPU path tracer. The product's clearance from the panel is checked again on every render. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GroundParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup before the ground is fitted, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, + /// How far the ground reaches past the product on each side, as a share of the product's + /// largest size: 0 to 10. Default: 0.25. + #[serde(default = "margin")] + #[schemars(range(min = 0.0, max = 10.0))] + pub margin_fraction: f64, + /// The gap between the product's lowest point and the ground (mm): 0.0001 to 1000. + /// Default: 0.1. + #[serde(default = "gap")] + #[schemars(range(min = 0.0001, max = 1000.0))] + pub gap_mm: f64, + /// How much light the ground reflects, as linear red, green and blue: each 0 to 1. + /// Default: 0.18 each. + #[serde(default = "reflectance")] + pub reflectance_linear: [f64; 3], + /// Replace a stage the setup already has. Without it, such a setup is refused. + #[serde(default)] + pub replace_stage: bool, +} + +/// Fit a floor and a wall, or a curved cyclorama of 24 flat strips, behind the visible product, +/// facing the setup's camera, and save it with the render setup in one undo step. The setup +/// must render with the CPU raytracer or the GPU path tracer. World +Z is up. This is a finite +/// background, not an infinite floor or a smooth CAD face. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct BackdropParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup before the backdrop is fitted, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, + pub kind: BackdropKind, + /// How much light the panels reflect, as linear red, green and blue: each 0 to 1. + /// Default: 0.18 each. + #[serde(default = "reflectance")] + pub reflectance_linear: [f64; 3], + /// Replace a stage the setup already has. Without it, such a setup is refused. + #[serde(default)] + pub replace_stage: bool, + /// The design's revision when the caller last read it, as `document.inspect` gives it. If + /// the design changed since, the call is refused: read it again and retry. + pub expected_revision: u64, +} + +/// The backdrop's shape. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BackdropKind { + /// A floor and a flat wall. + FloorWall, + /// A floor that curves up into the wall, in 24 flat strips. + Cyclorama, +} + +/// Remove the stage from a render setup in one undo step. The design's geometry and the +/// setup's lighting stay as they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ClearParams { + /// The render setup, saved or new. + pub name: String, + /// Changes to the setup made with the removal, as `render.settings.set` takes them: + /// an object of at most 13 setup fields. Default: none. + #[serde(default = "patch")] + #[schemars(schema_with = "set_schema")] + pub set: Value, +} + +/// What `render.stage.ground`, `render.stage.backdrop` and `render.stage.clear` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StageSaved { + /// The render setup. + pub name: String, + /// The setup as saved, as the render settings commands give it. + pub setup: Value, + /// Always true: the design's bodies don't change. + pub engineering_geometry_unchanged: bool, + /// Always true: the panels exist only in renders. + pub stage_only: bool, + /// How the product's clearance from the panels is checked. + pub clearance: String, + /// A backdrop's shape: `finite_floor_and_wall` or `24_segment_polygonal_cyclorama`. + #[serde(skip_serializing_if = "Option::is_none")] + pub geometry_kind: Option, + /// A backdrop's part in the lighting. + #[serde(skip_serializing_if = "Option::is_none")] + pub light_transport: Option, + /// A backdrop: always true, the setup's camera stays as it is. + #[serde(skip_serializing_if = "Option::is_none")] + pub camera_preserved: Option, + /// A backdrop's limits, in sentences. + #[serde(skip_serializing_if = "Option::is_none")] + pub limitations: Option>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "render_stage_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/render_stage_tests.rs b/crates/engine/src/schema/render_stage_tests.rs new file mode 100644 index 000000000..db14853e6 --- /dev/null +++ b/crates/engine/src/schema/render_stage_tests.rs @@ -0,0 +1,99 @@ +use serde_json::{Value, json}; + +use super::{BackdropParams, ClearParams, GroundParams, StageSaved}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A design with a box and a saved render setup, `Shot`, that renders with the GPU path tracer, +/// at the parameter-check level `level`. +fn with_a_shot(level: ParamCheck) -> Session { + let mut s = Session { param_check: level, ..Session::default() }; + for (id, p) in [ + ("solid.box", json!({"length": 20, "width": 15, "height": 10, "body_name": "Subject"})), + ("render.settings.set", json!({"name": "Shot", "set": {"width": 96, "height": 64, "job": {"method": "gpu_path", "options": {}}}})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + } + s +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["gap_mm", "margin_fraction", "name", "reflectance_linear", "replace_stage", "set"]); + assert_keys(input_schema_for::(), &["expected_revision", "kind", "name", "reflectance_linear", "replace_stage", "set"]); + assert_keys(input_schema_for::(), &["name", "set"]); +} + +/// The handlers refuse these calls after reading them; strict refuses them with their message. +/// They need a design with a body and a saved setup, and the design's revision, so the shared +/// helper, which has a sketch only, doesn't fit. +#[test] +fn strict_keeps_todays_errors() { + let cases: [(&str, fn(u64) -> Value); 12] = [ + ("render.stage.ground", |_| json!({"name": "Shot", "margin_fraction": 11})), + ("render.stage.ground", |_| json!({"name": "Shot", "gap_mm": 0})), + ("render.stage.ground", |_| json!({"name": "Shot", "reflectance_linear": [2, 0, 0]})), + ("render.stage.ground", |_| json!({"name": "Raster"})), + ("render.stage.ground", |_| json!({"name": " Shot"})), + ("render.stage.ground", |_| json!({"name": "Shot", "set": {"width": 0}})), + ("render.stage.backdrop", |_| json!({"name": "Shot", "kind": "cyclorama", "expected_revision": 999_999})), + ("render.stage.backdrop", |r| json!({"name": "Raster", "kind": "floor_wall", "expected_revision": r})), + ("render.stage.backdrop", |r| json!({"name": "Shot", "kind": "floor_wall", "reflectance_linear": [0, -1, 0], "expected_revision": r})), + ("render.stage.clear", |_| json!({"name": ""})), + ("render.stage.clear", |_| json!({"name": "Shot", "set": {"width": 0}})), + ("render.stage.clear", |_| json!({"name": "Shot", "set": 5})), + ]; + for (id, p) in cases { + let error = |level: ParamCheck| { + let mut s = with_a_shot(level); + let p = p(s.revision); + s.execute(id, &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{id} {} should fail today", p(0)); + assert_eq!(error(ParamCheck::Strict), off, "{id} {}", p(0)); + } + // A stage already there needs `replace_stage`, for a ground and a backdrop alike. + for level in [ParamCheck::Off, ParamCheck::Strict] { + let mut s = with_a_shot(level); + s.execute("render.stage.ground", &json!({"name": "Shot"})).unwrap_or_else(|e| panic!("{e}")); + let ground = s.execute("render.stage.ground", &json!({"name": "Shot"})).err().map(|e| e.to_string()); + let p = json!({"name": "Shot", "kind": "floor_wall", "expected_revision": s.revision}); + let backdrop = s.execute("render.stage.backdrop", &p).err().map(|e| e.to_string()); + for error in [ground, backdrop] { + assert!(error.as_deref().is_some_and(|e| e.contains("replace_stage: true")), "{level:?}: {error:?}"); + } + } +} + +/// #11455: a ground, both backdrops and a clear reply as the output schema says, in Warn +/// without warnings; only a backdrop carries its shape and limits. Like the handlers, warn and +/// strict refuse a misspelt key. +#[test] +fn stage_commands_reply_with_their_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = with_a_shot(ParamCheck::Warn); + let run = |s: &mut Session, id: &str, p: Value| { + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + r + }; + let p = json!({"name": "Shot", "set": {}, "margin_fraction": 0.5, "gap_mm": 1, "reflectance_linear": [0.2, 0.2, 0.2], "replace_stage": false}); + let r = run(&mut s, "render.stage.ground", p); + assert!(r["setup"].is_object() && r.get("geometry_kind").is_none(), "{r}"); + for kind in ["floor_wall", "cyclorama"] { + let revision = s.revision; + let p = json!({"name": "Shot", "kind": kind, "replace_stage": true, "expected_revision": revision}); + let r = run(&mut s, "render.stage.backdrop", p); + assert!(r["geometry_kind"].is_string() && r["limitations"].is_array(), "{r}"); + } + run(&mut s, "render.stage.clear", json!({"name": "Shot", "set": {}})); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = with_a_shot(level); + let error = s.execute("render.stage.clear", &json!({"nme": "Shot"})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("nme"), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 46f048b6e..5f1bf092b 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -181,9 +181,6 @@ render.settings.set render.shot.duplicate render.shot.remove render.shot.rename -render.stage.backdrop -render.stage.clear -render.stage.ground render.start render.status select.clear