diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 647146702..f0b0d4e02 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -140,7 +140,9 @@ CommandSpec::new("render.library.preview", "Inspect Original Surface Map", crate .contract(&library::PREVIEW_CONTRACT) .output(crate::schema::output_schema_for::) .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() +CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", crate::checked!("render.library.physical.prepare", physical_library::prepare)).icon("inspect").noundo().doc_only() + .contract(&physical_library::PREPARE_CONTRACT) + .output(crate::schema::output_schema_for::) .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", crate::checked!("render.stage.ground", staging::ground)).icon("render_scene") .contract(&staging::GROUND_CONTRACT) @@ -176,15 +178,25 @@ CommandSpec::new("render.library.describe", "Inspect Render Library Resource", c .contract(&library::DESCRIBE_CONTRACT) .output(crate::schema::output_schema_for::) .params("kind, id: exact authored resource. Returns original specification, runtime projection variants and explicit omissions. A concept is not an executable preset."), -CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appearance", library::apply_appearance).icon("appearance") +CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appearance", crate::checked!("render.library.appearance.apply", library::apply_appearance)).icon("appearance") + .contract(&library::APPEARANCE_APPLY_CONTRACT) + .output(crate::schema::output_schema_for::) .params("id: SURF-* or SELENE-AP-*; variant: uniform_opaque (required); bodies: 1..256 exact body names. Applies the original scalar baseline through ordinary appearance assignment in one undo, preserving physical properties. Spatial maps and advanced target effects are explicitly excluded."), -CommandSpec::new("render.library.environment.apply", "Apply Built-in HDR Environment", library::apply_environment).icon("settings").doc_only() +CommandSpec::new("render.library.environment.apply", "Apply Built-in HDR Environment", crate::checked!("render.library.environment.apply", library::apply_environment)).icon("settings").doc_only() + .contract(&library::ENVIRONMENT_APPLY_CONTRACT) + .output(crate::schema::output_schema_for::) .params("id: HDR-*; name: saved setup; set?: typed CPU/GPU setup patch; rotation_rad?: authored rotation (native origin offset is explicit in the reply); intensity?:1; samples?:16 for CPU; replace_environment?:false. Hash-verifies and embeds original bytes, saves one atomic undo without external files or a render device. An HDR-owned sun cannot duplicate an analytic sun."), -CommandSpec::new("render.library.surface.prepare", "Prepare Authored Surface Maps", library::prepare_surface).icon("appearance").noundo() +CommandSpec::new("render.library.surface.prepare", "Prepare Authored Surface Maps", crate::checked!("render.library.surface.prepare", library::prepare_surface)).icon("appearance").noundo() + .contract(&library::SURFACE_PREPARE_CONTRACT) + .output(crate::schema::output_schema_for::) .params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1; rotation_rad?:0 (positive around the plane normal). Returns an explicit GPU temporary planar binding and a source usable by saved CPU/GPU surface.bind, with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."), -CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", library::prepare_studio).icon("inspect").noundo().doc_only() +CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", crate::checked!("render.library.studio.prepare", library::prepare_studio)).icon("inspect").noundo().doc_only() + .contract(&library::STUDIO_PREPARE_CONTRACT) + .output(crate::schema::output_schema_for::) .params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius. Optional name and typed CPU set return the complete CPU projection and explicit indirect-lighting adoption plan; authored radiance beyond CPU intensity64 refuses without scaling. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."), -CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", library::apply_studio).icon("settings") +CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", crate::checked!("render.library.studio.apply", library::apply_studio)).icon("settings") + .contract(&library::STUDIO_APPLY_CONTRACT) + .output(crate::schema::output_schema_for::) .params("rig: id, variant, center_mm and subject_extent_mm; name; set?: typed CPU/GPU setup patch; expected_revision?:u64; enable_indirect?:false (explicit CPU Sun adoption after review); replace_lighting_and_environment:true required. Saves the explicit rig projection in one undo, removing prior lighting/environment only with that confirmation. Subject clearance still needs review; passive cards are never silently omitted."), CommandSpec::new("render.hdr.inspect", "Inspect HDR Source", crate::checked!("render.hdr.inspect", resources::inspect)).icon("inspect").noundo().doc_only() .contract(&resources::INSPECT_CONTRACT) diff --git a/crates/engine/src/cmd/render/library.rs b/crates/engine/src/cmd/render/library.rs index 032d44b64..30cd1bdbe 100644 --- a/crates/engine/src/cmd/render/library.rs +++ b/crates/engine/src/cmd/render/library.rs @@ -18,8 +18,10 @@ use solidcraft_render::{ use crate::schema::TypedContract; use crate::schema::render_library::{ - LibraryDescribeParams, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryResource, LibraryTargets, - LibraryTargetsParams, Pbr, RenderTarget, ResourceSummary, SceneBounds, StableRenderTarget, + AppearanceApplied, AppearanceApplyParams, CpuProjection, EnvironmentApplied, EnvironmentApplyParams, IndirectAdoption, LibraryDescribeParams, + LibraryListParams, LibraryLook, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryResource, LibraryTargets, LibraryTargetsParams, Pbr, + PreparedTexture, ProgressiveDefaults, RenderTarget, ResourceSummary, RigProjection, SceneBounds, StableRenderTarget, StudioApplied, + StudioApplyParams, StudioPrepareParams, StudioPrepared, SurfacePrepareParams, SurfacePrepared, }; use crate::{Result, Session, params::bad}; @@ -27,6 +29,11 @@ pub(super) const LIST_CONTRACT: TypedContract = TypedContract pub(super) const DESCRIBE_CONTRACT: TypedContract = TypedContract::new(); pub(super) const TARGETS_CONTRACT: TypedContract = TypedContract::new(); pub(super) const PREVIEW_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const APPEARANCE_APPLY_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const ENVIRONMENT_APPLY_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const SURFACE_PREPARE_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const STUDIO_PREPARE_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const STUDIO_APPLY_CONTRACT: TypedContract = TypedContract::new(); fn reply(command: &str, reply: impl serde::Serialize) -> Result { serde_json::to_value(reply).map_err(|e| bad(command, e.to_string())) @@ -397,20 +404,39 @@ pub(super) fn apply_appearance(s: &mut Session, params: &Value) -> Result let color = std::array::from_fn::<_, 3, _>(|i| crate::geom::srgb::encode8((lo[i] + hi[i]) * 0.5)); ( value, - json!({"color":color,"opacity":1.0,"pbr":{"metallic":value["metallic"],"roughness":value["roughness"],"dielectric_ior":1.5}}), + LibraryLook { + name: String::new(), + color: json!(color), + opacity: json!(1.0), + pbr: json!({"metallic":value["metallic"],"roughness":value["roughness"],"dielectric_ior":1.5}), + bodies: Vec::new(), + }, json!(["spatial_maps", "height_displacement", "true_anisotropic_brdf"]), ) } else { let value = item("selene_appearances", &input.id, command)?; let p = &value["baseline_projection"]["runtime_parameters"]; - (value, json!({"color":p["color"],"opacity":p["opacity"],"pbr":p["pbr"]}), value["baseline_projection"]["omitted_target_features"].clone()) + ( + value, + LibraryLook { name: String::new(), color: p["color"].clone(), opacity: p["opacity"].clone(), pbr: p["pbr"].clone(), bodies: Vec::new() }, + value["baseline_projection"]["omitted_target_features"].clone(), + ) }; let name = value["name"].as_str().ok_or_else(|| bad(command, "authored appearance has no name"))?; - look["name"] = json!(format!("{} {}", input.id, name).chars().take(128).collect::()); - look["bodies"] = json!(input.bodies); - let assigned = crate::cmd::inspect::appearance(s, &look)?; - Ok( - json!({"id":input.id,"variant":input.variant,"omitted":omitted,"appearance":look,"assignment":assigned,"engineering_properties_unchanged":true}), + look.name = format!("{} {}", input.id, name).chars().take(128).collect::(); + look.bodies = input.bodies; + let assigned = crate::cmd::inspect::appearance(s, &reply(command, &look)?)?; + reply( + command, + AppearanceApplied { + id: input.id, + variant: input.variant, + omitted, + appearance: look, + assignment: assigned, + engineering_properties_unchanged: true, + param_warnings: Vec::new(), + }, ) } @@ -500,8 +526,21 @@ pub(super) fn apply_environment(s: &mut Session, params: &Value) -> Result Result let frame = solidcraft_render::job::textures::PlanarFrame { origin, u, v }; frame.validate().map_err(|e| bad(command, e.to_string()))?; let manifest = item("surface_manifest", &input.id, command)?; - Ok(json!({"id":input.id,"revision":s.revision,"executor":"gpu-path","variant":"gpu_planar_maps", - "texture":{"body_index":input.body_index,"body_name":input.body_name,"frame":frame,"normal_strength":1.0,"flip_v":true,"base_color_mode":"replace", - "base_color_srgb":format!("builtin://{}/base_color",input.id),"normal_opengl":format!("builtin://{}/normal_open_gl",input.id), - "roughness_linear":format!("builtin://{}/roughness",input.id),"metallic_linear":format!("builtin://{}/metallic",input.id)}, - "source_maps":manifest["maps"],"omitted":["height_displacement","true_anisotropic_brdf","manufacturing_geometry"], - "dielectric_ior":"captured_body_value","persistence":"transient_request_binding; authored source bytes are built in", - "compatible_saved_methods":if cfg!(feature="bundled-render-library") {vec!["cpu_raytrace","gpu_path"]} else {Vec::<&str>::new()}, - "cpu_maps":"saved_builtin_opaque_only; direct_or_indirect_lighting; level_zero_bilinear; incompatible_optics_refuse"})) + let map = |role: &str| format!("builtin://{}/{role}", input.id); + reply( + command, + SurfacePrepared { + revision: s.revision, + executor: "gpu-path".into(), + variant: "gpu_planar_maps".into(), + texture: PreparedTexture { + body_index: input.body_index, + body_name: input.body_name, + frame, + normal_strength: 1.0, + flip_v: true, + base_color_mode: "replace".into(), + base_color_srgb: map("base_color"), + normal_opengl: map("normal_open_gl"), + roughness_linear: map("roughness"), + metallic_linear: map("metallic"), + }, + source_maps: manifest["maps"].clone(), + omitted: ["height_displacement", "true_anisotropic_brdf", "manufacturing_geometry"].map(String::from).into(), + dielectric_ior: "captured_body_value".into(), + persistence: "transient_request_binding; authored source bytes are built in".into(), + compatible_saved_methods: if cfg!(feature = "bundled-render-library") { + vec!["cpu_raytrace".into(), "gpu_path".into()] + } else { + Vec::new() + }, + cpu_maps: "saved_builtin_opaque_only; direct_or_indirect_lighting; level_zero_bilinear; incompatible_optics_refuse".into(), + id: input.id.clone(), + param_warnings: Vec::new(), + }, + ) } #[derive(Deserialize)] @@ -581,7 +645,9 @@ pub(super) struct RigInput { pub(super) subject_extent_mm: f64, } -pub(super) fn rig_lighting(input: &RigInput, command: &str) -> Result<(StudioLighting, Value)> { +/// The rig's lights and what it was scaled to, as `render.library.studio.prepare` and `.apply` +/// report them; `rig_lighting` gives the same projection as JSON. +fn rig_projection(input: &RigInput, command: &str) -> Result<(StudioLighting, RigProjection)> { let value = item("rigs", &input.id, command)?; if value["state"] != "authored_numeric_unbound" { return Err(bad(command, "rig requires unresolved calibration or an existing external sun")); @@ -643,11 +709,23 @@ pub(super) fn rig_lighting(input: &RigInput, command: &str) -> Result<(StudioLig lighting.validate().map_err(|e| bad(command, e.to_string()))?; Ok(( lighting, - json!({"id":input.id,"variant":input.variant,"passive_cards_omitted":if input.variant=="emitters_only" {cards}else{0},"passive_cards_included":if input.variant=="complete" {cards}else{0},"scale":scale, - "physical_units":"world millimetres; authored relative linear-sRGB radiance","reference_calibration_not_remeasured":true}), + RigProjection { + id: input.id.clone(), + variant: input.variant.clone(), + passive_cards_omitted: if input.variant == "emitters_only" { cards } else { 0 }, + passive_cards_included: if input.variant == "complete" { cards } else { 0 }, + scale, + physical_units: "world millimetres; authored relative linear-sRGB radiance".into(), + reference_calibration_not_remeasured: true, + }, )) } +pub(super) fn rig_lighting(input: &RigInput, command: &str) -> Result<(StudioLighting, Value)> { + let (lighting, projection) = rig_projection(input, command)?; + Ok((lighting, reply(command, projection)?)) +} + pub(super) fn rig_stage(input: &RigInput, command: &str) -> Result { use solidcraft_render::stage::{Stage, StagePanel}; if input.variant != "complete" { @@ -774,10 +852,17 @@ pub(super) fn prepare_studio(s: &mut Session, params: &Value) -> Result { let command = "render.library.studio.prepare"; let input: StudioPrepare = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; let rig = RigInput { id: input.id, variant: input.variant, center_mm: input.center_mm, subject_extent_mm: input.subject_extent_mm }; - let (lighting, projection) = rig_lighting(&rig, command)?; + let (lighting, projection) = rig_projection(&rig, command)?; let stage = rig_stage(&rig, command)?; - let mut report = - json!({"lighting":lighting,"stage":stage,"projection":projection,"requires_geometry_clearance_review":true,"document_changed":false}); + let mut report = StudioPrepared { + lighting, + stage: stage.clone(), + projection, + requires_geometry_clearance_review: true, + document_changed: false, + cpu: None, + param_warnings: Vec::new(), + }; if let Some(name) = input.name { let mut setup = super::patched_settings(s, &name, &input.set, command)?; let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { @@ -791,18 +876,22 @@ pub(super) fn prepare_studio(s: &mut Session, params: &Value) -> Result { } setup.stage = stage; setup.validate().map_err(|e| bad(command, e.to_string()))?; - report["setup"] = json!(setup); - report["executor"] = json!("cpu-raytrace"); - report["revision"] = json!(s.revision); - report["requires_indirect"] = json!(needs_indirect); - report["indirect_adoption"] = json!( - needs_indirect - .then_some(json!({"path_depth":8,"progressive_if_absent":{"samples_per_pixel":16,"seed":0},"primary_samples":1,"shadows":true})) - ); + report.cpu = Some(CpuProjection { + setup, + executor: "cpu-raytrace".into(), + revision: s.revision, + requires_indirect: needs_indirect, + indirect_adoption: needs_indirect.then_some(IndirectAdoption { + path_depth: 8, + progressive_if_absent: ProgressiveDefaults { samples_per_pixel: 16, seed: 0 }, + primary_samples: 1, + shadows: true, + }), + }); } else if input.enable_indirect || input.set != json!({}) { return Err(bad(command, "CPU rig context needs name and typed set")); } - Ok(report) + reply(command, report) } #[derive(Deserialize)] @@ -832,7 +921,7 @@ pub(super) fn apply_studio(s: &mut Session, params: &Value) -> Result { if !input.replace_stage && s.doc.render.setups.get(&input.name).is_some_and(|setup| !setup.stage.is_empty()) { return Err(bad(command, "existing stage requires replace_stage: true")); } - let (lighting, projection) = rig_lighting(&input.rig, command)?; + let (lighting, projection) = rig_projection(&input.rig, command)?; let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; let stage = rig_stage(&input.rig, command)?; if !setup.stage.is_empty() && !input.replace_stage { @@ -865,8 +954,15 @@ pub(super) fn apply_studio(s: &mut Session, params: &Value) -> Result { if settings != *s.doc.render { s.doc_mut().render = Arc::new(settings); } - Ok( - json!({"name":input.name,"setup":setup,"projection":projection,"clearance":"conservative product/stage AABB separation passed; not exact B-rep collision"}), + reply( + command, + StudioApplied { + name: input.name, + setup, + projection, + clearance: "conservative product/stage AABB separation passed; not exact B-rep collision".into(), + param_warnings: Vec::new(), + }, ) } diff --git a/crates/engine/src/cmd/render/physical_library.rs b/crates/engine/src/cmd/render/physical_library.rs index 8f54720e0..a6bbee120 100644 --- a/crates/engine/src/cmd/render/physical_library.rs +++ b/crates/engine/src/cmd/render/physical_library.rs @@ -1,5 +1,7 @@ //! Read-only bridge between optical concepts and sourced physical references. //! No appearance identifies a grade, assigns density, or supplies missing constants. +use crate::schema::TypedContract; +use crate::schema::render_library::{PhysicalPlan, PhysicalPrepareParams, PlannedCommand, PlannedMaterial}; use crate::{Result, Session, params::bad}; use serde::Deserialize; use serde_json::{Value, json}; @@ -161,6 +163,7 @@ pub(super) fn associations(id: &str) -> Result { ids.into_iter().map(|id| Ok(summary(by(profiles, "id", id, command)?, by(cards, "profile_id", id, command)?))).collect::>>()?; Ok(json!({"specifications":selected,"candidate_profiles":references,"auto_assign":false,"unknown_is_zero":false})) } +pub(super) const PREPARE_CONTRACT: TypedContract = TypedContract::new(); #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Prepare { @@ -191,11 +194,30 @@ pub(super) fn prepare(_s: &mut Session, params: &Value) -> Result { } let density = density.ok_or_else(|| bad(command, "profile lacks one supported point density; ranges and unknowns cannot be replaced by a midpoint"))?; - Ok(json!({"status":"plan_only_not_executed","profile_id":input.id,"receipts":description["receipts"], - "native_validation":description["native_validation"],"not_projected":description["native_projection"]["not_projected"], - "extended_profile":description["resource"],"document_changed":false,"assigned_bodies":[], - "command":{"command":"material.create","params":{"name":input.name,"density_g_cm3":density/1000.0,"physical_card":card}}, - "requirements":["Review grade, formulation, source and conditions before execution.","This partial card is not a complete constitutive model or a certification.","Create does not assign a body; never use a constituent as an effective laminate, foam or populated assembly.","Retain this profile and omission receipt; the native card cannot encode all extended properties."]})) + let plan = PhysicalPlan { + status: "plan_only_not_executed".into(), + profile_id: input.id, + receipts: description["receipts"].clone(), + native_validation: description["native_validation"].clone(), + not_projected: description["native_projection"]["not_projected"].clone(), + extended_profile: description["resource"].clone(), + document_changed: false, + assigned_bodies: Vec::new(), + command: PlannedCommand { + command: "material.create".into(), + params: PlannedMaterial { name: input.name, density_g_cm3: density / 1000.0, physical_card: card }, + }, + requirements: [ + "Review grade, formulation, source and conditions before execution.", + "This partial card is not a complete constitutive model or a certification.", + "Create does not assign a body; never use a constituent as an effective laminate, foam or populated assembly.", + "Retain this profile and omission receipt; the native card cannot encode all extended properties.", + ] + .map(String::from) + .into(), + param_warnings: Vec::new(), + }; + serde_json::to_value(plan).map_err(|e| bad(command, e.to_string())) } #[cfg(test)] mod tests { diff --git a/crates/engine/src/schema/render_library.rs b/crates/engine/src/schema/render_library.rs index 681cb7e7f..f8b431e25 100644 --- a/crates/engine/src/schema/render_library.rs +++ b/crates/engine/src/schema/render_library.rs @@ -4,10 +4,29 @@ //! keeps the two readers it has: the physical profiles' takes `availability: null`, the other //! catalogs' doesn't. Its type takes what either takes, and its schema says which `kind` takes //! which (`availability_by_kind`). Like the handlers, a contract refuses unknown keys. +//! +//! The apply and prepare commands (`render.library.appearance.apply`, `.environment.apply`, +//! `.physical.prepare`, `.studio.apply`, `.studio.prepare` and `.surface.prepare`, #12552) keep +//! the readers they have in `cmd/render/library.rs` and `cmd/render/physical_library.rs`: each +//! reads the raw parameters into a private struct. Their parameters types here read each key +//! as that struct does and fail with its message, whole (see `reads!`), so strict refuses a +//! call exactly as the handler does. A key the handler refuses when it is left out is optional +//! in the type and required in the schema, so the handler keeps its message. The handlers read +//! every key in every call, whatever the other keys are, so the types do too. use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; -use serde::{Deserialize, Serialize}; +use serde::de::{DeserializeOwned, Error as _}; +use serde::{Deserialize, Deserializer, Serialize}; use serde_json::{Map, Value}; +use solidcraft_doc::physical_material::ValidatedCard; +use solidcraft_doc::render_resources::HdrId; +use solidcraft_doc::render_settings::RenderSetup; +use solidcraft_render::job::StudioLighting; +use solidcraft_render::job::textures::PlanarFrame; +use solidcraft_render::stage::Stage; + +use super::appearance::AppearanceAssignResult; +use super::check::whole; /// Every catalog `render.library.list` and `render.library.describe` read. const KINDS: &[&str] = &[ @@ -391,6 +410,874 @@ pub struct LibraryPreview { pub param_warnings: Vec, } +/// A key's value as its handler's struct reads it: `T` is the type that struct gives the key, and +/// anything it refuses gets serde's own message, whole (no key put in front), as the handler +/// words it. +fn read_value<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result { + serde_json::from_value(Value::deserialize(d)?).map_err(|e| D::Error::custom(whole(e))) +} + +/// A deserializer for a key the handler reads as a `$ty`: a value `null` or of another type is +/// refused with the handler's message. +macro_rules! reads { + ($name:ident -> $ty:ty) => { + fn $name<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + read_value::(d).map(Some) + } + }; +} + +/// A deserializer for a key the handler reads as an `Option<$ty>`, which takes `null`. +macro_rules! reads_option { + ($name:ident -> $ty:ty) => { + fn $name<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + read_value::>(d) + } + }; +} + +reads!(read_string -> String); +reads!(read_bool -> bool); +reads!(read_f64 -> f64); +reads!(read_u32 -> u32); +reads!(read_usize -> usize); +reads!(read_strings -> Vec); +reads!(read_point -> [f64; 3]); +reads!(read_plane -> Plane); +reads!(read_rig -> RigInput); +reads_option!(read_origin -> [f64; 3]); +reads_option!(read_name -> String); +reads_option!(read_revision -> u64); + +/// The ids the handlers look up: 1 to 128 ASCII letters, digits, hyphens or underscores. +const ID_PATTERN: &str = "^[A-Za-z0-9_-]{1,128}$"; + +/// The fields of a render setup a `set` patch may name, as `render.settings.get` gives 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", + "coats", + "stage", +]; + +/// `set`: changes to the setup, which `patched_settings` in `cmd/render.rs` refuses unless it is +/// an object of at most 15 fields, with its own message. The type takes any value, so the +/// handler keeps that message; the schema says what it takes. +fn set_schema(_: &mut SchemaGenerator) -> Schema { + let properties: Map = SETUP_FIELDS.iter().map(|field| (field.to_string(), Value::Object(Map::new()))).collect(); + json_schema!({ + "description": "Changes to the render setup before the command works on it, as `render.settings.set` takes them: an object of at most 15 of the setup's fields. Default: none.", + "type": "object", + "properties": properties, + "additionalProperties": false, + "maxProperties": 15, + "default": {} + }) +} + +fn id_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "pattern": ID_PATTERN}) +} + +fn finite_vector_schema(maximum: f64) -> Value { + serde_json::json!({ + "type": "array", + "items": {"type": "number", "minimum": -maximum, "maximum": maximum}, + "minItems": 3, + "maxItems": 3 + }) +} + +fn require_all(schema: &mut Schema, keys: &[&str]) { + for key in keys { + super::motion::require(schema, key); + } +} + +/// Apply a library surface's or a Selene appearance's original scalar look (colour, opacity and +/// PBR response) to bodies, through the ordinary appearance assignment, in one undo step. The +/// physical properties of the bodies are kept. Spatial maps and advanced target effects are +/// left out. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = appearance_required)] +pub struct AppearanceApplyParams { + // `id`, `variant` and `bodies` are optional in the type and required in the schema + // (`appearance_required`): left out, the handler refuses them with its own message. + /// The appearance: a surface (`SURF-…`) or a Selene appearance (`SELENE-AP-…`), as + /// `render.library.list` gives its id. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "id_schema")] + pub id: Option, + /// Always `uniform_opaque`: the original scalar look as one opaque colour. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "uniform_opaque_schema")] + pub variant: Option, + /// The bodies to give the look, by exact name: 1 to 256, each 1 to 1024 bytes without + /// control characters. + #[serde(default, deserialize_with = "read_strings", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "target_bodies_schema")] + pub bodies: Option>, +} + +fn appearance_required(schema: &mut Schema) { + require_all(schema, &["id", "variant", "bodies"]); +} + +fn uniform_opaque_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "enum": ["uniform_opaque"]}) +} + +fn target_bodies_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 1024}, "minItems": 1, "maxItems": 256}) +} + +/// What `render.library.appearance.apply` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AppearanceApplied { + /// The appearance's id. + pub id: String, + /// Always `uniform_opaque`. + pub variant: String, + /// What the library's description of the appearance leaves out of this look. + #[schemars(schema_with = "omitted_schema")] + pub omitted: Value, + /// The look as it was assigned. + pub appearance: LibraryLook, + /// What `appearance.assign` reports for the bodies. + #[schemars(with = "AppearanceAssignResult")] + pub assignment: Value, + /// Always true: the bodies' materials and physical properties are as they were. + pub engineering_properties_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, +} + +/// A library appearance's look, as `render.library.appearance.apply` hands it to +/// `appearance.assign`. The library gives the values, so they are kept as it gives them. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryLook { + /// The appearance's id and name, at most 128 characters. + pub name: String, + /// A surface's colour is `[r, g, b]` (0 to 255), a Selene appearance's `"#rrggbb"`. + #[schemars(schema_with = "look_color_schema")] + pub color: Value, + /// Always 1: the look is opaque. + #[schemars(schema_with = "look_number_schema")] + pub opacity: Value, + /// The PBR response. + #[schemars(schema_with = "look_pbr_schema")] + pub pbr: Value, + /// The bodies it was given to. + pub bodies: Vec, +} + +fn omitted_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "What the library's description of the appearance leaves out of this look.", "type": "array", "items": {"type": "string"}}) +} + +fn look_number_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "number"}) +} + +fn look_color_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "anyOf": [ + {"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3}, + {"type": "string"} + ] + }) +} + +fn look_pbr_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "type": "object", + "properties": { + "metallic": {"description": "0 (a dielectric) to 1 (a metal).", "type": "number"}, + "roughness": {"description": "0 (smooth) to 1 (rough).", "type": "number"}, + "dielectric_ior": {"description": "The refractive index of its dielectric part.", "type": "number"} + }, + "required": ["metallic", "roughness", "dielectric_ior"] + }) +} + +/// Save a built-in HDR environment (a library `HDR-…`) in a CPU raytrace or GPU path setup, in +/// one undo step. The image's original bytes are checked against their hash and kept in the +/// design, so it reopens without the library. The setup's existing environment is replaced only +/// with `replace_environment`. An HDR that carries the sun cannot be used beside an analytic sun. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = environment_required)] +pub struct EnvironmentApplyParams { + // `id` and `name` are optional in the type and required in the schema + // (`environment_required`), as above. + /// The HDR, as `render.library.list` gives its id (`HDR-…`). + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "id_schema")] + pub id: Option, + /// The render setup, saved or new: trimmed, 1 to 128 bytes, without control characters. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub name: Option, + /// Changes to the setup before the HDR is added, as `render.settings.set` takes them: an + /// object of at most 15 of the setup's fields. The setup must render with the CPU raytracer + /// or the GPU path tracer. Default: none. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "set_schema")] + pub set: Option, + /// The image's rotation as authored, in radians: finite, within ±1000000. The reply gives the + /// rotation the renderers use, which has the image's origin offset by π. Default: 0. + #[serde(default, deserialize_with = "read_f64", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64", range(min = -1_000_000.0, max = 1_000_000.0), default = "zero")] + pub rotation_rad: Option, + /// The environment's brightness, linear: 0 to 64 for a CPU setup, 0 to 100 for a GPU one. + /// Default: 1. + #[serde(default, deserialize_with = "read_f64", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64", range(min = 0.0, max = 100.0), default = "one")] + pub intensity: Option, + /// A CPU setup's samples per lighting estimate: 1, 4, 16 or 64. A GPU setup reads it and + /// ignores it. Default: 16. + #[serde(default, deserialize_with = "read_u32", skip_serializing_if = "Option::is_none")] + #[schemars(with = "u32", default = "sixteen")] + pub samples: Option, + /// Replace an environment the setup already has: an HDR, a sky or a constant one. Without + /// it, such a setup is refused. Default: false. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool", default = "no")] + pub replace_environment: Option, +} + +// The schemas' defaults, as the field types give them (the types are optional so that the +// handler, not the check, fills in a key left out). +fn zero() -> Option { + Some(0.0) +} + +fn one() -> Option { + Some(1.0) +} + +fn sixteen() -> Option { + Some(16) +} + +fn no() -> Option { + Some(false) +} + +fn xy() -> Option { + Some(Plane::Xy) +} + +fn environment_required(schema: &mut Schema) { + require_all(schema, &["id", "name"]); +} + +/// What `render.library.environment.apply` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct EnvironmentApplied { + /// The HDR's id. + pub id: String, + /// The render setup. + pub name: String, + /// The setup as saved, as the render settings commands give it. + #[schemars(schema_with = "setup_reply_schema")] + pub setup: RenderSetup, + /// The image's SHA-256 in hex, the id the design keeps its bytes under. + #[schemars(with = "String")] + pub resource: HdrId, + /// The rotation as given, in radians. + pub author_rotation_rad: f64, + /// The rotation the setup keeps: the authored one plus `orientation_offset_rad`, within 0 to + /// 2π. + pub native_rotation_rad: f64, + /// Always π: where the image's origin sits in the renderers. + pub orientation_offset_rad: f64, + /// Always true: the design keeps the image's bytes. + pub self_contained: bool, + /// The SHA-256 the library records for the image, in hex: the same as `resource`. + #[schemars(schema_with = "hash_schema")] + pub source_sha256: Value, + /// 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, +} + +fn hash_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string"}) +} + +/// A render setup as the render settings commands give it. +fn setup_reply_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A render setup, as the render settings commands give it.", + "type": "object", + "properties": { + "backend": {"type": "string"}, + "mode": {"type": "string"}, + "camera": {"type": "object"}, + "width": {"type": "integer", "minimum": 0}, + "height": {"type": "integer", "minimum": 0}, + "format": {"type": "string"}, + "exposure_ev": {"type": "number"}, + "environment_rotation": {"type": "number"}, + "environment_intensity": {"type": "number"}, + "background": {"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3}, + "job": {"type": "object"}, + "surfaces": {}, + "optics": {}, + "coats": {}, + "stage": {"type": "array"} + }, + "required": ["backend", "mode", "camera", "width", "height", "format", "exposure_ev", "environment_rotation", "environment_intensity", "background"] + }) +} + +/// Plan a material from a built-in physical reference profile, without making it: a +/// `material.create` call that carries the profile's density and its native card, the receipts +/// of the sources it came from, and what the card leaves out. Nothing is created or assigned. +/// A profile with no single supported density is refused: nothing is guessed. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = physical_required)] +pub struct PhysicalPrepareParams { + // All three are optional in the type and required in the schema (`physical_required`). + /// The physical profile, as `render.library.list` gives it with `kind` `physical_profiles`. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "id_schema")] + pub id: Option, + /// The name for the material: trimmed, 1 to 128 bytes, without control characters. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "material_name_schema")] + pub name: Option, + /// Must be true: the profile is a reference to review, not a grade to rely on. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "acknowledge_schema")] + pub acknowledge_reference: Option, +} + +fn physical_required(schema: &mut Schema) { + require_all(schema, &["id", "name", "acknowledge_reference"]); +} + +fn material_name_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "minLength": 1, "maxLength": 128}) +} + +fn acknowledge_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "boolean", "const": true}) +} + +/// What `render.library.physical.prepare` returns: a plan, not a change. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PhysicalPlan { + /// Always `plan_only_not_executed`. + pub status: String, + /// The profile's id. + pub profile_id: String, + /// The SHA-256 digests of the profiles and cards read. + #[schemars(with = "ProfileReceipts")] + pub receipts: Value, + /// The native card's check. + pub native_validation: Value, + /// The profile's properties the card leaves out, each with why. + pub not_projected: Value, + /// The profile as its catalog holds it, unchanged. + #[schemars(with = "Map")] + pub extended_profile: Value, + /// Always false. + pub document_changed: bool, + /// Always empty: no body is assigned. + pub assigned_bodies: Vec, + /// The `material.create` call that would make the material. + pub command: PlannedCommand, + /// What to do before running it. + pub requirements: Vec, + /// 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, +} + +/// A command to run, not run yet. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PlannedCommand { + /// Always `material.create`. + pub command: String, + pub params: PlannedMaterial, +} + +/// `material.create`'s parameters, as planned. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PlannedMaterial { + /// The name asked for. + pub name: String, + /// The profile's density, in g/cm³. + pub density_g_cm3: f64, + /// The profile's native physical material card. + #[schemars(schema_with = "physical_card_schema")] + pub physical_card: ValidatedCard, +} + +fn physical_card_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A physical material card: the designation, family, sourced properties and sources.", + "type": "object", + "properties": { + "schema_version": {"type": "integer"}, + "designation": {"type": "string"}, + "family": {"type": "string"}, + "properties": {"type": "array", "items": {"type": "object"}}, + "sources": {"type": "array", "items": {"type": "object"}} + }, + "required": ["schema_version", "designation", "family", "properties", "sources"] + }) +} + +/// Which plane a surface's maps lie in. +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Plane { + /// The XY plane, repeating along X and Y. + #[default] + Xy, + /// The YZ plane. + Yz, + /// The ZX plane. + Zx, +} + +/// Prepare a library surface's original maps as a temporary planar binding on a body, for the +/// GPU path tracer, and as the source `render.library.surface.bind` saves. Nothing in the design +/// changes. Height and displacement maps and true anisotropy are not included. The body must be +/// opaque. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = surface_required)] +pub struct SurfacePrepareParams { + // `id`, `body_index` and `body_name` are optional in the type and required in the schema + // (`surface_required`). + /// The surface, as `render.library.list` gives its id (`SURF-…`). + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "id_schema")] + pub id: Option, + /// The body's place in the render scene, as `render.library.targets` gives it, from 0. + #[serde(default, deserialize_with = "read_usize", skip_serializing_if = "Option::is_none")] + #[schemars(with = "usize")] + pub body_index: Option, + /// The body's exact name, which must be the one at `body_index`. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub body_name: Option, + /// The point the maps start from, in mm. Default: the centre of the body's bounds. + #[serde(default, deserialize_with = "read_origin", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "origin_schema")] + pub origin: Option<[f64; 3]>, + /// The repeat scale: 0.001 to 1000. Default: 1. + #[serde(default, deserialize_with = "read_f64", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64", range(min = 0.001, max = 1000.0), default = "one")] + pub scale: Option, + /// The plane the maps lie in. Default: xy. + #[serde(default, deserialize_with = "read_plane", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Plane", default = "xy")] + pub plane: Option, + /// The grain's rotation about the plane's normal, in radians, positive around the normal: + /// finite, within ±1000000. Default: 0. + #[serde(default, deserialize_with = "read_f64", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64", range(min = -1_000_000.0, max = 1_000_000.0), default = "zero")] + pub rotation_rad: Option, +} + +fn surface_required(schema: &mut Schema) { + require_all(schema, &["id", "body_index", "body_name"]); +} + +fn origin_schema(_: &mut SchemaGenerator) -> Schema { + let mut schema = json_schema!({"description": "A point [x, y, z], in mm."}); + schema.insert("anyOf".into(), serde_json::json!([finite_vector_schema(f64::MAX), {"type": "null"}])); + schema +} + +/// What `render.library.surface.prepare` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SurfacePrepared { + /// The surface's id. + pub id: String, + /// The design's revision the body was read at. + pub revision: u64, + /// Always `gpu-path`. + pub executor: String, + /// Always `gpu_planar_maps`. + pub variant: String, + /// The binding, as `render.library.surface.bind` and the GPU render take it. + pub texture: PreparedTexture, + /// The surface's source maps by role (`base_color`, `normal_open_gl`, `roughness`, + /// `metallic`, `height`): the file, size, encoding and hashes the library records. + #[schemars(schema_with = "source_maps_schema")] + pub source_maps: Value, + /// What the binding leaves out. + pub omitted: Vec, + /// Always `captured_body_value`: the body's own refractive index is used. + pub dielectric_ior: String, + /// Always says the binding is a request's, not saved. + pub persistence: String, + /// The setups the maps can be saved in: both in a build with the bundled render library, none + /// without. + pub compatible_saved_methods: Vec, + /// What a saved CPU setup does with the maps. + pub cpu_maps: 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, +} + +fn source_maps_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The surface's source maps by role, each with its file, size, encoding and hashes.", + "type": "object", + "additionalProperties": {"type": "object"} + }) +} + +/// A planar binding of a surface's maps to a body. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PreparedTexture { + /// The body's place in the render scene. + pub body_index: usize, + /// The body's name. + pub body_name: String, + /// The maps' origin and the two repeat vectors, in world mm. + #[schemars(schema_with = "frame_schema")] + pub frame: PlanarFrame, + /// Always 1. + pub normal_strength: f64, + /// Always true: image v increases downward. + pub flip_v: bool, + /// Always `replace`: the map is the base colour. + pub base_color_mode: String, + /// The base-colour map, by its built-in address. + pub base_color_srgb: String, + /// The normal map, OpenGL convention. + pub normal_opengl: String, + /// The roughness map, linear. + pub roughness_linear: String, + /// The metallic map, linear. + pub metallic_linear: String, +} + +fn frame_schema(_: &mut SchemaGenerator) -> Schema { + let vector = finite_vector_schema(f64::MAX); + json_schema!({ + "description": "The maps' origin and the repeat vectors u and v, in world mm.", + "type": "object", + "properties": {"origin": vector, "u": vector, "v": vector}, + "required": ["origin", "u", "v"], + "additionalProperties": false + }) +} + +/// A rig as the studio commands take it: which authored rig, how much of it, and where the +/// subject is. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RigInput { + /// The rig, as `render.library.list` gives its id with `kind` `rigs` (`RIG-…`). + #[schemars(schema_with = "id_schema")] + pub id: String, + /// `complete` for every rig, `emitters_only` for a rig with passive cards, which it leaves + /// out. + #[schemars(schema_with = "variant_schema")] + pub variant: String, + /// The subject's centre, in mm: each within ±1e12. + #[schemars(schema_with = "centre_schema")] + pub center_mm: [f64; 3], + /// The subject's largest size, in mm: 0.001 to 1000000. The rig scales to it. + #[schemars(range(min = 0.001, max = 1_000_000.0))] + pub subject_extent_mm: f64, +} + +fn variant_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "enum": ["complete", "emitters_only"]}) +} + +fn centre_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "type": "array", + "items": {"type": "number", "minimum": -1e12, "maximum": 1e12}, + "minItems": 3, + "maxItems": 3 + }) +} + +/// Convert an authored lighting rig to the numbers the renderers use, for a subject: its +/// rectangular lights, a sun, and its passive cards as a stage. With `name`, also the setup a +/// CPU raytrace would save, and what adopting a sun's indirect lighting needs. Nothing is +/// changed. Rigs whose calibration is unresolved or that use an external sun are refused, and a +/// light brighter than the CPU takes is refused, not scaled. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = studio_prepare_required)] +pub struct StudioPrepareParams { + // `id`, `variant`, `center_mm` and `subject_extent_mm` are optional in the type and required + // in the schema (`studio_prepare_required`). + /// The rig (`RIG-…`). + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "id_schema")] + pub id: Option, + /// `complete`, or `emitters_only` for a rig with passive cards, which it leaves out. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "variant_schema")] + pub variant: Option, + /// The subject's centre, in mm: each within ±1e12. + #[serde(default, deserialize_with = "read_point", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "centre_schema")] + pub center_mm: Option<[f64; 3]>, + /// The subject's largest size, in mm: 0.001 to 1000000. + #[serde(default, deserialize_with = "read_f64", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64", range(min = 0.001, max = 1_000_000.0))] + pub subject_extent_mm: Option, + /// The render setup to work out the CPU projection in, saved or new. Without it, only the + /// rig's numbers are returned, and `set` and `enable_indirect` are refused. Default: none. + #[serde(default, deserialize_with = "read_name", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "optional_name_schema")] + pub name: Option, + /// Changes to the setup before the rig is projected, as `render.settings.set` takes them: an + /// object of at most 15 of the setup's fields. Only with `name`; the setup must render with + /// the CPU raytracer. Default: none. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "set_schema")] + pub set: Option, + /// Has no effect when `name` is given: the reply's `cpu.indirect_adoption` already shows what + /// `render.library.studio.apply` would adopt. Without `name`, `true` is refused (as is a + /// non-empty `set`). Default: false. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool", default = "no")] + pub enable_indirect: Option, +} + +fn studio_prepare_required(schema: &mut Schema) { + require_all(schema, &["id", "variant", "center_mm", "subject_extent_mm"]); +} + +fn optional_name_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["string", "null"]}) +} + +/// What `render.library.studio.prepare` returns. With `name`, also the CPU projection. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StudioPrepared { + /// The rig's lights as the renderers take them. + #[schemars(schema_with = "studio_lighting_schema")] + pub lighting: StudioLighting, + /// The rig's passive cards as stage panels; empty for `emitters_only` and for a rig without + /// cards. + #[schemars(schema_with = "stage_schema")] + pub stage: Stage, + /// What the rig was scaled to. + pub projection: RigProjection, + /// Always true: the lights' distance from the subject needs a look. + pub requires_geometry_clearance_review: bool, + /// Always false. + pub document_changed: bool, + /// With `name`: the CPU projection. + #[serde(flatten)] + pub cpu: 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, +} + +/// What a rig becomes in a CPU raytrace setup, given with `name`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CpuProjection { + /// The setup the rig would give, not saved. + #[schemars(schema_with = "setup_reply_schema")] + pub setup: RenderSetup, + /// Always `cpu-raytrace`. + pub executor: String, + /// The design's revision it was read at: pass it as `expected_revision` to apply. + pub revision: u64, + /// Whether a sun needs indirect lighting the setup lacks. + pub requires_indirect: bool, + /// What `enable_indirect` adopts; `null` when no sun needs it. + pub indirect_adoption: Option, +} + +/// The indirect lighting a CPU sun rig adopts. +#[derive(Debug, Serialize, JsonSchema)] +pub struct IndirectAdoption { + /// Always 8. + pub path_depth: u32, + /// The progressive settings given when the setup has none. + pub progressive_if_absent: ProgressiveDefaults, + /// Always 1. + pub primary_samples: u32, + /// Always true. + pub shadows: bool, +} + +/// The progressive sampling a CPU setup gets when it has none. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProgressiveDefaults { + /// Always 16. + pub samples_per_pixel: u32, + /// Always 0. + pub seed: u32, +} + +/// What a rig was scaled to. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RigProjection { + /// The rig. + pub id: String, + /// The variant asked for. + pub variant: String, + /// The passive cards left out: all of them for `emitters_only`. + pub passive_cards_omitted: usize, + /// The passive cards in the stage: all of them for `complete`. + pub passive_cards_included: usize, + /// The rig's size in mm divided by 1000. + pub scale: f64, + /// Always says the lengths are world millimetres and the radiance is relative linear sRGB. + pub physical_units: String, + /// Always true: the rig's calibration is as authored. + pub reference_calibration_not_remeasured: bool, +} + +fn studio_lighting_schema(_: &mut SchemaGenerator) -> Schema { + let vector = finite_vector_schema(f64::MAX); + json_schema!({ + "description": "Lights as the renderers take them, in world mm: rectangular area lights (a centre, half-edge vectors u and v, and an RGB radiance) and an optional sun.", + "type": "object", + "properties": { + "sun": { + "description": "A distant disk; `null` when the rig has none.", + "anyOf": [ + { + "type": "object", + "properties": { + "direction": {"description": "Unit vector toward the sun.", "type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "angular_radius_rad": {"type": "number"}, + "radiance": vector + }, + "required": ["direction", "angular_radius_rad", "radiance"] + }, + {"type": "null"} + ] + }, + "environment": vector, + "area_lights": { + "type": "array", + "items": { + "type": "object", + "properties": {"center": vector, "u": vector, "v": vector, "radiance": vector}, + "required": ["center", "u", "v", "radiance"] + } + } + }, + "required": ["sun", "environment", "area_lights"] + }) +} + +fn stage_schema(_: &mut SchemaGenerator) -> Schema { + let vector = finite_vector_schema(f64::MAX); + json_schema!({ + "description": "Render-only panels: each a rectangle by its centre and half-edge vectors u and v, in world mm, with a linear reflectance.", + "type": "array", + "items": { + "type": "object", + "properties": { + "id": {"type": "string"}, + "center_mm": vector, + "half_u_mm": vector, + "half_v_mm": vector, + "reflectance_linear": vector + }, + "required": ["id", "center_mm", "half_u_mm", "half_v_mm", "reflectance_linear"] + } + }) +} + +/// Save an authored lighting rig in a CPU raytrace or GPU path setup for a subject, in one undo +/// step: its lights, and its passive cards as the setup's stage. The setup's existing lighting +/// and environment go, and with them an existing stage only with `replace_stage`. The subject's +/// clearance from the lights is checked against bounding boxes, not exact geometry. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = studio_apply_required)] +pub struct StudioApplyParams { + // `rig`, `name` and `replace_lighting_and_environment` are optional in the type and required + // in the schema (`studio_apply_required`). + /// The rig and the subject it is scaled to. + #[serde(default, deserialize_with = "read_rig", skip_serializing_if = "Option::is_none")] + #[schemars(with = "RigInput")] + pub rig: Option, + /// The render setup, saved or new. + #[serde(default, deserialize_with = "read_string", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub name: Option, + /// Changes to the setup before the rig is added, as `render.settings.set` takes them: an + /// object of at most 15 of the setup's fields. The setup must render with the CPU raytracer + /// or the GPU path tracer. Default: none. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "set_schema")] + pub set: Option, + /// Must be true: the rig replaces the setup's lighting and environment, so that one thing + /// owns the energy. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "confirm_schema")] + pub replace_lighting_and_environment: Option, + /// Replace a stage the setup already has. Without it, such a setup is refused. Default: false. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool", default = "no")] + pub replace_stage: Option, + /// Adopt the indirect lighting a CPU sun rig needs, as `render.library.studio.prepare` + /// reports it. Without it, such a rig is refused. Default: false. + #[serde(default, deserialize_with = "read_bool", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool", default = "no")] + pub enable_indirect: Option, + /// The design's revision when the caller last read it, as `render.library.studio.prepare` + /// gives it. If the design changed since, the call is refused. Default: not checked. + #[serde(default, deserialize_with = "read_revision", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "revision_schema")] + pub expected_revision: Option, +} + +fn studio_apply_required(schema: &mut Schema) { + require_all(schema, &["rig", "name", "replace_lighting_and_environment"]); +} + +fn confirm_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "boolean", "const": true}) +} + +fn revision_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["integer", "null"], "minimum": 0}) +} + +/// What `render.library.studio.apply` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StudioApplied { + /// The render setup. + pub name: String, + /// The setup as saved, as the render settings commands give it. + #[schemars(schema_with = "setup_reply_schema")] + pub setup: RenderSetup, + /// What the rig was scaled to. + pub projection: RigProjection, + /// Says the clearance was checked against bounding boxes, not exact geometry. + pub clearance: 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, +} + #[cfg(test)] #[path = "render_library_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/render_library_tests.rs b/crates/engine/src/schema/render_library_tests.rs index bad110c6f..7d3d3fca5 100644 --- a/crates/engine/src/schema/render_library_tests.rs +++ b/crates/engine/src/schema/render_library_tests.rs @@ -1,8 +1,9 @@ use serde_json::{Value, json}; use super::{ - LibraryDescribeParams, LibraryDescription, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryTargets, - LibraryTargetsParams, RenderTarget, StableRenderTarget, + AppearanceApplied, AppearanceApplyParams, EnvironmentApplied, EnvironmentApplyParams, LibraryDescribeParams, LibraryDescription, + LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryTargets, LibraryTargetsParams, PhysicalPlan, PhysicalPrepareParams, + RenderTarget, StableRenderTarget, StudioApplied, StudioApplyParams, StudioPrepareParams, StudioPrepared, SurfacePrepareParams, SurfacePrepared, }; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; @@ -14,6 +15,15 @@ fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["id", "kind"]); assert_keys(input_schema_for::(), &["limit", "offset", "query"]); assert_keys(input_schema_for::(), &["id"]); + assert_keys(input_schema_for::(), &["bodies", "id", "variant"]); + assert_keys(input_schema_for::(), &["id", "intensity", "name", "replace_environment", "rotation_rad", "samples", "set"]); + assert_keys(input_schema_for::(), &["acknowledge_reference", "id", "name"]); + assert_keys(input_schema_for::(), &["body_index", "body_name", "id", "origin", "plane", "rotation_rad", "scale"]); + assert_keys(input_schema_for::(), &["center_mm", "enable_indirect", "id", "name", "set", "subject_extent_mm", "variant"]); + assert_keys( + input_schema_for::(), + &["enable_indirect", "expected_revision", "name", "replace_lighting_and_environment", "replace_stage", "rig", "set"], + ); } /// The list's schema takes an `availability` exactly when the reader for its `kind` does: the @@ -65,6 +75,103 @@ fn strict_keeps_todays_errors() { ("render.library.preview", json!({"id": "MAT-001"})), ("render.library.preview", json!({"id": ""})), ]); + // The six apply and prepare commands: the handlers' own messages, for a key left out and for + // a value of the wrong type, which the types read as the handlers' structs do. + let (rig, set) = (json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1}), json!({"width": 4})); + assert_strict_keeps_todays_errors(&[ + ("render.library.appearance.apply", json!({})), + ("render.library.appearance.apply", json!({"id": "SURF-001"})), + ("render.library.appearance.apply", json!({"id": 5, "variant": "uniform_opaque", "bodies": ["Target"]})), + ("render.library.appearance.apply", json!({"id": null, "variant": "uniform_opaque", "bodies": ["Target"]})), + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": "Target"})), + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": [7]})), + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "other", "bodies": ["Target"]})), + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": []})), + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": ["Nope"]})), + ("render.library.environment.apply", json!({})), + ("render.library.environment.apply", json!({"id": "HDR-001"})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": 3})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "set": 5})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "set": null})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "rotation_rad": "x"})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "rotation_rad": null})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "intensity": "x"})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "samples": -1})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "samples": 1.5})), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "replace_environment": "yes"})), + ( + "render.library.environment.apply", + json!({"id": "HDR-001", "name": "E", "set": {"job": {"method": "gpu_path", "options": {}}}, "rotation_rad": 1e9}), + ), + ("render.library.environment.apply", json!({"id": "HDR-001", "name": "E", "set": set})), + ("render.library.physical.prepare", json!({})), + ("render.library.physical.prepare", json!({"id": "steel-304-plate", "name": "R"})), + ("render.library.physical.prepare", json!({"id": "steel-304-plate", "name": "R", "acknowledge_reference": false})), + ("render.library.physical.prepare", json!({"id": "steel-304-plate", "name": "R", "acknowledge_reference": "true"})), + ("render.library.physical.prepare", json!({"id": "steel-304-plate", "name": "R", "acknowledge_reference": null})), + ("render.library.physical.prepare", json!({"id": "steel-304-plate", "name": " R", "acknowledge_reference": true})), + ("render.library.physical.prepare", json!({"id": 1, "name": "R", "acknowledge_reference": true})), + ("render.library.physical.prepare", json!({"id": "no-such-profile", "name": "R", "acknowledge_reference": true})), + ("render.library.surface.prepare", json!({})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": "0", "body_name": "Target"})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": -1, "body_name": "Target"})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0.0, "body_name": "Target"})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "origin": [1, 2]})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "origin": {"x": 1, "y": 2, "z": 3}})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "plane": "XY"})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "plane": null})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "scale": null})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "scale": 0})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target", "rotation_rad": null})), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target"})), + ("render.library.studio.prepare", json!({})), + ("render.library.studio.prepare", json!({"id": "RIG-002", "variant": "complete"})), + ("render.library.studio.prepare", json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0], "subject_extent_mm": 1})), + ("render.library.studio.prepare", json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": "1"})), + ("render.library.studio.prepare", json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 0})), + ("render.library.studio.prepare", json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "name": 5})), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "set": null}), + ), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "set": set}), + ), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "enable_indirect": true}), + ), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "enable_indirect": null}), + ), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "name": "R"}), + ), + ("render.library.studio.apply", json!({})), + ("render.library.studio.apply", json!({"rig": rig})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R"})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R", "replace_lighting_and_environment": false})), + ("render.library.studio.apply", json!({"rig": 5, "name": "R", "replace_lighting_and_environment": true})), + ("render.library.studio.apply", json!({"rig": null, "name": "R", "replace_lighting_and_environment": true})), + ("render.library.studio.apply", json!({"rig": {"id": "RIG-002"}, "name": "R", "replace_lighting_and_environment": true})), + ( + "render.library.studio.apply", + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "x": 1}, "name": "R", "replace_lighting_and_environment": true}), + ), + ( + "render.library.studio.apply", + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": "a", "subject_extent_mm": 1}, "name": "R", "replace_lighting_and_environment": true}), + ), + ("render.library.studio.apply", json!({"rig": rig, "name": 3, "replace_lighting_and_environment": true})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R", "replace_lighting_and_environment": true, "expected_revision": -1})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R", "replace_lighting_and_environment": true, "expected_revision": 99999})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R", "replace_lighting_and_environment": true, "replace_stage": "x"})), + ("render.library.studio.apply", json!({"rig": rig, "name": "R", "replace_lighting_and_environment": true, "set": 5})), + ]); } /// #11443: the four commands reply as their output schemas say, in Warn without warnings. Every @@ -172,3 +279,514 @@ fn render_library_commands_reply_with_their_schemas() { assert!(error.contains("knd"), "{level:?}: {error}"); } } + +/// A design with one box, `Target`, and a saved CPU setup, `Cpu`, at the check level `level`. +fn with_a_target(level: ParamCheck) -> Session { + let mut s = Session { param_check: level, ..Session::default() }; + for (id, p) in [ + ("solid.box", json!({"length": 10, "width": 20, "height": 5, "body_name": "Target"})), + ("render.settings.set", json!({"name": "Cpu", "set": {"width": 8, "height": 8, "job": {"method": "cpu_raytrace", "options": {}}}})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + } + s +} + +/// Every call, of the six commands, that reads its keys: working calls in every form, and calls +/// the handlers refuse for a key left out, a value of the wrong type or a value out of range. +fn apply_and_prepare_calls() -> Vec<(&'static str, Value)> { + let gpu = json!({"job": {"method": "gpu_path", "options": {}}}); + let cpu = json!({"width": 8, "height": 8, "job": {"method": "cpu_raytrace", "options": {}}}); + let rig = json!({"id": "RIG-002", "variant": "complete", "center_mm": [10, 20, 30], "subject_extent_mm": 100}); + let appearance = |extra: Value| { + let mut p = json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": ["Target"]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let environment = |extra: Value| { + let mut p = json!({"id": "HDR-001", "name": "E", "set": cpu}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let physical = |extra: Value| { + let mut p = json!({"id": "steel-304-plate", "name": "Reference", "acknowledge_reference": true}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let surface = |extra: Value| { + let mut p = json!({"id": "SURF-001", "body_index": 0, "body_name": "Target"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let prepare = |extra: Value| { + let mut p = rig.clone(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let apply = |extra: Value| { + let mut p = json!({"rig": rig, "name": "Rig", "set": gpu, "replace_lighting_and_environment": true}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let mut calls = vec![]; + let mut add = |id: &'static str, p: Value| calls.push((id, p)); + let (a, e, ph, su, pr, ap) = ( + "render.library.appearance.apply", + "render.library.environment.apply", + "render.library.physical.prepare", + "render.library.surface.prepare", + "render.library.studio.prepare", + "render.library.studio.apply", + ); + for p in [ + json!({}), + json!({"id": "SELENE-AP-001"}), + json!({"id": "MAT-001"}), + json!({"id": 5}), + json!({"id": null}), + json!({"variant": "x"}), + json!({"variant": null}), + json!({"bodies": []}), + json!({"bodies": "Target"}), + json!({"bodies": [1]}), + json!({"bodies": null}), + json!({"bodies": ["Nope"]}), + json!({"bodies": ["Target", "Target"]}), + ] { + add(a, appearance(p)); + } + add(a, json!({})); + add(a, json!({"id": "SURF-001"})); + add(a, json!({"id": "SURF-001", "variant": "uniform_opaque"})); + for id in ["SELENE-AP-001", "SELENE-AP-002", "SURF-002"] { + add(a, json!({"id": id, "variant": "uniform_opaque", "bodies": ["Target"]})); + } + for p in [ + json!({}), + json!({"rotation_rad": 0.5, "intensity": 2, "samples": 4, "replace_environment": true}), + json!({"rotation_rad": 1, "intensity": 0, "samples": 1}), + json!({"set": gpu, "intensity": 3, "samples": 5}), + json!({"set": gpu, "intensity": 300}), + json!({"set": {}}), + json!({"set": null}), + json!({"set": 5}), + json!({"set": [1]}), + json!({"rotation_rad": null}), + json!({"rotation_rad": "x"}), + json!({"rotation_rad": 1e9}), + json!({"intensity": null}), + json!({"intensity": "x"}), + json!({"samples": null}), + json!({"samples": -1}), + json!({"samples": 1.5}), + json!({"samples": 3}), + json!({"samples": 4294967296u64}), + json!({"replace_environment": null}), + json!({"replace_environment": "yes"}), + json!({"id": 5}), + json!({"name": 3}), + json!({"name": null}), + json!({"name": " E"}), + ] { + add(e, environment(p)); + } + add(e, json!({})); + add(e, json!({"id": "HDR-001"})); + add(e, json!({"name": "E"})); + for p in [ + json!({}), + json!({"name": "R"}), + json!({"acknowledge_reference": false}), + json!({"acknowledge_reference": "true"}), + json!({"acknowledge_reference": null}), + json!({"name": " R"}), + json!({"name": ""}), + json!({"name": 4}), + json!({"id": 1}), + json!({"id": "no-such-profile"}), + json!({"id": "../profiles"}), + json!({"id": "aluminum-6061-t6"}), + ] { + add(ph, physical(p)); + } + add(ph, json!({})); + add(ph, json!({"id": "steel-304-plate", "name": "R"})); + add(ph, json!({"name": "R", "acknowledge_reference": true})); + for p in [ + json!({}), + json!({"origin": [1, 2, 3], "scale": 2.5, "plane": "yz", "rotation_rad": 0.4}), + json!({"plane": "zx"}), + json!({"plane": "xy"}), + json!({"origin": null}), + json!({"origin": [1, 2]}), + json!({"origin": [1, 2, 3, 4]}), + json!({"origin": ["a", 2, 3]}), + json!({"origin": {"x": 1, "y": 2, "z": 3}}), + json!({"plane": "XY"}), + json!({"plane": null}), + json!({"plane": 1}), + json!({"scale": null}), + json!({"scale": 0}), + json!({"scale": "2"}), + json!({"rotation_rad": null}), + json!({"rotation_rad": 1e7}), + json!({"body_index": "0"}), + json!({"body_index": -1}), + json!({"body_index": 1.5}), + json!({"body_index": 1}), + json!({"body_name": 1}), + json!({"body_name": "Other"}), + json!({"id": "MAT-001"}), + ] { + add(su, surface(p)); + } + add(su, json!({})); + add(su, json!({"id": "SURF-001", "body_index": 0})); + add(su, json!({"id": "SURF-001", "body_name": "Target"})); + add(su, json!({"body_index": 0, "body_name": "Target"})); + for p in [ + json!({}), + json!({"variant": "emitters_only"}), + json!({"id": "RIG-001", "variant": "emitters_only"}), + json!({"id": "RIG-001", "variant": "complete"}), + json!({"id": "RIG-020", "name": "Cpu", "set": cpu, "enable_indirect": true}), + json!({"id": "RIG-020", "name": "Cpu", "set": cpu}), + json!({"name": "Cpu"}), + json!({"name": "Cpu", "set": {"width": 16}}), + json!({"name": null}), + json!({"name": 5}), + json!({"name": "Cpu", "set": null}), + json!({"name": "Cpu", "set": 5}), + json!({"set": {"width": 4}}), + json!({"enable_indirect": true}), + json!({"enable_indirect": false}), + json!({"enable_indirect": null}), + json!({"enable_indirect": "yes"}), + json!({"name": "Rig", "set": gpu}), + json!({"center_mm": [0, 0]}), + json!({"center_mm": [0, 0, 0, 0]}), + json!({"center_mm": [0, "a", 0]}), + json!({"center_mm": [1e13, 0, 0]}), + json!({"center_mm": null}), + json!({"subject_extent_mm": 0}), + json!({"subject_extent_mm": "100"}), + json!({"subject_extent_mm": null}), + json!({"variant": 1}), + json!({"id": 1}), + ] { + add(pr, prepare(p)); + } + for key in ["id", "variant", "center_mm", "subject_extent_mm"] { + let mut p = rig.clone(); + p.as_object_mut().unwrap().remove(key); + add(pr, p); + } + add(pr, json!({})); + for p in [ + json!({}), + json!({"set": cpu}), + json!({"set": cpu, "enable_indirect": true}), + json!({"set": cpu, "enable_indirect": null}), + json!({"set": cpu, "enable_indirect": "x"}), + json!({"rig": {"id": "RIG-020", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 100}, "set": cpu}), + json!({"rig": {"id": "RIG-020", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 100}, "set": cpu, "enable_indirect": true}), + json!({"rig": {"id": "RIG-001", "variant": "emitters_only", "center_mm": [0, 0, 0], "subject_extent_mm": 100}}), + json!({"set": null}), + json!({"set": 5}), + json!({"set": {"width": 0}}), + json!({"replace_stage": true}), + json!({"replace_stage": null}), + json!({"replace_stage": "x"}), + json!({"expected_revision": 3}), + json!({"expected_revision": null}), + json!({"expected_revision": 99999}), + json!({"expected_revision": -1}), + json!({"expected_revision": "3"}), + json!({"replace_lighting_and_environment": false}), + json!({"replace_lighting_and_environment": null}), + json!({"replace_lighting_and_environment": 1}), + json!({"name": 3}), + json!({"name": "Rig", "set": {}}), + json!({"rig": 5}), + json!({"rig": null}), + json!({"rig": {}}), + json!({"rig": {"id": "RIG-002"}}), + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0]}}), + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1, "extra": 1}}), + json!({"rig": {"id": 2, "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 1}}), + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": "a", "subject_extent_mm": 1}}), + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": null}}), + json!({"rig": {"id": "RIG-002", "variant": "other", "center_mm": [0, 0, 0], "subject_extent_mm": 1}}), + ] { + add(ap, apply(p)); + } + for key in ["rig", "name", "replace_lighting_and_environment"] { + let mut p = apply(json!({})); + p.as_object_mut().unwrap().remove(key); + add(ap, p); + } + calls +} + +/// The types read each key as the handlers do: a call the handler accepts is accepted at every +/// check level, with no `param_warnings`, and a call it refuses gets its own message in warn and +/// in strict. That includes calls with a key left out or `null`, which the handler's struct +/// refuses or reads as absent, depending on the key. +#[test] +fn the_types_read_each_key_as_the_handlers_do() { + let calls = apply_and_prepare_calls(); + assert!(calls.len() > 150, "{}", calls.len()); + let mut tally = std::collections::BTreeMap::<&str, (usize, usize)>::new(); + for (id, p) in &calls { + let run = |level: ParamCheck| { + let mut s = with_a_target(level); + s.execute(id, p).map_err(|e| e.to_string()) + }; + let off = run(ParamCheck::Off); + assert_eq!(run(ParamCheck::Warn), off, "warn: {id} {p}"); + assert_eq!(run(ParamCheck::Strict), off, "strict: {id} {p}"); + let count = tally.entry(id).or_default(); + match &off { + Ok(reply) => { + count.0 += 1; + assert!(reply.get("param_warnings").is_none(), "{id} {p}: {reply}"); + assert!(crate::schema::issues(id, p).is_empty(), "{id} {p}"); + } + Err(_) => count.1 += 1, + } + } + // Every command ran calls of both kinds (the HDR ones accept only in a build with the bundled + // library). + assert_eq!(tally.len(), 6, "{tally:?}"); + for (id, (accepted, refused)) in &tally { + let bundled = cfg!(feature = "bundled-render-library") || !id.ends_with("environment.apply"); + assert!((*accepted >= 2 || !bundled) && *refused >= 3, "{id}: {accepted} accepted, {refused} refused"); + } +} + +/// The schemas take what the handlers read: the keys a handler refuses without are required, a +/// default is the one the handler fills in, and a value of the wrong type is refused. +#[test] +fn the_schemas_take_what_the_handlers_read() { + let requires = |schema: schemars::Schema, keys: &[&str]| { + let mut required: Vec<_> = schema.as_value()["required"].as_array().unwrap().iter().map(|k| k.as_str().unwrap().to_string()).collect(); + required.sort(); + assert_eq!(required, keys); + }; + requires(input_schema_for::(), &["bodies", "id", "variant"]); + requires(input_schema_for::(), &["id", "name"]); + requires(input_schema_for::(), &["acknowledge_reference", "id", "name"]); + requires(input_schema_for::(), &["body_index", "body_name", "id"]); + requires(input_schema_for::(), &["center_mm", "id", "subject_extent_mm", "variant"]); + requires(input_schema_for::(), &["name", "replace_lighting_and_environment", "rig"]); + let defaults = |schema: schemars::Schema, key: &str| schema.as_value()["properties"][key]["default"].clone(); + assert_eq!(defaults(input_schema_for::(), "rotation_rad"), json!(0.0)); + assert_eq!(defaults(input_schema_for::(), "intensity"), json!(1.0)); + assert_eq!(defaults(input_schema_for::(), "samples"), json!(16)); + assert_eq!(defaults(input_schema_for::(), "replace_environment"), json!(false)); + assert_eq!(defaults(input_schema_for::(), "set"), json!({})); + assert_eq!(defaults(input_schema_for::(), "scale"), json!(1.0)); + assert_eq!(defaults(input_schema_for::(), "plane"), json!("xy")); + assert_eq!(defaults(input_schema_for::(), "rotation_rad"), json!(0.0)); + assert_eq!(defaults(input_schema_for::(), "enable_indirect"), json!(false)); + assert_eq!(defaults(input_schema_for::(), "replace_stage"), json!(false)); + // Every call that works conforms to its schema; so does no call that is missing a required + // key or has a value of the wrong type. + let mut conforming = 0; + for (id, p) in apply_and_prepare_calls() { + let schema = crate::cmd::find_command(id).and_then(|c| c.contract).map(|c| c.input_schema()).unwrap(); + let schema = schema.as_value(); + let works = with_a_target(ParamCheck::Off).execute(id, &p).is_ok(); + let fits = conforms(schema, schema, &p); + assert!(!works || fits, "{id} {p} works but doesn't match its schema"); + conforming += usize::from(fits); + let object = p.as_object().unwrap(); + let required = schema["required"].as_array().unwrap(); + assert!(required.iter().all(|k| object.contains_key(k.as_str().unwrap())) || !fits, "{id} {p}"); + } + assert!(conforming > 40, "{conforming}"); +} + +/// The id pattern, the `const: true` confirmations and the cap on `set` are in the schemas, so +/// that a client sees them without calling. +#[test] +fn the_id_pattern_the_confirmations_and_the_set_cap_are_pinned() { + let id = json!({"type": "string", "pattern": "^[A-Za-z0-9_-]{1,128}$"}); + let property = |schema: schemars::Schema, key: &str| schema.as_value()["properties"][key].clone(); + for (name, schema) in [ + ("appearance", input_schema_for::()), + ("environment", input_schema_for::()), + ("surface", input_schema_for::()), + ("studio prepare", input_schema_for::()), + ] { + let found = property(schema, "id"); + assert_eq!((&found["type"], &found["pattern"]), (&id["type"], &id["pattern"]), "{name}"); + } + let confirmed = json!({"type": "boolean", "const": true}); + for (schema, key) in [ + (input_schema_for::(), "acknowledge_reference"), + (input_schema_for::(), "replace_lighting_and_environment"), + ] { + let found = property(schema, key); + assert_eq!((&found["type"], &found["const"]), (&confirmed["type"], &confirmed["const"]), "{key}"); + } + for (name, schema) in [ + ("environment", input_schema_for::()), + ("studio prepare", input_schema_for::()), + ("studio apply", input_schema_for::()), + ] { + let set = property(schema, "set"); + assert_eq!(set["maxProperties"], json!(15), "{name}"); + assert_eq!(set["type"], json!("object"), "{name}"); + } + // The schema says what the handlers do about them. + let apply = |p: Value| with_a_target(ParamCheck::Off).execute("render.library.studio.apply", &p).is_err(); + assert!(apply(json!({"name": "Rig", "rig": {"id": "RIG-001", "variant": "emitters_only", "center_mm": [0, 0, 0], "subject_extent_mm": 1}}))); + let physical = with_a_target(ParamCheck::Off) + .execute("render.library.physical.prepare", &json!({"id": "PHYS-001", "name": "x", "acknowledge_reference": false})); + assert!(physical.is_err()); + // Without `name`, enable_indirect true is refused; with it, it makes no difference to a prepare. + let prepare = |p: Value| with_a_target(ParamCheck::Off).execute("render.library.studio.prepare", &p); + let rig = json!({"id": "RIG-001", "variant": "emitters_only", "center_mm": [0, 0, 0], "subject_extent_mm": 100}); + let mut with = rig.clone(); + with["enable_indirect"] = json!(true); + assert!(prepare(with).is_err()); + let description = property(input_schema_for::(), "enable_indirect")["description"].as_str().unwrap().to_string(); + assert!(description.contains("no effect when `name` is given") && description.contains("refused"), "{description}"); +} + +/// The six commands reply as their output schemas say, in Warn without warnings: every surface, +/// Selene appearance, physical profile and rig, in each form the commands take. +#[test] +fn apply_and_prepare_commands_reply_with_their_schemas() { + let (appearance, environment, physical, surface, prepared, applied) = ( + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + ); + let ids = |kind: &str| -> Vec { + let mut s = Session::default(); + let r = s.execute("render.library.list", &json!({"kind": kind, "limit": 128})).unwrap(); + r["items"].as_array().unwrap().iter().map(|i| i["id"].as_str().unwrap().to_string()).collect() + }; + let run = |schema: &schemars::Schema, id: &str, p: Value| -> Result { + let mut s = with_a_target(ParamCheck::Warn); + let r = s.execute(id, &p).map_err(|e| e.to_string())?; + let schema = schema.as_value(); + assert!(conforms(schema, schema, &r), "{id} {p}: {r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}"); + Ok(r) + }; + let mut made = [0usize; 6]; + for id in ids("surfaces").into_iter().chain(ids("selene_appearances")) { + let r = run(&appearance, "render.library.appearance.apply", json!({"id": id, "variant": "uniform_opaque", "bodies": ["Target"]})); + made[0] += usize::from(r.is_ok()); + } + for id in ids("surfaces") { + for plane in ["xy", "yz", "zx"] { + let p = json!({"id": id, "body_index": 0, "body_name": "Target", "plane": plane, "scale": 2, "rotation_rad": 0.3, "origin": [1, 2, 3]}); + made[1] += usize::from(run(&surface, "render.library.surface.prepare", p).is_ok()); + } + let p = json!({"id": id, "body_index": 0, "body_name": "Target", "origin": null}); + made[1] += usize::from(run(&surface, "render.library.surface.prepare", p).is_ok()); + } + for id in ids("physical_profiles") { + let r = run(&physical, "render.library.physical.prepare", json!({"id": id, "name": "Reference", "acknowledge_reference": true})); + made[2] += usize::from(r.is_ok()); + } + let cpu = json!({"width": 8, "height": 8, "job": {"method": "cpu_raytrace", "options": {}}}); + let gpu = json!({"width": 8, "height": 8, "job": {"method": "gpu_path", "options": {}}}); + for id in ids("rigs") { + for variant in ["complete", "emitters_only"] { + let rig = json!({"id": id, "variant": variant, "center_mm": [10, 20, 30], "subject_extent_mm": 100}); + made[3] += usize::from(run(&prepared, "render.library.studio.prepare", rig.clone()).is_ok()); + for extra in [json!({"name": "Cpu"}), json!({"name": "Rig", "set": cpu, "enable_indirect": true}), json!({"name": null, "set": {}})] { + let mut p = rig.clone(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + made[3] += usize::from(run(&prepared, "render.library.studio.prepare", p).is_ok()); + } + for (set, indirect) in [(&gpu, false), (&cpu, false), (&cpu, true)] { + let p = json!({"rig": rig, "name": "Rig", "set": set, "replace_lighting_and_environment": true, "enable_indirect": indirect, + "replace_stage": false, "expected_revision": null}); + made[4] += usize::from(run(&applied, "render.library.studio.apply", p).is_ok()); + } + } + } + if cfg!(feature = "bundled-render-library") { + for id in ids("hdr") { + for set in [&cpu, &gpu] { + let p = json!({"id": id, "name": "E", "set": set, "rotation_rad": 0.5, "intensity": 2, "samples": 4, "replace_environment": false}); + made[5] += usize::from(run(&environment, "render.library.environment.apply", p).is_ok()); + } + } + let p = json!({"id": "HDR-001", "name": "Cpu", "replace_environment": true}); + made[5] += usize::from(run(&environment, "render.library.environment.apply", p).is_ok()); + } + // Surfaces and appearances, profiles with one density, rigs with a CPU or GPU projection: + // each command made some replies, and `physical.prepare` refuses the profiles without one. + assert!(made[0] >= 90 && made[1] >= 190 && (40..=60).contains(&made[2]) && made[3] >= 50 && made[4] >= 30, "{made:?}"); + assert!(!cfg!(feature = "bundled-render-library") || made[5] >= 45, "{made:?}"); + // Exact fields, not only the shape. + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let r = s + .execute( + "render.library.studio.prepare", + &json!({"id": "RIG-001", "variant": "complete", "center_mm": [10, 20, 30], "subject_extent_mm": 100}), + ) + .unwrap(); + assert_eq!((r["projection"]["passive_cards_included"].as_u64(), r["stage"][0]["id"].as_str()), (Some(1), Some("RIG-001_fill_card")), "{r}"); + assert!(r.get("setup").is_none() && r.get("indirect_adoption").is_none(), "without `name`, no CPU projection: {r}"); +} + +/// Like the handlers' structs, which refuse a key they don't know, warn and strict refuse a +/// misspelt key. What warn reports for a call the handler accepted (`issues`) is the same issue +/// strict refuses with: the key, and the one it was probably meant to be. +#[test] +fn a_misspelt_key_is_reported_in_warn_and_refused_in_strict() { + let cases = [ + ("render.library.appearance.apply", json!({"id": "SURF-001", "variant": "uniform_opaque", "bodies": ["Target"]}), "bodie", "bodies"), + ( + "render.library.physical.prepare", + json!({"id": "steel-304-plate", "name": "R", "acknowledge_reference": true}), + "acknowledge_referense", + "acknowledge_reference", + ), + ("render.library.surface.prepare", json!({"id": "SURF-001", "body_index": 0, "body_name": "Target"}), "scal", "scale"), + ( + "render.library.studio.prepare", + json!({"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 100}), + "subject_extent", + "subject_extent_mm", + ), + ( + "render.library.studio.apply", + json!({"rig": {"id": "RIG-002", "variant": "complete", "center_mm": [0, 0, 0], "subject_extent_mm": 100}, "name": "Rig", + "set": {"job": {"method": "gpu_path", "options": {}}}, "replace_lighting_and_environment": true}), + "replace_stag", + "replace_stage", + ), + ( + "render.library.environment.apply", + json!({"id": "HDR-001", "name": "E", "set": {"width": 64, "height": 32, "job": {"method": "cpu_raytrace", "options": {}}}}), + "intensty", + "intensity", + ), + ]; + for (id, mut p, typo, key) in cases { + let ok = p.clone(); + p[typo] = json!(1); + assert!(crate::schema::issues(id, &ok).is_empty(), "{id}: the call without the typo is fine"); + let issues = crate::schema::issues(id, &p); + let want = format!("unknown key `{typo}`; did you mean `{key}`?"); + assert_eq!(issues.iter().map(|i| i.message.as_str()).collect::>(), [want.as_str()], "{id}"); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = with_a_target(level); + let error = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains(typo), "{id} {level:?}: {error}"); + assert_eq!(error.contains(&want), level == ParamCheck::Strict, "{id} {level:?}: {error}"); + } + } +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 1a0ab3f87..80b7ede8a 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -84,12 +84,6 @@ render.backends render.cancel render.effects.describe render.export -render.library.appearance.apply -render.library.environment.apply -render.library.physical.prepare -render.library.studio.apply -render.library.studio.prepare -render.library.surface.prepare render.preflight render.result.pin render.result.regrade