Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: the render binding commands for library surfaces and optics describe their exact parameters and reply (#11741) (#11742)

austin62jakec66752e8d31c
diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs
index a58b722d40..2d42e74620 100644
--- a/crates/engine/src/cmd/render.rs
+++ b/crates/engine/src/cmd/render.rs
@@ -89,9 +89,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&crate::schema::TypedContract::<crate::schema::render::CoatUnbindParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render::CoatUnbindResult>)
.params("name; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that stable coat assignment in one undo, without device or file access."),
- CommandSpec::new("render.optics.bind","Save Optical Binding",optical_bindings::bind).icon("appearance")
+ CommandSpec::new("render.optics.bind","Save Optical Binding",crate::checked!("render.optics.bind", optical_bindings::bind)).icon("appearance")
+ .contract(&optical_bindings::BIND_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsBindingSaved>)
.params("name: CPU or GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy}}; replace?:false. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. CPU consumes at most eight certified optical targets. Without options.path, sheets and axis-aligned boxes retain the existing transport. Explicit progressive options.path enables exact closed-mesh certification, bounded nested convex-parent media, Beer/Snell/Fresnel and thin transmitted shadows; touching or unproven boundaries and closed transmitted-shadow connections refuse explicitly. Existing subsurface parameters may be consumed on certified closed Path media with denoising explicitly off; scalar free-flight/HG walks and separate Beer absorption are supported without refracting-boundary next-event approximation. A zero scattering rate preserves transport. GPU nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."),
- CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only()
+ CommandSpec::new("render.optics.unbind","Remove Optical Binding",crate::checked!("render.optics.unbind", optical_bindings::unbind)).icon("appearance").doc_only()
+ .contract(&optical_bindings::UNBIND_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsUnbound>)
.params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."),
CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only()
.params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."),
@@ -143,9 +147,13 @@ CommandSpec::new("render.stage.clear", "Remove Render Stage", crate::checked!("r
.contract(&staging::CLEAR_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_stage::StageSaved>)
.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")
+CommandSpec::new("render.library.surface.bind", "Save Surface Binding", crate::checked!("render.library.surface.bind", surface_bindings::bind)).icon("appearance")
+ .contract(&surface_bindings::BIND_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::render_bindings::SurfaceBindingSaved>)
.params("name: CPU or 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."),
-CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only()
+CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", crate::checked!("render.library.surface.unbind", surface_bindings::unbind)).icon("appearance").doc_only()
+ .contract(&surface_bindings::UNBIND_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::render_bindings::SurfaceBindingSaved>)
.params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."),
CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only()
.params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
diff --git a/crates/engine/src/cmd/render/optical_bindings.rs b/crates/engine/src/cmd/render/optical_bindings.rs
index 7353f36600..56b63390f1 100644
--- a/crates/engine/src/cmd/render/optical_bindings.rs
+++ b/crates/engine/src/cmd/render/optical_bindings.rs
@@ -1,12 +1,12 @@
//! Stable, render-only optical assignments. Raw request overrides remain a
//! separate mode; saved optics cannot silently disappear into another target.
+use crate::schema::TypedContract;
+use crate::schema::render_bindings::{OpticsBindParams, OpticsBindingSaved, OpticsUnbindParams, OpticsUnbound};
use crate::{Result, Session, params::bad};
-use serde::Deserialize;
use serde_json::{Value, json};
use solidcraft_doc::{
render_optics::{OpticalBindings, OpticalMaterial, SavedOptics},
render_settings::RenderJob,
- render_surface::RenderBodyTarget,
};
use solidcraft_render::ProductScene;
use std::{collections::BTreeMap, sync::Arc};
@@ -62,25 +62,12 @@ pub(super) fn resolve_cpu_path(
})
}
-fn empty() -> Value {
- json!({})
-}
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct Bind {
- name: String,
- #[serde(default = "empty")]
- set: Value,
- body_index: usize,
- body_name: String,
- optics: OpticalMaterial,
- expected_revision: u64,
- #[serde(default)]
- replace: bool,
-}
+pub(super) const BIND_CONTRACT: TypedContract<OpticsBindParams> = TypedContract::new();
+pub(super) const UNBIND_CONTRACT: TypedContract<OpticsUnbindParams> = TypedContract::new();
+
pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.optics.bind";
- let input: Bind = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
+ let input: OpticsBindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
input.optics.validate().map_err(|e| bad(command, e.to_string()))?;
if input.expected_revision != s.revision {
return Err(bad(command, "optical binding review is stale"));
@@ -119,23 +106,23 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
let mut settings = (*s.doc.render).clone();
settings.setups.insert(input.name.clone(), setup.clone());
settings.validate().map_err(|e| bad(command, e.to_string()))?;
+ // Serialized before the document changes, so a setup that can't be written leaves it as it was.
+ 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":input.name,"setup":setup,"geometry_and_engineering_unchanged":true,"certification":"closed topology and nested containment are checked by the selected image producer before transport"}),
- )
-}
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct Unbind {
- name: String,
- target: RenderBodyTarget,
- expected_revision: u64,
+ let reply = OpticsBindingSaved {
+ name: input.name,
+ setup,
+ geometry_and_engineering_unchanged: true,
+ certification: "closed topology and nested containment are checked by the selected image producer before transport".into(),
+ param_warnings: Vec::new(),
+ };
+ serde_json::to_value(reply).map_err(|e| bad(command, e.to_string()))
}
pub(super) fn unbind(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.optics.unbind";
- let input: Unbind = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
+ let input: OpticsUnbindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
input.target.validate().map_err(|e| bad(command, e.to_string()))?;
if input.expected_revision != s.revision {
return Err(bad(command, "optical removal review is stale"));
@@ -147,7 +134,8 @@ pub(super) fn unbind(s: &mut Session, params: &Value) -> Result<Value> {
if settings != *s.doc.render {
s.doc_mut().render = Arc::new(settings);
}
- Ok(json!({"name":input.name,"removed":removed}))
+ let reply = OpticsUnbound { name: input.name, removed, param_warnings: Vec::new() };
+ serde_json::to_value(reply).map_err(|e| bad(command, e.to_string()))
}
#[cfg(test)]
diff --git a/crates/engine/src/cmd/render/surface_bindings.rs b/crates/engine/src/cmd/render/surface_bindings.rs
index 7a6a3cec43..11403b5a93 100644
--- a/crates/engine/src/cmd/render/surface_bindings.rs
+++ b/crates/engine/src/cmd/render/surface_bindings.rs
@@ -1,7 +1,8 @@
//! Resolve portable surface intent into the existing captured GPU texture contract.
//! Definition/feature/occurrence identities are checked on every Check and Start.
+use crate::schema::TypedContract;
+use crate::schema::render_bindings::{SurfaceBindParams, SurfaceBindingSaved, SurfaceUnbindParams};
use crate::{Result, Session, params::bad};
-use serde::Deserialize;
use serde_json::{Value, json};
use solidcore_record::Vec3;
use solidcraft_doc::{
@@ -132,32 +133,32 @@ pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &SurfaceBindi
}
Ok(result)
}
-fn empty() -> Value {
- json!({})
-}
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct Bind {
- name: String,
- surface: Value,
- #[serde(default = "empty")]
- set: Value,
- #[serde(default)]
- replace: bool,
-}
+pub(super) const BIND_CONTRACT: TypedContract<SurfaceBindParams> = TypedContract::new();
+pub(super) const UNBIND_CONTRACT: TypedContract<SurfaceUnbindParams> = TypedContract::new();
+
+/// Save `setup` under `name` in one undo step (none when nothing changed) and reply with it.
fn publish(s: &mut Session, name: String, setup: RenderSetup, command: &str) -> Result<Value> {
let mut settings = (*s.doc.render).clone();
settings.setups.insert(name.clone(), setup.clone());
settings.validate().map_err(|e| bad(command, e.to_string()))?;
+ // Serialized before the document changes, so a setup that can't be written leaves it as it was.
+ 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,"mapping_space":"definition_local_mm","geometry_and_physical_materials_unchanged":true}))
+ let reply = SurfaceBindingSaved {
+ name,
+ setup,
+ mapping_space: "definition_local_mm".into(),
+ geometry_and_physical_materials_unchanged: true,
+ param_warnings: Vec::new(),
+ };
+ serde_json::to_value(reply).map_err(|e| bad(command, e.to_string()))
}
pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
super::library::require_bundled("render.library.surface.bind")?;
let command = "render.library.surface.bind";
- let input: Bind = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
+ let input: SurfaceBindParams = 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)?;
if s.doc.render.setups.get(&input.name).is_some_and(|old| old.surfaces != setup.surfaces) {
return Err(bad(command, "setup patch cannot erase or replace saved surface bindings; use explicit bind/unbind commands"));
@@ -200,17 +201,9 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
super::textures::validate_targets(&scene, &resolved, command)?;
publish(s, input.name, setup, command)
}
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct Unbind {
- name: String,
- target: RenderBodyTarget,
- #[serde(default = "empty")]
- set: Value,
-}
pub(super) fn unbind(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.library.surface.unbind";
- let input: Unbind = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
+ let input: SurfaceUnbindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
input.target.validate().map_err(|e| bad(command, e.to_string()))?;
let mut setup = super::patched_settings(s, &input.name, &input.set, command)?;
setup.surfaces.remove(&input.target);
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 609ffcfe8f..f6b59100af 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -83,6 +83,7 @@ pub mod parts;
pub mod plastic;
pub mod print_face;
pub mod render;
+pub mod render_bindings;
pub mod render_hdr;
pub mod render_library;
pub mod render_lights;
diff --git a/crates/engine/src/schema/render_bindings.rs b/crates/engine/src/schema/render_bindings.rs
new file mode 100644
index 0000000000..e3cce6ca2e
--- /dev/null
+++ b/crates/engine/src/schema/render_bindings.rs
@@ -0,0 +1,248 @@
+//! Contracts and result types for the render binding commands (#11741): a body of a render setup
+//! bound to a library surface's maps (`cmd/render/surface_bindings.rs`) or to optical numbers
+//! (`cmd/render/optical_bindings.rs`). The handlers read these same parameter types, so each
+//! contract is exactly what its handler takes; like the handlers, a contract refuses unknown
+//! keys.
+//!
+//! Three parameters keep their own readers, and their schemas here are written by hand:
+//! - `target` and `optics` are the doc crate's `RenderBodyTarget` and `OpticalMaterial`, which
+//! don't derive `JsonSchema` (the doc crate doesn't depend on schemars).
+//! - `surface` is passed on whole to `render.library.surface.prepare`, which checks it.
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use solidcraft_doc::render_optics::OpticalMaterial;
+use solidcraft_doc::render_surface::RenderBodyTarget;
+
+/// `set`'s default: no change to the setup.
+fn no_change() -> Value {
+ serde_json::json!({})
+}
+
+/// `set`: changes to the setup, as `render.settings.set` takes them. `patched_settings` in
+/// `cmd/render.rs` refuses anything but an object of at most 13 fields, with its own message.
+/// The fields of a render setup, as `render.settings.get` gives them. A `set` patch may give up
+/// to 13 of them; `patched_settings` reads the patched setup as a `RenderSetup`, which refuses any
+/// other key.
+const SETUP_FIELDS: &[&str] = &[
+ "backend",
+ "mode",
+ "camera",
+ "width",
+ "height",
+ "format",
+ "exposure_ev",
+ "environment_rotation",
+ "environment_intensity",
+ "background",
+ "job",
+ "surfaces",
+ "optics",
+ "stage",
+];
+
+/// Each setup field, without its own schema: `patched_settings` checks the values.
+fn setup_properties() -> serde_json::Map<String, Value> {
+ SETUP_FIELDS.iter().map(|field| (field.to_string(), Value::Object(serde_json::Map::new()))).collect()
+}
+
+fn set_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Changes to the setup made with the binding, as `render.settings.set` takes them: at most 13 of the setup's fields. Default: none.",
+ "type": "object",
+ "properties": setup_properties(),
+ "additionalProperties": false,
+ "maxProperties": 13,
+ "default": {}
+ })
+}
+
+/// A body of the design, by the identity a render setup keeps for it: its definition, the
+/// feature that made it, and the component occurrence it's in. The ids survive a rebuild, so a
+/// binding follows the body, and never another body that took its place in the list.
+fn target_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A body, by the identity a render setup keeps for it, as the setup's `surfaces` or `optics` list gives it. A component and its occurrence path are both 0 and empty for a body outside components.",
+ "type": "object",
+ "properties": {
+ "definition": {"description": "The design or component definition that holds the body: 1 to 1024 bytes, without control characters.", "type": "string"},
+ "feature": {"description": "The id of the feature that made the body: 1 or more.", "type": "integer", "minimum": 1},
+ "component": {"description": "The id of the component the body is in, or 0 outside components.", "type": "integer", "minimum": 0},
+ "occurrence_path": {"description": "The occurrence ids from the top of the design down to the body's occurrence, each 1 or more and none twice; empty outside components.", "type": "array", "items": {"type": "integer", "minimum": 1}}
+ },
+ "required": ["definition", "feature", "component", "occurrence_path"],
+ "additionalProperties": false
+ })
+}
+
+/// Optical numbers for a body, as `solidcraft_doc::render_optics::OpticalMaterial` reads them.
+/// Every field has a default, so `{}` is clear glass with a refractive index of 1.5.
+fn optics_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The body's optical numbers, for the CPU or GPU renderer. Each field has a default: `{}` is clear glass with a refractive index of 1.5. These are render-only numbers, not an engineering material.",
+ "type": "object",
+ "properties": {
+ "ior": {"description": "Refractive index. Default: 1.5.", "type": "number"},
+ "absorption_per_mm": {"description": "How much light the inside absorbs per mm, as linear red, green and blue: each 0 or more. Default: none.", "type": "array", "items": {"type": "number", "minimum": 0}, "minItems": 3, "maxItems": 3},
+ "boundary": {"description": "How the body's surface bounds the medium: `thin_sheet` (a sheet of `thickness_mm`), `closed_box` or `closed_mesh` (the thickness comes from the geometry). Default: closed_mesh.", "type": "string", "enum": ["thin_sheet", "closed_box", "closed_mesh"]},
+ "thickness_mm": {"description": "A thin sheet's thickness (mm); 0 for a closed boundary. Default: 0.", "type": "number", "minimum": 0},
+ "shadow_transmission": {"description": "Let light through for shadows too. Default: false.", "type": "boolean"},
+ "subsurface": {
+ "description": "Light scattering inside the body, as in wax or skin; `null` for none. Default: none.",
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "scattering_per_mm": {"description": "How often light scatters per mm: 0 to 100.", "type": "number", "minimum": 0, "maximum": 100},
+ "anisotropy": {"description": "Which way it scatters: -0.95 (back) to 0.95 (forward). Default: 0, every way alike.", "type": "number", "minimum": -0.95, "maximum": 0.95}
+ },
+ "required": ["scattering_per_mm"],
+ "additionalProperties": false
+ },
+ {"type": "null"}
+ ]
+ }
+ },
+ "additionalProperties": false
+ })
+}
+
+/// `surface`: a library surface placed on a body, exactly as `render.library.surface.prepare`
+/// takes it. That command isn't converted yet, so its keys are described here.
+fn surface_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The library surface and where it goes on the body, as `render.library.surface.prepare` takes it.",
+ "type": "object",
+ "properties": {
+ "id": {"description": "The surface: `SURF-` and its number, as `render.library.list` gives it.", "type": "string"},
+ "body_index": {"description": "The body's place in the render scene, from 0, as `render.library.targets` gives it.", "type": "integer", "minimum": 0},
+ "body_name": {"description": "The body's name at that place, as `render.library.targets` gives it; a body that moved in the list is refused.", "type": "string"},
+ "origin": {"description": "Where the maps start, in mm, as [x, y, z]. Default: the centre of the body's bounding box.", "type": ["array", "null"], "items": {"type": "number"}, "minItems": 3, "maxItems": 3},
+ "plane": {"description": "The plane the maps lie in: `xy`, `yz` or `zx`. Default: xy.", "type": "string", "enum": ["xy", "yz", "zx"]},
+ "scale": {"description": "How much larger than authored the maps repeat: 0.001 to 1000. Default: 1.", "type": "number", "minimum": 0.001, "maximum": 1000}
+ },
+ "required": ["id", "body_index", "body_name"],
+ "additionalProperties": false
+ })
+}
+
+/// Bind a body of a render setup to a library surface's authored maps, for the CPU or GPU renderer,
+/// in one undo step. The binding keeps the maps' exact source hashes and the body's identity,
+/// mapped in the body's own millimetres, so it follows the body when it moves. Needs a build with
+/// the bundled render library and a CPU or GPU setup.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct SurfaceBindParams {
+ /// The render setup, saved or new.
+ pub name: String,
+ #[schemars(schema_with = "surface_schema")]
+ pub surface: Value,
+ #[serde(default = "no_change")]
+ #[schemars(schema_with = "set_schema")]
+ pub set: Value,
+ /// Replace a binding the body already has. Without it, such a body is refused.
+ #[serde(default)]
+ pub replace: bool,
+}
+
+/// Remove one body's surface binding from a render setup, in one undo step. The design's
+/// geometry, and any render device, aren't needed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct SurfaceUnbindParams {
+ /// The render setup.
+ pub name: String,
+ #[schemars(schema_with = "target_schema")]
+ pub target: RenderBodyTarget,
+ #[serde(default = "no_change")]
+ #[schemars(schema_with = "set_schema")]
+ pub set: Value,
+}
+
+/// Bind a body of a render setup to optical numbers (glass, tinted media, subsurface
+/// scattering), for the CPU or GPU renderer, in one undo step. The design's geometry and engineering
+/// materials don't change. The setup may render on the CPU or GPU.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct OpticsBindParams {
+ /// The render setup, saved or new.
+ pub name: String,
+ #[serde(default = "no_change")]
+ #[schemars(schema_with = "set_schema")]
+ pub set: Value,
+ /// The body's place in the render scene, from 0, as `render.library.targets` gives it.
+ pub body_index: usize,
+ /// The body's name at that place; a body that moved in the list is refused.
+ pub body_name: String,
+ #[schemars(schema_with = "optics_schema")]
+ pub optics: OpticalMaterial,
+ /// 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,
+ /// Replace optics the body already has. Without it, such a body is refused.
+ #[serde(default)]
+ pub replace: bool,
+}
+
+/// Remove one body's optical binding from a saved render setup, in one undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct OpticsUnbindParams {
+ /// The saved render setup.
+ pub name: String,
+ #[schemars(schema_with = "target_schema")]
+ pub target: RenderBodyTarget,
+ /// 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,
+}
+
+/// What `render.library.surface.bind` and `render.library.surface.unbind` return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SurfaceBindingSaved {
+ /// The render setup.
+ pub name: String,
+ /// The setup as saved, as the render settings commands give it.
+ pub setup: Value,
+ /// Always `definition_local_mm`: the maps are placed in the body's own millimetres.
+ pub mapping_space: String,
+ /// Always true: the design's geometry and physical materials don't change.
+ pub geometry_and_physical_materials_unchanged: bool,
+ /// 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<String>,
+}
+
+/// What `render.optics.bind` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OpticsBindingSaved {
+ /// 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 geometry and engineering data don't change.
+ pub geometry_and_engineering_unchanged: bool,
+ /// What the image producer checks before it draws the body: closed topology and nested
+ /// containment.
+ pub certification: String,
+ /// 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<String>,
+}
+
+/// What `render.optics.unbind` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OpticsUnbound {
+ /// The render setup.
+ pub name: String,
+ /// Whether the body had optics to remove; `false` leaves the setup as it was.
+ pub removed: bool,
+ /// 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<String>,
+}
+
+#[cfg(test)]
+#[path = "render_bindings_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/render_bindings_tests.rs b/crates/engine/src/schema/render_bindings_tests.rs
new file mode 100644
index 0000000000..59075ad803
--- /dev/null
+++ b/crates/engine/src/schema/render_bindings_tests.rs
@@ -0,0 +1,168 @@
+use serde_json::{Value, json};
+
+use super::{OpticsBindParams, OpticsBindingSaved, OpticsUnbindParams, OpticsUnbound, SurfaceBindParams, SurfaceBindingSaved, SurfaceUnbindParams};
+use crate::Session;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+/// A design with one box, `Lens`, and a saved render setup, `Studio`, that renders with the GPU
+/// path tracer, at the parameter-check level `level`.
+fn with_a_studio(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ for (id, p) in [
+ ("solid.box", json!({"length": 10, "width": 10, "height": 4, "body_name": "Lens"})),
+ ("render.settings.set", json!({"name": "Studio", "set": {"job": {"method": "gpu_path"}}})),
+ ] {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ }
+ s
+}
+
+/// `render.optics.bind`'s call for the box, at the design's revision `revision`.
+fn optics_on_the_lens(revision: u64) -> Value {
+ json!({"name": "Studio", "body_index": 0, "body_name": "Lens", "expected_revision": revision,
+ "optics": {"ior": 1.45, "subsurface": {"scattering_per_mm": 0.4, "anisotropy": 0.2}}})
+}
+
+/// The identity `Studio` keeps for the box once its optics are bound, as the unbind commands take it.
+fn lens_target(s: &Session) -> Value {
+ let target = s.doc.render.setups.get("Studio").and_then(|setup| setup.optics.iter().next()).map(|b| b.target.clone());
+ serde_json::to_value(target.unwrap_or_else(|| panic!("no optics bound"))).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<SurfaceBindParams>(), &["name", "replace", "set", "surface"]);
+ assert_keys(input_schema_for::<SurfaceUnbindParams>(), &["name", "set", "target"]);
+ assert_keys(input_schema_for::<OpticsBindParams>(), &["body_index", "body_name", "expected_revision", "name", "optics", "replace", "set"]);
+ assert_keys(input_schema_for::<OpticsUnbindParams>(), &["expected_revision", "name", "target"]);
+}
+
+/// The handlers refuse these calls after reading them; strict refuses them with their message.
+/// They need a body, 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 stranger = json!({"definition": "", "feature": 1, "component": 0, "occurrence_path": []});
+ let cases: Vec<(&str, Box<dyn Fn(u64) -> Value>)> = vec![
+ (
+ "render.optics.bind",
+ Box::new(|_| json!({"name": "Studio", "body_index": 0, "body_name": "Lens", "expected_revision": 999_999, "optics": {}})),
+ ),
+ (
+ "render.optics.bind",
+ Box::new(|r| json!({"name": "Studio", "body_index": 0, "body_name": "Lens", "expected_revision": r, "optics": {"ior": 0.5}})),
+ ),
+ (
+ "render.optics.bind",
+ Box::new(|r| json!({"name": "Studio", "body_index": 0, "body_name": "Lens", "expected_revision": r, "optics": {"thickness_mm": 1}})),
+ ),
+ ("render.optics.bind", Box::new(|r| json!({"name": "Studio", "body_index": 3, "body_name": "Lens", "expected_revision": r, "optics": {}}))),
+ ("render.optics.bind", Box::new(|r| json!({"name": "Studio", "body_index": 0, "body_name": "Nope", "expected_revision": r, "optics": {}}))),
+ ("render.optics.bind", Box::new(|r| json!({"name": "Raster", "body_index": 0, "body_name": "Lens", "expected_revision": r, "optics": {}}))),
+ (
+ "render.optics.bind",
+ Box::new(|r| json!({"name": "Studio", "set": 5, "body_index": 0, "body_name": "Lens", "expected_revision": r, "optics": {}})),
+ ),
+ (
+ "render.optics.unbind",
+ Box::new(
+ |r| json!({"name": "Nope", "target": {"definition": "d", "feature": 1, "component": 0, "occurrence_path": []}, "expected_revision": r}),
+ ),
+ ),
+ (
+ "render.optics.unbind",
+ Box::new(
+ |_| json!({"name": "Studio", "target": {"definition": "d", "feature": 1, "component": 0, "occurrence_path": []}, "expected_revision": 999_999}),
+ ),
+ ),
+ ("render.optics.unbind", Box::new(move |r| json!({"name": "Studio", "target": stranger, "expected_revision": r}))),
+ (
+ "render.library.surface.unbind",
+ Box::new(|_| json!({"name": "Studio", "target": {"definition": "d", "feature": 0, "component": 0, "occurrence_path": []}})),
+ ),
+ (
+ "render.library.surface.unbind",
+ Box::new(|_| json!({"name": " Studio", "target": {"definition": "d", "feature": 1, "component": 0, "occurrence_path": []}})),
+ ),
+ (
+ "render.library.surface.unbind",
+ Box::new(|_| json!({"name": "Studio", "set": 5, "target": {"definition": "d", "feature": 1, "component": 0, "occurrence_path": []}})),
+ ),
+ // Without the bundled render library, both refuse before reading anything else.
+ ("render.library.surface.bind", Box::new(|_| json!({"name": "Studio", "surface": {"id": "MAT-001", "body_index": 0, "body_name": "Lens"}}))),
+ ("render.library.surface.bind", Box::new(|_| json!({"name": "Raster", "surface": {"id": "SURF-001", "body_index": 0, "body_name": "Lens"}}))),
+ ];
+ for (id, p) in &cases {
+ let error = |level: ParamCheck| {
+ let mut s = with_a_studio(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));
+ }
+}
+
+/// #11741: binding and unbinding reply as their output schemas say, in Warn without warnings.
+/// With the bundled render library, a surface binding is saved and removed as well. Like the
+/// handlers, warn and strict refuse a misspelt key.
+#[test]
+fn binding_commands_reply_with_their_schemas() {
+ let (optics_saved, unbound, surface_saved) =
+ (output_schema_for::<OpticsBindingSaved>(), output_schema_for::<OpticsUnbound>(), output_schema_for::<SurfaceBindingSaved>());
+ let mut s = with_a_studio(ParamCheck::Warn);
+ let run = |s: &mut Session, schema: &schemars::Schema, id: &str, p: Value| {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ r
+ };
+ let revision = s.revision;
+ let r = run(&mut s, &optics_saved, "render.optics.bind", optics_on_the_lens(revision));
+ assert!(r["setup"]["optics"].is_array(), "{r}");
+ let target = lens_target(&s);
+ let p = json!({"name": "Studio", "target": target, "expected_revision": s.revision});
+ assert_eq!(run(&mut s, &unbound, "render.optics.unbind", p)["removed"], true);
+ let p = json!({"name": "Studio", "target": target, "expected_revision": s.revision});
+ assert_eq!(run(&mut s, &unbound, "render.optics.unbind", p)["removed"], false, "nothing left to remove");
+ // Removing a surface binding the body doesn't have saves the setup as it is.
+ run(&mut s, &surface_saved, "render.library.surface.unbind", json!({"name": "Studio", "target": target, "set": {}}));
+ if cfg!(feature = "bundled-render-library") {
+ let surface = json!({"id": "SURF-001", "body_index": 0, "body_name": "Lens", "plane": "xy", "scale": 2, "origin": [0, 0, 0]});
+ let r = run(&mut s, &surface_saved, "render.library.surface.bind", json!({"name": "Studio", "surface": surface, "replace": false}));
+ assert_eq!(r["mapping_space"], "definition_local_mm", "{r}");
+ run(&mut s, &surface_saved, "render.library.surface.unbind", json!({"name": "Studio", "target": target}));
+ }
+ for level in [ParamCheck::Warn, ParamCheck::Strict] {
+ let mut s = with_a_studio(level);
+ let mut p = optics_on_the_lens(s.revision);
+ // Rename the key, so the call has a misspelt `optic` and no `optics` at all.
+ if let Some(keys) = p.as_object_mut()
+ && let Some(optics) = keys.remove("optics")
+ {
+ keys.insert("optic".into(), optics);
+ }
+ let error = s.execute("render.optics.bind", &p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("`optic`"), "{level:?}: {error}");
+ }
+}
+
+/// `set` names the render setup's fields: `patched_settings` reads the patched setup as a
+/// `RenderSetup`, which refuses any other key, so the schema refuses a misspelt one too (and
+/// more than 13 at once).
+#[test]
+fn the_set_schema_names_the_setup_fields() {
+ let root = input_schema_for::<SurfaceBindParams>();
+ let root = root.as_value();
+ let set = &root["properties"]["set"];
+ for (patch, takes) in
+ [(json!({}), true), (json!({"width": 640, "height": 480, "job": {"method": "gpu_path"}}), true), (json!({"widht": 640}), false)]
+ {
+ assert_eq!(conforms(root, set, &patch), takes, "{patch}");
+ }
+ // `conforms` doesn't read `maxProperties`, so the limit is pinned here.
+ assert_eq!((set["maxProperties"].as_u64(), set["properties"].as_object().map(|p| p.len())), (Some(13), Some(super::SETUP_FIELDS.len())), "{set}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 4f68cd0b70..80861315b7 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -102,11 +102,7 @@ render.library.environment.apply
render.library.physical.prepare
render.library.studio.apply
render.library.studio.prepare
-render.library.surface.bind
render.library.surface.prepare
-render.library.surface.unbind
-render.optics.bind
-render.optics.unbind
render.preflight
render.result.pin
render.result.regrade