Compare commits

..
Author SHA1 Message Date
selune 492e2d1c17 docs(render): portable shutdown handoff and exact validation status 2026-10-31 13:09:55 +01:00
selune a09ecc2ec6 wip(render): preserve exact progressive-render source before handoff
Emergency draft source checkpoint from A077; existing authored history is retained through the real parent. No source repair or claimed authorship reassignment. Exact C28 source binding d38a: 28 PASS / 1 font-fixture FAIL / 954 UNRUN; three postchecks UNRUN. Native acceptance/full CI/readiness incomplete. Separate unadopted fixture/compatibility proposals remain separate; see preservation notes.
2026-10-31 13:04:20 +01:00
lillith a077906234 feat(render): add bounded CPU Interactive request lifecycle 2026-10-29 20:18:50 +01:00
lillith b2733d607a claim: #8936 2026-10-29 18:16:13 +01:00
283 changed files with 204218 additions and 157639 deletions

No files matched your search

-1
View File
@@ -609,7 +609,6 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments.
| assets/icons/ui/design/svg/model/timeline_stop.svg | SolidCraft contributors | Original history playback icon; canonical grey_cube base and original action cue | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/flat/status_pin.svg | SolidCraft contributors | Original analytic pin icon for persistent viewport results | MIT OR Apache-2.0 |
| assets/locales/pending/render-wear.json | SolidCraft contributors | Original UI labels and translations | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/equation_curve.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
## Code adapted from sibling projects
Generated
+17 -17
View File
@@ -4210,7 +4210,7 @@ dependencies = [
[[package]]
name = "solidcraft"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"block2 0.6.2",
"eframe",
@@ -4246,11 +4246,11 @@ dependencies = [
[[package]]
name = "solidcraft-3dx-client"
version = "0.27.0"
version = "0.26.1"
[[package]]
name = "solidcraft-cli"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"image",
"log",
@@ -4262,7 +4262,7 @@ dependencies = [
[[package]]
name = "solidcraft-derive"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"proc-macro2",
"quote",
@@ -4271,7 +4271,7 @@ dependencies = [
[[package]]
name = "solidcraft-doc"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"log",
"serde",
@@ -4288,7 +4288,7 @@ dependencies = [
[[package]]
name = "solidcraft-engine"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"image",
"log",
@@ -4309,7 +4309,7 @@ dependencies = [
[[package]]
name = "solidcraft-geom"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"serde",
"serde_json",
@@ -4318,7 +4318,7 @@ dependencies = [
[[package]]
name = "solidcraft-gpu"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"image",
"log",
@@ -4338,7 +4338,7 @@ dependencies = [
[[package]]
name = "solidcraft-io"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"cadmpeg-core",
"cadmpeg-ir",
@@ -4362,7 +4362,7 @@ dependencies = [
[[package]]
name = "solidcraft-kernel"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"log",
"proptest",
@@ -4382,7 +4382,7 @@ dependencies = [
[[package]]
name = "solidcraft-mcp"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"serde_json",
"solidcraft-engine",
@@ -4391,7 +4391,7 @@ dependencies = [
[[package]]
name = "solidcraft-render"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"image",
"moxcms",
@@ -4405,7 +4405,7 @@ dependencies = [
[[package]]
name = "solidcraft-sketch"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"harfrust",
"serde",
@@ -4418,14 +4418,14 @@ dependencies = [
[[package]]
name = "solidcraft-space-mouse"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"serde",
]
[[package]]
name = "solidcraft-ui-egui"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"arboard",
"egui",
@@ -4455,7 +4455,7 @@ dependencies = [
[[package]]
name = "solidcraft-web"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"eframe",
"egui",
@@ -5998,7 +5998,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.27.0"
version = "0.26.1"
dependencies = [
"proc-macro2",
"serde",
+1 -1
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"]
exclude = ["vendor"]
[workspace.package]
version = "0.27.0"
version = "0.26.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+3 -4
View File
@@ -42,8 +42,8 @@
</p>
<p align="center">
<a href="https://trendshift.io/repositories/296178?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-296178" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/296178/daily" alt="tangency-labs%2Fsolidcraft | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/296178?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-296178" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/296178/daily?language=Rust" alt="tangency-labs%2Fsolidcraft | Trendshift (Rust)" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/296178?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-296178" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/296178/daily" alt="tangency-labs%2Fsolidcraft | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/296178?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-296178" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/296178/daily?language=Rust" alt="tangency-labs%2Fsolidcraft | Trendshift (Rust)" width="250" height="55"/></a>
</p>
![SolidCraft: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo.gif)
@@ -98,7 +98,7 @@ More commands, the Windows cross-build and the browser build are in [docs/buildi
runs its own design session, or with `--connect` it drives the running app so you can watch.
Claude Code: `claude mcp add solidcraft -- solidcraft-cli mcp`. If a terminal doesn't find
`solidcraft-cli` (older Windows installers don't put it on `PATH`), give its full path (by default
`"C:\\Program Files\\SolidCraft\\solidcraft-cli.exe"`). Tools, access rules and an example session:
`"C:\Program Files\SolidCraft\solidcraft-cli.exe"`). Tools, access rules and an example session:
[docs/mcp.md](docs/mcp.md).
## Scripts
@@ -150,4 +150,3 @@ Tinkercad are trademarks of their respective owners, named only to describe comp
[linux-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage
[snap-store]: https://snapcraft.io/solidcraft
[web-app]: https://solidcraft.io/app
@@ -66,7 +66,7 @@ fn run() -> Result<(), String> {
let mut session = Session::default();
eprintln!("Generating original CAD scene from {recipe_path}");
let generation_start = Instant::now();
let (commands, command_timings) = session.run_script_timed(&recipe, false, &mut |_, _| {}).map_err(|e| e.to_string())?;
let (commands, command_timings) = session.run_script_timed(&recipe, false).map_err(|e| e.to_string())?;
let generation_seconds = generation_start.elapsed().as_secs_f64();
let design_path = output.with_extension(solidcraft_engine::io::DESIGN_EXT);
session.execute("file.save_as", &json!({"path":design_path})).map_err(|e| e.to_string())?;
+31 -54
View File
@@ -2,7 +2,6 @@
//!
//! ```text
//! solidcraft-cli run <script.json|design.sc|part.step|mesh.3mf> [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]
//! [--param-check off|warn|strict]
//! solidcraft-cli eval <script.json|design.sc|part.step> [--in design.sc|part.step] [--json-out FILE] (alias: inspect) measurements as JSON
//! solidcraft-cli script <design.sc> [--out script.json] the design's history as a command script
//! solidcraft-cli bench-open <design.sc | part.step> [--parse-only] [--save OUT.sc] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] loading timings as JSON lines
@@ -58,7 +57,7 @@ struct Command {
}
/// `run`'s lines in the usage.
const USAGE_RUN: &str = " solidcraft-cli run <script.json|design.sc|part.step> [--in design.sc|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]\n [--param-check off|warn|strict]\n solidcraft-cli run --in <design.sc|part.step> [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--param-check checks each step against its command's contract: warn reports on stderr, strict stops the run)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n";
const USAGE_RUN: &str = " solidcraft-cli run <script.json|design.sc|part.step> [--in design.sc|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]\n solidcraft-cli run --in <design.sc|part.step> [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n";
/// `eval`'s lines in the usage.
const USAGE_EVAL: &str = " solidcraft-cli eval <script.json|design.sc|part.step> [--in design.sc|part.step] [--json-out FILE] (alias: inspect)\n solidcraft-cli eval --in <script.json|design.sc|part.step> [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n";
/// `script`'s lines in the usage.
@@ -300,36 +299,18 @@ fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Res
s.execute("doc.open", &json!({"path": path})).map_err(|e| e.to_string())?;
} else {
let script = if v.get("features").is_some() && v.get("commands").is_none() { recipe::to_script(&v)? } else { v };
run_script_warning(&mut s, path, &script)?;
// Warn level: each step's `param_warnings` as it completes, even when a later step fails
// (stderr, so stdout stays the caller's).
let mut warn = |step: usize, r: &Value| {
for w in r.get("param_warnings").and_then(Value::as_array).into_iter().flatten() {
eprintln!("{path}: step {}: {}", step + 1, w.as_str().unwrap_or_default());
}
};
s.run_script_each(&script, &mut warn).map_err(|e| e.to_string())?;
}
Ok(s)
}
/// Run `script`, read from `path`, on `s`. At the warn level each step's `param_warnings` go to
/// stderr as the step completes, even when a later step fails (stdout stays the caller's).
fn run_script_warning(s: &mut Session, path: &str, script: &Value) -> Result<Vec<Value>, String> {
s.run_script_each(script, &mut |step, r| print_param_warnings(path, step, r)).map_err(|e| e.to_string())
}
/// Step `step`'s `param_warnings` on stderr, one per line, named after the script at `path`.
fn print_param_warnings(path: &str, step: usize, r: &Value) {
for w in r.get("param_warnings").and_then(Value::as_array).into_iter().flatten() {
eprintln!("{path}: step {}: {}", step + 1, w.as_str().unwrap_or_default());
}
}
/// `--param-check off|warn|strict`: how calls that break a command's parameter contract are
/// treated (docs/mcp.md); off when the option isn't given.
fn parse_param_check(cmd: &str, args: &[String]) -> Result<solidcraft_engine::schema::ParamCheck, String> {
match flag(args, "--param-check") {
None if args.iter().any(|a| a == "--param-check") => Err(format!("{cmd}: --param-check wants off, warn or strict")),
None => Ok(solidcraft_engine::schema::ParamCheck::Off),
Some(v) => {
solidcraft_engine::schema::ParamCheck::parse(v).ok_or_else(|| format!("{cmd}: --param-check wants off, warn or strict, not `{v}`"))
}
}
}
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
@@ -386,15 +367,7 @@ fn print_json(v: &Value, file: Option<&str>) -> Result<(), String> {
fn cmd_run(args: &[String]) -> Result<(), String> {
install_renderer();
let json_out = json_out(args)?;
// Before the option check, so a bare `--param-check` gets the words `mcp` uses.
let check = parse_param_check("run", args)?;
known_args(
"run",
args,
&["--in", "--out", "--save", "--json-out", "--param-check"],
&["--quiet", "--results", "--timings", "--profile", "--allow-errors"],
true,
)?;
known_args("run", args, &["--in", "--out", "--save", "--json-out"], &["--quiet", "--results", "--timings", "--profile", "--allow-errors"], true)?;
let base = flag(args, "--in");
let path = positional(args);
if path.is_none() && base.is_none() {
@@ -407,25 +380,23 @@ fn cmd_run(args: &[String]) -> Result<(), String> {
let (mut s, results) = if want_results || timings {
// Collect every command's result or time (scripts only), then process requested files too.
let mut s = match base {
Some(b) => load_checked(b, check)?,
Some(b) => load(b)?,
None => Session::default(),
};
s.param_check = check;
let needs = if want_results { "--results needs a script" } else { "--timings needs a script" };
let script = path.ok_or(needs)?;
let v = read_json(script)?;
let v = read_json(path.ok_or(needs)?)?;
let out = if timings {
let (r, mut t) = s.run_script_timed(&v, profile, &mut |step, r| print_param_warnings(script, step, r)).map_err(|e| e.to_string())?;
let (r, mut t) = s.run_script_timed(&v, profile).map_err(|e| e.to_string())?;
if want_results && let Some(o) = t.as_object_mut() {
o.insert("results".into(), Value::Array(r));
}
t
} else {
Value::Array(run_script_warning(&mut s, script, &v)?)
Value::Array(s.run_script(&v).map_err(|e| e.to_string())?)
};
(s, Some(out))
} else {
(open(base, path, check)?, None)
(open(base, path)?, None)
};
// A feature that fails leaves the bodies as they were before it (a parameter change can
// break a feature without failing the command that made it): writing them would hand out
@@ -450,16 +421,16 @@ fn cmd_run(args: &[String]) -> Result<(), String> {
}
/// The session `run`, `eval` and `snapshot` start from: `--in` (a design or STEP file) with the
/// positional script run on top of it, or either one alone, with scripts run at `check`.
fn open(base: Option<&str>, path: Option<&String>, check: solidcraft_engine::schema::ParamCheck) -> Result<Session, String> {
/// positional script run on top of it, or either one alone.
fn open(base: Option<&str>, path: Option<&String>) -> Result<Session, String> {
match (base, path) {
(Some(b), Some(p)) => {
let mut s = load_checked(b, check)?;
run_script_warning(&mut s, p, &read_json(p)?)?;
let mut s = load(b)?;
s.run_script(&read_json(p)?).map_err(|e| e.to_string())?;
Ok(s)
}
(Some(b), None) => load_checked(b, check),
(None, Some(p)) => load_checked(p, check),
(Some(b), None) => load(b),
(None, Some(p)) => load(p),
(None, None) => Err(usage()),
}
}
@@ -502,7 +473,7 @@ fn timeline_ok(s: &Session) -> Result<(), String> {
fn cmd_eval(args: &[String]) -> Result<(), String> {
let json_out = json_out(args)?;
known_args("eval", args, &["--in", "--json-out"], &[], true)?;
let mut s = open(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off)?;
let mut s = open(flag(args, "--in"), positional(args))?;
let m = s.execute("inspect.measure", &json!({})).map_err(|e| e.to_string())?;
let d = s.execute("document.inspect", &json!({})).map_err(|e| e.to_string())?;
let out = json!({
@@ -596,7 +567,7 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> {
Some(x) => x.parse().ok().filter(|n| (16..=8192).contains(n)).ok_or_else(|| format!("{name} must be 16 to 8192 pixels, not `{x}`")),
};
let (w, h) = (size("--width", 1280)?, size("--height", 800)?);
let mut s = open(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off)?;
let mut s = open(flag(args, "--in"), positional(args))?;
// How the bodies are drawn and where the model is cut, through the commands the app's
// Appearance dialog and Section Analysis run (`preview`).
preview::apply(&mut s, &flags(args, "--body"), &flags(args, "--tool"), flag(args, "--section"))?;
@@ -720,8 +691,14 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
eprintln!("solidcraft mcp: the design's folder is left out because {why}; add it with --allow-path if you mean it");
}
}
// How a headless session treats calls that break a command's parameter contract.
let param_check = parse_param_check("mcp", args)?;
// How a headless session treats calls that break a command's parameter contract (docs/mcp.md).
let param_check = match flag(args, "--param-check") {
None if args.iter().any(|a| a == "--param-check") => return Err("mcp: --param-check wants off, warn or strict".into()),
None => solidcraft_engine::schema::ParamCheck::Off,
Some(v) => {
solidcraft_engine::schema::ParamCheck::parse(v).ok_or_else(|| format!("mcp: --param-check wants off, warn or strict, not `{v}`"))?
}
};
if param_check != solidcraft_engine::schema::ParamCheck::Off && flag(args, "--connect").is_some() {
eprintln!("solidcraft mcp: --param-check applies to headless sessions; calls to the app are not checked yet");
}
-44
View File
@@ -288,47 +288,3 @@ fn undoing_an_edit_after_opening_reuses_the_saved_results() {
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_file(format!("{}.bak", path.display()));
}
/// A design saved before body names were pinned (#6403) pins them as it opens, as its first
/// command would, and opening it is no change. That command pinned them as part of itself, so
/// undoing it went back to the unpinned design, which no evaluated result matched: the first
/// undo after opening from the command line evaluated every feature again (82-93 s in a
/// 5,484-feature design); `doc.open` pinned them after opening, which marked the design changed.
#[test]
fn a_design_saved_before_names_were_pinned_opens_pinned_and_unchanged() {
let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap();
let mut built = Session::default();
for c in (plate.script)()["commands"].as_array().unwrap() {
built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap();
}
let mut doc = built.design().into_owned();
for f in &mut doc.features {
f.body_names.clear();
}
doc.reserved_body_names.clear();
let unpinned = Session::new(doc);
let design = unpinned.design();
let saved = unpinned.model.saved(&design).unwrap();
let bytes = solidcraft_engine::io::write_design_container_with_cache(&design, solidcraft_engine::io::DesignCompression::Fast, None, Some(&saved))
.unwrap();
let path = temp("unpinned");
std::fs::write(&path, &bytes).unwrap();
let file = path.to_string_lossy().to_string();
// As the command line opens a design (`load`), and as the app does (`doc.open`).
let (doc, saved) = solidcraft_engine::io::read_design_file(&file, None::<fn(solidcraft_engine::io::DesignPreview)>).unwrap();
for (how, mut s) in [("opened_at", Session::opened_at(doc, saved.as_ref(), Some(&file))), ("doc.open", open(&path))] {
assert_eq!(s.model.last_recomputed, 0, "{how}: taken from the file");
assert!(s.doc.features.iter().any(|f| !f.body_names.is_empty()), "{how}: the names are pinned");
assert!(!s.is_dirty(), "{how}: opening is no change");
let read: Vec<Arc<ModelState>> = s.model.results.iter().map(|r| r.state.clone()).collect();
s.execute("solid.box", &json!({"length": 3, "width": 3, "height": 3, "operation": "new"})).unwrap();
// As in a large design, whose evaluation cache keeps only a few results: undo finds the
// results in the model itself or evaluates them again.
*s.model.cache.lock().unwrap() = Default::default();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.model.last_recomputed, 0, "{how}: the first undo evaluates nothing");
assert!(s.model.results.iter().zip(&read).all(|(r, st)| Arc::ptr_eq(&r.state, st)), "{how}: the states read from the file");
assert!(!s.is_dirty(), "{how}: undone to the design as opened");
}
let _ = std::fs::remove_file(&path);
}
-72
View File
@@ -496,78 +496,6 @@ fn timings_and_profile_report_each_command() {
assert!(String::from_utf8_lossy(&output.stderr).contains("--timings needs a script"));
}
/// #6921: `--param-check` checks a script's steps against their contracts on every path `run`
/// takes (a script alone, on an `--in` design or script, with `--results`, `--timings` or
/// `--profile`), and a warning reaches stderr even when a later step fails.
#[test]
fn param_check_reaches_every_script_run_takes() {
let dir = Scratch::new();
let typo = dir.0.join("typo.json");
let step = json!({"command": "solid.box", "params": {"length": 2, "width": 3, "height": 4, "operaton": "new"}});
std::fs::write(&typo, json!({"commands": [step.clone()]}).to_string()).unwrap();
let base = dir.0.join("base.solidcraft");
json_output(cli().arg("run").arg(dir.script()).arg("--save").arg(&base).output().unwrap());
let saved = dir.0.join("saved.solidcraft");
let start = dir.script();
let (typo, base, saved_arg, start) = (typo.to_str().unwrap(), base.to_str().unwrap(), saved.to_str().unwrap(), start.to_str().unwrap());
let paths = [&[][..], &["--in", base], &["--in", start], &["--results"], &["--timings"], &["--timings", "--profile"]];
let run = |level: Option<&str>, extra: &[&str]| {
std::fs::remove_file(&saved).ok();
let check = level.map(|l| ["--param-check", l]).into_iter().flatten();
cli().args(["run", typo, "--save", saved_arg]).args(check).args(extra).output().unwrap()
};
// Off, the default: the step runs as it always has, without a word.
let off = run(None, &[]);
assert!(off.status.success() && !String::from_utf8_lossy(&off.stderr).contains("operaton"), "{off:?}");
assert_eq!(body_count(&saved), 1);
// Warn: each path runs the step, saves, and reports it on stderr; `--results` keeps it too.
for extra in paths {
let output = run(Some("warn"), extra);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{extra:?}: {stderr}");
assert!(stderr.contains("step 1: unknown key `operaton`; did you mean `operation`?"), "{extra:?}: {stderr}");
assert!(saved.exists(), "{extra:?}");
if extra == ["--results"] {
let results: Value = serde_json::from_slice(&output.stdout).unwrap();
assert!(results[0]["param_warnings"][0].as_str().is_some_and(|w| w.contains("operaton")), "{results}");
}
}
// Strict: on each path the run stops at the step, and nothing is written.
for extra in paths {
let output = run(Some("strict"), extra);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{extra:?}: {stderr}");
assert!(stderr.contains("unknown key `operaton`"), "{extra:?}: {stderr}");
assert!(!saved.exists(), "{extra:?}");
}
// Warn, with a later step that fails: the run fails, and the first step's warning is still
// reported, timed or not.
let failing = dir.0.join("failing.json");
let fail = json!({"command": "solid.extrude", "params": {"sketch": "Nope"}});
std::fs::write(&failing, json!({"commands": [step, fail]}).to_string()).unwrap();
for extra in [&[][..], &["--timings"]] {
let output = cli().arg("run").arg(&failing).args(["--param-check", "warn"]).args(extra).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{extra:?}: {stderr}");
assert!(stderr.contains("step 1: unknown key `operaton`") && stderr.contains("no sketch `Nope`"), "{extra:?}: {stderr}");
}
// A level it doesn't know and a missing value fail.
for (bad, says) in [
(&["--param-check", "loud"][..], "--param-check wants off, warn or strict, not `loud`"),
(&["--param-check"], "run: --param-check wants off, warn or strict"),
] {
let output = cli().args(["run", typo]).args(bad).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{bad:?}: {stderr}");
assert!(stderr.contains(says), "{bad:?}: {stderr}");
}
}
fn render_setup_script(dir: &Scratch, job: Value) -> PathBuf {
let path = dir.0.join("render.json");
std::fs::write(
+1 -1
View File
@@ -34,7 +34,7 @@ serde_json = { workspace = true }
web-sys = { version = "0.3", features = [
"Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager",
"FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream",
"WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", "StorageEvent",
"WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage",
"IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode",
"Headers", "ReadableStream", "ReadableStreamDefaultReader",
"BeforeUnloadEvent", "Event", "EventTarget", "KeyboardEvent", "Response", "FormData", "RequestInit", "MediaQueryList", "Gamepad", "Performance",
+5 -131
View File
@@ -119,43 +119,6 @@ fn closes_design(key: &str, command: bool, shift: bool, alt: bool, design_shown:
design_shown && command && !shift && !alt && key.eq_ignore_ascii_case("w")
}
/// The settings a tab last wrote to the browser's storage, or loaded from another tab (#8644).
/// Every open tab of the app shares that storage, and eframe saves each tab's whole copy every
/// 30 s and when the page loses focus, so a tab still holding old settings put them back over a
/// change made in another. A change is now written in the frame it is made, and the other tabs
/// load it ([`settings_written`]).
#[cfg(any(target_arch = "wasm32", test))]
#[derive(Default, Debug)]
struct PrefsWriter {
written: Option<String>,
}
#[cfg(any(target_arch = "wasm32", test))]
impl PrefsWriter {
/// `prefs` if they are not the settings written or loaded last (they count as written from
/// now on).
fn take(&mut self, prefs: String) -> Option<String> {
if self.written.as_deref() == Some(prefs.as_str()) {
return None;
}
self.written = Some(prefs.clone());
Some(prefs)
}
/// The settings the tab holds after loading another tab's: the tab doesn't write them back.
fn loaded(&mut self, prefs: String) {
self.written = Some(prefs);
}
}
/// The settings another tab wrote, from a `storage` event (the browser sends one to every other
/// tab of the page when one tab writes). Other keys, and settings taken away (clearing the site's
/// data), leave this tab's settings as they are.
#[cfg(any(target_arch = "wasm32", test))]
fn settings_written(key: Option<&str>, value: Option<String>) -> Option<String> {
value.filter(|_| key == Some(solidcraft_ui_egui::prefs::STORAGE_KEY))
}
#[cfg(target_arch = "wasm32")]
mod web {
use std::rc::Rc;
@@ -254,24 +217,6 @@ mod web {
on_key.forget();
}
/// Settings another tab wrote, waiting for this tab's next frame (#8644).
type PrefsInbox = Rc<std::cell::Cell<Option<String>>>;
/// Settings another tab of the app writes go to `inbox`, and this tab draws a frame, which
/// loads them.
fn hear_settings_from_other_tabs(window: &web_sys::Window, ctx: &egui::Context, inbox: PrefsInbox) {
let ctx = ctx.clone();
let on_storage = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::StorageEvent)>::new(move |e: web_sys::StorageEvent| {
if let Some(prefs) = crate::settings_written(e.key().as_deref(), e.new_value()) {
inbox.set(Some(prefs));
ctx.request_repaint();
}
});
let _ = window.add_event_listener_with_callback("storage", on_storage.as_ref().unchecked_ref());
// The listener lives as long as the page.
on_storage.forget();
}
const JAPANESE_FONT_PATH: &str = "./fonts/BIZUDPGothic-Regular.ttf";
type FontLoadResult = Rc<std::cell::RefCell<Option<Result<Vec<u8>, String>>>>;
@@ -301,48 +246,9 @@ mod web {
font_language: String,
space_mouse: SpaceMouse,
wheel_gestures: solidcraft_ui_egui::WebWheelGestures,
/// The settings this tab wrote or loaded last, and those another tab wrote since (#8644).
prefs_writer: crate::PrefsWriter,
other_tab_prefs: PrefsInbox,
}
impl Shell {
/// The settings as they are kept between visits: with the user's own language, not a
/// session-only English fallback.
fn persisted_prefs(&mut self) -> String {
let saved = self.font.persisted_language(&self.app.preferences.language).to_owned();
let live = std::mem::replace(&mut self.app.preferences.language, saved);
let prefs = self.app.prefs();
self.app.preferences.language = live;
prefs
}
/// A settings change goes to the browser's storage in the frame it is made, and from
/// there to the other open tabs (#8644). Input is what changes settings, so a frame
/// without any is skipped; eframe's own save still catches anything else.
fn store_prefs(&mut self, ctx: &egui::Context) {
if !self.launch.persists() || ctx.input(|i| i.events.is_empty()) {
return;
}
let prefs = self.persisted_prefs();
let Some(prefs) = self.prefs_writer.take(prefs) else { return };
let stored =
web_sys::window().and_then(|w| w.local_storage().ok().flatten()).map(|s| s.set_item(solidcraft_ui_egui::prefs::STORAGE_KEY, &prefs));
if !matches!(stored, Some(Ok(()))) {
log::warn!("settings: the browser's storage did not take them; they are saved again later");
self.prefs_writer = crate::PrefsWriter::default();
}
}
/// Settings another tab wrote replace this tab's, so this tab's own saves keep them
/// instead of putting its older copy back (#8644).
fn load_other_tabs_prefs(&mut self) {
let Some(prefs) = self.other_tab_prefs.take() else { return };
self.app.load_prefs(&prefs);
let held = self.persisted_prefs();
self.prefs_writer.loaded(held);
}
/// Files from the computer, writes to store, messages and the autosave.
fn files_tick(&mut self, ctx: &egui::Context) {
if !self.launch.persists() {
@@ -741,8 +647,6 @@ mod web {
impl eframe::App for Shell {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// First: a language another tab chose fetches its font this frame.
self.load_other_tabs_prefs();
self.tick_font(ctx);
self.app.logic(ctx);
self.api.poll();
@@ -785,7 +689,6 @@ mod web {
self.recovery_prompt(&ctx);
}
self.watch_text_for_font(&ctx);
self.store_prefs(&ctx);
}
fn persist_egui_memory(&self) -> bool {
self.launch.persists()
@@ -794,8 +697,11 @@ mod web {
if !self.launch.persists() {
return;
}
let prefs = self.persisted_prefs();
storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, prefs);
// Persist the user's own language, not a session-only English fallback.
let saved = self.font.persisted_language(&self.app.preferences.language).to_owned();
let live = std::mem::replace(&mut self.app.preferences.language, saved);
storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, self.app.prefs());
self.app.preferences.language = live;
}
}
@@ -916,12 +822,6 @@ mod web {
let (sender, receiver) = std::sync::mpsc::channel();
let mut app = SolveApp::new(Session::default(), services).with_control(receiver);
app.embedded = launch.embed;
// Listening before reading: settings another tab writes from now on are
// newer than those read here.
let other_tab_prefs = PrefsInbox::default();
if launch.persists() {
hear_settings_from_other_tabs(&window, &cc.egui_ctx, other_tab_prefs.clone());
}
if launch.persists() && let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(k))) {
app.load_prefs(&p);
}
@@ -965,8 +865,6 @@ mod web {
font_language,
space_mouse: SpaceMouse::default(),
wheel_gestures: solidcraft_ui_egui::WebWheelGestures::default(),
prefs_writer: crate::PrefsWriter::default(),
other_tab_prefs,
}))
}),
)
@@ -1103,28 +1001,4 @@ mod tests {
assert!(!closes_design("w", false, false, false, true));
assert!(!closes_design("s", true, false, false, true));
}
/// A tab writes its settings when they change, and not again while they stay the same; the
/// settings it loaded from another tab aren't written back (#8644).
#[test]
fn changed_settings_are_written_once_and_loaded_ones_not_at_all() {
let mut writer = PrefsWriter::default();
assert_eq!(writer.take(r#"{"a":1}"#.into()).as_deref(), Some(r#"{"a":1}"#), "the first settings are written");
assert_eq!(writer.take(r#"{"a":1}"#.into()), None, "the same settings are not written again");
assert_eq!(writer.take(r#"{"a":2}"#.into()).as_deref(), Some(r#"{"a":2}"#), "a change is written at once");
writer.loaded(r#"{"a":3}"#.into());
assert_eq!(writer.take(r#"{"a":3}"#.into()), None, "settings from another tab are not written back");
assert_eq!(writer.take(r#"{"a":4}"#.into()).as_deref(), Some(r#"{"a":4}"#), "this tab's next change is written");
}
/// Only the settings another tab wrote are loaded: not other keys, and not settings taken
/// away by clearing the site's data (#8644).
#[test]
fn only_settings_another_tab_wrote_are_loaded() {
let key = solidcraft_ui_egui::prefs::STORAGE_KEY;
assert_eq!(settings_written(Some(key), Some("{}".into())).as_deref(), Some("{}"));
assert_eq!(settings_written(Some("solidcraft.webgl"), Some("1".into())), None);
assert_eq!(settings_written(Some(key), None), None, "removed settings leave this tab's");
assert_eq!(settings_written(None, None), None, "clearing all storage leaves this tab's settings");
}
}
+1 -1
View File
@@ -188,7 +188,7 @@ surface = [
sketch = [
"arc3", "arc_center", "arc_slot", "arc_slot_center", "arc_tangent",
"blend", "circle", "circle2", "circle3", "circle_tt",
"circle_ttt", "conic", "constrainer", "dimension", "ellipse", "equation_curve",
"circle_ttt", "conic", "constrainer", "dimension", "ellipse",
"extend", "finish", "fit_section", "include",
"intersect", "intersection_curve", "iso_curve", "line", "line_mid",
"offset", "offset_two_sides", "offset_symmetric", "point", "polygon", "polygon_circumscribed", "polygon_edge",
@@ -95,7 +95,6 @@ edit false
ellipse false
emboss false
environment_map false
equation_curve false
error false
explode false
export false
@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Equation curve</title>
<path d="M12 8L12 56M6 32L58 32" fill="none" stroke="#6f879c" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M12 32C15.42 24.83 18.72 18 22.5 18C26.28 18 29.58 24.83 33 32C36.42 39.17 39.72 46 43.5 46C47.28 46 50.58 39.17 54 32" fill="none" stroke="#236ead" stroke-width="4.25" stroke-linejoin="round" stroke-linecap="round"/>
<circle cx="12" cy="32" r="5.8" fill="#ffffff"/>
<circle cx="12" cy="32" r="3.4" fill="#236ead"/>
<circle cx="54" cy="32" r="5.8" fill="#ffffff"/>
<circle cx="54" cy="32" r="3.4" fill="#236ead"/>
</svg>

Before

Width:  |  Height:  |  Size: 666 B

+4624 -4692
View File
File diff suppressed because it is too large. Load diff
+4310 -4310
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+3910 -3974
View File
File diff suppressed because it is too large. Load diff
+4624 -4692
View File
File diff suppressed because it is too large. Load diff
+3658 -3659
View File
File diff suppressed because it is too large. Load diff
+4314 -4317
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4624 -4692
View File
File diff suppressed because it is too large. Load diff
+4310 -4310
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4295 -4296
View File
File diff suppressed because it is too large. Load diff
+4624 -4692
View File
File diff suppressed because it is too large. Load diff
+3681 -3718
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4291 -4294
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,56 @@
{
"en": {
"render.cpu_glass_continue": "Continue reflections",
"render.cpu_glass_help": "Standard uses bounded paths and may darken reflective glass. Continue reflections stops with an error if a supported optical limit is reached. Selected opaque reflections and unsupported glass shapes remain unavailable.",
"render.cpu_glass_label": "Glass rendering",
"render.cpu_glass_standard": "Standard"
},
"ar": {
"render.cpu_glass_continue": "متابعة الانعكاسات",
"render.cpu_glass_help": "يستخدم الوضع القياسي مسارات ضوء محدودة، وقد يجعل الزجاج العاكس أغمق. يوقف خيار «متابعة الانعكاسات» التصيير مع ظهور خطأ عند بلوغ أحد الحدود البصرية المدعومة. تظل الانعكاسات المحددة على الأجسام المعتمة وأشكال الزجاج غير المدعومة غير متاحة.",
"render.cpu_glass_label": "تصيير الزجاج",
"render.cpu_glass_standard": "قياسي"
},
"de": {
"render.cpu_glass_continue": "Reflexionen fortsetzen",
"render.cpu_glass_help": "Standard begrenzt die Lichtwege und kann reflektierendes Glas abdunkeln. Reflexionen fortsetzen stoppt das Rendering mit einem Fehler, wenn eine unterstützte optische Grenze erreicht wird. Ausgewählte opake Reflexionen und nicht unterstützte Glasformen bleiben nicht verfügbar.",
"render.cpu_glass_label": "Glasdarstellung",
"render.cpu_glass_standard": "Standard"
},
"es": {
"render.cpu_glass_continue": "Continuar reflejos",
"render.cpu_glass_help": "Estándar limita los recorridos y puede oscurecer el vidrio reflectante. Continuar reflejos detiene el render con un error si alcanza un límite óptico admitido. Los reflejos opacos seleccionados y las formas de vidrio no compatibles siguen sin estar disponibles.",
"render.cpu_glass_label": "Render de vidrio",
"render.cpu_glass_standard": "Estándar"
},
"he": {
"render.cpu_glass_continue": "המשך השתקפויות",
"render.cpu_glass_help": "המצב הרגיל מגביל את מסלולי האור ועלול להכהות זכוכית מחזירת אור. האפשרות «המשך השתקפויות» עוצרת את הרינדור עם שגיאה כאשר מגיעים לאחת המגבלות האופטיות הנתמכות. השתקפויות נבחרות על גופים אטומים וצורות זכוכית שאינן נתמכות נשארות לא זמינות.",
"render.cpu_glass_label": "רינדור זכוכית",
"render.cpu_glass_standard": "רגיל"
},
"ja": {
"render.cpu_glass_continue": "反射を継続",
"render.cpu_glass_help": "標準では光路を制限するため、反射するガラスが暗くなる場合があります。反射を継続する設定では、対応する光学的な上限に達するとエラーでレンダリングを停止します。選択された不透明面の反射や未対応のガラス形状は引き続き使用できません。",
"render.cpu_glass_label": "ガラスの描画",
"render.cpu_glass_standard": "標準"
},
"ko": {
"render.cpu_glass_continue": "반사 계속",
"render.cpu_glass_help": "표준은 광선 경로를 제한하므로 반사 유리가 어둡게 보일 수 있습니다. 반사 계속은 지원되는 광학 한계에 도달하면 오류와 함께 렌더링을 중지합니다. 선택한 불투명 표면 반사와 지원되지 않는 유리 형상은 계속 사용할 수 없습니다.",
"render.cpu_glass_label": "유리 렌더링",
"render.cpu_glass_standard": "표준"
},
"vi": {
"render.cpu_glass_continue": "Tiếp tục phản xạ",
"render.cpu_glass_help": "Chế độ tiêu chuẩn giới hạn đường truyền ánh sáng và có thể làm kính phản xạ trông tối hơn. Tùy chọn Tiếp tục phản xạ dừng kết xuất kèm lỗi khi đạt một giới hạn quang học được hỗ trợ. Các phản xạ đã chọn trên vật thể đục và các hình dạng kính không được hỗ trợ vẫn không khả dụng.",
"render.cpu_glass_label": "Kết xuất kính",
"render.cpu_glass_standard": "Tiêu chuẩn"
},
"zh": {
"render.cpu_glass_continue": "继续反射",
"render.cpu_glass_help": "标准模式限制光线路径,可能使反射玻璃变暗。继续反射模式在达到支持的光学限制时会报错并停止渲染。所选不透明表面反射和不支持的玻璃形状仍不可用。",
"render.cpu_glass_label": "玻璃渲染",
"render.cpu_glass_standard": "标准"
}
}
@@ -0,0 +1,47 @@
{
"en": {
"render.cpu_directional_shadow_help": "CPU optics are temporary and require certified sheets or axis-aligned boxes with opaque body and face appearances. Directional transmitted shadows require global shadows on and all active assignments to agree. Mixed choices, nesting, environment lighting and local lights are unsupported in that mode. This is straight RGB visibility, not refracted shadows or caustics. Subsurface, coats and maps remain unsupported; fixed and progressive sampling retain finite-depth limits.",
"render.cpu_shadow_conflict": "The global directional transmission option conflicts with an optical assignment whose transmitted shadows are off. No authored option was changed.",
"render.cpu_shadow_mixed": "CPU uses one transmitted-shadow switch for all active optical assignments. Mixed on/off choices cannot be represented and have been preserved."
},
"es": {
"render.cpu_directional_shadow_help": "La óptica CPU es temporal y requiere láminas o cajas alineadas con los ejes certificadas, con aspectos opacos de cuerpo y caras. Las sombras transmitidas direccionales requieren sombras globales activadas y que todas las asignaciones activas coincidan. Ese modo no admite mezclas, nesting, iluminación de entorno ni luces locales. Es visibilidad RGB recta, sin sombras refractadas ni cáusticas. La dispersión subsuperficial, las capas y los mapas siguen sin admitirse; el muestreo fijo y progresivo conserva los límites de profundidad.",
"render.cpu_shadow_conflict": "La opción global de transmisión direccional contradice una asignación óptica con sombras transmitidas desactivadas. No se ha cambiado ninguna opción definida.",
"render.cpu_shadow_mixed": "CPU usa un único control de sombras transmitidas para todas las asignaciones ópticas activas. No puede representar opciones activadas y desactivadas mezcladas; se han conservado."
},
"de": {
"render.cpu_directional_shadow_help": "CPU-Optik ist temporär und erfordert zertifizierte Scheiben oder achsenparallele Quader mit opaken Körper- und Flächenerscheinungen. Gerichtete durchgelassene Schatten erfordern globale Schatten und übereinstimmende aktive Zuweisungen. Gemischte Optionen, Verschachtelung, Umgebungslicht und lokale Lichter sind in diesem Modus nicht unterstützt. Dies ist geradlinige RGB-Sichtbarkeit, keine gebrochenen Schatten oder Kaustiken. Subsurface-Streuung, Beschichtungen und Maps bleiben nicht unterstützt; feste und progressive Abtastung behalten die endliche Tiefengrenze.",
"render.cpu_shadow_conflict": "Die globale gerichtete Transmission widerspricht einer optischen Zuweisung mit ausgeschalteten durchgelassenen Schatten. Keine festgelegte Option wurde geändert.",
"render.cpu_shadow_mixed": "CPU verwendet einen Schalter für durchgelassene Schatten aller aktiven optischen Zuweisungen. Gemischte Ein-/Aus-Werte sind nicht darstellbar und wurden beibehalten."
},
"ko": {
"render.cpu_directional_shadow_help": "CPU 광학은 임시 설정이며 불투명한 바디와 면 외관을 가진 인증된 판 또는 축 정렬 상자가 필요합니다. 방향성 투과 그림자는 전역 그림자가 켜져 있고 모든 활성 할당의 설정이 같아야 합니다. 이 모드는 혼합 설정, 중첩, 환경 조명 및 로컬 광원을 지원하지 않습니다. 이는 직선 RGB 가시성이며 굴절 그림자나 코스틱이 아닙니다. 표면하 산란, 코팅 및 맵은 계속 지원하지 않으며 고정 및 점진적 샘플링은 유한 깊이 제한을 유지합니다.",
"render.cpu_shadow_conflict": "전역 방향성 투과 옵션이 투과 그림자가 꺼진 광학 할당과 충돌합니다. 작성된 옵션은 변경되지 않았습니다.",
"render.cpu_shadow_mixed": "CPU는 모든 활성 광학 할당에 하나의 투과 그림자 스위치를 사용합니다. 켜짐과 꺼짐이 섞인 설정은 표현할 수 없으며 그대로 보존되었습니다."
},
"ar": {
"render.cpu_directional_shadow_help": "بصريات CPU مؤقتة وتتطلب صفائح أو صناديق محاذية للمحاور اجتازت التحقق، بمظاهر معتمة للجسم والأوجه. تتطلب الظلال النافذة الاتجاهية تفعيل الظلال العامة وتطابق كل التعيينات النشطة. لا يدعم هذا الوضع الخيارات المختلطة أو التداخل أو إضاءة البيئة أو الأضواء المحلية. هذه رؤية RGB مستقيمة وليست ظلالًا منكسرة أو كاوستيك. يبقى التشتت تحت السطحي والطلاءات والخرائط غير مدعوم، وتبقى حدود العمق المحدودة لأخذ العينات الثابت والتدريجي.",
"render.cpu_shadow_conflict": "يتعارض خيار النفاذ الاتجاهي العام مع تعيين بصري تكون ظلاله النافذة معطلة. لم يتغير أي خيار محدد.",
"render.cpu_shadow_mixed": "يستخدم CPU مفتاح ظلال نافذة واحدًا لجميع التعيينات البصرية النشطة. لا يمكن تمثيل خليط من التفعيل والتعطيل، وقد تم الاحتفاظ بالخيارات."
},
"he": {
"render.cpu_directional_shadow_help": "אופטיקת CPU היא זמנית ודורשת יריעות או תיבות מיושרות לצירים שעברו אימות, עם מראה אטום של הגוף והפאות. צללים מועברים כיווניים דורשים צללים כלליים פעילים ואחידות בכל ההקצאות הפעילות. מצב זה אינו תומך בערכים מעורבים, קינון, תאורת סביבה או אורות מקומיים. זו נראות RGB בקו ישר, ללא צללים נשברים או קאוסטיקה. פיזור תת-משטחי, ציפויים ומפות עדיין אינם נתמכים; דגימה קבועה והדרגתית שומרות על מגבלות העומק הסופי.",
"render.cpu_shadow_conflict": "אפשרות ההעברה הכיוונית הכללית סותרת הקצאה אופטית שהצללים המועברים שלה כבויים. שום אפשרות שנקבעה לא שונתה.",
"render.cpu_shadow_mixed": "CPU משתמש במתג צללים מועברים אחד לכל ההקצאות האופטיות הפעילות. לא ניתן לייצג ערכים מעורבים של פעיל וכבוי, והם נשמרו."
},
"ja": {
"render.cpu_directional_shadow_help": "CPU 光学設定は一時的で、不透明なボディと面の外観を持つ認証済みの薄板または軸に平行なボックスが必要です。平行光源の透過シャドウには全体のシャドウを有効にし、すべての有効な割り当ての設定を一致させる必要があります。このモードでは混在設定、入れ子、環境光、ローカルライトは非対応です。これは直線上の RGB 可視性であり、屈折シャドウやコースティクスではありません。表面下散乱、コート、マップは引き続き非対応で、固定およびプログレッシブサンプリングでも有限深度制限は残ります。",
"render.cpu_shadow_conflict": "全体の平行光透過オプションが、透過シャドウを無効にした光学割り当てと競合しています。設定したオプションは変更されていません。",
"render.cpu_shadow_mixed": "CPU はすべての有効な光学割り当てに単一の透過シャドウスイッチを使用します。有効と無効の混在は表現できないため、その設定を保持しています。"
},
"vi": {
"render.cpu_directional_shadow_help": "Quang học CPU là tạm thời và cần tấm hoặc hộp song song các trục đã được kiểm chứng, với diện mạo thân và mặt đục. Bóng truyền qua từ đèn định hướng cần bật bóng toàn cục và mọi phép gán đang bật phải cùng lựa chọn. Chế độ này không hỗ trợ lựa chọn lẫn bật/tắt, lồng nhau, ánh sáng môi trường hoặc đèn cục bộ. Đây là độ nhìn thấy RGB theo đường thẳng, không phải bóng khúc xạ hay caustic. Tán xạ dưới bề mặt, lớp phủ và bản đồ vẫn không được hỗ trợ; lấy mẫu cố định và lũy tiến vẫn có giới hạn độ sâu hữu hạn.",
"render.cpu_shadow_conflict": "Tùy chọn truyền sáng định hướng toàn cục xung đột với phép gán quang học có bóng truyền qua đang tắt. Không thay đổi tùy chọn đã soạn nào.",
"render.cpu_shadow_mixed": "CPU dùng một công tắc bóng truyền qua cho tất cả phép gán quang học đang bật. Không thể biểu diễn lựa chọn lẫn bật và tắt; các lựa chọn đã được giữ nguyên."
},
"zh": {
"render.cpu_directional_shadow_help": "CPU 光学设置是临时的,需要通过认证的薄片或轴对齐盒体,以及不透明的实体和面外观。方向光透射阴影要求开启全局阴影,并且所有启用的分配采用相同设置。此模式不支持混合开关、嵌套、环境照明或局部光源。这是直线 RGB 可见性,并非折射阴影或焦散。次表面散射、涂层和贴图仍不支持;固定和渐进采样仍保留有限深度限制。",
"render.cpu_shadow_conflict": "全局方向光透射选项与关闭透射阴影的光学分配冲突。未更改任何已设置的选项。",
"render.cpu_shadow_mixed": "CPU 对所有启用的光学分配使用一个透射阴影开关。无法表示开启和关闭混合的设置,已保留这些设置。"
}
}
@@ -0,0 +1,29 @@
{
"en": {
"render.cpu_optics_certification": "CPU Check and Start validate captured identity, opaque body and face appearances, and the requested sheet or axis-aligned box certificate. Choosing a boundary does not certify geometry. Start rechecks the capture; passing Check does not guarantee later admission."
},
"es": {
"render.cpu_optics_certification": "Comprobar e Iniciar en CPU validan la identidad capturada, los aspectos opacos del cuerpo y sus caras, y el certificado de lámina o caja alineada con los ejes solicitado. Elegir una frontera no certifica la geometría. Iniciar comprueba de nuevo la captura; superar Comprobar no garantiza una admisión posterior."
},
"de": {
"render.cpu_optics_certification": "Prüfen und Starten auf der CPU validieren die erfasste Identität, opake Körper- und Flächenerscheinungen sowie das angeforderte Zertifikat für Scheiben oder achsenparallele Quader. Die Wahl einer Grenze zertifiziert keine Geometrie. Starten prüft die Erfassung erneut; erfolgreiches Prüfen garantiert keine spätere Zulassung."
},
"ko": {
"render.cpu_optics_certification": "CPU의 확인과 시작은 캡처한 식별 정보, 불투명한 바디와 면 외관, 요청한 판 또는 축 정렬 상자의 인증을 검증합니다. 경계를 선택하는 것만으로 형상이 인증되지는 않습니다. 시작 시 캡처를 다시 확인하며, 확인에 성공해도 이후 승인이 보장되지는 않습니다."
},
"ar": {
"render.cpu_optics_certification": "يتحقق الفحص والبدء على CPU من الهوية الملتقطة ومظاهر الجسم والأوجه المعتمة وشهادة الصفيحة أو الصندوق المحاذي للمحاور المطلوبة. اختيار حد لا يثبت صلاحية الهندسة. يعيد البدء فحص اللقطة؛ نجاح الفحص لا يضمن القبول لاحقًا."
},
"he": {
"render.cpu_optics_certification": "בדיקה והתחלה ב-CPU מאמתות את הזהות שנלכדה, מראה אטום של הגוף והפאות ואת האישור המבוקש ליריעה או לתיבה מיושרת לצירים. בחירת גבול אינה מאשרת את הגאומטריה. התחלה בודקת שוב את הלכידה; הצלחה בבדיקה אינה מבטיחה אישור מאוחר יותר."
},
"ja": {
"render.cpu_optics_certification": "CPU の確認と開始では、取得した識別情報、不透明なボディと面の外観、要求された薄板または軸に平行なボックスの認証を検証します。境界の選択だけでは形状は認証されません。開始時に取得内容を再確認するため、確認の成功は後の受け入れを保証しません。"
},
"vi": {
"render.cpu_optics_certification": "Kiểm tra và Bắt đầu trên CPU xác thực danh tính đã chụp, diện mạo thân và mặt đục, cùng chứng nhận tấm hoặc hộp song song các trục được yêu cầu. Chọn biên không chứng nhận hình học. Bắt đầu kiểm tra lại bản chụp; vượt qua Kiểm tra không bảo đảm được chấp nhận về sau."
},
"zh": {
"render.cpu_optics_certification": "CPU 的检查和开始会验证捕获的身份、不透明的实体和面外观,以及请求的薄片或轴对齐盒体认证。选择边界本身并不能认证几何体。开始时会重新检查捕获内容;通过检查并不保证之后仍能获准执行。"
}
}
@@ -0,0 +1,110 @@
{
"en": {
"render.cpu_optics_boundary": "CPU requires an explicit Thin sheet or Box boundary. The captured geometry must pass certification.",
"render.cpu_optics_conflict": "CPU optical assignments cannot replace existing dielectric overrides.",
"render.cpu_optics_enable": "Use these optics on CPU",
"render.cpu_optics_explicit": "Review this assignment and explicitly enable its CPU optical route.",
"render.cpu_optics_fixed": "The installed CPU transport cannot admit this optical sampling request.",
"render.cpu_optics_help": "Temporary CPU optics: fixed or progressive sampling, opaque body and face appearances, certified sheets or axis-aligned boxes. Transmitted shadows, subsurface, coats and maps are unsupported. Box nesting needs explicit opt-in and certification. Accumulation retains the finite-depth transport limits.",
"render.cpu_optics_limit": "CPU supports at most eight optical body assignments.",
"render.cpu_optics_request": "CPU optics require the typed CPU image request and its existing options.",
"render.cpu_optics_saved": "Saved GPU optics cannot be mixed with temporary CPU optical assignments.",
"render.cpu_optics_unsupported": "This CPU route supports glass without transmitted shadows, subsurface, coats or maps. Review the authored options; they have been preserved."
},
"es": {
"render.cpu_optics_boundary": "CPU requiere elegir explícitamente Lámina fina o Caja. La geometría capturada debe superar la certificación.",
"render.cpu_optics_conflict": "Las asignaciones ópticas CPU no pueden sustituir las modificaciones dieléctricas existentes.",
"render.cpu_optics_enable": "Usar esta óptica en CPU",
"render.cpu_optics_explicit": "Revisa esta asignación y activa explícitamente su ruta óptica CPU.",
"render.cpu_optics_fixed": "El transporte CPU instalado no puede admitir esta solicitud de muestreo óptico.",
"render.cpu_optics_help": "Óptica CPU temporal: muestreo fijo o progresivo, aspectos opacos de cuerpo y caras, láminas o cajas alineadas con los ejes certificadas. No admite sombras transmitidas, dispersión subsuperficial, capas ni mapas. Las cajas anidadas requieren activación explícita y certificación. La acumulación conserva los límites de profundidad del transporte.",
"render.cpu_optics_limit": "CPU admite como máximo ocho asignaciones ópticas de cuerpo.",
"render.cpu_optics_request": "La óptica CPU requiere la solicitud de imagen CPU tipada y sus opciones existentes.",
"render.cpu_optics_saved": "La óptica GPU guardada no se puede mezclar con asignaciones ópticas CPU temporales.",
"render.cpu_optics_unsupported": "Esta ruta CPU admite vidrio sin sombras transmitidas, dispersión subsuperficial, capas ni mapas. Revisa las opciones definidas; se han conservado."
},
"de": {
"render.cpu_optics_boundary": "CPU erfordert die ausdrückliche Wahl von Dünner Scheibe oder Quader. Die erfasste Geometrie muss zertifiziert werden.",
"render.cpu_optics_conflict": "Optische CPU-Zuweisungen können vorhandene dielektrische Überschreibungen nicht ersetzen.",
"render.cpu_optics_enable": "Diese Optik auf der CPU verwenden",
"render.cpu_optics_explicit": "Prüfen Sie diese Zuweisung und aktivieren Sie ihren optischen CPU-Pfad ausdrücklich.",
"render.cpu_optics_fixed": "Der installierte CPU-Transport kann diese optische Abtastanforderung nicht zulassen.",
"render.cpu_optics_help": "Temporäre CPU-Optik: feste oder progressive Abtastung, opake Körper- und Flächenerscheinungen, zertifizierte Scheiben oder achsenparallele Quader. Durchgelassene Schatten, Subsurface-Streuung, Beschichtungen und Maps werden nicht unterstützt. Verschachtelte Quader erfordern ausdrückliche Aktivierung und Zertifizierung. Die Akkumulation behält die endliche Transporttiefe bei.",
"render.cpu_optics_limit": "CPU unterstützt höchstens acht optische Körperzuweisungen.",
"render.cpu_optics_request": "CPU-Optik erfordert die typisierte CPU-Bildanforderung und deren vorhandene Optionen.",
"render.cpu_optics_saved": "Gespeicherte GPU-Optik kann nicht mit temporären optischen CPU-Zuweisungen kombiniert werden.",
"render.cpu_optics_unsupported": "Dieser CPU-Pfad unterstützt Glas ohne durchgelassene Schatten, Subsurface-Streuung, Beschichtungen oder Maps. Prüfen Sie die unverändert erhaltenen Optionen."
},
"ko": {
"render.cpu_optics_boundary": "CPU에서는 얇은 판 또는 상자 경계를 명시적으로 선택해야 합니다. 캡처한 형상은 인증을 통과해야 합니다.",
"render.cpu_optics_conflict": "CPU 광학 할당은 기존 유전체 재정의를 대체할 수 없습니다.",
"render.cpu_optics_enable": "이 광학 설정을 CPU에서 사용",
"render.cpu_optics_explicit": "이 할당을 검토하고 CPU 광학 경로를 명시적으로 활성화하세요.",
"render.cpu_optics_fixed": "설치된 CPU 전송 모델은 이 광학 샘플링 요청을 허용할 수 없습니다.",
"render.cpu_optics_help": "임시 CPU 광학: 고정 또는 점진적 샘플링, 불투명한 바디와 면 외관, 인증된 판 또는 축 정렬 상자. 투과 그림자, 표면하 산란, 코팅 및 맵은 지원하지 않습니다. 중첩 상자는 명시적 활성화와 인증이 필요합니다. 누적해도 전송의 유한 깊이 제한은 유지됩니다.",
"render.cpu_optics_limit": "CPU는 최대 8개의 광학 바디 할당을 지원합니다.",
"render.cpu_optics_request": "CPU 광학에는 형식화된 CPU 이미지 요청과 기존 옵션이 필요합니다.",
"render.cpu_optics_saved": "저장된 GPU 광학을 임시 CPU 광학 할당과 혼합할 수 없습니다.",
"render.cpu_optics_unsupported": "이 CPU 경로는 투과 그림자, 표면하 산란, 코팅 및 맵이 없는 유리를 지원합니다. 작성된 옵션을 검토하세요. 옵션은 그대로 보존되었습니다."
},
"ar": {
"render.cpu_optics_boundary": "يتطلب CPU اختيار حد صفيحة رقيقة أو صندوق صراحةً. يجب أن تجتاز الهندسة الملتقطة التحقق.",
"render.cpu_optics_conflict": "لا يمكن لتعيينات البصريات على CPU استبدال تجاوزات العوازل الموجودة.",
"render.cpu_optics_enable": "استخدام هذه البصريات على CPU",
"render.cpu_optics_explicit": "راجع هذا التعيين وفعّل مساره البصري على CPU صراحةً.",
"render.cpu_optics_fixed": "لا يمكن لنموذج النقل المثبت على CPU قبول طلب أخذ العينات البصري هذا.",
"render.cpu_optics_help": "بصريات CPU مؤقتة: أخذ عينات ثابت أو تدريجي، ومظاهر معتمة للجسم والأوجه، وصفائح أو صناديق محاذية للمحاور اجتازت التحقق. الظلال النافذة والتشتت تحت السطحي والطلاءات والخرائط غير مدعومة. تتطلب الصناديق المتداخلة تفعيلًا صريحًا والتحقق. يبقى عمق النقل محدودًا حتى مع التراكم.",
"render.cpu_optics_limit": "يدعم CPU ثمانية تعيينات بصرية للأجسام كحد أقصى.",
"render.cpu_optics_request": "تتطلب بصريات CPU طلب صورة CPU محدد النوع وخياراته الموجودة.",
"render.cpu_optics_saved": "لا يمكن خلط بصريات GPU المحفوظة مع تعيينات بصريات CPU المؤقتة.",
"render.cpu_optics_unsupported": "يدعم مسار CPU هذا الزجاج دون ظلال نافذة أو تشتت تحت سطحي أو طلاءات أو خرائط. راجع الخيارات المحددة؛ فقد تم الاحتفاظ بها."
},
"he": {
"render.cpu_optics_boundary": "CPU דורש בחירה מפורשת בגבול יריעה דקה או תיבה. הגאומטריה שנלכדה חייבת לעבור אימות.",
"render.cpu_optics_conflict": "הקצאות אופטיות של CPU אינן יכולות להחליף דריסות דיאלקטריות קיימות.",
"render.cpu_optics_enable": "שימוש באופטיקה זו ב-CPU",
"render.cpu_optics_explicit": "יש לבדוק הקצאה זו ולהפעיל במפורש את הנתיב האופטי שלה ב-CPU.",
"render.cpu_optics_fixed": "מודל התעבורה המותקן ב-CPU אינו יכול לאשר בקשת דגימה אופטית זו.",
"render.cpu_optics_help": "אופטיקה זמנית ב-CPU: דגימה קבועה או הדרגתית, מראה אטום של הגוף והפאות, יריעות או תיבות מיושרות לצירים שעברו אימות. צללים מועברים, פיזור תת-משטחי, ציפויים ומפות אינם נתמכים. תיבות מקוננות דורשות הפעלה מפורשת ואימות. הצבירה שומרת על מגבלת עומק התעבורה הסופית.",
"render.cpu_optics_limit": "CPU תומך בעד שמונה הקצאות אופטיות לגופים.",
"render.cpu_optics_request": "אופטיקת CPU דורשת בקשת תמונת CPU מטיפוס מוגדר ואת האפשרויות הקיימות שלה.",
"render.cpu_optics_saved": "לא ניתן לערבב אופטיקת GPU שמורה עם הקצאות אופטיות זמניות של CPU.",
"render.cpu_optics_unsupported": "נתיב CPU זה תומך בזכוכית ללא צללים מועברים, פיזור תת-משטחי, ציפויים או מפות. יש לבדוק את האפשרויות שנקבעו; הן נשמרו ללא שינוי."
},
"ja": {
"render.cpu_optics_boundary": "CPU では薄板またはボックス境界を明示的に選択する必要があります。取得した形状は認証に合格する必要があります。",
"render.cpu_optics_conflict": "CPU の光学割り当てで既存の誘電体オーバーライドを置き換えることはできません。",
"render.cpu_optics_enable": "この光学設定を CPU で使用",
"render.cpu_optics_explicit": "この割り当てを確認し、CPU 光学経路を明示的に有効にしてください。",
"render.cpu_optics_fixed": "インストール済みの CPU 光輸送では、この光学サンプリング要求を受け付けられません。",
"render.cpu_optics_help": "一時的な CPU 光学設定:固定またはプログレッシブサンプリング、不透明なボディと面の外観、認証済みの薄板または軸に平行なボックス。透過シャドウ、表面下散乱、コート、マップは非対応です。入れ子のボックスには明示的な有効化と認証が必要です。累積しても光輸送の有限深度制限は残ります。",
"render.cpu_optics_limit": "CPU はボディへの光学割り当てを最大 8 個までサポートします。",
"render.cpu_optics_request": "CPU 光学設定には型付きの CPU 画像リクエストと既存のオプションが必要です。",
"render.cpu_optics_saved": "保存済み GPU 光学設定と一時的な CPU 光学割り当ては混在できません。",
"render.cpu_optics_unsupported": "この CPU 経路は透過シャドウ、表面下散乱、コート、マップのないガラスに対応します。設定したオプションを確認してください。内容は保持されています。"
},
"vi": {
"render.cpu_optics_boundary": "CPU yêu cầu chọn rõ ràng biên Tấm mỏng hoặc Hộp. Hình học đã chụp phải vượt qua kiểm chứng.",
"render.cpu_optics_conflict": "Các gán quang học CPU không thể thay thế các ghi đè điện môi hiện có.",
"render.cpu_optics_enable": "Dùng quang học này trên CPU",
"render.cpu_optics_explicit": "Hãy xem lại phép gán này và bật rõ ràng tuyến quang học CPU của nó.",
"render.cpu_optics_fixed": "Mô hình truyền ánh sáng CPU đã cài không thể chấp nhận yêu cầu lấy mẫu quang học này.",
"render.cpu_optics_help": "Quang học CPU tạm thời: lấy mẫu cố định hoặc lũy tiến, diện mạo thân và mặt đục, tấm hoặc hộp song song các trục đã được kiểm chứng. Không hỗ trợ bóng truyền qua, tán xạ dưới bề mặt, lớp phủ và bản đồ. Hộp lồng nhau cần được bật rõ ràng và kiểm chứng. Tích lũy vẫn giữ giới hạn độ sâu hữu hạn của truyền ánh sáng.",
"render.cpu_optics_limit": "CPU hỗ trợ tối đa tám phép gán quang học cho thân.",
"render.cpu_optics_request": "Quang học CPU yêu cầu yêu cầu ảnh CPU có kiểu cùng các tùy chọn hiện có.",
"render.cpu_optics_saved": "Không thể trộn quang học GPU đã lưu với các gán quang học CPU tạm thời.",
"render.cpu_optics_unsupported": "Tuyến CPU này hỗ trợ kính không có bóng truyền qua, tán xạ dưới bề mặt, lớp phủ hoặc bản đồ. Hãy xem lại các tùy chọn đã soạn; chúng đã được giữ nguyên."
},
"zh": {
"render.cpu_optics_boundary": "CPU 要求明确选择薄片或盒体边界。捕获的几何体必须通过认证。",
"render.cpu_optics_conflict": "CPU 光学分配不能替换现有的电介质覆盖设置。",
"render.cpu_optics_enable": "在 CPU 上使用此光学设置",
"render.cpu_optics_explicit": "请检查此分配并明确启用其 CPU 光学路径。",
"render.cpu_optics_fixed": "已安装的 CPU 光传输无法接受此光学采样请求。",
"render.cpu_optics_help": "临时 CPU 光学设置:固定或渐进采样、不透明的实体和面外观、通过认证的薄片或轴对齐盒体。不支持透射阴影、次表面散射、涂层或贴图。嵌套盒体需要明确启用并通过认证。累积仍保留光传输的有限深度限制。",
"render.cpu_optics_limit": "CPU 最多支持八个实体光学分配。",
"render.cpu_optics_request": "CPU 光学设置要求类型化的 CPU 图像请求及其现有选项。",
"render.cpu_optics_saved": "已保存的 GPU 光学设置不能与临时 CPU 光学分配混用。",
"render.cpu_optics_unsupported": "此 CPU 路径支持不含透射阴影、次表面散射、涂层或贴图的玻璃。请检查所编写的选项;这些选项已保留。"
}
}
@@ -0,0 +1,20 @@
{
"de": {
"render.cpu_pass_progress": "Vollständige Durchgänge: {current} / {target} · vorläufig"
},
"en": {
"render.cpu_pass_progress": "Complete passes: {current} / {target} · provisional"
},
"es": {
"render.cpu_pass_progress": "Pasadas completas: {current} / {target} · provisional"
},
"ja": {
"render.cpu_pass_progress": "完了したパス: {current} / {target} · 暫定"
},
"ko": {
"render.cpu_pass_progress": "완료된 패스: {current} / {target} · 임시"
},
"zh": {
"render.cpu_pass_progress": "完整遍数:{current} / {target} · 临时结果"
}
}
@@ -0,0 +1,29 @@
{
"ar": {
"render.product_exposure_invalid": "يجب أن يكون تعريض معاينة النموذج قيمة محدودة بين ‎−32 و32 EV."
},
"de": {
"render.product_exposure_invalid": "Die Belichtung der Modellvorschau muss endlich sein und zwischen −32 und 32 EV liegen."
},
"en": {
"render.product_exposure_invalid": "Model Preview exposure must be finite and between −32 and 32 EV."
},
"es": {
"render.product_exposure_invalid": "La exposición de la vista previa del modelo debe ser finita y estar entre −32 y 32 EV."
},
"he": {
"render.product_exposure_invalid": "חשיפת תצוגת המודל המקדימה חייבת להיות סופית ובטווח שבין ‎−32 ל־32 EV."
},
"ja": {
"render.product_exposure_invalid": "モデルプレビューの露出は −32~32 EV の有限値にしてください。"
},
"ko": {
"render.product_exposure_invalid": "모델 미리보기 노출은 −32~32 EV 범위의 유한한 값이어야 합니다."
},
"vi": {
"render.product_exposure_invalid": "Phơi sáng xem trước Mô hình phải là số hữu hạn trong khoảng −32 đến 32 EV."
},
"zh": {
"render.product_exposure_invalid": "模型预览曝光必须是 −32 到 32 EV 之间的有限值。"
}
}
@@ -0,0 +1,47 @@
{
"ar": {
"render.preview_environment_fixed": "تتطلب معاينة النموذج دوران بيئة بقيمة 0 وشدة بقيمة 1.",
"render.raster_exposure_help": "يضبط تعريض التصيير النقطي من ‎−32 إلى 32 EV بعد التظليل. يحافظ الصفر على الاستجابة الحالية، دون تغيير الأضواء أو المواد.",
"render.raster_exposure_invalid": "يجب أن يكون تعريض التصيير النقطي قيمة محدودة بين ‎−32 و32 EV."
},
"de": {
"render.preview_environment_fixed": "Die Modellvorschau benötigt eine Umgebungsdrehung von 0 und eine Intensität von 1.",
"render.raster_exposure_help": "Passt die Rasterbelichtung nach der Schattierung von −32 bis 32 EV an. Null erhält die bisherige Darstellung; Licht und Materialien bleiben unverändert.",
"render.raster_exposure_invalid": "Die Rasterbelichtung muss endlich sein und zwischen −32 und 32 EV liegen."
},
"en": {
"render.preview_environment_fixed": "Model Preview requires environment rotation 0 and intensity 1.",
"render.raster_exposure_help": "Adjusts Raster exposure from −32 to 32 EV after shading. Zero preserves the current response; lights and materials stay unchanged.",
"render.raster_exposure_invalid": "Raster exposure must be finite and between −32 and 32 EV."
},
"es": {
"render.preview_environment_fixed": "La vista previa del modelo requiere una rotación del entorno de 0 y una intensidad de 1.",
"render.raster_exposure_help": "Ajusta la exposición Raster de −32 a 32 EV después del sombreado. Cero conserva la respuesta actual; no cambia luces ni materiales.",
"render.raster_exposure_invalid": "La exposición Raster debe ser finita y estar entre −32 y 32 EV."
},
"he": {
"render.preview_environment_fixed": "תצוגת המודל המקדימה מחייבת סיבוב סביבה של 0 ועוצמה של 1.",
"render.raster_exposure_help": "התאמת חשיפת רסטר בין ‎−32 ל־32 EV לאחר ההצללה. אפס שומר על התוצאה הנוכחית; התאורה והחומרים אינם משתנים.",
"render.raster_exposure_invalid": "חשיפת הרסטר חייבת להיות סופית ובטווח שבין ‎−32 ל־32 EV."
},
"ja": {
"render.preview_environment_fixed": "モデルプレビューでは、環境の回転を 0、強度を 1 にしてください。",
"render.raster_exposure_help": "シェーディング後のラスター露出を −32~32 EV で調整します。0 は現在の表示を維持し、ライトやマテリアルは変更しません。",
"render.raster_exposure_invalid": "ラスター露出は −32~32 EV の有限値にしてください。"
},
"ko": {
"render.preview_environment_fixed": "모델 미리보기에서는 환경 회전이 0이고 강도가 1이어야 합니다.",
"render.raster_exposure_help": "셰이딩 후 래스터 노출을 −32~32 EV로 조정합니다. 0은 현재 표현을 유지하며 조명과 재질은 변경하지 않습니다.",
"render.raster_exposure_invalid": "래스터 노출은 −32~32 EV 범위의 유한한 값이어야 합니다."
},
"vi": {
"render.preview_environment_fixed": "Xem trước Mô hình yêu cầu góc xoay môi trường là 0 và cường độ là 1.",
"render.raster_exposure_help": "Điều chỉnh phơi sáng Raster từ −32 đến 32 EV sau khi tô bóng. Giá trị 0 giữ cách hiển thị hiện tại; ánh sáng và vật liệu không thay đổi.",
"render.raster_exposure_invalid": "Phơi sáng Raster phải là số hữu hạn trong khoảng −32 đến 32 EV."
},
"zh": {
"render.preview_environment_fixed": "模型预览要求环境旋转为 0,强度为 1。",
"render.raster_exposure_help": "在着色后将光栅曝光调整为 −32 到 32 EV。0 保留当前效果,不更改灯光和材质。",
"render.raster_exposure_invalid": "光栅曝光必须是 −32 到 32 EV 之间的有限值。"
}
}
@@ -0,0 +1,65 @@
{
"en": {
"render.glass_library_conflict": "This body already has optical settings. Edit or remove them before preparing a different recipe.",
"render.glass_library_edit": "Prepare physical glass",
"render.glass_library_help": "Prepares the recipe in the existing editor without assigning an appearance or rendering. CPU needs explicit optical permission and a Thin sheet or Box that passes actual certification. Closed-mesh and shadow settings stay unchanged.",
"render.glass_library_method": "Choose CPU or GPU rendering to prepare physical glass. Raster has no physical-glass route.",
"render.glass_library_prepared": "Physical glass recipe prepared for editing; review its boundary and optical settings before rendering."
},
"es": {
"render.glass_library_conflict": "Este cuerpo ya tiene ajustes ópticos. Edítalos o elimínalos antes de preparar otra receta.",
"render.glass_library_edit": "Preparar vidrio físico",
"render.glass_library_help": "Prepara la receta en el editor existente sin asignar un aspecto ni renderizar. CPU necesita permiso óptico explícito y una lámina o caja que supere la certificación real. No cambia los ajustes de malla cerrada ni de sombras.",
"render.glass_library_method": "Elige renderizado CPU o GPU para preparar vidrio físico. Raster no tiene una ruta de vidrio físico.",
"render.glass_library_prepared": "Receta de vidrio físico preparada para editar; revisa su frontera y sus ajustes ópticos antes de renderizar."
},
"de": {
"render.glass_library_conflict": "Dieser Körper hat bereits optische Einstellungen. Bearbeite oder entferne sie, bevor du ein anderes Rezept vorbereitest.",
"render.glass_library_edit": "Physikalisches Glas vorbereiten",
"render.glass_library_help": "Bereitet das Rezept im vorhandenen Editor vor, ohne ein Aussehen zuzuweisen oder zu rendern. CPU benötigt eine ausdrückliche Freigabe der Optik und eine dünne Scheibe oder einen Quader mit tatsächlicher Zertifizierung. Einstellungen für geschlossene Netze und Schatten bleiben unverändert.",
"render.glass_library_method": "Wähle CPU- oder GPU-Rendering, um physikalisches Glas vorzubereiten. Raster unterstützt kein physikalisches Glas.",
"render.glass_library_prepared": "Glasrezept zur Bearbeitung vorbereitet; prüfe vor dem Rendern seine Begrenzung und optischen Einstellungen."
},
"ko": {
"render.glass_library_conflict": "이 바디에는 이미 광학 설정이 있습니다. 다른 레시피를 준비하기 전에 기존 설정을 편집하거나 제거하세요.",
"render.glass_library_edit": "물리 기반 유리 준비",
"render.glass_library_help": "모양을 지정하거나 렌더링하지 않고 기존 편집기에서 레시피를 준비합니다. CPU에는 명시적인 광학 허용과 실제 검증을 통과하는 얇은 판 또는 상자가 필요합니다. 닫힌 메시와 그림자 설정은 변경하지 않습니다.",
"render.glass_library_method": "물리 기반 유리를 준비하려면 CPU 또는 GPU 렌더링을 선택하세요. Raster는 물리 기반 유리를 지원하지 않습니다.",
"render.glass_library_prepared": "편집할 유리 레시피를 준비했습니다. 렌더링 전에 경계와 광학 설정을 검토하세요."
},
"ar": {
"render.glass_library_conflict": "لهذا الجسم إعدادات بصرية بالفعل. عدّلها أو أزلها قبل تجهيز وصفة مختلفة.",
"render.glass_library_edit": "تجهيز زجاج فيزيائي",
"render.glass_library_help": "يجهّز الوصفة في المحرر الحالي دون تعيين مظهر أو تصيير. يتطلب CPU إذنًا بصريًا صريحًا وصفيحة رقيقة أو صندوقًا يجتاز التحقق الفعلي. تبقى إعدادات الشبكة المغلقة والظلال دون تغيير.",
"render.glass_library_method": "اختر التصيير عبر CPU أو GPU لتجهيز زجاج فيزيائي. لا يدعم Raster الزجاج الفيزيائي.",
"render.glass_library_prepared": "جُهّزت وصفة الزجاج للتحرير؛ راجع حدودها وإعداداتها البصرية قبل التصيير."
},
"he": {
"render.glass_library_conflict": "לגוף הזה כבר יש הגדרות אופטיות. יש לערוך או להסיר אותן לפני הכנת מתכון אחר.",
"render.glass_library_edit": "הכנת זכוכית פיזיקלית",
"render.glass_library_help": "מכין את המתכון בעורך הקיים בלי להקצות מראה או לרנדר. CPU דורש אישור אופטי מפורש ולוח דק או תיבה שעוברים אימות בפועל. הגדרות רשת סגורה וצללים אינן משתנות.",
"render.glass_library_method": "יש לבחור רינדור CPU או GPU כדי להכין זכוכית פיזיקלית. Raster אינו תומך בזכוכית פיזיקלית.",
"render.glass_library_prepared": "מתכון הזכוכית הוכן לעריכה; יש לבדוק את הגבול ואת ההגדרות האופטיות לפני הרינדור."
},
"ja": {
"render.glass_library_conflict": "このボディには既に光学設定があります。別のレシピを準備する前に、既存の設定を編集または削除してください。",
"render.glass_library_edit": "物理ガラスを準備",
"render.glass_library_help": "外観の割り当てやレンダリングを行わず、既存のエディターでレシピを準備します。CPU では光学処理の明示的な許可と、実際の認証に合格する薄板またはボックスが必要です。閉じたメッシュと影の設定は変更しません。",
"render.glass_library_method": "物理ガラスを準備するには CPU または GPU レンダリングを選択してください。Raster は物理ガラスに対応していません。",
"render.glass_library_prepared": "編集用のガラスレシピを準備しました。レンダリング前に境界と光学設定を確認してください。"
},
"vi": {
"render.glass_library_conflict": "Thân này đã có thiết lập quang học. Hãy sửa hoặc xóa chúng trước khi chuẩn bị công thức khác.",
"render.glass_library_edit": "Chuẩn bị kính vật lý",
"render.glass_library_help": "Chuẩn bị công thức trong trình chỉnh sửa hiện có mà không gán diện mạo hay kết xuất. CPU cần cho phép quang học rõ ràng và tấm mỏng hoặc hộp vượt qua kiểm chứng thực tế. Không đổi thiết lập lưới kín và bóng đổ.",
"render.glass_library_method": "Chọn kết xuất CPU hoặc GPU để chuẩn bị kính vật lý. Raster không hỗ trợ kính vật lý.",
"render.glass_library_prepared": "Đã chuẩn bị công thức kính để chỉnh sửa; hãy kiểm tra biên và thiết lập quang học trước khi kết xuất."
},
"zh": {
"render.glass_library_conflict": "此实体已有光学设置。准备其他配方前,请编辑或移除现有设置。",
"render.glass_library_edit": "准备物理玻璃",
"render.glass_library_help": "在现有编辑器中准备配方,不分配外观,也不进行渲染。CPU 需要明确启用光学处理,并使用通过实际认证的薄片或盒体。封闭网格和阴影设置保持不变。",
"render.glass_library_method": "请选择 CPU 或 GPU 渲染来准备物理玻璃。Raster 不支持物理玻璃。",
"render.glass_library_prepared": "玻璃配方已准备好供编辑;渲染前请检查边界和光学设置。"
}
}
@@ -0,0 +1,227 @@
{
"en": {
"cmd.render.interactive": "Interactive Render",
"help.render.interactive": "Explicitly enable a provisional CPU preview while editing. Final render settings and exportable images stay unchanged.",
"render.interactive_error": "Interactive preview error",
"render.interactive_feedback_milestones_complete": "No more preview updates are scheduled for this render.",
"render.interactive_feedback_policy": "Preview updates are limited per render; final image settings stay unchanged.",
"render.interactive_feedback_quota_exhausted": "Preview update limit reached for this render.",
"render.interactive_feedback_usage": "{started}/{limit} preview updates started for this render.",
"render.interactive_final_active": "Final render active",
"render.interactive_off": "Off",
"render.interactive_on": "On",
"render.interactive_partial_dimensions": "Display {display_width} × {display_height} px · Sampling {source_width} × {source_height} px · Output {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "Not enough remaining work budget for another partial image.",
"render.interactive_partial_samples": "Samples/pixel {min}–{max} · {known}/{pixels} source pixels sampled",
"render.interactive_pause": "Pause",
"render.interactive_paused": "Paused",
"render.interactive_provisional": "Provisional preview",
"render.interactive_refining": "Refining preview",
"render.interactive_requires_cpu": "Interactive preview requires CPU ray tracing.",
"render.interactive_resume": "Resume",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "Out of date",
"render.interactive_target": "Sample target reached",
"render.interactive_updating": "Updating"
},
"ar": {
"cmd.render.interactive": "تصيير تفاعلي",
"help.render.interactive": "فعّل معاينة مؤقتة باستخدام المعالج CPU أثناء التحرير. تبقى إعدادات التصيير النهائي والصور القابلة للتصدير دون تغيير.",
"render.interactive_error": "خطأ في المعاينة التفاعلية",
"render.interactive_feedback_milestones_complete": "لم تُجدول تحديثات معاينة أخرى لهذا التصيير.",
"render.interactive_feedback_policy": "تحديثات المعاينة محدودة لكل تصيير؛ تبقى إعدادات الصورة النهائية دون تغيير.",
"render.interactive_feedback_quota_exhausted": "تم بلوغ حد تحديثات المعاينة لهذا التصيير.",
"render.interactive_feedback_usage": "بدأ {started}/{limit} تحديثًا للمعاينة لهذا التصيير.",
"render.interactive_final_active": "التصيير النهائي قيد التنفيذ",
"render.interactive_off": "إيقاف",
"render.interactive_on": "تفعيل",
"render.interactive_partial_dimensions": "العرض {display_width} × {display_height} بكسل · أخذ العينات {source_width} × {source_height} بكسل · الإخراج {final_width} × {final_height} بكسل",
"render.interactive_partial_exhausted": "لا تكفي ميزانية المعالجة المتبقية لصورة جزئية أخرى.",
"render.interactive_partial_samples": "عينات لكل بكسل {min}–{max} · أُخذت عينات من {known}/{pixels} بكسل من المصدر",
"render.interactive_pause": "إيقاف مؤقت",
"render.interactive_paused": "متوقف مؤقتًا",
"render.interactive_provisional": "معاينة مؤقتة",
"render.interactive_refining": "جارٍ تحسين المعاينة",
"render.interactive_requires_cpu": "تتطلب المعاينة التفاعلية تتبّع الأشعة على المعالج CPU.",
"render.interactive_resume": "استئناف",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "غير محدثة",
"render.interactive_target": "تم بلوغ عدد العينات المطلوب",
"render.interactive_updating": "جارٍ التحديث"
},
"de": {
"cmd.render.interactive": "Interaktives Rendering",
"help.render.interactive": "Aktivieren Sie die vorläufige CPU-Vorschau zum Bearbeiten manuell. Einstellungen für das finale Rendering und exportierbare Bilder bleiben unverändert.",
"render.interactive_error": "Fehler in der interaktiven Vorschau",
"render.interactive_feedback_milestones_complete": "Für dieses Rendering sind keine weiteren Vorschauaktualisierungen geplant.",
"render.interactive_feedback_policy": "Vorschauaktualisierungen sind pro Rendering begrenzt; die Einstellungen des finalen Bildes bleiben unverändert.",
"render.interactive_feedback_quota_exhausted": "Limit für Vorschauaktualisierungen dieses Renderings erreicht.",
"render.interactive_feedback_usage": "{started}/{limit} Vorschauaktualisierungen für dieses Rendering gestartet.",
"render.interactive_final_active": "Finales Rendering aktiv",
"render.interactive_off": "Aus",
"render.interactive_on": "Ein",
"render.interactive_partial_dimensions": "Anzeige {display_width} × {display_height} px · Abtastung {source_width} × {source_height} px · Ausgabe {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "Das verbleibende Rechenbudget reicht nicht für ein weiteres Teilbild.",
"render.interactive_partial_samples": "Samples/Pixel {min}–{max} · {known}/{pixels} Quellpixel abgetastet",
"render.interactive_pause": "Pausieren",
"render.interactive_paused": "Pausiert",
"render.interactive_provisional": "Vorläufige Vorschau",
"render.interactive_refining": "Vorschau wird verfeinert",
"render.interactive_requires_cpu": "Die interaktive Vorschau erfordert CPU-Raytracing.",
"render.interactive_resume": "Fortsetzen",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "Nicht aktuell",
"render.interactive_target": "Zielanzahl an Samples erreicht",
"render.interactive_updating": "Wird aktualisiert"
},
"es": {
"cmd.render.interactive": "Render interactivo",
"help.render.interactive": "Activa explícitamente una vista previa provisional por CPU mientras editas. Los ajustes del render final y las imágenes exportables se mantienen intactos.",
"render.interactive_error": "Error en la vista previa interactiva",
"render.interactive_feedback_milestones_complete": "No hay más actualizaciones de vista previa programadas para este renderizado.",
"render.interactive_feedback_policy": "Las actualizaciones de vista previa se limitan por renderizado; los ajustes de la imagen final no cambian.",
"render.interactive_feedback_quota_exhausted": "Se ha alcanzado el límite de actualizaciones de vista previa de este renderizado.",
"render.interactive_feedback_usage": "Se han iniciado {started}/{limit} actualizaciones de vista previa para este renderizado.",
"render.interactive_final_active": "Render final activo",
"render.interactive_off": "Desactivar",
"render.interactive_on": "Activar",
"render.interactive_partial_dimensions": "Visualización {display_width} × {display_height} px · Muestreo {source_width} × {source_height} px · Salida {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "El presupuesto de cálculo restante no permite otra imagen parcial.",
"render.interactive_partial_samples": "Muestras/píxel {min}–{max} · {known}/{pixels} píxeles de origen muestreados",
"render.interactive_pause": "Pausar",
"render.interactive_paused": "En pausa",
"render.interactive_provisional": "Vista previa provisional",
"render.interactive_refining": "Refinando vista previa",
"render.interactive_requires_cpu": "La vista previa interactiva requiere trazado de rayos por CPU.",
"render.interactive_resume": "Reanudar",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "Desactualizada",
"render.interactive_target": "Número objetivo de muestras alcanzado",
"render.interactive_updating": "Actualizando"
},
"he": {
"cmd.render.interactive": "רינדור אינטראקטיבי",
"help.render.interactive": "יש להפעיל במפורש תצוגה מקדימה זמנית במעבד CPU בזמן העריכה. הגדרות הרינדור הסופי והתמונות הזמינות לייצוא נשארות ללא שינוי.",
"render.interactive_error": "שגיאה בתצוגה המקדימה האינטראקטיבית",
"render.interactive_feedback_milestones_complete": "לא מתוכננים עדכוני תצוגה מקדימה נוספים לרינדור זה.",
"render.interactive_feedback_policy": "עדכוני התצוגה המקדימה מוגבלים לכל רינדור; הגדרות התמונה הסופית אינן משתנות.",
"render.interactive_feedback_quota_exhausted": "הושגה מגבלת עדכוני התצוגה המקדימה לרינדור זה.",
"render.interactive_feedback_usage": "החלו {started}/{limit} עדכוני תצוגה מקדימה לרינדור זה.",
"render.interactive_final_active": "הרינדור הסופי פעיל",
"render.interactive_off": "כיבוי",
"render.interactive_on": "הפעלה",
"render.interactive_partial_dimensions": "תצוגה {display_width} × {display_height} פיקסלים · דגימה {source_width} × {source_height} פיקסלים · פלט {final_width} × {final_height} פיקסלים",
"render.interactive_partial_exhausted": "תקציב החישוב שנותר אינו מספיק לתמונה חלקית נוספת.",
"render.interactive_partial_samples": "דגימות לפיקסל {min}–{max} · נדגמו {known}/{pixels} פיקסלים במקור",
"render.interactive_pause": "השהיה",
"render.interactive_paused": "מושהה",
"render.interactive_provisional": "תצוגה מקדימה זמנית",
"render.interactive_refining": "משפר את התצוגה המקדימה",
"render.interactive_requires_cpu": "תצוגה מקדימה אינטראקטיבית דורשת עקיבת קרניים במעבד CPU.",
"render.interactive_resume": "המשך",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "לא עדכני",
"render.interactive_target": "הושג מספר הדגימות המבוקש",
"render.interactive_updating": "מעדכן"
},
"ja": {
"cmd.render.interactive": "インタラクティブレンダリング",
"help.render.interactive": "編集中にCPUによる暫定プレビューを明示的に有効にします。最終レンダリングの設定とエクスポート可能な画像は変更しません。",
"render.interactive_error": "インタラクティブプレビューのエラー",
"render.interactive_feedback_milestones_complete": "このレンダリングでは、これ以上のプレビュー更新は予定されていません。",
"render.interactive_feedback_policy": "プレビュー更新はレンダリングごとに制限されます。最終画像の設定は変わりません。",
"render.interactive_feedback_quota_exhausted": "このレンダリングのプレビュー更新上限に達しました。",
"render.interactive_feedback_usage": "このレンダリングで開始したプレビュー更新:{started}/{limit}。",
"render.interactive_final_active": "最終レンダリング中",
"render.interactive_off": "無効にする",
"render.interactive_on": "有効にする",
"render.interactive_partial_dimensions": "表示 {display_width} × {display_height} px · サンプリング {source_width} × {source_height} px · 出力 {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "残りの計算予算では、次の部分画像を生成できません。",
"render.interactive_partial_samples": "ピクセルあたり {min}~{max} サンプル · 元画像の {known}/{pixels} ピクセルをサンプリング済み",
"render.interactive_pause": "一時停止",
"render.interactive_paused": "一時停止中",
"render.interactive_provisional": "暫定プレビュー",
"render.interactive_refining": "プレビューを改善中",
"render.interactive_requires_cpu": "インタラクティブプレビューにはCPUレイトレーシングが必要です。",
"render.interactive_resume": "再開",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "最新ではありません",
"render.interactive_target": "目標サンプル数に到達",
"render.interactive_updating": "更新中"
},
"ko": {
"cmd.render.interactive": "대화형 렌더링",
"help.render.interactive": "편집하는 동안 임시 CPU 미리 보기를 직접 켭니다. 최종 렌더링 설정과 내보낼 수 있는 이미지는 변경하지 않습니다.",
"render.interactive_error": "대화형 미리 보기 오류",
"render.interactive_feedback_milestones_complete": "이 렌더링에는 추가 미리 보기 업데이트가 예정되어 있지 않습니다.",
"render.interactive_feedback_policy": "미리 보기 업데이트는 렌더링별로 제한되며 최종 이미지 설정은 바뀌지 않습니다.",
"render.interactive_feedback_quota_exhausted": "이 렌더링의 미리 보기 업데이트 한도에 도달했습니다.",
"render.interactive_feedback_usage": "이 렌더링에서 시작한 미리 보기 업데이트: {started}/{limit}.",
"render.interactive_final_active": "최종 렌더링 진행 중",
"render.interactive_off": "끄기",
"render.interactive_on": "켜기",
"render.interactive_partial_dimensions": "표시 {display_width} × {display_height} px · 샘플링 {source_width} × {source_height} px · 출력 {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "남은 연산 예산으로는 부분 이미지를 더 만들 수 없습니다.",
"render.interactive_partial_samples": "픽셀당 샘플 {min}–{max} · 원본 픽셀 {known}/{pixels}개 샘플링됨",
"render.interactive_pause": "일시 중지",
"render.interactive_paused": "일시 중지됨",
"render.interactive_provisional": "임시 미리 보기",
"render.interactive_refining": "미리 보기 개선 중",
"render.interactive_requires_cpu": "대화형 미리 보기에는 CPU 레이 트레이싱이 필요합니다.",
"render.interactive_resume": "계속",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "최신 상태가 아님",
"render.interactive_target": "목표 샘플 수 도달",
"render.interactive_updating": "업데이트 중"
},
"vi": {
"cmd.render.interactive": "Kết xuất tương tác",
"help.render.interactive": "Chủ động bật bản xem trước tạm thời bằng CPU khi chỉnh sửa. Thiết lập kết xuất cuối và các ảnh có thể xuất vẫn được giữ nguyên.",
"render.interactive_error": "Lỗi xem trước tương tác",
"render.interactive_feedback_milestones_complete": "Không còn cập nhật xem trước nào được lên lịch cho lần kết xuất này.",
"render.interactive_feedback_policy": "Số lần cập nhật xem trước được giới hạn theo từng lần kết xuất; cài đặt ảnh cuối cùng không thay đổi.",
"render.interactive_feedback_quota_exhausted": "Đã đạt giới hạn cập nhật xem trước cho lần kết xuất này.",
"render.interactive_feedback_usage": "Đã bắt đầu {started}/{limit} cập nhật xem trước cho lần kết xuất này.",
"render.interactive_final_active": "Đang kết xuất ảnh cuối",
"render.interactive_off": "Tắt",
"render.interactive_on": "Bật",
"render.interactive_partial_dimensions": "Hiển thị {display_width} × {display_height} px · Lấy mẫu {source_width} × {source_height} px · Đầu ra {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "Ngân sách tính toán còn lại không đủ cho một ảnh từng phần nữa.",
"render.interactive_partial_samples": "Mẫu/điểm ảnh {min}–{max} · Đã lấy mẫu {known}/{pixels} điểm ảnh nguồn",
"render.interactive_pause": "Tạm dừng",
"render.interactive_paused": "Đã tạm dừng",
"render.interactive_provisional": "Bản xem trước tạm thời",
"render.interactive_refining": "Đang cải thiện bản xem trước",
"render.interactive_requires_cpu": "Xem trước tương tác yêu cầu dò tia bằng CPU.",
"render.interactive_resume": "Tiếp tục",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "Chưa cập nhật",
"render.interactive_target": "Đã đạt số mẫu mục tiêu",
"render.interactive_updating": "Đang cập nhật"
},
"zh": {
"cmd.render.interactive": "交互式渲染",
"help.render.interactive": "编辑时手动启用临时 CPU 预览。最终渲染设置和可导出的图像保持不变。",
"render.interactive_error": "交互式预览错误",
"render.interactive_feedback_milestones_complete": "本次渲染不再计划新的预览更新。",
"render.interactive_feedback_policy": "每次渲染的预览更新次数有限;最终图像设置保持不变。",
"render.interactive_feedback_quota_exhausted": "本次渲染的预览更新已达到上限。",
"render.interactive_feedback_usage": "本次渲染已启动 {started}/{limit} 次预览更新。",
"render.interactive_final_active": "最终渲染进行中",
"render.interactive_off": "关闭",
"render.interactive_on": "启用",
"render.interactive_partial_dimensions": "显示 {display_width} × {display_height} px · 采样 {source_width} × {source_height} px · 输出 {final_width} × {final_height} px",
"render.interactive_partial_exhausted": "剩余计算预算不足以生成另一张部分图像。",
"render.interactive_partial_samples": "每像素样本数 {min}–{max} · 已采样 {known}/{pixels} 个源像素",
"render.interactive_pause": "暂停",
"render.interactive_paused": "已暂停",
"render.interactive_provisional": "临时预览",
"render.interactive_refining": "正在细化预览",
"render.interactive_requires_cpu": "交互式预览需要 CPU 光线追踪。",
"render.interactive_resume": "继续",
"render.interactive_samples": "{done}/{total} SPP",
"render.interactive_stale": "不是最新状态",
"render.interactive_target": "已达到目标采样数",
"render.interactive_updating": "正在更新"
}
}
@@ -0,0 +1,38 @@
{
"ar": {
"prefs.render_open_result_on_start": "فتح النتيجة عند بدء التصيير",
"prefs.render_open_result_on_start_help": "افتح النتيجة مرة واحدة بعد بدء التصيير بنجاح. عطّل هذا الخيار للاحتفاظ بالعرض المحدد. يمكنك العودة إلى النموذج أثناء التصيير."
},
"de": {
"prefs.render_open_result_on_start": "Ergebnis beim Renderstart öffnen",
"prefs.render_open_result_on_start_help": "Nach erfolgreichem Renderstart einmal das Ergebnis öffnen. Deaktivieren, um die gewählte Ansicht beizubehalten. Während des Renderns können Sie zum Modell zurückkehren."
},
"en": {
"prefs.render_open_result_on_start": "Open Result when rendering starts",
"prefs.render_open_result_on_start_help": "After starting a render successfully, open Result once. Turn off to keep your selected view. You can return to Model while rendering."
},
"es": {
"prefs.render_open_result_on_start": "Abrir Resultado al iniciar el renderizado",
"prefs.render_open_result_on_start_help": "Abre Resultado una vez tras iniciar correctamente el renderizado. Desactiva esta opción para conservar la vista seleccionada. Puedes volver a Modelo durante el renderizado."
},
"he": {
"prefs.render_open_result_on_start": "פתיחת התוצאה עם תחילת הרינדור",
"prefs.render_open_result_on_start_help": "פתיחת התוצאה פעם אחת לאחר התחלת רינדור בהצלחה. יש לבטל אפשרות זו כדי לשמור על התצוגה שנבחרה. אפשר לחזור למודל בזמן הרינדור."
},
"ja": {
"prefs.render_open_result_on_start": "レンダリング開始時に結果を開く",
"prefs.render_open_result_on_start_help": "レンダリングの開始に成功したら、結果を一度だけ開きます。無効にすると、選択中の表示を維持します。レンダリング中でもモデルに戻れます。"
},
"ko": {
"prefs.render_open_result_on_start": "렌더링 시작 시 결과 열기",
"prefs.render_open_result_on_start_help": "렌더링이 성공적으로 시작되면 결과를 한 번 엽니다. 끄면 선택한 보기가 유지됩니다. 렌더링 중에도 모델로 돌아갈 수 있습니다."
},
"vi": {
"prefs.render_open_result_on_start": "Mở Kết quả khi bắt đầu kết xuất",
"prefs.render_open_result_on_start_help": "Mở Kết quả một lần sau khi bắt đầu kết xuất thành công. Tắt để giữ chế độ xem đã chọn. Bạn có thể quay lại Mô hình trong khi kết xuất."
},
"zh": {
"prefs.render_open_result_on_start": "开始渲染时打开结果",
"prefs.render_open_result_on_start_help": "成功开始渲染后打开结果一次。关闭此选项可保留当前选中的视图。渲染期间也可以返回模型视图。"
}
}
-5
View File
@@ -1300,10 +1300,6 @@
"shortcut.pin": "Przypnij na górze pola S",
"shortcut.unpin": "Odepnij",
"sketch.degrees_of_freedom": "Stopnie swobody: {count}",
"sketch.dimension_added_driven": "Szkic już określa ten wymiar, więc dodano go jako wymiar sterowany (referencyjny)",
"sketch.dimension_applied": "Wymiar zastosowany",
"sketch.dimension_applied_defined": "Wymiar zastosowany; zdefiniowano parametr `{name}`",
"sketch.dimension_applied_renamed": "Wymiar zastosowany; parametr nazywa się teraz `{name}`",
"sketch.dof_left": "Pozostałe stopnie swobody: {count}",
"sketch.dof_left_one": "Pozostał {count} stopień swobody",
"sketch.draw_curves": "Rysuj jako {linetype}",
@@ -2118,7 +2114,6 @@
"ui.select": "Zaznacz",
"ui.selectOther": "Wybierz inny…",
"ui.selectTangentChain": "Zaznacz łańcuch styczny",
"ui.select_all": "Zaznacz wszystko",
"ui.selection": "Zaznaczenie",
"ui.selection_modifiers": "Modyfikatory zaznaczania",
"ui.selection_shift_add_only": "Shift+kliknięcie tylko dodaje",
-1
View File
@@ -2244,7 +2244,6 @@
"ui.select": "Selecionar",
"ui.selectOther": "Selecionar outro…",
"ui.selectTangentChain": "Selecionar cadeia tangente",
"ui.select_all": "Selecionar tudo",
"ui.selection": "Seleção",
"ui.selection_modifiers": "Modificadores de seleção",
"ui.selection_shift_add_only": "Shift+clique adiciona sem remover",
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4022 -4023
View File
File diff suppressed because it is too large. Load diff
+4310 -4310
View File
File diff suppressed because it is too large. Load diff
+4287 -4287
View File
File diff suppressed because it is too large. Load diff
+4306 -4307
View File
File diff suppressed because it is too large. Load diff
+4287 -4288
View File
File diff suppressed because it is too large. Load diff
+4624 -4692
View File
File diff suppressed because it is too large. Load diff
+4287 -4288
View File
File diff suppressed because it is too large. Load diff
+4624 -4692
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-6
View File
@@ -253,12 +253,6 @@ impl crate::Feature {
for e in sketch.text_exprs_mut() {
*e = clone_expression(e, parameters);
}
// An equation curve's variable is its own: a parameter of that name is not renamed in it.
for (variable, e) in sketch.equation_exprs_mut() {
let others: BTreeMap<String, String> =
parameters.iter().filter(|(old, _)| old.as_str() != variable).map(|(o, n)| (o.clone(), n.clone())).collect();
*e = clone_expression(e, &others);
}
for link in &mut sketch.links {
remap_link(&mut link.source, ids, names, bodies, 0);
for n in link.face_name.iter_mut().chain(&mut link.edge_name) {
+3 -4
View File
@@ -3705,7 +3705,7 @@ impl Document {
}
/// Add or change a parameter. Fails if the result would not evaluate. A new parameter
/// without a unit takes the unit of its value (a length in the design's units, deg or none).
/// without a unit takes the unit of its value (mm, deg or none).
pub fn set_param(&mut self, name: &str, expr_s: &str, unit: Option<&str>, comment: Option<&str>) -> Result<()> {
// A text parameter: one with the text unit, or an existing one when no unit is given.
match (unit.map(crate::text_params::is_text_unit), self.text_param(name).is_some()) {
@@ -3889,11 +3889,10 @@ impl Document {
}
}
/// Apply parameter values to every dimension in a sketch, to its points placed by parameters
/// and to its equation curves (in place).
/// Apply parameter values to every dimension in a sketch, and to its points placed by
/// parameters (in place).
pub fn apply_dimension_values(&self, vals: &std::collections::BTreeMap<String, expr::Value>, sk: &mut Sketch) -> Result<()> {
self.apply_point_values(vals, sk)?;
self.apply_equation_values(vals, sk)?;
self.apply_pattern_values(vals, sk)?;
for c in &mut sk.constraints {
if let Some(p) = &c.param {
+2 -29
View File
@@ -2523,40 +2523,13 @@ fn point(vals: &BTreeMap<String, Value>, p: &crate::PointExpr) -> Result<Vec3> {
pub(crate) fn val(vals: &BTreeMap<String, Value>, e: &str, k: Kind) -> Result<f64> {
let scale = vals.get(DESIGN_LEN).map(|x| x.v).unwrap_or(1.0);
// Non-literal lengths (a parameter ± a bare number) must read that bare number in the design's
// units during the expression, not only when the whole result is unit-less (#9015).
if k == Kind::Length && scale != 1.0 && !expr::is_literal(e) {
let defaults = expr::Defaults { len: scale, ..expr::Defaults::default() };
let look = |n: &str| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`")));
return expr::eval_with_defaults(e, &look, defaults)?.to_kind_in(k, defaults);
let v = expr::eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))))?;
return v.to_kind_in(k, expr::Defaults { len: scale, ..expr::Defaults::default() });
}
Document::eval_in(vals, e, k)
}
#[cfg(test)]
mod design_unit_val_tests {
use super::*;
use expr::Value;
/// #9015: with inches as the design unit, `baseLength - 1` subtracts one inch (not one mm).
#[test]
fn bare_offsets_beside_a_length_follow_the_design_units() {
let mut vals = BTreeMap::new();
vals.insert(DESIGN_LEN.into(), Value::num(25.4));
vals.insert("baseLength".into(), Value::length(76.0 * 25.4));
let got = val(&vals, "baseLength - 1", Kind::Length).unwrap();
assert!((got - 75.0 * 25.4).abs() < 1e-9, "got {got} mm, want 75 in");
let got = val(&vals, "baseLength - 1.5", Kind::Length).unwrap();
assert!((got - 74.5 * 25.4).abs() < 1e-9, "got {got} mm, want 74.5 in");
// An explicit millimetre still wins.
let got = val(&vals, "baseLength - 1 mm", Kind::Length).unwrap();
assert!((got - (76.0 * 25.4 - 1.0)).abs() < 1e-9, "got {got}");
// A bare literal stays millimetres (feature inputs write the design unit in when typed).
let got = val(&vals, "2", Kind::Length).unwrap();
assert!((got - 2.0).abs() < 1e-12, "got {got}");
}
}
/// Collapsing the outline and its holes onto one apex cannot make a manifold solid.
fn refuse_loft_holes(r: &Region2) -> Result<()> {
if r.holes.is_empty() {
-11
View File
@@ -46,17 +46,6 @@ impl FeatureKind {
found
}
/// Bodies the feature works on (by name).
pub fn input_bodies(&self) -> Vec<String> {
let mut v = Vec::new();
self.walk_refs(&mut |r| {
if let Ref::Body(name) = r {
v.push(name.as_ref().to_string());
}
});
v
}
/// Point references to sketches and features (both by id) at their copies, and references
/// that are still keyed by name at a feature's new name (`timeline.rename`).
pub fn remap_refs(&mut self, ids: &BTreeMap<u64, u64>, names: &BTreeMap<String, String>) {
@@ -0,0 +1,6 @@
//! CPU render setups save their explicit dielectric transport choice. Missing or
//! older values retain LegacyBounded; its default is omitted. StrictTir preserves
//! deterministic internal reflection and refuses unresolved positive optical tails;
//! it does not make captured body bindings portable or add unsupported geometry.
//! No existing value needs migration or clamping. The last release refuses the
//! newer design format and asks for an update instead of losing the saved choice.
@@ -0,0 +1,6 @@
//! Saved CPU render setups accept finite exposure from -32 through32 EV, matching the
//! existing RenderSetup/UI range. Exposure is still saved only on RenderSetup, applied
//! once after linear accumulation, with default0 unchanged. Existing valid designs keep
//! their numerical intent; no migration/clamping or second exposure field is introduced.
//! The last release refuses this newer design format and requests an update instead of
//! accepting a CPU setup whose wider exposure it cannot execute.
@@ -0,0 +1,4 @@
//! Saves up to eight bounded linear-RGB directional lights in a Raster render job.
//! Older jobs without lights retain the exact implicit studio; an explicit empty
//! rig remains dark. No older data rewrite is needed. The last released reader
//! asks for an update instead of silently discarding this newer saved intent.
@@ -0,0 +1,4 @@
//! Raster product images now apply the existing saved exposure_ev control.
//! Older zero/omitted exposure retains the exact old path. Nonzero exposure
//! changes explicit rendering intent that was previously refused or ignored;
//! the last released reader asks for an update for this newer meaning.
@@ -1,5 +0,0 @@
//! A sketch saves its equation curves (#8352) in `equations`: for each, the fit point spline it
//! places, its formulas (x(t) and y(t), or y = f(x) without `x`), the range of the variable and
//! the tolerance its points were chosen for. An older design has none, and its sketches mean
//! what they meant. The last release refuses a design that has them (it asks for an update)
//! instead of opening the splines as plain fixed splines that no longer follow their formulas.
+1 -5
View File
@@ -191,11 +191,7 @@ impl Document {
}
let mut out = Vec::with_capacity(found.defs.len());
for d in found.defs {
// A value of no fixed kind (a joint's) is evaluated without the design's units, so
// its bare number stays a millimetre length whatever they are (#8865): `w = 5` is
// what `5` is there.
let unit = d.unit.unwrap_or_else(|| Self::infer_unit_in(&next.param_values().0, &d.expression, "mm"));
next.add_user_param(&d.name, &d.expression, Some(&unit), None)
next.add_user_param(&d.name, &d.expression, d.unit.as_deref(), None)
.map_err(|e| DocError::Invalid(format!("`{} = {}`: {e}", d.name, d.expression)))?;
let unit = next.param(&d.name).map(|p| p.unit.clone()).unwrap_or_default();
out.push(Defined { name: d.name, expression: d.expression, unit });
-1
View File
@@ -71,7 +71,6 @@ pub mod render_settings;
pub mod render_surface;
pub use project3d::iso_grid;
pub mod sheet;
pub mod sketch_equation;
pub mod text_params;
pub use assembly::{
+7 -20
View File
@@ -268,7 +268,7 @@ impl Document {
.filter(|(_, _, k)| *k == Kind::Length)
.map(|(_, e, _)| {
let d = if expr::is_literal(&e) { expr::Defaults::default() } else { expr::Defaults { len: scale, ..expr::Defaults::default() } };
expr::eval_with_defaults(&e, &look, d).and_then(|v| v.to_kind_in(Kind::Length, d)).ok()
expr::eval_with(&e, &look).and_then(|v| v.to_kind_in(Kind::Length, d)).ok()
})
.collect()
}
@@ -585,7 +585,7 @@ impl Document {
}
let unit = match unit {
Some(u) => u.trim().to_string(),
None => Self::infer_unit_in(vals, expr_s, &self.units),
None => Self::infer_unit_in(vals, expr_s),
};
self.params.push(crate::Param {
name: name.into(),
@@ -696,19 +696,18 @@ impl Document {
}
/// The unit for a new parameter with this expression: that of its value; a bare number is
/// a length in the design's units, as a typed length reads it (#8865).
/// a length (mm).
pub(crate) fn infer_unit(&self, e: &str) -> String {
Self::infer_unit_in(&self.param_values().0, e, &self.units)
Self::infer_unit_in(&self.param_values().0, e)
}
/// [`Document::infer_unit`] against parameter values already worked out, a length taking
/// `units` (the design's, or `mm` where a bare number reads as millimetres).
pub(crate) fn infer_unit_in(vals: &BTreeMap<String, Value>, e: &str, units: &str) -> String {
/// [`Document::infer_unit`] against parameter values already worked out.
fn infer_unit_in(vals: &BTreeMap<String, Value>, e: &str) -> String {
let v = expr::eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))));
match v.ok().and_then(|v| v.kind()) {
Some(Kind::Unitless) if !expr::references(e).is_empty() => String::new(),
Some(Kind::Angle) => "deg".into(),
_ => expr::length_unit_or_mm(units).to_string(),
_ => "mm".into(),
}
}
@@ -897,18 +896,6 @@ impl Document {
n += 1;
}
}
// An equation curve's variable hides a parameter of its name: such a parameter is
// not what its formulas refer to.
for (variable, e) in sketch.equation_exprs_mut() {
if variable == old {
continue;
}
let r = expr::rename_reference(e, old, new);
if r != *e {
*e = r;
n += 1;
}
}
for e in sketch.text_word_exprs_mut() {
let r = crate::text_params::rename_reference(e, old, new);
if r != *e {
+53 -4
View File
@@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize};
use solidcraft_render::{
Camera,
job::{
CpuBudget, CpuProgressiveOptions, DirectionalLightOptions, JobOptions, LightingPreset, PunctualLightOptions, RaytraceEnvironmentOptions,
RaytraceOptions, RectangleLightOptions, StudioLighting, ThinLens, ToneMap,
CpuBudget, CpuDielectricTransport, CpuProgressiveOptions, DirectionalLightOptions, JobOptions, LightingPreset, PunctualLightOptions,
RaytraceEnvironmentOptions, RaytraceOptions, RectangleLightOptions, StudioLighting, ThinLens, ToneMap,
},
lighting::environment::SkyGradient,
};
@@ -25,6 +25,9 @@ pub enum RenderJob {
Raster {
#[serde(default)]
transparent_background: bool,
/// Omission retains the fixed studio; an explicit empty rig is dark.
#[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_lights", skip_serializing_if = "Option::is_none")]
lights: Option<Vec<DirectionalLightOptions>>,
},
CpuRaytrace {
#[serde(default)]
@@ -42,8 +45,12 @@ pub enum RenderJob {
impl RenderJob {
pub fn validate(&self, camera: &Camera, exposure_ev: f64) -> Result<()> {
match self {
Self::Raster { .. } if exposure_ev != 0.0 => Err(DocError::Invalid("saved raster rendering requires exposure_ev: 0".into())),
Self::Raster { .. } => Ok(()),
Self::Raster { lights, .. } => {
if !exposure_ev.is_finite() || !(-32.0..=32.0).contains(&exposure_ev) {
return Err(DocError::Invalid("saved Raster exposure must be finite and within -32..32 EV".into()));
}
solidcraft_render::job::validate_raster_lights(lights).map_err(|e| DocError::Invalid(e.to_string()))
}
Self::CpuRaytrace { options } => options.to_runtime(exposure_ev).map(|_| ()),
Self::GpuPath { options, transparent_background } => {
if *transparent_background && options.backdrop.is_some() {
@@ -67,6 +74,8 @@ impl RenderJob {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CpuJob {
#[serde(skip_serializing_if = "CpuDielectricTransport::is_legacy")]
pub dielectric_transport: CpuDielectricTransport,
#[serde(skip_serializing_if = "CpuBudget::is_compact")]
pub budget: CpuBudget,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -94,6 +103,7 @@ pub struct CpuJob {
impl Default for CpuJob {
fn default() -> Self {
Self {
dielectric_transport: CpuDielectricTransport::LegacyBounded,
budget: CpuBudget::Compact,
progressive: None,
primary_samples: 1,
@@ -129,6 +139,7 @@ impl CpuJob {
// a light family that is explicitly absent. This does not rewrite the file.
let active_area = self.area_lights.as_ref().is_some_and(|lights| !lights.is_empty());
let options = RaytraceOptions {
dielectric_transport: self.dielectric_transport,
budget: self.budget,
progressive: self.progressive,
primary_samples: self.primary_samples,
@@ -346,3 +357,41 @@ fn punctual_lights<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resul
fn area_lights<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Option<Vec<RectangleLightOptions>>, D::Error> {
optional_lights::<D, RectangleLightOptions, 4>(d)
}
#[cfg(test)]
#[test]
fn cpu_dielectric_transport_saved_field_has_legacy_default_and_explicit_runtime_forward() {
let legacy: CpuJob = serde_json::from_str("{}").unwrap();
assert_eq!(legacy.dielectric_transport, CpuDielectricTransport::LegacyBounded);
assert!(serde_json::to_value(&legacy).unwrap().get("dielectric_transport").is_none());
for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] {
let saved = CpuJob { dielectric_transport: policy, ..Default::default() };
let reopened: CpuJob = serde_json::from_value(serde_json::to_value(&saved).unwrap()).unwrap();
assert_eq!(reopened, saved);
let runtime = reopened.to_runtime(0.0).unwrap();
assert_eq!(runtime.dielectric_transport, policy);
assert_eq!(runtime.exposure_ev, 0.0);
assert_eq!(runtime.budget, CpuBudget::Compact);
}
for value in [serde_json::json!(null), serde_json::json!(true), serde_json::json!(17), serde_json::json!("unlimited")] {
assert!(serde_json::from_value::<CpuJob>(serde_json::json!({"dielectric_transport":value})).is_err());
}
}
#[cfg(test)]
#[test]
fn cpu_dielectric_transport_document_roundtrip_keeps_choice_without_captured_bindings() {
for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] {
let setup = crate::render_settings::RenderSetup {
job: Some(RenderJob::CpuRaytrace { options: CpuJob { dielectric_transport: policy, ..Default::default() } }),
..Default::default()
};
let mut document = crate::Document::default();
std::sync::Arc::make_mut(&mut document.render).setups.insert("Policy".into(), setup.clone());
let reopened = crate::Document::from_json(&document.to_json()).unwrap();
assert_eq!(document, reopened);
assert_eq!(reopened.render.setups["Policy"], setup);
let Some(RenderJob::CpuRaytrace { options }) = &reopened.render.setups["Policy"].job else { panic!("saved CPU method changed") };
assert_eq!(options.to_runtime(0.0).unwrap().dielectric_transport, policy);
}
}
+124 -2
View File
@@ -238,6 +238,81 @@ mod tests {
use crate::Document;
use std::sync::Arc;
#[test]
fn raster_saved_exposure_uses_the_existing_field_and_roundtrips_its_real_bounds() {
for ev in [-32.0, -1.0, 0.0, 1.0, 2.0, 32.0] {
let setup =
RenderSetup { exposure_ev: ev, job: Some(RenderJob::Raster { transparent_background: false, lights: None }), ..Default::default() };
setup.validate().unwrap();
let mut document = Document::default();
Arc::make_mut(&mut document.render).setups.insert("EV".into(), setup.clone());
let loaded = Document::from_json(&document.to_json()).unwrap();
assert_eq!(loaded.render.setups["EV"], setup);
}
}
#[test]
fn raster_directional_jobs_roundtrip_original_intent_and_omit_legacy_none() {
use serde_json::json;
use solidcraft_render::job::DirectionalLightOptions;
let old = json!({"method":"raster","transparent_background":false});
let job: RenderJob = serde_json::from_value(old.clone()).unwrap();
assert_eq!(serde_json::to_value(&job).unwrap(), old);
let null: RenderJob = serde_json::from_value(json!({"method":"raster","lights":null})).unwrap();
assert_eq!(null, job);
let source = DirectionalLightOptions { direction: [3.0, -4.0, 0.0], color: [0.25, 0.5, 1.0], intensity: 2.0 };
for count in [0, 1, 8] {
let setup = RenderSetup {
job: Some(RenderJob::Raster { transparent_background: true, lights: Some(vec![source.clone(); count]) }),
width: 32,
height: 24,
background: [17, 29, 53],
..Default::default()
};
setup.validate().unwrap();
let mut document = Document::default();
let settings = Arc::make_mut(&mut document.render);
settings.setups.insert("Raster".into(), setup.clone());
settings
.setups
.insert("CPU".into(), RenderSetup { job: Some(RenderJob::CpuRaytrace { options: CpuJob::default() }), ..Default::default() });
settings.setups.insert(
"GPU".into(),
RenderSetup { job: Some(RenderJob::GpuPath { transparent_background: false, options: Box::default() }), ..Default::default() },
);
let loaded = Document::from_json(&document.to_json()).unwrap();
assert_eq!(loaded, document);
assert_eq!(loaded.render.setups["Raster"], setup);
let Some(RenderJob::Raster { lights: Some(lights), .. }) = &loaded.render.setups["Raster"].job else {
panic!("saved method or explicit rig lost")
};
assert_eq!(lights, &vec![source.clone(); count]);
}
}
#[test]
fn saved_raster_rigs_refuse_invalid_values_unknown_controls_and_excess_capacity() {
use serde_json::json;
let light = json!({"direction":[0,0,1],"color":[1,1,1],"intensity":1});
for job in [
json!({"method":"raster","lights":vec![light;9]}),
json!({"method":"raster","lights":[{"direction":[0,0,0],"color":[1,1,1],"intensity":0}]}),
json!({"method":"raster","lights":[{"direction":[0,0,1],"color":[2,1,1],"intensity":1}]}),
json!({"method":"raster","lights":[],"options":{"shadows":true}}),
] {
assert!(serde_json::from_value::<RenderJob>(job).is_err());
}
let setup =
RenderSetup { job: Some(RenderJob::Raster { transparent_background: false, lights: Some(Vec::with_capacity(9)) }), ..Default::default() };
assert!(setup.validate().is_err());
let exposure = RenderSetup {
exposure_ev: 33.0,
job: Some(RenderJob::Raster { transparent_background: false, lights: Some(Vec::new()) }),
..Default::default()
};
assert!(exposure.validate().is_err());
}
#[test]
fn saved_light_coordinates_are_admitted_only_when_the_document_can_reopen() {
use serde_json::json;
@@ -642,8 +717,9 @@ mod tests {
for setup in [
json!({"job":{}}),
json!({"job":{"method":"cpu_raytrace","options":{"primary_samples":2}}}),
json!({"exposure_ev":17,"job":{"method":"cpu_raytrace"}}),
json!({"exposure_ev":1,"job":{"method":"raster"}}),
// CPU17 is now valid within the shared saved range;33 remains invalid.
json!({"exposure_ev":33,"job":{"method":"cpu_raytrace"}}),
json!({"exposure_ev":33,"job":{"method":"raster"}}),
json!({"environment_rotation":0.5,"job":{"method":"gpu_path"}}),
json!({"environment_intensity":0,"job":{"method":"cpu_raytrace"}}),
json!({"job":{"method":"cpu_raytrace","options":{"seed":-1}}}),
@@ -739,7 +815,9 @@ mod tests {
#[cfg(test)]
mod cpu_budget_tests {
use super::*;
use crate::Document;
use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions};
use std::sync::Arc;
#[test]
fn inactive_area_tuning_roundtrips_without_leaking_into_runtime_options() {
@@ -783,4 +861,48 @@ mod cpu_budget_tests {
let legacy_large = RenderSetup { width: 3840, height: 2160, ..Default::default() };
assert!(legacy_large.validate().is_err(), "large intent must name an explicit CPU job profile");
}
#[test]
fn cpu_exposure_expanded_range_roundtrips_offline_with_one_saved_authority() {
use serde_json::json;
assert_eq!(RenderSetup::default().exposure_ev, 0.0);
for ev in [-32.0, -17.0, 17.0, 32.0] {
for progressive in [false, true] {
let mut options = json!({"lights":[],"shadows":false});
if progressive {
options["progressive"] = json!({"samples_per_pixel":3,"seed":31});
}
let saved = json!({"setups":{"EV":{"width":2,"height":1,"exposure_ev":ev,
"job":{"method":"cpu_raytrace","options":options}}}});
let settings: RenderSettings = serde_json::from_value(saved).unwrap();
let document = Document { render: Arc::new(settings), ..Default::default() };
let text = document.to_json();
let wire: serde_json::Value = serde_json::from_str(&text).unwrap();
let pending = crate::format::pending_names();
if !pending.is_empty() {
assert_eq!(wire["format_pending"], json!(pending));
}
let reopened = Document::from_json(&text).unwrap();
assert_eq!(document, reopened);
let setup = &reopened.render.setups["EV"];
assert_eq!(setup.exposure_ev, ev);
let RenderJob::CpuRaytrace { options } = setup.job.as_ref().unwrap() else { panic!("CPU method changed") };
let runtime = options.to_runtime(setup.exposure_ev).unwrap();
assert_eq!(runtime.exposure_ev, ev);
assert_eq!(runtime.budget, solidcraft_render::job::CpuBudget::Compact);
assert_eq!(runtime.progressive.is_some(), progressive);
assert!(serde_json::to_value(options).unwrap().get("exposure_ev").is_none());
}
}
}
#[test]
fn cpu_exposure_expansion_keeps_nonfinite_and_outside_saved_values_invalid() {
for ev in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -33.0, 33.0, -32.01, 32.01] {
let options = CpuJob::default();
assert!(options.to_runtime(ev).is_err());
let setup = RenderSetup { exposure_ev: ev, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() };
assert!(setup.validate().is_err());
}
}
}
-363
View File
@@ -1,363 +0,0 @@
//! Equation curves (#8352): the points of a sketch curve worked out from its formulas over the
//! design's parameters. The formulas are evaluated at evenly spaced values of the curve's
//! variable; the sketch draws a cubic fit spline through those points. How many points: as many
//! as it takes for the spline to stay within the curve's tolerance of the formulas, checked
//! between the points, up to the most a spline takes. When the parameters change, the same
//! number of points is placed again (`Document::apply_equation_values`), before every solve.
use std::collections::BTreeMap;
use solidcraft_geom::Vec2;
use solidcraft_sketch::{EquationCurve, MAX_COORD, MAX_EQUATION_TEXT, MAX_SPLINE_POINTS, Sketch, fit_beziers_mode};
use crate::expr::{self, Defaults, Kind, Value};
use crate::{DocError, Result};
/// The tolerance a new equation curve gets (mm).
pub const DEFAULT_TOLERANCE: f64 = 0.01;
/// The tightest and loosest tolerances (mm).
pub const MIN_TOLERANCE: f64 = 1e-4;
pub const MAX_TOLERANCE: f64 = 10.0;
/// The fewest points a fit starts from.
const FIRST_COUNT: usize = 9;
/// The widest range of the variable.
const MAX_RANGE: f64 = 1e6;
/// How many times the point count is raised before the fit gives up.
const MAX_ROUNDS: usize = 12;
/// An equation curve's points and how well the spline through them follows the formulas.
#[derive(Clone, Debug, PartialEq)]
pub struct EquationFit {
/// The spline's points in order; a closed curve's last point is its first one again.
pub points: Vec<Vec2>,
/// The curve ends where it starts: the spline closes smoothly there.
pub closed: bool,
/// The largest distance (mm) found between the spline and the formulas.
pub deviation: f64,
}
/// How bare numbers read in the formulas: angles in radians (the variable is a plain number,
/// `sin(t)` its sine), lengths in the design's unit.
fn defaults(vals: &BTreeMap<String, Value>) -> Defaults {
let len = vals.get(crate::eval::DESIGN_LEN).map(|v| v.v).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0);
Defaults { len, ang: 1.0 }
}
fn checked_text<'a>(what: &str, e: &'a str) -> Result<&'a str> {
let e = e.trim();
if e.is_empty() {
return Err(DocError::Invalid(format!("{what} is empty")));
}
if e.chars().count() > MAX_EQUATION_TEXT {
return Err(DocError::Invalid(format!("{what} is longer than {MAX_EQUATION_TEXT} characters")));
}
Ok(e)
}
/// A formula's value (mm) where the variable is `at`. The variable hides a parameter of its name.
fn formula(vals: &BTreeMap<String, Value>, e: &str, variable: &str, at: f64, d: Defaults) -> Result<f64> {
let lookup = |n: &str| {
if n == variable { Ok(Value::num(at)) } else { vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))) }
};
let v = expr::eval_with_defaults(e, &lookup, d)?.to_kind_in(Kind::Length, d)?;
if v.is_finite() && v.abs() < MAX_COORD { Ok(v) } else { Err(DocError::Expr("the curve goes out of range".into())) }
}
/// Where the variable starts or ends, as the plain number the formulas see: a number, an angle
/// (in radians) or a length (in the design's unit).
fn range_end(vals: &BTreeMap<String, Value>, e: &str, d: Defaults) -> Result<f64> {
let v = expr::eval_with_defaults(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), d)?;
let out = match v.kind() {
Some(Kind::Unitless | Kind::Angle) => v.v,
Some(Kind::Length) => v.v / d.len,
None => return Err(DocError::Expr(format!("expected a number, an angle or a length, got {}", v.describe()))),
};
if out.is_finite() { Ok(out) } else { Err(DocError::Expr("not a finite number".into())) }
}
/// The variable's range, checked.
fn range(vals: &BTreeMap<String, Value>, eq: &EquationCurve, d: Defaults) -> Result<(f64, f64)> {
let a = range_end(vals, checked_text("the start", &eq.start)?, d).map_err(|e| DocError::Expr(format!("start: {e}")))?;
let b = range_end(vals, checked_text("the end", &eq.end)?, d).map_err(|e| DocError::Expr(format!("end: {e}")))?;
if (b - a).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0) {
return Err(DocError::Invalid("the start and the end of the range must differ".into()));
}
if (b - a).abs() > MAX_RANGE {
return Err(DocError::Invalid(format!("the range is wider than {MAX_RANGE}")));
}
Ok((a, b))
}
/// The curve's point where the variable is `at`.
fn point_at(vals: &BTreeMap<String, Value>, eq: &EquationCurve, at: f64, d: Defaults) -> Result<Vec2> {
let variable = eq.variable();
let x = match &eq.x {
Some(e) => formula(vals, e, variable, at, d).map_err(|e| DocError::Expr(format!("x: {e}")))?,
// The explicit form: x is the variable, in the design's unit.
None => {
let x = at * d.len;
if !(x.is_finite() && x.abs() < MAX_COORD) {
return Err(DocError::Expr("the curve goes out of range".into()));
}
x
}
};
let y = formula(vals, &eq.y, variable, at, d).map_err(|e| DocError::Expr(format!("y: {e}")))?;
Ok(Vec2::new(x, y))
}
/// The formulas' points at `count` evenly spaced values of the variable, from start to end.
fn samples(vals: &BTreeMap<String, Value>, eq: &EquationCurve, (a, b): (f64, f64), count: usize, d: Defaults) -> Result<Vec<Vec2>> {
let last = count.saturating_sub(1).max(1) as f64;
(0..count)
.map(|i| {
let at = a + (b - a) * (i as f64 / last);
point_at(vals, eq, at, d).map_err(|e| DocError::Expr(format!("at {} = {}: {e}", eq.variable(), short(at))))
})
.collect()
}
/// A number short enough for a message.
fn short(v: f64) -> String {
let s = format!("{v:.6}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
/// The size of the curve: the larger side of its box (for closing tolerances).
fn extent(points: &[Vec2]) -> f64 {
let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
for p in points {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
(hi.x - lo.x).max(hi.y - lo.y).max(0.0)
}
/// Does a curve through these samples end where it starts?
fn closes(points: &[Vec2]) -> bool {
match (points.first(), points.last()) {
(Some(a), Some(b)) => points.len() >= 4 && a.dist(*b) <= 1e-7 * extent(points).max(1.0),
_ => false,
}
}
/// Refuse samples a spline cannot pass through: two in a row on the same spot, or all of them.
fn check_samples(points: &[Vec2], closed: bool) -> Result<()> {
let size = extent(points);
if size <= 1e-9 {
return Err(DocError::Invalid("the formulas give the same point all along the range".into()));
}
let spans = if closed { points.len().saturating_sub(1) } else { points.len() };
for w in points.windows(2).take(spans) {
if let [p, q] = w
&& p.dist(*q) <= 1e-9 * size.max(1.0)
{
return Err(DocError::Invalid("the curve stands still between two of its points: narrow the range or use fewer points".into()));
}
}
Ok(())
}
/// Distance from `q` to the cubic Bézier `b`, sampled finely.
fn bezier_distance(b: &[Vec2; 4], q: Vec2) -> f64 {
const STEPS: usize = 32;
let at = |t: f64| {
let s = 1.0 - t;
b[0] * (s * s * s) + b[1] * (3.0 * t * s * s) + b[2] * (3.0 * t * t * s) + b[3] * (t * t * t)
};
let mut best = f64::INFINITY;
let mut prev = at(0.0);
for i in 1..=STEPS {
let next = at(i as f64 / STEPS as f64);
let d = next - prev;
let l2 = d.len2();
let t = if l2 > 0.0 { ((q - prev).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
best = best.min(q.dist(prev + d * t));
prev = next;
}
best
}
/// How far the spline through `points` strays from the formulas: the largest distance from the
/// formulas' points a quarter, a half and three quarters of the way between two samples to the
/// spline's piece between them.
fn deviation(vals: &BTreeMap<String, Value>, eq: &EquationCurve, (a, b): (f64, f64), points: &[Vec2], closed: bool, d: Defaults) -> Result<f64> {
let pieces = fit_beziers_mode(points, closed).map_err(|e| DocError::Invalid(e.to_string()))?;
let step = (b - a) / points.len().saturating_sub(1).max(1) as f64;
let mut worst: f64 = 0.0;
for (i, piece) in pieces.iter().enumerate() {
for k in [0.25, 0.5, 0.75] {
let q = point_at(vals, eq, a + step * (i as f64 + k), d)?;
worst = worst.max(bezier_distance(piece, q));
}
}
Ok(worst)
}
/// Check an equation's text and tolerance before any evaluation.
pub fn check(eq: &EquationCurve) -> Result<()> {
if let Some(x) = &eq.x {
checked_text("x(t)", x)?;
}
checked_text(if eq.x.is_some() { "y(t)" } else { "y(x)" }, &eq.y)?;
checked_text("the start", &eq.start)?;
checked_text("the end", &eq.end)?;
if !(eq.tolerance.is_finite() && (MIN_TOLERANCE..=MAX_TOLERANCE).contains(&eq.tolerance)) {
return Err(DocError::Invalid(format!("the tolerance must be from {MIN_TOLERANCE} mm to {MAX_TOLERANCE} mm")));
}
Ok(())
}
/// The points of `count` samples (a closed curve's last one is its first), whether it closes,
/// and how far the spline through them strays.
pub fn sample(vals: &BTreeMap<String, Value>, eq: &EquationCurve, count: usize, closed: Option<bool>) -> Result<EquationFit> {
check(eq)?;
if !(2..=MAX_SPLINE_POINTS).contains(&count) {
return Err(DocError::Invalid(format!("an equation curve takes 2 to {MAX_SPLINE_POINTS} points")));
}
let d = defaults(vals);
let span = range(vals, eq, d)?;
let mut points = samples(vals, eq, span, count, d)?;
let closed = closed.unwrap_or_else(|| closes(&points)) && count >= 4;
if closed
&& let Some(first) = points.first().copied()
&& let Some(last) = points.last_mut()
{
*last = first;
}
check_samples(&points, closed)?;
let deviation = deviation(vals, eq, span, &points, closed, d)?;
Ok(EquationFit { points, closed, deviation })
}
/// The points of an equation curve, as few as keep the spline within its tolerance of the
/// formulas. Refused when even the most points a spline takes are not close enough.
pub fn fit(vals: &BTreeMap<String, Value>, eq: &EquationCurve) -> Result<EquationFit> {
let mut count = FIRST_COUNT;
for _ in 0..MAX_ROUNDS {
let fit = sample(vals, eq, count, None)?;
if fit.deviation <= eq.tolerance {
return Ok(fit);
}
if count >= MAX_SPLINE_POINTS {
return Err(DocError::Invalid(format!(
"even {MAX_SPLINE_POINTS} points stray {} mm from the formulas, more than the tolerance of {} mm: raise the tolerance or narrow the range",
short(fit.deviation),
short(eq.tolerance)
)));
}
// A cubic fit's error falls with the fourth power of the spacing: aim a little past
// what that asks for, at least half as many points again.
let ratio = (fit.deviation / eq.tolerance).powf(0.25) * 1.2;
let next = (count as f64 * ratio.max(1.5)).ceil();
count = if next.is_finite() && next < MAX_SPLINE_POINTS as f64 { next as usize } else { MAX_SPLINE_POINTS };
}
Err(DocError::Invalid("the equation curve's points could not be fitted".into()))
}
impl crate::Document {
/// Place the points of the sketch's equation curves where their formulas put them now (in
/// place), with the number of points each has. Their points are fixed, so the solve keeps
/// them there. A curve that is gone or is no longer a fit point spline is left as it is.
pub fn apply_equation_values(&self, vals: &BTreeMap<String, Value>, sk: &mut Sketch) -> Result<()> {
for k in 0..sk.equations.len() {
let Some(eq) = sk.equations.get(k).cloned() else { continue };
let Some(ci) = sk.curve_index(&eq.curve) else { continue };
let Some(solidcraft_sketch::CurveKind::Spline { pts, control: false, periodic, .. }) = sk.curves.get(ci).map(|c| &c.kind) else {
continue;
};
let (count, closed) = (pts.len(), *periodic);
let fit = sample(vals, &eq, count, Some(closed)).map_err(|e| DocError::Expr(format!("equation curve {}: {e}", eq.curve)))?;
sk.place_equation_points(ci, &fit.points)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn eq(x: Option<&str>, y: &str, start: &str, end: &str) -> EquationCurve {
EquationCurve {
curve: String::new(),
x: x.map(str::to_string),
y: y.into(),
start: start.into(),
end: end.into(),
tolerance: DEFAULT_TOLERANCE,
}
}
#[test]
fn a_circle_closes_and_stays_within_the_tolerance() {
let vals = BTreeMap::new();
let fit = fit(&vals, &eq(Some("10 * cos(t)"), "10 * sin(t)", "0", "2 * pi")).unwrap();
assert!(fit.closed);
assert!(fit.deviation <= DEFAULT_TOLERANCE, "{}", fit.deviation);
for p in &fit.points {
assert!((p.len() - 10.0).abs() < 1e-9, "{p:?}");
}
assert_eq!(fit.points.first(), fit.points.last());
}
#[test]
fn the_variable_hides_a_parameter_and_parameters_drive_the_curve() {
let mut vals = BTreeMap::new();
vals.insert("t".to_string(), Value::length(1000.0));
vals.insert("amp".to_string(), Value::length(5.0));
let fit = fit(&vals, &eq(None, "amp * sin(x / 10)", "0 mm", "100 mm")).unwrap();
assert!(!fit.closed);
let (first, last) = (fit.points[0], *fit.points.last().unwrap());
assert!((first - Vec2::new(0.0, 0.0)).len() < 1e-9, "{first:?}");
assert!((last.x - 100.0).abs() < 1e-9 && (last.y - 5.0 * 10f64.sin()).abs() < 1e-9, "{last:?}");
assert!(fit.points.iter().all(|p| p.y.abs() <= 5.0 + 1e-9));
}
#[test]
fn a_design_in_inches_reads_bare_numbers_in_inches() {
let mut vals = BTreeMap::new();
vals.insert(crate::eval::DESIGN_LEN.to_string(), Value::num(25.4));
let fit = fit(&vals, &eq(Some("t"), "2", "0", "1")).unwrap();
let last = *fit.points.last().unwrap();
assert!((last - Vec2::new(25.4, 50.8)).len() < 1e-9, "{last:?}");
}
#[test]
fn more_points_where_the_tolerance_is_tighter() {
let vals = BTreeMap::new();
let mut e = eq(Some("t * cos(t)"), "t * sin(t)", "0", "6 * pi");
e.tolerance = 0.1;
let loose = fit(&vals, &e).unwrap();
e.tolerance = 0.005;
let tight = fit(&vals, &e).unwrap();
assert!(tight.points.len() > loose.points.len(), "{} vs {}", tight.points.len(), loose.points.len());
assert!(tight.deviation <= 0.005 && loose.deviation <= 0.1);
}
#[test]
fn hostile_formulas_and_ranges_are_refused() {
let vals = BTreeMap::new();
for (x, y, a, b, tol) in [
(Some("t"), "sqrt(t)", "-1", "1", DEFAULT_TOLERANCE),
(Some("t"), "1 / t", "-1", "1", DEFAULT_TOLERANCE),
(Some("t"), "t", "0", "0", DEFAULT_TOLERANCE),
(Some("t"), "t", "0", "1e300", DEFAULT_TOLERANCE),
(Some("t"), "t", "0", "nan", DEFAULT_TOLERANCE),
(Some("t * 1 deg"), "t", "0", "1", DEFAULT_TOLERANCE),
(Some("1e300 * t"), "t", "0", "1", DEFAULT_TOLERANCE),
(Some("5"), "5", "0", "1", DEFAULT_TOLERANCE),
(Some(""), "t", "0", "1", DEFAULT_TOLERANCE),
(Some("t"), "t", "0", "1", f64::NAN),
(Some("t"), "t", "0", "1", 0.0),
(Some("t"), "unknown_name * t", "0", "1", DEFAULT_TOLERANCE),
(Some("t"), "sin(1e5 * t)", "0", "1000", 1e-4),
] {
let mut e = eq(x, y, a, b);
e.tolerance = tol;
assert!(fit(&vals, &e).is_err(), "{x:?} {y} {a}..{b} {tol}");
}
let long = "t + ".repeat(400) + "t";
assert!(fit(&vals, &eq(Some(&long), "t", "0", "1")).is_err());
}
}
+2 -2
View File
@@ -23,9 +23,9 @@ pub struct TextParam {
pub comment: String,
}
/// Is `unit` the text unit, ignoring ASCII case and surrounding whitespace?
/// Is `unit` the text unit?
pub fn is_text_unit(unit: &str) -> bool {
unit.trim().eq_ignore_ascii_case(TEXT_UNIT)
unit.trim() == TEXT_UNIT
}
/// A text as typed for a text parameter: inside matching quotes, what they hold (a quote doubled
+1 -1
View File
@@ -39,7 +39,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Origin planes become explicit planes so a translation can move them.
pub(in crate::cmd) fn explicit_planes(p: &mut PlaneRef) {
fn explicit_planes(p: &mut PlaneRef) {
match p {
PlaneRef::Origin { name } => {
if let Some(plane) = solidcraft_geom::Plane::named(name) {
+2 -41
View File
@@ -12,35 +12,26 @@ use solidcraft_geom::Vec3;
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list, vec3};
use crate::schema::component::{
EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, OccurrenceAlignParams,
OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult,
EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, OccurrenceAlignParams, OccurrenceAlignResult,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
const EDIT_IN_PLACE_CONTRACT: TypedContract<EditInPlaceParams> = TypedContract::new();
const FINISH_EDIT_CONTRACT: TypedContract<FinishEditParams> = TypedContract::new();
const MOVE_FEATURES_CONTRACT: TypedContract<MoveFeaturesParams> = TypedContract::new();
const REPARENT_ITEMS_CONTRACT: TypedContract<ReparentItemsParams> = TypedContract::new();
#[path = "component_align.rs"]
mod align;
#[path = "component_drag.rs"]
mod drag;
#[path = "component_foreign.rs"]
mod foreign;
#[path = "component_matrix.rs"]
pub(super) mod matrix;
#[path = "component_move_features.rs"]
mod move_features;
#[path = "component_placing.rs"]
pub(super) mod placing;
#[path = "component_properties.rs"]
pub(super) mod properties;
#[path = "component_reparent.rs"]
mod reparent;
#[path = "component_reparent_items.rs"]
mod reparent_items;
#[path = "component_transfer.rs"]
mod transfer;
@@ -112,37 +103,7 @@ pub static COMMANDS: &[CommandSpec] = &[
by (default: its only one, else the active one; a component placed more than once gets them in every instance). Each \
copy stays where its body is in the world; the copies' names come back as `bodies`",
),
CommandSpec::new("component.paste_from_design", "Paste from Another Design", foreign::paste_from_design).icon("paste").params(
"component?: where it goes (default: the active one); component_path?: its placement (default: the active one, else its \
only one). Pastes what was copied in another design, at the same world coordinates: its bodies as imported bodies \
(no history) in one Import feature, or its components as independent copies with their history, appearances, \
joints and motion (as `component.paste_new`); the user parameters they use come along, renamed `w_2` when taken. \
A component that uses what isn't in it (another body, sketch or parameter) is refused, saying what. Returns \
`bodies` and `feature`, or the pasted components' `paths`",
),
CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches)
.icon("move")
.params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world)"),
CommandSpec::new("component.move_features", "Move Features to Component", crate::checked!("component.move_features", move_features::move_features))
.icon("move")
.contract(&MOVE_FEATURES_CONTRACT)
.output(output_schema_for::<MoveFeaturesResult>)
.params(
"features: [ids or names] (sketches too); component?: where they go (default: the active one) → moved, component, bodies. \
Ids, names and timeline order stay; the geometry stays where it is in the world; the bodies the features made move with \
them. Refused while the timeline is rolled back, for a component placed more than once, and for a move that would break \
a feature (nothing changes)",
),
CommandSpec::new("browser.reparent", "Move to Component", crate::checked!("browser.reparent", reparent_items::reparent_items))
.icon("move")
.contract(&REPARENT_ITEMS_CONTRACT)
.output(output_schema_for::<ReparentItemsResult>)
.params(
"Moves placements, features and bodies into a component. occurrences?: [ids or paths], features?: [ids or names], bodies?: [names], component?: where they go (default: the active \
one), component_path?: its placement → component, occurrences, features, bodies (what moved). One undo step, all or \
nothing: placements move first (taking what they hold), then features (taking the bodies they made), then the bodies \
still elsewhere (a body transfer, which leaves its features behind)",
),
CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches).icon("move").params("sketches: [ids or names], component"),
CommandSpec::new("occurrence.copy", "Paste (Instance)", copy_occurrence).icon("copy")
.params("component (or occurrence): what to place again; path?: validates selected occurrence; parent?: component (default: the same parent); translate?: [x,y,z]; in_place?: bool (default false: the selected transform within the parent; true: where the selected placement is in the world, translate in world axes; a parent placed more than once is placed by parent_path?, else the active placement, and every instance gets the copy). Copies the selected effective transform, including pending moves"),
CommandSpec::new("component.paste_new", "Paste New", paste_new).icon("paste").params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; parent?: component the copy goes in (default: the source placement's; not the component or one inside it); in_place?, parent_path?: as occurrence.copy; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"),
+56 -211
View File
@@ -83,10 +83,8 @@ fn cloned_path(source: &Document, path: &[u64], root: u64, destination: &[u64],
Ok(mapped)
}
/// A name for a copy of `base` that isn't in `used` (and then is): numbered, or with `keep`
/// (pasting into another design, where the original isn't) `base` itself while it is free.
fn unique(base: &str, used: &mut BTreeSet<String>, keep: bool) -> String {
let name = if keep && !used.contains(base.trim()) { base.trim().to_string() } else { solidcraft_doc::copy_name(base, |n| used.contains(n)) };
fn unique(base: &str, used: &mut BTreeSet<String>) -> String {
let name = solidcraft_doc::copy_name(base, |n| used.contains(n));
used.insert(name.clone());
name
}
@@ -184,32 +182,6 @@ fn graph(doc: &Document, root: u64) -> Result<Vec<u64>> {
Ok(sorted)
}
/// The design Paste New copies from: its document, its evaluated model and its placements moved
/// but not yet applied. The session pasted into is the target; they are the same design for a
/// paste within one design.
pub(super) struct Source<'a> {
pub doc: &'a Document,
pub model: &'a solidcraft_doc::Model,
pub pending_moves: &'a BTreeMap<u64, Mat>,
/// Another design than the target: the copy can't point at anything outside it (it is
/// refused, saying what), and the user parameters it uses come along.
pub other_design: bool,
}
impl<'a> Source<'a> {
/// The session's own design.
pub fn of(s: &'a Session) -> Source<'a> {
Source { doc: &s.doc, model: &s.model, pending_moves: &s.pending_moves, other_design: false }
}
/// What was copied in another design.
pub fn copied(copy: &'a crate::ForeignCopy) -> Source<'a> {
Source { doc: &copy.doc, model: &copy.model, pending_moves: &copy.pending_moves, other_design: true }
}
}
/// An independent copy of `component` (and what it holds), from the session's own design, into
/// `parent`.
pub(super) fn paste(
s: &mut Session,
component: u64,
@@ -218,26 +190,7 @@ pub(super) fn paste(
parent: u64,
params: &Value,
) -> Result<Value> {
let (scratch, out) = build(s, &Source::of(s), component, source_occurrence, transform, parent, None, params)?;
s.accept_computed(scratch);
Ok(out)
}
/// [`paste`] from `origin` into `s`: the computed session to accept, and what the paste made.
/// `parent_path`: the placement of `parent` the copy is placed by (default: the source
/// placement's parent's).
#[allow(clippy::too_many_arguments)]
pub(super) fn build(
s: &Session,
origin: &Source<'_>,
component: u64,
source_occurrence: Option<Occurrence>,
transform: Mat,
parent: u64,
parent_path: Option<Vec<u64>>,
params: &Value,
) -> Result<(Session, Value)> {
let source = origin.doc;
let source = s.doc.clone();
let source_parameters: BTreeMap<_, _> = source.params.iter().map(|p| (p.name.as_str(), p)).collect();
let generated_parameters: BTreeSet<_> = source
.params
@@ -246,25 +199,22 @@ pub(super) fn build(
.map(|p| p.name.as_str())
.chain(source.features.iter().flat_map(|f| f.param_names.iter().map(String::as_str)))
.collect();
let definitions = graph(source, component)?;
let definitions = graph(&source, component)?;
let definition_records: BTreeMap<_, _> = source.components.iter().map(|c| (c.id, c)).collect();
let selected: BTreeSet<_> = definitions.iter().copied().collect();
if source.marker.is_some_and(|m| m < source.features.len()) {
return Err(bad(CMD, "move the timeline marker to the end before Paste New"));
}
if origin.other_design && s.doc.marker.is_some_and(|m| m < s.doc.features.len()) {
return Err(bad(CMD, "move the timeline marker to the end in this design before pasting"));
}
let feats: Vec<Feature> = source.features.iter().filter(|f| selected.contains(&f.component)).cloned().collect();
if feats.len() + source.features.len() > MAX_WORK {
return Err(bad(CMD, "too many features to copy"));
}
for f in &feats {
if origin.model.result(f.id).is_some_and(|r| r.error.is_some()) {
if s.model.result(f.id).is_some_and(|r| r.error.is_some()) {
return Err(bad(CMD, format!("source feature {} has an evaluation error", f.name)));
}
}
let state = origin.model.state();
let state = s.model.state();
if state.bodies.len() > MAX_WORK {
return Err(bad(CMD, "body set exceeds copy work limit"));
}
@@ -278,12 +228,11 @@ pub(super) fn build(
let mut names = BTreeMap::new();
let mut bodies = BTreeMap::new();
let mut parameters = BTreeMap::new();
// Names are numbered among their own kind, against the names the target has: a component
// named after its body takes the same number as the body's copy, and neither skips one the
// other took.
let mut used_components: BTreeSet<String> = s.doc.components.iter().map(|c| c.name.clone()).collect();
let mut used_features: BTreeSet<String> = s.doc.features.iter().map(|f| f.name.clone()).collect();
let mut used_bodies: BTreeSet<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
// Names are numbered among their own kind: a component named after its body takes the same
// number as the body's copy, and neither skips one the other took.
let mut used_components: BTreeSet<String> = source.components.iter().map(|c| c.name.clone()).collect();
let mut used_features: BTreeSet<String> = source.features.iter().map(|f| f.name.clone()).collect();
let mut used_bodies: BTreeSet<String> = state.bodies.iter().map(|b| b.name.clone()).collect();
let mut new_ids = Vec::new();
let mut frozen = Vec::new();
// Allocate definitions, discarding their automatic placeholder occurrence except root.
@@ -294,7 +243,7 @@ pub(super) fn build(
} else {
components.get(&c.parent).copied().unwrap_or(*components.get(&component).ok_or_else(|| bad(CMD, "missing clone root"))?)
};
let name = unique(&c.name, &mut used_components, origin.other_design);
let name = unique(&c.name, &mut used_components);
let new = scratch.doc_mut().add_component(Some(&name), mapped_parent)?;
// A copy keeps the definition's part properties.
if let Some(added) = scratch.doc_mut().components.iter_mut().find(|x| x.id == new) {
@@ -309,14 +258,12 @@ pub(super) fn build(
}
let root = *components.get(&component).ok_or_else(|| bad(CMD, "missing clone root"))?;
let root_occurrence = scratch.doc.occurrence_of(root).map(|o| o.id).ok_or_else(|| bad(CMD, "missing cloned placement"))?;
let mut clone_path = if let Some(path) = parent_path {
path
} else if let Some(o) = &source_occurrence {
let mut clone_path = if let Some(o) = &source_occurrence {
let mut path = super::component::occurrence_path(s, params, o.id, CMD)?;
path.pop();
path
} else {
s.doc.first_path(parent)
source.first_path(parent)
};
clone_path.push(root_occurrence);
if let Some(o) = scratch.doc_mut().occurrences.iter_mut().find(|o| o.id == root_occurrence) {
@@ -330,7 +277,7 @@ pub(super) fn build(
for old in source.occurrences.iter().filter(|o| selected.contains(&o.parent)) {
let child = *components.get(&old.component).ok_or_else(|| bad(CMD, "missing child definition"))?;
let owner = *components.get(&old.parent).ok_or_else(|| bad(CMD, "missing parent definition"))?;
let pose = origin.pending_moves.get(&old.id).copied().unwrap_or(old.transform);
let pose = s.pending_moves.get(&old.id).copied().unwrap_or(old.transform);
if !super::component::valid_position(&pose) {
return Err(bad(CMD, "invalid internal pending occurrence transform"));
}
@@ -345,10 +292,10 @@ pub(super) fn build(
// The names the bodies of a feature have in the model, where they are its stored names, numbered.
let mut shown: BTreeMap<u64, Vec<String>> = BTreeMap::new();
for f in &feats {
if let Some(result) = origin.model.result(f.id) {
if let Some(result) = s.model.result(f.id) {
let created: Vec<_> = result.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.clone()).collect();
for name in &created {
bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies, origin.other_design));
bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies));
}
if named_by(&f.body_names, &created) {
shown.insert(f.id, created.clone());
@@ -360,7 +307,7 @@ pub(super) fn build(
if !shown.contains_key(&f.id) {
for name in &f.body_names {
if !name.is_empty() {
bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies, origin.other_design));
bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies));
}
}
}
@@ -381,32 +328,23 @@ pub(super) fn build(
!f.suppressed
&& matches!(&f.kind, FeatureKind::BodyTransfer { bodies, from, to, .. }
if !selected.contains(from) && bodies.iter().any(|b| *b == body.name)
&& origin.model.result(f.id).is_some_and(|result| !result.skipped && result.error.is_none()
&& s.model.result(f.id).is_some_and(|result| !result.skipped && result.error.is_none()
&& result.state.body(&body.name).is_some_and(|entered| source.model_body_component(entered) == *to)))
});
let before = feats.iter().find_map(|f| {
let before = origin.model.state_before(f.id);
let before = s.model.state_before(f.id);
let prior = before.body(&body.name)?;
let after = origin.model.result(f.id)?.state.body(&body.name);
let after = s.model.result(f.id)?.state.body(&body.name);
if after.is_none_or(|after| !prior.body.same(&after.body)) { Some(before) } else { None }
});
let entered = entry.and_then(|f| origin.model.result(f.id)).map(|r| r.state.clone());
let entered = entry.and_then(|f| s.model.result(f.id)).map(|r| r.state.clone());
let base = entered.as_ref().and_then(|st| st.body(&body.name)).or_else(|| before.as_ref().and_then(|st| st.body(&body.name))).unwrap_or(body);
let baseline_component = source.model_body_component(base);
let geometry = solidcraft_kernel::transform_matrix(&base.body, offset)?;
let step = solidcraft_kernel::step_export(&[&geometry], "SolidCraft independent reassigned body")?;
let new_name = unique(&body.name, &mut used_bodies, origin.other_design);
let new_name = unique(&body.name, &mut used_bodies);
bodies.insert(body.name.clone(), new_name.clone());
// From another design it is named as what it is there, an imported body, numbered as
// the timeline numbers its features ("BodyImport1").
let feature_name = if origin.other_design {
let name =
(1..=MAX_WORK + 1).map(|n| format!("BodyImport{n}")).find(|n| !used_features.contains(n)).unwrap_or_else(|| "BodyImport".into());
used_features.insert(name.clone());
name
} else {
unique(&format!("{} Base", body.name), &mut used_features, false)
};
let feature_name = unique(&format!("{} Base", body.name), &mut used_features);
let id = scratch.doc_mut().add_feature(
FeatureKind::Import { file: format!("{} independent base", body.name), step: step.into(), components: Vec::new(), skip: Vec::new() },
Some(&feature_name),
@@ -420,12 +358,8 @@ pub(super) fn build(
}
// Allocate all history IDs before rewriting any forward reference.
for f in &feats {
let name = unique(&f.name, &mut used_features, origin.other_design);
// A transfer is checked as it is added: it names the copy's components (another design
// has none of the original ones).
let mut kind = f.kind.clone();
transfer_into_copy(&mut kind, &components)?;
let id = scratch.doc_mut().add_feature(kind, Some(&name))?;
let name = unique(&f.name, &mut used_features);
let id = scratch.doc_mut().add_feature(f.kind.clone(), Some(&name))?;
if let Some(new) = scratch.doc.feature(id) {
for (old, pn) in f.param_names.iter().zip(&new.param_names) {
parameters.insert(old.clone(), pn.clone());
@@ -453,11 +387,6 @@ pub(super) fn build(
}
}
}
// From another design, the user parameters the copy uses come along (and the ones they use),
// renamed `w_2` where this design has a `w` already.
if origin.other_design {
copy_user_parameters(&mut scratch, source, &feats, &mut parameters)?;
}
for (old, new) in &parameters {
if let Some(comment) = source.param_comments.get(old) {
scratch.doc_mut().param_comments.insert(new.clone(), comment.clone());
@@ -485,18 +414,26 @@ pub(super) fn build(
f.body_names = outputs.get(&old.id).cloned().unwrap_or_default();
}
f.remap_clone(&features, &names, &bodies, &parameters)?;
transfer_into_copy(&mut f.kind, &components)?;
if let FeatureKind::BodyTransfer { from, to, transform, .. } = &mut f.kind {
*to = *components.get(to).ok_or_else(|| bad(CMD, "transfer destination is outside the copied graph"))?;
if let Some(mapped) = components.get(from) {
*from = *mapped;
} else {
*from = *to;
*transform = solidcraft_doc::IDENTITY;
}
}
if let FeatureKind::Emboss { face: Some(face), .. } = &mut f.kind
&& !face.path.is_empty()
&& let FeatureKind::Emboss { face: Some(old_face), .. } = &old.kind
&& bodies.contains_key(old_face.body.as_ref())
{
face.path = cloned_path(source, &old_face.path, component, &clone_path, &occurrences)?;
face.path = cloned_path(&source, &old_face.path, component, &clone_path, &occurrences)?;
}
if let FeatureKind::Emboss { face: Some(face), .. } = &mut f.kind
&& !face.author_path.is_empty()
{
face.author_path = cloned_path(source, &face.author_path, component, &clone_path, &occurrences)?;
face.author_path = cloned_path(&source, &face.author_path, component, &clone_path, &occurrences)?;
}
if let (FeatureKind::Sketch { plane, .. }, FeatureKind::Sketch { plane: old_plane, .. }) = (&mut f.kind, &old.kind)
&& let (Some(anchor), Some(original)) = (super::sketch::face::anchor_mut(plane), super::sketch::face::anchor(old_plane))
@@ -504,9 +441,9 @@ pub(super) fn build(
if bodies.contains_key(&original.target.body) {
anchor.component =
*components.get(&original.component).ok_or_else(|| bad(CMD, "anchored source component is outside copied graph"))?;
anchor.path = cloned_path(source, &original.path, component, &clone_path, &occurrences)?;
anchor.path = cloned_path(&source, &original.path, component, &clone_path, &occurrences)?;
}
anchor.author_path = cloned_path(source, &original.author_path, component, &clone_path, &occurrences)?;
anchor.author_path = cloned_path(&source, &original.author_path, component, &clone_path, &occurrences)?;
}
if let Some(slot) = scratch.doc_mut().feature_mut(f.id) {
*slot = f;
@@ -545,7 +482,7 @@ pub(super) fn build(
.filter_map(|b| bodies.get(&b.name).cloned())
.collect();
if !moved_out.is_empty() {
let name = unique("Assigned-out bodies", &mut used_features, origin.other_design);
let name = unique("Assigned-out bodies", &mut used_features);
let id = scratch.doc_mut().add_feature(FeatureKind::Remove { bodies: moved_out.into_iter().map(BodyName).collect() }, Some(&name))?;
if let Some(f) = scratch.doc_mut().feature_mut(id) {
f.component = root;
@@ -577,20 +514,14 @@ pub(super) fn build(
scratch.doc_mut().appearances.faces.push(face);
}
}
// Typed configuration and assembly helpers preserve original targets (another design's
// configurations stay with it: this design's table has its own targets).
if !origin.other_design {
scratch.doc_mut().configs.clone_targets(&solidcraft_doc::config::ConfigCloneMaps {
features: features.clone(),
components: components.clone(),
bodies: bodies.clone(),
parameters: parameters.clone(),
})?;
}
let mut notices = super::component_clone_assembly::clone_assembly(scratch.doc_mut(), source, &occurrences, &features, &bodies)?;
// Joints and motion to the outside are left behind (those notices); what follows is what
// the copied features point at outside it.
let assembly_notices = notices.len();
// Typed configuration and assembly helpers preserve original targets.
scratch.doc_mut().configs.clone_targets(&solidcraft_doc::config::ConfigCloneMaps {
features: features.clone(),
components: components.clone(),
bodies: bodies.clone(),
parameters: parameters.clone(),
})?;
let mut notices = super::component_clone_assembly::clone_assembly(scratch.doc_mut(), &source, &occurrences, &features, &bodies)?;
let mut reference_work = 0usize;
for feature in &feats {
if let FeatureKind::Emboss { face: Some(face), .. } = &feature.kind
@@ -674,22 +605,12 @@ pub(super) fn build(
}
}
}
if origin.other_design {
// What the copy points at outside itself isn't in this design.
let mut outside = outside_references(notices.get(assembly_notices..).unwrap_or_default(), &feats, &bodies);
if !outside.is_empty() {
outside.sort();
outside.dedup();
let name = definition_records.get(&component).map(|c| c.name.clone()).unwrap_or_default();
return Err(bad(CMD, format!("{name} uses what isn't in it, so it can't be pasted into another design: {}", outside.join("; "))));
}
}
notices.sort();
notices.dedup();
scratch.refresh();
let original_errors: BTreeMap<_, _> = s.model.results.iter().map(|result| (result.id, result.error.as_ref())).collect();
let refreshed_errors: BTreeMap<_, _> = scratch.model.results.iter().map(|result| (result.id, result.error.as_ref())).collect();
if s.doc.features.iter().any(|feature| original_errors.get(&feature.id) != refreshed_errors.get(&feature.id)) {
if source.features.iter().any(|feature| original_errors.get(&feature.id) != refreshed_errors.get(&feature.id)) {
return Err(bad(CMD, "copy would change an original feature's error state"));
}
// Base imports acquire new face identities. Resolve copied face overrides against the
@@ -719,14 +640,14 @@ pub(super) fn build(
let copied_bodies: BTreeMap<_, _> = copied.bodies.iter().map(|body| (body.name.as_str(), body)).collect();
// Adding placements can invalidate cached source evaluation. Compare clone effects
// against that same evaluation's source prefix, not older shared B-rep pointers.
if scratch.doc.features.get(..s.doc.features.len()) != Some(s.doc.features.as_slice())
|| scratch.doc.params.get(..s.doc.params.len()) != Some(s.doc.params.as_slice())
if scratch.doc.features.get(..source.features.len()) != Some(source.features.as_slice())
|| scratch.doc.params.get(..source.params.len()) != Some(source.params.as_slice())
{
return Err(bad(CMD, "copy would change original feature history or parameters"));
}
let original_state = new_ids.first().map(|id| scratch.model.state_before(*id)).unwrap_or_else(|| copied.clone());
let all_columns = std::mem::take(&mut scratch.doc_mut().configs.columns);
scratch.doc_mut().configs.columns = all_columns.iter().skip(s.doc.configs.columns.len()).cloned().collect();
scratch.doc_mut().configs.columns = all_columns.iter().skip(source.configs.columns.len()).cloned().collect();
let style_validation = scratch.doc.configuration_style_status(&copied);
scratch.doc_mut().configs.columns = all_columns;
style_validation?;
@@ -793,86 +714,10 @@ pub(super) fn build(
}
}
scratch.selection = vec![Sel::Occurrence { path: clone_path }];
let out = json!({"component":root,"occurrence":root_occurrence,"features":new_ids,"components":components.len(),"bodies":expected_count,"frozen_bodies":frozen,"notices":notices});
Ok((scratch, out))
}
/// A copied body transfer moves its bodies between the copies of its components; one from
/// outside the copy is where the copy starts (it stays in place, in its destination).
fn transfer_into_copy(kind: &mut FeatureKind, components: &BTreeMap<u64, u64>) -> Result<()> {
if let FeatureKind::BodyTransfer { from, to, transform, .. } = kind {
*to = *components.get(to).ok_or_else(|| bad(CMD, "transfer destination is outside the copied graph"))?;
if let Some(mapped) = components.get(from) {
*from = *mapped;
} else {
*from = *to;
*transform = solidcraft_doc::IDENTITY;
}
}
Ok(())
}
/// What copied features point at outside the copy, in words: the external references Paste New
/// keeps within one design (`notices`), and the bodies they work on that aren't copied.
fn outside_references(notices: &[String], feats: &[Feature], bodies: &BTreeMap<String, String>) -> Vec<String> {
let mut out: Vec<String> =
notices.iter().map(|n| n.replace(" retains an external ", " uses a ").replace(" retains external ", " uses ")).collect();
for f in feats {
for body in f.kind.input_bodies() {
if !bodies.contains_key(&body) {
out.push(format!("{} uses body {body}", f.name));
}
}
}
out
}
/// The user parameters copied features use (their expressions and their dimensions'), and the
/// ones those use, copied from `source` into `scratch`: named as they were where that name is
/// free, else `w_2`, `w_3`…; `parameters` maps each to its copy.
fn copy_user_parameters(scratch: &mut Session, source: &Document, feats: &[Feature], parameters: &mut BTreeMap<String, String>) -> Result<()> {
let user: BTreeMap<&str, &solidcraft_doc::Param> = source.params.iter().filter(|p| !p.model).map(|p| (p.name.as_str(), p)).collect();
let mut pending: Vec<String> = feats.iter().flat_map(|f| f.kind.expressions()).map(str::to_string).collect();
pending.extend(parameters.keys().filter_map(|old| source.params.iter().find(|p| p.model && p.name == *old)).map(|p| p.expr.clone()));
let mut used: BTreeSet<&str> = BTreeSet::new();
let mut work = 0usize;
while let Some(expr) = pending.pop() {
for name in solidcraft_doc::expr::references(&expr) {
work += 1;
if work > 100_000 {
return Err(bad(CMD, "parameter references exceed copy work limit"));
}
if let Some((key, p)) = user.get_key_value(name.as_str())
&& used.insert(key)
{
pending.push(p.expr.clone());
}
}
}
let copied: Vec<&solidcraft_doc::Param> = source.params.iter().filter(|p| used.contains(p.name.as_str())).collect();
if scratch.doc.params.len() + copied.len() > solidcraft_doc::MAX_PARAMS {
return Err(bad(CMD, "too many copied parameters"));
}
let mut taken: BTreeSet<String> = scratch.doc.params.iter().map(|p| p.name.clone()).collect();
for p in &copied {
let mut name = p.name.clone();
let mut n = 2;
while taken.contains(&name) || Document::param_name_problem(&name).is_some() {
name = format!("{}_{n}", p.name);
n += 1;
if n > 10_000 {
return Err(bad(CMD, format!("no free name for parameter {}", p.name)));
}
}
taken.insert(name.clone());
parameters.insert(p.name.clone(), name);
}
for p in copied {
let name = parameters.get(&p.name).cloned().unwrap_or_default();
let expr = solidcraft_doc::clone_expression(&p.expr, parameters);
scratch.doc_mut().params.push(solidcraft_doc::Param { name, expr, unit: p.unit.clone(), comment: p.comment.clone(), model: false });
}
Ok(())
s.accept_computed(scratch);
Ok(
json!({"component":root,"occurrence":root_occurrence,"features":new_ids,"components":components.len(),"bodies":expected_count,"frozen_bodies":frozen,"notices":notices}),
)
}
#[cfg(test)]
-107
View File
@@ -1,107 +0,0 @@
//! Pasting what was copied in another design (`Session::foreign_copy`). Bodies come as an
//! imported body each, without their history (that stays with the design they were made in), at
//! the same world coordinates as in their design, in one Import base feature in the target
//! component. Components come as a Paste New does: an independent copy of each with what it
//! holds, its history, appearances, joints and motion, where it is in the world.
use super::*;
pub(super) fn paste_from_design(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.paste_from_design";
let copy = s.foreign_copy.clone().ok_or_else(|| bad(cmd, "nothing was copied in another design"))?;
if copy.bodies.is_empty() && copy.placed.is_empty() {
return Err(bad(cmd, "nothing was copied in another design"));
}
let to = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };
let given = match p.get("component_path") {
None => None,
Some(v) => Some(
v.as_array()
.filter(|a| a.len() <= 64)
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
.ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?,
),
};
let path = match given {
Some(path) => path,
None if to == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(to)),
None => placing::placement_of(s, &s.placed_document(), to, None, "component_path", cmd)?.0,
};
let frame = s.placed_document().path_transform(to, &path).ok_or_else(|| bad(cmd, "that path is not a placement of the target"))?;
let into_target = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| bad(cmd, "the target's frame is not invertible"))?;
if copy.bodies.is_empty() {
return paste_components(s, &copy, to, path, into_target, p);
}
// Each body at its world coordinates in its design, in the target's frame, named as in its
// component (a body seen in another placement without that placement) where that name is
// free here, else numbered.
let state = s.model.state();
let mut names: Vec<String> = Vec::new();
let mut shapes = Vec::new();
for (i, seen) in copy.bodies.iter().enumerate() {
let body = copy.world.body(seen).ok_or_else(|| bad(cmd, format!("no body `{seen}` in {}", copy.design)))?;
let name = copy.names.get(i).unwrap_or(seen);
let taken = |n: &str| state.body(n).is_some() || names.iter().any(|x| x == n);
let new = if taken(name) { solidcraft_doc::copy_name(name, taken) } else { name.clone() };
shapes.push(solidcraft_kernel::transform_matrix(&body.body, into_target)?);
names.push(new);
}
drop(state);
let list: Vec<solidcraft_kernel::ExportBody> =
names.iter().zip(&shapes).map(|(name, body)| solidcraft_kernel::ExportBody { name: name.clone(), body, color: body.color() }).collect();
let header = solidcraft_kernel::StepHeader { organization: "SolidCraft".into(), ..Default::default() };
let step = solidcraft_kernel::step_export_bodies(&list, &header)?;
let mut scratch = s.scratch();
let kind = FeatureKind::Import { file: format!("{} (pasted)", copy.design), step: step.into(), components: Vec::new(), skip: Vec::new() };
// Named as any import is ("Import1"); the design they came from stays on it as its file.
let id = scratch.doc_mut().add_feature(kind, None)?;
let feature = scratch.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
if let Some(f) = scratch.doc_mut().feature_mut(id) {
f.component = to;
f.body_names = names.clone();
}
scratch.refresh();
if let Some(error) = scratch.model.result(id).and_then(|r| r.error.as_ref()) {
return Err(bad(cmd, format!("the pasted bodies didn't import: {error}")));
}
scratch.selection = names.iter().map(|name| crate::Sel::Body { name: name.clone() }).collect();
s.accept_computed(scratch);
Ok(json!({"bodies": names, "feature": feature, "component": to}))
}
/// Independent copies of the components copied in another design, each with what it holds, in
/// `to` (placed by `path`; `into_target` takes world coordinates into it), where each is in the
/// world; one step to undo. They are selected.
fn paste_components(
s: &mut Session,
copy: &crate::ForeignCopy,
to: u64,
path: Vec<u64>,
into_target: solidcraft_doc::Mat,
p: &Value,
) -> Result<Value> {
let origin = crate::cmd::component_clone::Source::copied(copy);
let mut computed: Option<Session> = None;
let mut made = Vec::new();
for (component, occurrence, world) in &copy.placed {
let source_occurrence = copy.doc.occurrences.iter().find(|o| o.id == *occurrence).cloned();
let transform = solidcraft_doc::mat_mul(&into_target, world);
if !super::valid_position(&transform) {
return Err(bad("component.paste_from_design", "copy transform exceeds supported numeric range"));
}
let target = computed.as_ref().unwrap_or(s);
let (next, out) = crate::cmd::component_clone::build(target, &origin, *component, source_occurrence, transform, to, Some(path.clone()), p)?;
if let Some(id) = out.get("occurrence").and_then(Value::as_u64) {
made.push(path.iter().copied().chain([id]).collect::<Vec<u64>>());
}
computed = Some(next);
}
let Some(mut scratch) = computed else { return Err(bad("component.paste_from_design", "the copied components are gone")) };
scratch.selection = made.iter().map(|path| crate::Sel::Occurrence { path: path.clone() }).collect();
s.accept_computed(scratch);
Ok(json!({"paths": made, "component": to}))
}
#[cfg(test)]
#[path = "component_foreign_tests.rs"]
mod tests;
@@ -1,134 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::{ForeignCopy, Session};
use serde_json::{Value, json};
use std::sync::Arc;
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap()
}
fn created(s: &mut Session, name: &str) -> (u64, u64) {
let c = run(s, "component.create", json!({"name": name}));
(c["component"].as_u64().unwrap(), c["occurrence"].as_u64().unwrap())
}
fn volume(s: &mut Session, id: u64) -> f64 {
run(s, "component.properties", json!({"component": id}))["total"]["volume_mm3"].as_f64().unwrap()
}
fn design(name: &str) -> Session {
let mut s = Session::default();
s.doc_mut().name = name.into();
s
}
/// `s` copies its placement `path` for another design.
fn copied(s: &Session, path: Vec<u64>) -> Option<Arc<ForeignCopy>> {
Some(Arc::new(ForeignCopy::of(s, Vec::new(), vec![path])))
}
/// A component copied in another design pastes as an independent copy of it and what it holds:
/// its history, its appearances, a part placed twice in it still one component placed twice,
/// where it is in the world, named "(2)" where the name is taken, as one step to undo.
#[test]
fn a_component_from_another_design_pastes_with_its_history() {
let mut source = design("Bracket");
let (assembly, at) = created(&mut source, "Assembly");
let (child, _) = created(&mut source, "Child");
run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
run(&mut source, "appearance.assign", json!({"bodies": ["Cube"], "color": "#abcdef"}));
run(&mut source, "occurrence.copy", json!({"component": child}));
run(&mut source, "component.activate", json!({"component": 0}));
run(&mut source, "occurrence.ground", json!({"occurrence": at, "grounded": false}));
run(&mut source, "occurrence.move", json!({"occurrence": at, "translate": [0, 30, 0]}));
let was = source.world_state().body("Cube").unwrap().mesh().bounds();
let box_features = source.doc.features.len();
let mut s = design("Frame");
created(&mut s, "Assembly");
run(&mut s, "component.activate", json!({"component": 0}));
s.foreign_copy = copied(&source, vec![at]);
let undo = s.undo.len();
let out = run(&mut s, "component.paste_from_design", json!({}));
assert_eq!(s.undo.len(), undo + 1);
let new = s.doc.components.iter().find(|c| c.name == "Assembly (2)").expect("named (2)").id;
assert_eq!(out["paths"], json!([[s.doc.occurrence_of(new).unwrap().id]]));
let kids: Vec<_> = s.doc.occurrences.iter().filter(|o| o.parent == new).collect();
assert_eq!(kids.len(), 2);
assert_eq!(kids[0].component, kids[1].component, "still one component placed twice");
assert_eq!(s.doc.features.len(), box_features, "the box's history came along");
assert!((volume(&mut s, new) - 16.0).abs() < 1e-6);
assert_eq!(s.doc.appearances.bodies["Cube"].color, [0xab, 0xcd, 0xef]);
let is = s.world_state().body("Cube").unwrap().mesh().bounds();
assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}");
// Its history is its own: changing it here leaves the original as it was.
let copy = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Box { .. })).unwrap();
let parameter = copy.param_names[0].clone();
run(&mut s, "parameters.change", json!({"name": parameter, "expression": "3 mm"}));
assert!((volume(&mut s, new) - 24.0).abs() < 1e-6);
assert!((volume(&mut source, assembly) - 16.0).abs() < 1e-6);
let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(reopened.occurrences.iter().filter(|o| o.parent == new).count(), 2);
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(s.doc.components.iter().all(|c| c.name != "Assembly (2)"));
}
/// The user parameters a pasted component uses come along: as they were where the name is
/// free, else renamed `w_2`, its features following; this design's own `w` stays as it is.
#[test]
fn user_parameters_come_along_renamed_where_taken() {
let mut source = design("Bracket");
run(&mut source, "parameters.add", json!({"name": "w", "expression": "4 mm"}));
let (_, at) = created(&mut source, "Part");
let feature = run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}))["feature"].as_u64().unwrap();
let length = source.doc.feature(feature).unwrap().param_names[0].clone();
run(&mut source, "parameters.change", json!({"name": length, "expression": "w"}));
let mut s = design("Frame");
run(&mut s, "parameters.add", json!({"name": "w", "expression": "10 mm"}));
s.foreign_copy = copied(&source, vec![at]);
run(&mut s, "component.paste_from_design", json!({}));
let w2 = s.doc.params.iter().find(|p| p.name == "w_2").expect("w came along as w_2");
assert_eq!(w2.expr, "4 mm");
assert_eq!(s.doc.params.iter().find(|p| p.name == "w").unwrap().expr, "10 mm");
let part = s.doc.components.iter().find(|c| c.name == "Part").unwrap().id;
assert!((volume(&mut s, part) - 16.0).abs() < 1e-6);
run(&mut s, "parameters.change", json!({"name": "w_2", "expression": "1 mm"}));
assert!((volume(&mut s, part) - 4.0).abs() < 1e-6, "the copy follows w_2");
}
/// A component whose features use what isn't in it (here a body outside it) isn't pasted into
/// another design: it is refused, saying what, and the design is left as it was.
#[test]
fn a_component_using_what_is_outside_it_is_refused_saying_what() {
let mut source = design("Bracket");
run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
let (_, at) = created(&mut source, "Part");
run(&mut source, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Pin"}));
run(&mut source, "solid.move", json!({"bodies": ["Cube"], "translate": [10, 0, 0]}));
let mut s = design("Frame");
s.foreign_copy = copied(&source, vec![at]);
let saved = s.doc.to_json();
let error = s.execute("component.paste_from_design", &json!({})).unwrap_err().to_string();
assert!(error.contains("uses body Cube"), "{error}");
assert_eq!(s.doc.to_json(), saved);
}
/// A component that bodies were moved into (a body transfer, as Create Components from Bodies
/// makes) pastes into another design, which has none of the components the transfer names.
#[test]
fn a_component_bodies_were_moved_into_pastes_into_another_design() {
let mut source = design("Bracket");
run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
let (part, at) = created(&mut source, "Part");
run(&mut source, "component.move_bodies", json!({"bodies": ["Cube"], "component": part}));
run(&mut source, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Pin"}));
let mut s = design("Frame");
s.foreign_copy = copied(&source, vec![at]);
run(&mut s, "component.paste_from_design", json!({}));
let new = s.doc.components.iter().find(|c| c.name == "Part").unwrap().id;
let state = s.model.state();
assert_eq!(s.doc.model_body_component(state.body("Cube").unwrap()), new);
assert_eq!(s.doc.model_body_component(state.body("Pin").unwrap()), new);
// The body moved in from outside comes as an imported body.
assert!(s.doc.find_feature("BodyImport1").is_some_and(|f| f.component == new));
}
@@ -1,143 +0,0 @@
//! Moving timeline features (sketches included) into another component.
//!
//! It is an organisational change: ids, names and timeline positions stay, nothing is copied, and
//! the geometry stays where it is in the world (a moved feature's picks, planes and directions are
//! re-expressed in the new component's frame). Bodies follow the feature that made them. The move
//! is made on a scratch copy and the whole timeline is evaluated; the result is adopted only when
//! no feature, moved or left behind, gained an error. Otherwise nothing changes.
use std::collections::{BTreeMap, BTreeSet};
use solidcraft_doc::{Feature, FeatureKind, is_identity, mat_inverse, mat_mul};
use super::super::clipboard::explicit_planes;
use super::*;
use crate::params::name_or_id_list;
pub(super) fn move_features(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.move_features";
let dest = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };
let keys = name_or_id_list(cmd, p, "features")?;
if keys.is_empty() || keys.len() > 1000 {
return Err(bad(cmd, "`features` must list 1…1000 features"));
}
if s.doc.marker.is_some() {
return Err(bad(cmd, "finish timeline rollback before moving features"));
}
if !s.pending_moves.is_empty() {
return Err(bad(cmd, "finish the component move in progress first"));
}
let mut ids = BTreeSet::new();
for k in &keys {
ids.insert(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?);
}
let moving: BTreeSet<u64> = ids.into_iter().filter(|id| s.doc.feature(*id).is_some_and(|f| f.component != dest)).collect();
if moving.is_empty() {
return Err(bad(cmd, "already in that component"));
}
let moved: Vec<Feature> = s.doc.features.iter().filter(|f| moving.contains(&f.id)).cloned().collect();
// One placement each: a component placed twice has no single frame to keep the geometry in.
let placements = |c: u64| s.doc.occurrences.iter().filter(|o| o.component == c).count();
let sources: BTreeSet<u64> = moved.iter().map(|f| f.component).collect();
if sources.iter().chain([&dest]).any(|c| *c != 0 && placements(*c) > 1) {
return Err(bad(cmd, "a component placed more than once can't take part in this move"));
}
if moved.iter().any(|f| matches!(f.kind, FeatureKind::BodyTransfer { .. })) {
return Err(bad(cmd, "a recorded body transfer can't be moved"));
}
// The bodies that move with the features: those they are the origin of.
let moved_bodies: BTreeSet<String> = s.body_origins().into_iter().filter(|(_, f)| moving.contains(f)).map(|(body, _)| body).collect();
if moved_bodies.iter().any(|b| s.doc.body_components.contains_key(b) || s.doc.body_offsets.contains_key(b)) {
return Err(bad(cmd, "a body that was transferred between components can't be moved with its features"));
}
// A join or boolean whose inputs would end up in two components.
for f in &s.doc.features {
let mut inputs: BTreeSet<String> = f.kind.input_bodies().into_iter().collect();
inputs.extend(f.participants.iter().cloned());
let (inside, outside) =
(inputs.iter().filter(|b| moved_bodies.contains(*b)).count(), inputs.iter().filter(|b| !moved_bodies.contains(*b)).count());
if inside > 0 && outside > 0 && inputs.len() > 1 {
return Err(bad(cmd, format!("{} works on bodies that would be split between components", f.name)));
}
}
let to_dest = mat_inverse(&s.doc.component_transform(dest)).ok_or_else(|| bad(cmd, "the target component's frame is not invertible"))?;
let dest_path = s.doc.first_path(dest);
let before_errors: BTreeMap<u64, bool> = s.doc.features.iter().map(|f| (f.id, s.model.result(f.id).is_some_and(|r| r.error.is_some()))).collect();
let mut scratch = s.scratch();
let doc = scratch.doc_mut();
for old in &moved {
let delta = mat_mul(&to_dest, &s.doc.component_transform(old.component));
let Some(f) = doc.feature_mut(old.id) else { continue };
f.component = dest;
if !is_identity(&delta) {
if let FeatureKind::Sketch { plane, .. } | FeatureKind::ConstructionPlane { plane } = &mut f.kind {
explicit_planes(plane);
}
f.kind.transform_geometry(&delta);
}
}
// Attached sketches and embossed faces carry the placement of the body they sit on and of
// the component they were authored in: those that moved are rewritten, nothing else changes.
for f in &mut doc.features {
let authored_here = moving.contains(&f.id);
let rewrite = |body: &str, path: &mut Vec<u64>, author_path: &mut Vec<u64>| {
if moved_bodies.contains(body) {
*path = dest_path.clone();
}
if authored_here {
*author_path = dest_path.clone();
}
};
match &mut f.kind {
FeatureKind::Sketch { plane, .. } => {
if let Some(anchor) = crate::cmd::sketch::face::anchor_mut(plane) {
let moved_body = moved_bodies.contains(&anchor.target.body);
rewrite(&anchor.target.body, &mut anchor.path, &mut anchor.author_path);
if moved_body {
anchor.component = dest;
}
}
}
FeatureKind::Emboss { face: Some(face), .. } => {
let body = face.body.as_ref().to_string();
rewrite(&body, &mut face.path, &mut face.author_path);
}
_ => {}
}
}
scratch.refresh();
// Any feature that gains an error, moved or left behind, stops the move.
let broken = scratch
.doc
.features
.iter()
.filter(|f| !before_errors.get(&f.id).copied().unwrap_or(false))
.find_map(|f| scratch.model.result(f.id).and_then(|r| r.error.clone()).map(|e| (f.name.clone(), e)));
if let Some((name, error)) = broken {
return Err(bad(cmd, format!("moving would break {name}: {error}")));
}
s.accept_computed(scratch);
let names: Vec<&str> = moved.iter().map(|f| f.name.as_str()).collect();
Ok(json!({"moved": names, "component": dest, "bodies": moved_bodies}))
}
impl Session {
/// The feature each body depends on first, by body name: the earliest feature whose own result
/// holds a body of that name (a converted mesh keeps its import), else the creator the body
/// carries (the pieces of a split). Moving that feature moves the body.
pub fn body_origins(&self) -> BTreeMap<String, u64> {
let mut origins = BTreeMap::new();
for f in &self.doc.features {
if let Some(r) = self.model.result(f.id) {
for b in r.state.bodies.iter().filter(|b| b.feature == f.id) {
origins.entry(b.name.clone()).or_insert(f.id);
}
}
}
for b in &self.model.state().bodies {
origins.entry(b.name.clone()).or_insert(b.feature);
}
origins
}
}
+3 -9
View File
@@ -92,22 +92,16 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.accept_computed(scratch);
follow_visibility(s, &old_path, &new_path);
Ok(json!({"occurrence": id, "parent": to, "path": new_path, "transform": transform}))
}
/// Hidden placements and folders under `old_path` follow it to `new_path`. `accept_computed` does
/// not carry them, so whoever accepts a computed move into a session does this after.
pub(super) fn follow_visibility(s: &mut Session, old_path: &[u64], new_path: &[u64]) {
for hidden in &mut s.visibility.hidden_occurrences {
if let Some(moved) = rebased(hidden, old_path, new_path) {
if let Some(moved) = rebased(hidden, &old_path, &new_path) {
*hidden = moved;
}
}
let (old_scope, new_scope) = (Session::folder_scope(old_path), Session::folder_scope(new_path));
let (old_scope, new_scope) = (Session::folder_scope(&old_path), Session::folder_scope(&new_path));
for key in &mut s.visibility.hidden_folders {
if let Some(rest) = key.strip_prefix(&old_scope).filter(|rest| rest.starts_with('/')) {
*key = format!("{new_scope}{rest}");
}
}
Ok(json!({"occurrence": id, "parent": to, "path": new_path, "transform": transform}))
}
@@ -1,151 +0,0 @@
//! Moving placements, timeline features and bodies into a component in one undo step
//! (`browser.reparent`: the owner of each changes, whatever its kind).
//!
//! What Paste does after Cut. Each kind moves by its own command (`occurrence.reparent`,
//! `component.move_features`, `component.move_bodies`), in that order, on a scratch copy, so what
//! an earlier step carried along is left alone by a later one: a moved component takes its
//! features and bodies with it, moved features take the bodies they made. The result is adopted
//! only when every step succeeds, as one undo step; otherwise nothing changes.
use std::collections::BTreeSet;
use super::move_features::move_features;
use super::reparent::{follow_visibility, reparent};
use super::transfer;
use super::*;
use crate::params::{name_or_id_list, string_list};
/// Most items of each kind in one move.
const MAX_ITEMS: usize = 1000;
/// A placement named by its occurrence id, or by its path from the top of the design.
fn placements(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(u64, Option<Vec<u64>>)>> {
let list = match p.get("occurrences") {
None | Some(Value::Null) => return Ok(Vec::new()),
Some(Value::Array(a)) if a.len() <= MAX_ITEMS => a,
Some(_) => return Err(bad(cmd, format!("`occurrences` must list at most {MAX_ITEMS} placements"))),
};
let mut out: Vec<(u64, Option<Vec<u64>>)> = Vec::new();
for entry in list {
let found = match entry {
Value::Number(n) => n.as_u64().map(|id| (id, None)),
Value::Array(a) if !a.is_empty() && a.len() <= 64 => {
a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>().and_then(|path| path.last().copied().map(|id| (id, Some(path))))
}
_ => None,
};
let (id, path) = found.ok_or_else(|| bad(cmd, "`occurrences` must list occurrence ids or paths of 1..64 occurrence ids"))?;
if !s.doc.occurrences.iter().any(|o| o.id == id) {
return Err(bad(cmd, format!("no occurrence {id}")));
}
if !out.iter().any(|(seen, _)| *seen == id) {
out.push((id, path));
}
}
Ok(out)
}
pub(super) fn reparent_items(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "browser.reparent";
let dest = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };
let dest_path = p.get("component_path").cloned();
let occurrences = placements(s, p, cmd)?;
let features = name_or_id_list(cmd, p, "features")?;
let bodies = string_list(cmd, p, "bodies")?;
if features.len() > MAX_ITEMS || bodies.len() > MAX_ITEMS {
return Err(bad(cmd, format!("`features` and `bodies` must list at most {MAX_ITEMS} items each")));
}
if occurrences.is_empty() && features.is_empty() && bodies.is_empty() {
return Err(bad(cmd, "give `occurrences`, `features` or `bodies` to move"));
}
if s.doc.marker.is_some() {
return Err(bad(cmd, "finish timeline rollback before moving"));
}
let mut feature_ids = BTreeSet::new();
for k in &features {
feature_ids.insert(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?);
}
{
let state = s.model.state();
if let Some(missing) = bodies.iter().find(|b| state.body(b).is_none()) {
return Err(bad(cmd, format!("no body `{missing}`")));
}
}
let mut sc = s.scratch();
sc.active_component = s.active_component;
sc.active_occurrence_path = s.active_occurrence_path.clone();
// Components first: each takes everything it holds.
let mut moved_placements = Vec::new();
let mut moved_components = Vec::new();
let mut followed: Vec<(Vec<u64>, Vec<u64>)> = Vec::new();
for (id, path) in &occurrences {
let Some(o) = sc.doc.occurrences.iter().find(|o| o.id == *id).cloned() else { continue };
if o.parent == dest {
continue;
}
let mut params = json!({"occurrence": id, "parent": dest});
if let Some(path) = path {
params["path"] = json!(path);
}
if let Some(parent_path) = &dest_path {
params["parent_path"] = parent_path.clone();
}
let old_path = occurrence_path(&sc, &params, *id, cmd)?;
let out = reparent(&mut sc, &params)?;
let new_path = out.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect::<Vec<_>>());
followed.extend(new_path.map(|new| (old_path, new)));
moved_placements.push(*id);
moved_components.push(o.component);
}
// What a moved component holds travels with it.
let travels = |sc: &Session, component: u64| moved_components.iter().any(|c| sc.doc.inside_component(component, *c));
// Then features, which take the bodies they made.
let features_to_move: Vec<u64> =
feature_ids.iter().copied().filter(|id| sc.doc.feature(*id).is_some_and(|f| f.component != dest && !travels(&sc, f.component))).collect();
let mut moved_features = Vec::new();
if !features_to_move.is_empty() {
let mut params = json!({"features": features_to_move, "component": dest});
if let Some(path) = &dest_path {
params["component_path"] = path.clone();
}
let out = move_features(&mut sc, &params)?;
moved_features =
out.get("moved").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
}
// Last the bodies still elsewhere: one a moved component or feature carried is already there.
let bodies_to_move: Vec<String> = {
let state = sc.model.state();
bodies
.iter()
.filter(|b| {
state.body(b).is_some_and(|body| {
let at = sc.doc.model_body_component(body);
at != dest && !travels(&sc, at)
})
})
.cloned()
.collect()
};
if !bodies_to_move.is_empty() {
let mut params = json!({"bodies": bodies_to_move, "component": dest});
if let Some(path) = &dest_path {
params["component_path"] = path.clone();
}
transfer::move_bodies(&mut sc, &params)?;
}
if moved_placements.is_empty() && moved_features.is_empty() && bodies_to_move.is_empty() {
return Err(bad(cmd, "already in that component"));
}
// The steps above are this command's one undo step.
sc.undo.clear();
s.accept_computed(sc);
for (old, new) in &followed {
follow_visibility(s, old, new);
}
Ok(json!({"component": dest, "occurrences": moved_placements, "features": moved_features, "bodies": bodies_to_move}))
}
@@ -290,205 +290,3 @@ fn edited_transfer_destination_updates_history_owner_copy_and_reopen() {
assert_eq!(reopened.model.state().body("Block").unwrap().component, b);
assert_eq!(reopened.model.state().body("Block (2)").unwrap().component, copied);
}
/// A 10 × 10 × 5 block (sketch `S`, extrude `Extrude1`, body `Block`) in the design with a sketch
/// `Top` on its top face, and a component `Part` placed 100 mm along X. The design is active.
fn block_and_part() -> (Session, u64) {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 5, "body_name": "Block"}));
run(&mut s, "sketch.create", json!({"plane": {"face": [5, 5, 5]}, "name": "Top"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [4, 4]}));
run(&mut s, "sketch.finish", json!({}));
let part = run(&mut s, "component.create", json!({"name": "Part"}))["component"].as_u64().unwrap();
let first = s.doc.occurrence_of(part).map(|o| o.id).unwrap();
run(&mut s, "occurrence.move", json!({"occurrence": first, "translate": [100, 0, 0], "capture": true, "move_grounded": true}));
run(&mut s, "component.activate", json!({"component": 0}));
(s, part)
}
/// The lowest corner of every body in the world, rounded.
fn world_corners(s: &Session) -> Vec<Vec<f64>> {
s.world_state()
.bodies
.iter()
.map(|b| {
let min = b.mesh().bounds().min;
vec![min.x.round(), min.y.round(), min.z.round()]
})
.collect()
}
#[test]
fn move_features_keeps_the_world_and_the_attachment_in_the_active_component() {
let (mut s, part) = block_and_part();
let ids: Vec<u64> = s.doc.features.iter().map(|f| f.id).collect();
let names: Vec<String> = s.doc.features.iter().map(|f| f.name.clone()).collect();
let corners = world_corners(&s);
// No `component`: the features go to the active one.
run(&mut s, "component.activate", json!({"component": part}));
let r = run(&mut s, "component.move_features", json!({"features": ["S", "Extrude1"]}));
assert_eq!(r["moved"], json!(["S", "Extrude1"]), "{r}");
// Nothing was added or renamed.
assert_eq!(s.doc.features.iter().map(|f| f.id).collect::<Vec<_>>(), ids);
assert_eq!(s.doc.features.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), names);
for name in ["S", "Extrude1"] {
assert_eq!(s.doc.find_feature(name).map(|f| f.component), Some(part));
}
assert_eq!(s.doc.find_feature("Top").map(|f| f.component), Some(0));
assert_eq!(world_corners(&s), corners, "the block is where it was in the world");
// The sketch left behind follows the body into its new component and still evaluates.
let top = s.doc.find_feature("Top").unwrap();
assert!(s.model.result(top.id).is_some_and(|r| r.error.is_none()));
let anchor = match top.kind.clone() {
FeatureKind::Sketch { mut plane, .. } => crate::cmd::sketch::face::anchor_mut(&mut plane).cloned(),
_ => None,
};
assert_eq!(anchor.map(|a| (a.component, a.path)), Some((part, s.doc.first_path(part))));
}
/// Moved without its body, or with the body moved from under it, a feature would break: the move
/// is refused and nothing changes.
#[test]
fn move_features_refuses_a_move_that_would_break_a_feature() {
for moves in [["S2", "Cut1"], ["S1", "Extrude1"]] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 20]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S1", "distance": 10, "body_name": "Block"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S2"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S2", "distance": 4, "operation": "cut", "name": "Cut1"}));
let part = run(&mut s, "component.create", json!({"name": "Part", "activate": false}))["component"].as_u64().unwrap();
let (before, steps) = (s.doc.to_json(), s.undo.len());
let e = s.execute("component.move_features", &json!({"features": moves, "component": part})).unwrap_err().to_string();
assert!(e.contains("moving would"), "{moves:?}: {e}");
assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps), "{moves:?}");
}
}
#[test]
fn move_features_refusals_change_nothing() {
let (mut s, part) = block_and_part();
let refused = |s: &mut Session, params: Value, why: &str| {
let (before, steps) = (s.doc.to_json(), s.undo.len());
let e = s.execute("component.move_features", &params).unwrap_err().to_string();
assert!(e.contains(why), "{e}");
assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));
};
refused(&mut s, json!({"features": ["S"], "component": 0}), "already in that component");
refused(&mut s, json!({"features": ["Nope"], "component": part}), "no feature");
refused(&mut s, json!({"features": [], "component": part}), "1…1000");
refused(&mut s, json!({"features": ["S"], "component": "Nowhere"}), "no component");
// A component placed twice.
run(&mut s, "occurrence.copy", json!({"component": part}));
refused(&mut s, json!({"features": ["S", "Extrude1"], "component": part}), "more than once");
// Rolled back.
run(&mut s, "timeline.roll_to", json!({"position": 1}));
refused(&mut s, json!({"features": ["S"], "component": part}), "rollback");
}
#[test]
fn move_features_refuses_a_boolean_whose_inputs_would_be_split() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A", "name": "BoxA"}));
run(
&mut s,
"solid.box",
json!({"length": 10, "width": 10, "height": 10, "corner": [10, 0, 0], "operation": "new_body", "body_name": "B", "name": "BoxB"}),
);
run(&mut s, "solid.combine", json!({"target": "A", "tools": ["B"], "operation": "join", "name": "Joined"}));
let part = run(&mut s, "component.create", json!({"name": "Part", "activate": false}))["component"].as_u64().unwrap();
let before = s.doc.to_json();
let e = s.execute("component.move_features", &json!({"features": ["BoxA"], "component": part})).unwrap_err().to_string();
assert!(e.contains("split between components"), "{e}");
assert_eq!(s.doc.to_json(), before);
}
/// Each kind moves by its own step, all or nothing, as one undo step: a block's features without
/// the cut that works on it break, so the first call changes nothing; with it, the second moves
/// the placement, the features and the body that is not made by them, and skips the block they carry.
#[test]
fn reparent_items_moves_each_kind_all_or_nothing() {
let (mut s, part) = block_and_part();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S2"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S2", "distance": 4, "operation": "cut", "name": "Cut1"}));
run(
&mut s,
"solid.box",
json!({"length": 10, "width": 10, "height": 10, "corner": [50, 0, 0], "operation": "new_body", "body_name": "Plate", "name": "PlateBox"}),
);
let sub = run(&mut s, "component.create", json!({"name": "Sub", "activate": false}));
let sub_occurrence = sub["occurrence"].as_u64().unwrap();
let (before, steps, corners) = (s.doc.to_json(), s.undo.len(), world_corners(&s));
let moves = |features: Value| json!({"occurrences": [sub_occurrence], "features": features, "bodies": ["Block", "Plate"], "component": part});
// Cut1 would be left without its body: nothing moves, the placement included.
let e = s.execute("browser.reparent", &moves(json!(["S", "Extrude1"]))).unwrap_err().to_string();
assert!(e.contains("moving would"), "{e}");
assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));
let r = run(&mut s, "browser.reparent", moves(json!(["S", "Extrude1", "S2", "Cut1"])));
assert_eq!(r["occurrences"], json!([sub_occurrence]), "{r}");
assert_eq!(r["features"], json!(["S", "Extrude1", "S2", "Cut1"]), "{r}");
assert_eq!(r["bodies"], json!(["Plate"]), "Block went with its features: {r}");
assert_eq!(s.undo.len(), steps + 1, "one undo step");
assert_eq!(s.doc.occurrences.iter().find(|o| o.id == sub_occurrence).map(|o| o.parent), Some(part));
assert_eq!(world_corners(&s), corners, "everything is where it was in the world");
}
#[test]
fn reparent_items_leaves_the_contents_of_a_moved_component_alone() {
let (mut s, part) = block_and_part();
let dest = run(&mut s, "component.create", json!({"name": "Dest", "activate": false}))["component"].as_u64().unwrap();
let occurrence = s.doc.occurrence_of(part).map(|o| o.id).unwrap();
// A feature inside Part is named as well as Part: it travels with Part, not on its own.
run(&mut s, "component.activate", json!({"component": part}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Inner", "name": "InnerBox"}));
run(&mut s, "component.activate", json!({"component": 0}));
let r = run(&mut s, "browser.reparent", json!({"occurrences": [occurrence], "features": ["InnerBox"], "bodies": ["Inner"], "component": dest}));
assert_eq!(r["features"], json!([]), "{r}");
assert_eq!(r["bodies"], json!([]), "{r}");
assert_eq!(s.doc.find_feature("InnerBox").map(|f| f.component), Some(part));
}
#[test]
fn reparent_items_refusals_change_nothing() {
let (mut s, part) = block_and_part();
let refused = |s: &mut Session, params: Value, why: &str| {
let (before, steps) = (s.doc.to_json(), s.undo.len());
let e = s.execute("browser.reparent", &params).unwrap_err().to_string();
assert!(e.contains(why), "{e}");
assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));
};
refused(&mut s, json!({"component": part}), "give `occurrences`");
refused(&mut s, json!({"features": ["S"], "component": 0}), "already in that component");
refused(&mut s, json!({"bodies": ["Nope"], "component": part}), "no body");
refused(&mut s, json!({"occurrences": [9999], "component": part}), "no occurrence");
refused(&mut s, json!({"occurrences": ["x"], "component": part}), "occurrence ids");
let many: Vec<u64> = (0..1001).collect();
refused(&mut s, json!({"occurrences": many, "component": part}), "at most 1000");
run(&mut s, "timeline.roll_to", json!({"position": 1}));
refused(&mut s, json!({"features": ["S"], "component": part}), "rollback");
}
/// Placements hidden inside a moved component are still hidden under their new path.
#[test]
fn reparent_items_keeps_hidden_placements_hidden() {
let (mut s, part) = block_and_part();
let made = run(&mut s, "component.create", json!({"name": "Dest", "activate": false}));
let (dest, dest_occurrence) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap());
let outer = run(&mut s, "component.create", json!({"name": "Outer", "activate": false}));
let (outer_component, outer_occurrence) = (outer["component"].as_u64().unwrap(), outer["occurrence"].as_u64().unwrap());
let inner =
run(&mut s, "component.create", json!({"name": "Inner", "parent": outer_component, "activate": false}))["occurrence"].as_u64().unwrap();
s.visibility.hidden_occurrences.push(vec![outer_occurrence, inner]);
run(&mut s, "browser.reparent", json!({"occurrences": [outer_occurrence], "component": dest}));
assert_eq!(s.visibility.hidden_occurrences, vec![vec![dest_occurrence, outer_occurrence, inner]]);
assert_eq!(s.doc.occurrences.iter().find(|o| o.id == outer_occurrence).map(|o| o.parent), Some(dest));
let _ = part;
}
+2 -16
View File
@@ -67,7 +67,7 @@ pub static COMMANDS: &[CommandSpec] = &[
"features: [id|name], position: insertion slot in the current history; selected features keep their relative order; active?: bool (as timeline.reorder's); refused when a feature that worked would fail, unless allow_errors?: bool (default false): then made, and broken: [{feature, error}] lists the features it broke",
),
CommandSpec::new("timeline.redefine", "Edit Feature", redefine).icon("edit")
.params("feature: id|name, command: the feature's command id, params: its parameters (the feature is rebuilt in place) → feature, recomputed, restored, rolled_back: bool (the feature is after the history marker, so the edit is not built yet; `note` then says so), warning?"),
.params("feature: id|name, command: the feature's command id, params: its parameters (the feature is rebuilt in place)"),
CommandSpec::new("timeline.dependents", "Feature Dependents", dependents).icon("graph")
.noundo()
.params("feature: id|name → features deleted with it, and features that would fail without it"),
@@ -1773,23 +1773,9 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) {
return Err(EngineError::Other(e));
}
// A feature behind the history marker is not built, so the edit changes nothing in the model
// yet: the reply says so, or the edit would look as if it had silently failed (#8100). Its
// warning is the one the constructor met building it in the trial, at its place.
let rolled_back = s.doc.marker.is_some_and(|marker| s.doc.feature_index(id).is_some_and(|index| index >= marker));
let warning =
if rolled_back { r.get("warning").and_then(Value::as_str).map(str::to_string) } else { s.model.result(id).and_then(|r| r.warning.clone()) };
// Report the trial's rebuild, plus anything the session still had to compute itself (a kept
// result its budget dropped); `s.model`'s own counters would only report the reuse (#5694).
let mut reply = json!({"feature": id, "recomputed": rebuilt + s.model.last_recomputed, "restored": reused, "rolled_back": rolled_back});
if let Some(warning) = warning {
reply["warning"] = json!(warning);
}
if rolled_back {
let name = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
reply["note"] = json!(format!("{name} is after the history marker, so it is not built: move the marker past it to build it"));
}
Ok(reply)
Ok(json!({"feature": id, "recomputed": rebuilt + s.model.last_recomputed, "restored": reused}))
}
fn dependents(s: &mut Session, p: &Value) -> Result<Value> {
-8
View File
@@ -469,14 +469,6 @@ impl Session {
super::component_link::resolve_design_links(&mut doc, path);
let mut session = Self::opened(doc, saved);
session.path = path.map(str::to_owned);
// A design saved before body names were pinned (#6403) is pinned now, as its first
// command would pin it: that command pinned them as part of itself, so undoing it went
// back to the unpinned design, whose fingerprints no evaluated result matched, and the
// first undo after opening evaluated the whole timeline again (82-93 s in a
// 5,484-feature design). The pinned names are the ones the file's bodies have, so
// opening is no change: the pinned design is the saved one.
session.pin_body_names();
session.saved = session.doc.clone();
session
}
@@ -188,22 +188,6 @@ fn a_screw_advances_its_pitch_per_turn() {
assert!(close_to(shown(&mut s, "Lift"), 10.0), "{}", shown(&mut s, "Lift"));
}
/// A coupling's length reads a bare number as millimetres in any design, so a parameter defined
/// in it (`lead = 1.5`) keeps that millimetre, while `parameters.add` without a unit takes the
/// design's units (#8865): the screw advances 1.5 mm a turn in an inch design too.
#[test]
fn a_pitch_defined_in_an_inch_design_reads_as_the_screw_does() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
base(&mut s);
part(&mut s, "Nut", [-1.0, -1.0, 0.0]);
pin(&mut s, "cylindrical", "Thread", "Base", "Nut", Vec3::ZERO, Vec3::Z);
run(&mut s, "joint.screw", json!({"joint": "Thread", "pitch": "lead = 1.5"}));
assert_eq!(s.doc.param("lead").map(|p| (p.expr.as_str(), p.unit.as_str())), Some(("1.5", "mm")));
let r = run(&mut s, "joint.drive", json!({"joint": "Thread", "values": [720]}));
assert!(close_to(r["values"][1]["value"].as_f64().unwrap_or(f64::NAN), 3.0), "{r}");
}
/// A motor gear turns the four-bar's crank: half as fast, the other way round, and the loop
/// follows.
#[test]
+402 -402
View File
@@ -1,404 +1,404 @@
//! The command registry. Ids are SolidCraft's own dotted ids (`solid.extrude`,
//! `sketch.rectangle.two_point`); the toolbar placement (`tab`, `panel`) follows the familiar
//! Design workspace layout.
//! The command registry. Ids are SolidCraft's own dotted ids (`solid.extrude`,
//! `sketch.rectangle.two_point`); the toolbar placement (`tab`, `panel`) follows the familiar
//! Design workspace layout.
/// The params-doc note of every command that adds sketch geometry (see `sketch::created`).
macro_rules! created_doc {
() => {
". Returns created: {points, curves, constraints, dimensions}: the ids of what it added (stable and never reused: usable right away in sketch.dimension, sketch.constraint.*, sketch.delete…)"
};
}
/// A command that is designed and registered (id, toolbar place, icon, params doc) but not built
/// yet. It is disabled with the reason, so the toolbar greys it and says why, and its `run`
/// refuses too, however it is reached. `$issue` is the GitHub issue that tracks building it.
macro_rules! planned {
($id:literal, $label:literal, $issue:literal) => {
CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $label, " (issue #", $issue, ")").into())))
.enabled(|_| Err(concat!("not supported yet (issue #", $issue, ")").into()))
.planned($issue)
};
}
mod bom;
mod browser;
pub(crate) mod clearance;
mod clipboard;
mod compare;
mod component;
mod component_clone;
mod component_clone_assembly;
mod construct;
mod delete;
mod diagnostics;
mod edit;
mod face;
mod features;
mod features_more;
mod join_pieces;
pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, axis_dir_form, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach, shown_scope};
pub use join_pieces::{Addition, addition};
pub use sketch::dimension_roles;
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
pub use view_navigation::standard_view;
mod component_link;
pub use component_link::resolve_design_links;
mod config;
mod design_link;
mod file;
mod frame;
pub(crate) mod inspect;
mod interference;
pub(crate) mod joints;
mod libraries;
mod material_properties;
mod materials;
mod measure_sel;
mod measure_shape;
mod mesh;
mod metadata;
pub(crate) mod motion;
mod parts;
mod point_cloud;
mod script;
mod section;
pub(crate) use measure_sel::{measure_items, shape_of};
pub(crate) use measure_shape::Shape;
#[cfg(test)]
mod kernel_heal_tests;
mod parameter_sweep;
mod parameters;
mod plastic;
mod render;
mod render_ui;
#[cfg(test)]
mod script_tests;
mod sheet;
pub(crate) use sheet::{
FlangeType, ThenStep, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position, perforation_pattern, sheet_points,
then_list,
};
mod silhouette;
mod sketch;
pub(crate) use sketch::author_path_for_rebind;
pub(crate) use sketch::created as sketch_created;
mod canvas_sketch;
mod sketch_3d;
mod sketch_canvas;
pub mod sketch_clipboard;
mod sketch_constraints;
mod sketch_create;
mod sketch_ends;
mod sketch_freeform;
mod sketch_import;
mod sketch_inspect;
mod sketch_modify;
mod sketch_project;
mod sketch_store;
mod surface;
mod surface_analysis;
mod surface_boundary;
mod surface_match;
mod view_dxf;
mod view_navigation;
use serde::Serialize;
use serde_json::Value;
use crate::{Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
/// A command's form for one frame of an interactive gesture: its result and the sketch it
/// changed, for [`Session::execute`] to show without evaluating the rest of the model (`None`:
/// evaluate as usual).
pub type LiveRun = fn(&mut Session, &Value) -> Result<(Value, Option<crate::LiveEdit>)>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub type SchemaFn = fn() -> schemars::Schema;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Toolbar tab (`SOLID`, `SKETCH`…); empty = not on the toolbar.
pub tab: &'static str,
/// Toolbar panel (`CREATE`, `MODIFY`…).
pub panel: &'static str,
/// Icon name for the UI (drawn in code).
pub icon: &'static str,
pub shortcut: Option<&'static str>,
/// One-line parameter documentation.
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
pub undoable: bool,
/// What runs instead of `run` when the command is given `live: true` (a frame of an
/// interactive gesture, see [`Session::execute`]).
pub live: Option<LiveRun>,
/// Reads the evaluated model (the default). A command that reads only the document and the
/// session's history runs on a model left stale by a live gesture without evaluating it first.
pub reads_model: bool,
/// Registered but not built yet (see `planned!`): the GitHub issue number that tracks it.
pub planned: Option<&'static str>,
/// The command's typed parameter contract, which carries its input schema; `None` until
/// the command is converted (see `crate::schema`).
pub contract: Option<&'static dyn crate::schema::Contract>,
/// The JSON Schema of a successful result; `None` until described.
pub output: Option<SchemaFn>,
}
impl CommandSpec {
pub const fn new(id: &'static str, label: &'static str, run: Run) -> Self {
CommandSpec {
id,
label,
tab: "",
panel: "",
icon: "",
shortcut: None,
params: "",
enabled: always,
run,
undoable: true,
live: None,
reads_model: true,
planned: None,
contract: None,
output: None,
}
}
/// Not built yet; `issue` tracks building it.
pub const fn planned(mut self, issue: &'static str) -> Self {
self.planned = Some(issue);
self
}
/// Takes `live: true`, run by `run`.
pub const fn live(mut self, run: LiveRun) -> Self {
self.live = Some(run);
self
}
/// Reads only the document (and history), never the evaluated model.
pub const fn doc_only(mut self) -> Self {
self.reads_model = false;
self
}
pub const fn at(mut self, tab: &'static str, panel: &'static str) -> Self {
self.tab = tab;
self.panel = panel;
self
}
pub const fn icon(mut self, i: &'static str) -> Self {
self.icon = i;
self
}
pub const fn key(mut self, k: &'static str) -> Self {
self.shortcut = Some(k);
self
}
/// The command's typed parameter contract (see `crate::schema`).
pub const fn contract(mut self, c: &'static dyn crate::schema::Contract) -> Self {
self.contract = Some(c);
self
}
/// The JSON Schema of a successful result.
pub const fn output(mut self, f: SchemaFn) -> Self {
self.output = Some(f);
self
}
pub const fn params(mut self, p: &'static str) -> Self {
self.params = p;
self
}
pub const fn enabled(mut self, e: Enabled) -> Self {
self.enabled = e;
self
}
pub const fn noundo(mut self) -> Self {
self.undoable = false;
self
}
/// Run inside another command: when it is enabled, its `run` (the caller's command owns the
/// undo step and the evaluation).
pub(crate) fn run_nested(&self, s: &mut Session, p: &Value) -> Result<Value> {
(self.enabled)(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?;
let r = (self.run)(s, p);
// A parameter error that did not name the command names it here (see `Session::execute`).
match r {
Err(crate::EngineError::BadParams { cmd, msg }) if cmd.is_empty() => Err(crate::EngineError::BadParams { cmd: self.id.to_string(), msg }),
other => other,
}
}
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
let (label, icon) = match self.id {
"inspect.colored_components" if s.colored_components.is_some() => ("Disable Component Colors", "colored_components_off"),
_ => (self.label, self.icon),
};
CommandInfo {
id: self.id,
label,
tab: self.tab,
panel: self.panel,
icon,
shortcut: self.shortcut,
params: self.params,
enabled: e.is_ok(),
disabled_reason: e.err(),
planned: self.planned,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct CommandInfo {
pub id: &'static str,
pub label: &'static str,
pub tab: &'static str,
pub panel: &'static str,
pub icon: &'static str,
pub shortcut: Option<&'static str>,
pub params: &'static str,
pub enabled: bool,
pub disabled_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub planned: Option<&'static str>,
}
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub fn in_sketch(s: &Session) -> std::result::Result<(), String> {
if s.active_sketch.is_some() { Ok(()) } else { Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()) }
}
/// The mirror of [`in_sketch`], for a command that acts on bodies and has nothing to offer the
/// geometry under the cursor while a sketch is open.
pub fn not_in_sketch(s: &Session) -> std::result::Result<(), String> {
if s.active_sketch.is_none() { Ok(()) } else { Err("a sketch is being edited (this works on bodies: Finish Sketch first)".into()) }
}
/// Every command, in toolbar order.
pub fn command_specs() -> Vec<&'static CommandSpec> {
let mut v: Vec<&'static CommandSpec> = Vec::new();
v.extend(sketch::COMMANDS.iter());
v.extend(sketch_create::COMMANDS.iter());
v.extend(sketch_constraints::COMMANDS.iter());
v.extend(sketch_import::COMMANDS.iter());
v.extend(sketch_inspect::COMMANDS.iter());
v.extend(sketch_ends::COMMANDS.iter());
v.extend(sketch_canvas::COMMANDS.iter());
v.extend(canvas_sketch::COMMANDS.iter());
v.extend(point_cloud::COMMANDS.iter());
v.extend(sketch_3d::COMMANDS.iter());
v.extend(surface_analysis::COMMANDS.iter());
v.extend(surface_boundary::COMMANDS.iter());
v.extend(surface::COMMANDS.iter());
v.extend(surface_match::COMMANDS.iter());
v.extend(sketch_modify::COMMANDS.iter());
v.extend(sketch_project::COMMANDS.iter());
v.extend(features::COMMANDS.iter());
v.extend(features_more::COMMANDS.iter());
v.extend(mesh::COMMANDS.iter());
v.extend(construct::COMMANDS.iter());
v.extend(sheet::COMMANDS.iter());
v.extend(plastic::COMMANDS.iter());
v.extend(frame::COMMANDS.iter());
v.extend(component::COMMANDS.iter());
v.extend(component_link::COMMANDS.iter());
v.extend(joints::COMMANDS.iter());
v.extend(clearance::COMMANDS.iter());
v.extend(motion::COMMANDS.iter());
v.extend(config::COMMANDS.iter());
v.extend(parts::COMMANDS.iter());
v.extend(bom::COMMANDS.iter());
v.extend(browser::COMMANDS.iter());
v.extend(delete::COMMANDS.iter());
v.extend(edit::COMMANDS.iter());
v.extend(clipboard::COMMANDS.iter());
v.extend(sketch_clipboard::COMMANDS.iter());
v.extend(script::COMMANDS.iter());
v.extend(parameters::COMMANDS.iter());
v.extend(parameter_sweep::COMMANDS.iter());
v.extend(file::COMMANDS.iter());
v.extend(metadata::COMMANDS.iter());
v.extend(inspect::COMMANDS.iter());
v.extend(compare::COMMANDS.iter());
v.extend(silhouette::COMMANDS.iter());
v.extend(materials::COMMANDS.iter());
v.extend(material_properties::COMMANDS.iter());
v.extend(libraries::COMMANDS.iter());
v.extend(section::COMMANDS.iter());
v.extend(view_navigation::COMMANDS.iter());
v.extend(view_dxf::COMMANDS.iter());
v.extend(diagnostics::COMMANDS.iter());
v.extend(render::COMMANDS.iter());
v.extend(render_ui::COMMANDS.iter());
v
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
let all = command_specs();
all.iter().find(|c| c.id == id).or_else(|| all.iter().find(|c| c.id.eq_ignore_ascii_case(id))).copied()
}
/// The end of an unknown command's error: up to three ids like `id`, nearest first. Ids a few
/// letters away (`solid.extrud` → `solid.extrude`) come before ids that end in the same word
/// (`file.open` → `doc.open`). Empty when nothing is close.
pub(crate) fn did_you_mean(id: &str) -> String {
let id = id.to_ascii_lowercase();
if id.len() > 64 {
return String::new();
}
let last = |s: &str| s.rsplit('.').next().unwrap_or(s).to_string();
let near = (id.chars().count() / 4).max(2);
let mut found: Vec<(bool, usize, &str)> = command_specs()
.iter()
.filter_map(|c| {
let d = edit_distance(&id, c.id);
(d <= near || last(&id) == last(c.id)).then_some((d > near, d, c.id))
})
.collect();
found.sort();
let ids: Vec<String> = found.iter().take(3).map(|(_, _, c)| format!("`{c}`")).collect();
match ids.as_slice() {
[] => String::new(),
[one] => format!(" (did you mean {one}?)"),
[rest @ .., end] => format!(" (did you mean {} or {end}?)", rest.join(", ")),
}
}
/// Levenshtein distance: the single-character edits that turn `a` into `b`.
pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
let mut row: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.chars().enumerate() {
let mut prev = row[0];
row[0] = i + 1;
for (j, cb) in b.iter().enumerate() {
let next = (prev + usize::from(ca != *cb)).min(row[j] + 1).min(row[j + 1] + 1);
prev = row[j + 1];
row[j + 1] = next;
}
}
row[b.len()]
}
pub(super) fn alignment_param(p: &Value, key: &str, cmd: &str) -> Result<solidcraft_sketch::PatternAlignment> {
p.get(key).map_or(Ok(solidcraft_sketch::PatternAlignment::default()), |value| {
serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be left, center or right")))
})
}
pub(super) fn reversed_param(p: &Value, key: &str, cmd: &str) -> Result<bool> {
p.get(key).map_or(Ok(false), |value| {
serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be true or false")))
})
}
/// The params-doc note of every command that adds sketch geometry (see `sketch::created`).
macro_rules! created_doc {
() => {
". Returns created: {points, curves, constraints, dimensions}: the ids of what it added (stable and never reused: usable right away in sketch.dimension, sketch.constraint.*, sketch.delete…)"
};
}
/// A command that is designed and registered (id, toolbar place, icon, params doc) but not built
/// yet. It is disabled with the reason, so the toolbar greys it and says why, and its `run`
/// refuses too, however it is reached. `$issue` is the GitHub issue that tracks building it.
macro_rules! planned {
($id:literal, $label:literal, $issue:literal) => {
CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $label, " (issue #", $issue, ")").into())))
.enabled(|_| Err(concat!("not supported yet (issue #", $issue, ")").into()))
.planned($issue)
};
}
mod bom;
mod browser;
pub(crate) mod clearance;
mod clipboard;
mod compare;
mod component;
mod component_clone;
mod component_clone_assembly;
mod construct;
mod delete;
mod diagnostics;
mod edit;
mod face;
mod features;
mod features_more;
mod join_pieces;
pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, axis_dir_form, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach, shown_scope};
pub use join_pieces::{Addition, addition};
pub use sketch::dimension_roles;
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
pub use view_navigation::standard_view;
mod component_link;
pub use component_link::resolve_design_links;
mod config;
mod design_link;
mod file;
mod frame;
pub(crate) mod inspect;
mod interference;
pub(crate) mod joints;
mod libraries;
mod material_properties;
mod materials;
mod measure_sel;
mod measure_shape;
mod mesh;
mod metadata;
pub(crate) mod motion;
mod parts;
mod point_cloud;
mod script;
mod section;
pub mod settings;
pub(crate) use measure_sel::{measure_items, shape_of};
pub(crate) use measure_shape::Shape;
#[cfg(test)]
mod kernel_heal_tests;
mod parameter_sweep;
mod parameters;
mod plastic;
mod render;
mod render_ui;
#[cfg(test)]
mod script_tests;
mod sheet;
pub(crate) use sheet::{
FlangeType, ThenStep, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position, perforation_pattern, sheet_points,
then_list,
};
mod silhouette;
mod sketch;
pub(crate) use sketch::author_path_for_rebind;
pub(crate) use sketch::created as sketch_created;
mod canvas_sketch;
mod sketch_3d;
mod sketch_canvas;
pub mod sketch_clipboard;
mod sketch_constraints;
mod sketch_create;
mod sketch_ends;
mod sketch_equation;
mod sketch_freeform;
mod sketch_import;
mod sketch_inspect;
mod sketch_modify;
mod sketch_project;
mod sketch_store;
mod surface;
mod surface_analysis;
mod surface_boundary;
mod surface_match;
mod view_dxf;
mod view_navigation;
use serde::Serialize;
use serde_json::Value;
use crate::{Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
/// A command's form for one frame of an interactive gesture: its result and the sketch it
/// changed, for [`Session::execute`] to show without evaluating the rest of the model (`None`:
/// evaluate as usual).
pub type LiveRun = fn(&mut Session, &Value) -> Result<(Value, Option<crate::LiveEdit>)>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub type SchemaFn = fn() -> schemars::Schema;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Toolbar tab (`SOLID`, `SKETCH`…); empty = not on the toolbar.
pub tab: &'static str,
/// Toolbar panel (`CREATE`, `MODIFY`…).
pub panel: &'static str,
/// Icon name for the UI (drawn in code).
pub icon: &'static str,
pub shortcut: Option<&'static str>,
/// One-line parameter documentation.
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
pub undoable: bool,
/// What runs instead of `run` when the command is given `live: true` (a frame of an
/// interactive gesture, see [`Session::execute`]).
pub live: Option<LiveRun>,
/// Reads the evaluated model (the default). A command that reads only the document and the
/// session's history runs on a model left stale by a live gesture without evaluating it first.
pub reads_model: bool,
/// Registered but not built yet (see `planned!`): the GitHub issue number that tracks it.
pub planned: Option<&'static str>,
/// The command's typed parameter contract, which carries its input schema; `None` until
/// the command is converted (see `crate::schema`).
pub contract: Option<&'static dyn crate::schema::Contract>,
/// The JSON Schema of a successful result; `None` until described.
pub output: Option<SchemaFn>,
}
impl CommandSpec {
pub const fn new(id: &'static str, label: &'static str, run: Run) -> Self {
CommandSpec {
id,
label,
tab: "",
panel: "",
icon: "",
shortcut: None,
params: "",
enabled: always,
run,
undoable: true,
live: None,
reads_model: true,
planned: None,
contract: None,
output: None,
}
}
/// Not built yet; `issue` tracks building it.
pub const fn planned(mut self, issue: &'static str) -> Self {
self.planned = Some(issue);
self
}
/// Takes `live: true`, run by `run`.
pub const fn live(mut self, run: LiveRun) -> Self {
self.live = Some(run);
self
}
/// Reads only the document (and history), never the evaluated model.
pub const fn doc_only(mut self) -> Self {
self.reads_model = false;
self
}
pub const fn at(mut self, tab: &'static str, panel: &'static str) -> Self {
self.tab = tab;
self.panel = panel;
self
}
pub const fn icon(mut self, i: &'static str) -> Self {
self.icon = i;
self
}
pub const fn key(mut self, k: &'static str) -> Self {
self.shortcut = Some(k);
self
}
/// The command's typed parameter contract (see `crate::schema`).
pub const fn contract(mut self, c: &'static dyn crate::schema::Contract) -> Self {
self.contract = Some(c);
self
}
/// The JSON Schema of a successful result.
pub const fn output(mut self, f: SchemaFn) -> Self {
self.output = Some(f);
self
}
pub const fn params(mut self, p: &'static str) -> Self {
self.params = p;
self
}
pub const fn enabled(mut self, e: Enabled) -> Self {
self.enabled = e;
self
}
pub const fn noundo(mut self) -> Self {
self.undoable = false;
self
}
/// Run inside another command: when it is enabled, its `run` (the caller's command owns the
/// undo step and the evaluation).
pub(crate) fn run_nested(&self, s: &mut Session, p: &Value) -> Result<Value> {
(self.enabled)(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?;
let r = (self.run)(s, p);
// A parameter error that did not name the command names it here (see `Session::execute`).
match r {
Err(crate::EngineError::BadParams { cmd, msg }) if cmd.is_empty() => Err(crate::EngineError::BadParams { cmd: self.id.to_string(), msg }),
other => other,
}
}
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
let (label, icon) = match self.id {
"inspect.colored_components" if s.colored_components.is_some() => ("Disable Component Colors", "colored_components_off"),
_ => (self.label, self.icon),
};
CommandInfo {
id: self.id,
label,
tab: self.tab,
panel: self.panel,
icon,
shortcut: self.shortcut,
params: self.params,
enabled: e.is_ok(),
disabled_reason: e.err(),
planned: self.planned,
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct CommandInfo {
pub id: &'static str,
pub label: &'static str,
pub tab: &'static str,
pub panel: &'static str,
pub icon: &'static str,
pub shortcut: Option<&'static str>,
pub params: &'static str,
pub enabled: bool,
pub disabled_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub planned: Option<&'static str>,
}
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub fn in_sketch(s: &Session) -> std::result::Result<(), String> {
if s.active_sketch.is_some() { Ok(()) } else { Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()) }
}
/// The mirror of [`in_sketch`], for a command that acts on bodies and has nothing to offer the
/// geometry under the cursor while a sketch is open.
pub fn not_in_sketch(s: &Session) -> std::result::Result<(), String> {
if s.active_sketch.is_none() { Ok(()) } else { Err("a sketch is being edited (this works on bodies: Finish Sketch first)".into()) }
}
/// Every command, in toolbar order.
pub fn command_specs() -> Vec<&'static CommandSpec> {
let mut v: Vec<&'static CommandSpec> = Vec::new();
v.extend(sketch::COMMANDS.iter());
v.extend(sketch_create::COMMANDS.iter());
v.extend(sketch_equation::COMMANDS.iter());
v.extend(sketch_constraints::COMMANDS.iter());
v.extend(sketch_import::COMMANDS.iter());
v.extend(sketch_inspect::COMMANDS.iter());
v.extend(sketch_ends::COMMANDS.iter());
v.extend(sketch_canvas::COMMANDS.iter());
v.extend(canvas_sketch::COMMANDS.iter());
v.extend(point_cloud::COMMANDS.iter());
v.extend(sketch_3d::COMMANDS.iter());
v.extend(surface_analysis::COMMANDS.iter());
v.extend(surface_boundary::COMMANDS.iter());
v.extend(surface::COMMANDS.iter());
v.extend(surface_match::COMMANDS.iter());
v.extend(sketch_modify::COMMANDS.iter());
v.extend(sketch_project::COMMANDS.iter());
v.extend(features::COMMANDS.iter());
v.extend(features_more::COMMANDS.iter());
v.extend(mesh::COMMANDS.iter());
v.extend(construct::COMMANDS.iter());
v.extend(sheet::COMMANDS.iter());
v.extend(plastic::COMMANDS.iter());
v.extend(frame::COMMANDS.iter());
v.extend(component::COMMANDS.iter());
v.extend(component_link::COMMANDS.iter());
v.extend(joints::COMMANDS.iter());
v.extend(clearance::COMMANDS.iter());
v.extend(motion::COMMANDS.iter());
v.extend(config::COMMANDS.iter());
v.extend(parts::COMMANDS.iter());
v.extend(bom::COMMANDS.iter());
v.extend(browser::COMMANDS.iter());
v.extend(delete::COMMANDS.iter());
v.extend(edit::COMMANDS.iter());
v.extend(clipboard::COMMANDS.iter());
v.extend(sketch_clipboard::COMMANDS.iter());
v.extend(script::COMMANDS.iter());
v.extend(parameters::COMMANDS.iter());
v.extend(parameter_sweep::COMMANDS.iter());
v.extend(file::COMMANDS.iter());
v.extend(metadata::COMMANDS.iter());
v.extend(inspect::COMMANDS.iter());
v.extend(compare::COMMANDS.iter());
v.extend(silhouette::COMMANDS.iter());
v.extend(materials::COMMANDS.iter());
v.extend(material_properties::COMMANDS.iter());
v.extend(libraries::COMMANDS.iter());
v.extend(section::COMMANDS.iter());
v.extend(view_navigation::COMMANDS.iter());
v.extend(view_dxf::COMMANDS.iter());
v.extend(settings::COMMANDS.iter());
v.extend(diagnostics::COMMANDS.iter());
v.extend(render::COMMANDS.iter());
v.extend(render_ui::COMMANDS.iter());
v
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
let all = command_specs();
all.iter().find(|c| c.id == id).or_else(|| all.iter().find(|c| c.id.eq_ignore_ascii_case(id))).copied()
}
/// The end of an unknown command's error: up to three ids like `id`, nearest first. Ids a few
/// letters away (`solid.extrud` → `solid.extrude`) come before ids that end in the same word
/// (`file.open` → `doc.open`). Empty when nothing is close.
pub(crate) fn did_you_mean(id: &str) -> String {
let id = id.to_ascii_lowercase();
if id.len() > 64 {
return String::new();
}
let last = |s: &str| s.rsplit('.').next().unwrap_or(s).to_string();
let near = (id.chars().count() / 4).max(2);
let mut found: Vec<(bool, usize, &str)> = command_specs()
.iter()
.filter_map(|c| {
let d = edit_distance(&id, c.id);
(d <= near || last(&id) == last(c.id)).then_some((d > near, d, c.id))
})
.collect();
found.sort();
let ids: Vec<String> = found.iter().take(3).map(|(_, _, c)| format!("`{c}`")).collect();
match ids.as_slice() {
[] => String::new(),
[one] => format!(" (did you mean {one}?)"),
[rest @ .., end] => format!(" (did you mean {} or {end}?)", rest.join(", ")),
}
}
/// Levenshtein distance: the single-character edits that turn `a` into `b`.
pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
let mut row: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.chars().enumerate() {
let mut prev = row[0];
row[0] = i + 1;
for (j, cb) in b.iter().enumerate() {
let next = (prev + usize::from(ca != *cb)).min(row[j] + 1).min(row[j + 1] + 1);
prev = row[j + 1];
row[j + 1] = next;
}
}
row[b.len()]
}
pub(super) fn alignment_param(p: &Value, key: &str, cmd: &str) -> Result<solidcraft_sketch::PatternAlignment> {
p.get(key).map_or(Ok(solidcraft_sketch::PatternAlignment::default()), |value| {
serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be left, center or right")))
})
}
pub(super) fn reversed_param(p: &Value, key: &str, cmd: &str) -> Result<bool> {
p.get(key).map_or(Ok(false), |value| {
serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be true or false")))
})
pub(crate) fn prepare_interactive(s: &crate::Session, params: &serde_json::Value) -> crate::Result<crate::render_interactive::Prepared> {
render::prepare_interactive(s, params)
}
-56
View File
@@ -1638,59 +1638,3 @@ fn occurrence_align_keeps_every_pick_and_reports_shared_definitions() {
let r = run(&mut s, "occurrence.align", json!({"paths": [[b]], "from": [0, 0, 0], "to": [1, 0, 0]}));
assert!(r.get("shared").is_none(), "{r}");
}
/// A body copied in another design pastes here as an imported body: at the world coordinates it
/// had there, into the component asked for (placed elsewhere), named as it was or numbered when
/// that name is taken, from one Import feature named as any import is, as one step to undo.
#[test]
fn a_body_copied_in_another_design_pastes_as_an_imported_body() {
let mut source = Session::default();
source.doc_mut().name = "Bracket".into();
let (_, holder) = created(&mut source, "Holder");
run(&mut source, "occurrence.move", json!({"occurrence": holder, "translate": [0,50,0]}));
run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
let was = source.world_state().body("Cube").unwrap().mesh().bounds();
let copy = crate::ForeignCopy::of(&source, vec!["Cube".into()], Vec::new());
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Cube"}));
let (a, a_at) = created(&mut s, "A");
run(&mut s, "occurrence.move", json!({"occurrence": a_at, "translate": [100,0,0]}));
s.foreign_copy = Some(std::sync::Arc::new(copy));
let undo = s.undo.len();
let out = run(&mut s, "component.paste_from_design", json!({"component": a, "component_path": [a_at]}));
assert_eq!(out["bodies"], json!(["Cube (2)"]));
assert_eq!(out["feature"], "Import1");
assert_eq!(s.undo.len(), undo + 1);
let is = s.world_state().body("Cube (2)").unwrap().mesh().bounds();
assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}");
let state = s.model.state();
assert_eq!(s.doc.model_body_component(state.body("Cube (2)").unwrap()), a);
assert!(matches!(&s.doc.find_feature("Import1").unwrap().kind, solidcraft_doc::FeatureKind::Import { file, .. } if file == "Bracket (pasted)"));
run(&mut s, "edit.undo", json!({}));
assert!(s.model.state().body("Cube (2)").is_none());
}
/// A body seen in another placement of its component ("Cube (Holder:2)") pastes into another
/// design under its own name, at that placement's position.
#[test]
fn a_body_seen_in_another_placement_pastes_into_another_design_under_its_own_name() {
let mut source = Session::default();
source.doc_mut().name = "Bracket".into();
let (holder, first) = created(&mut source, "Holder");
run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
run(&mut source, "component.activate", json!({"component": 0}));
let second = run(&mut source, "occurrence.copy", json!({"occurrence": first}))["occurrence"].as_u64().unwrap();
run(&mut source, "occurrence.move", json!({"occurrence": second, "translate": [0,40,0]}));
let seen = source.placed_document().world_body_name(&source.model.state(), "Cube", holder, &[second]);
assert_ne!(seen, "Cube");
let was = source.world_state().body(&seen).unwrap().mesh().bounds();
let copy = crate::ForeignCopy::of(&source, vec![seen], Vec::new());
assert_eq!(copy.names, vec!["Cube".to_string()]);
let mut s = Session { foreign_copy: Some(std::sync::Arc::new(copy)), ..Default::default() };
let out = run(&mut s, "component.paste_from_design", json!({}));
assert_eq!(out["bodies"], json!(["Cube"]));
let is = s.world_state().body("Cube").unwrap().mesh().bounds();
assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}");
}
+2 -4
View File
@@ -13,7 +13,7 @@ use crate::{EngineError, Result, Session};
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit, a length the design's units; \
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit; \
a text parameter's expression is its text, quotes round it optional: sketch texts' words are built from it), comment?, \
favorite?: bool, new_name?: rename (references follow; an expression `new = value` renames to `new` and sets value, \
or sets `new` when the expression is just `new`); or delete: name; or changes: {name: expression, …} (existing \
@@ -467,9 +467,7 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) => None,
};
let (vals, _) = s.doc.param_values();
// Bare numbers follow the asked-for unit when given, else the design's length unit (#9015).
let doc_len = expr::unit_info(s.doc.units.trim()).filter(|(k, _)| *k == Kind::Length).map(|(_, s)| s).unwrap_or(1.0);
let defaults = expr::Defaults::for_unit(unit.unwrap_or(""), doc_len);
let defaults = expr::Defaults::for_unit(unit.unwrap_or(""), 1.0);
let refs = expr::references(&e);
let lookup = |n: &str| vals.get(n).copied().ok_or_else(|| solidcraft_doc::DocError::Expr(format!("unknown parameter `{n}`")));
let r = expr::eval_with_defaults(&e, &lookup, defaults).and_then(|v| match kind {
-150
View File
@@ -326,81 +326,6 @@ fn csv_and_json_round_trip() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #8960: the text marker accepts ASCII case variants without changing numeric units.
#[test]
fn text_parameter_imports_accept_mixed_case_units() {
for unit in ["text", "Text", "TEXT", "tExT", " Text "] {
let csv = format!("name,unit,expression,comment\nwidth,in,1,numeric control\nverID,{unit},\"\"\"REV-A\"\"\",quoted label\n");
let json_text = json!([
{"name": "width", "unit": "in", "expression": "1", "comment": "numeric control"},
{"name": "verID", "unit": unit, "expression": "\"REV-A\"", "comment": "quoted label"}
])
.to_string();
for text in [csv, json_text] {
let mut s = Session::default();
// Check both adding and updating a text parameter through the import command.
for expected in ["REV-A", "REV-B"] {
let r = run(&mut s, "parameters.import", json!({"text": text.replace("REV-A", expected)}));
assert_eq!(r["imported"], json!(["width", "verID"]));
assert_eq!(r["errors"], json!([]));
let list = run(&mut s, "parameters.list", json!({}));
assert_eq!(list["count"], 2);
let label = row(&list, "verID");
assert_eq!(label["unit"], "text");
assert_eq!(label["text"], expected);
assert_eq!(label["expression"], expected);
assert_eq!(label["comment"], "quoted label");
assert!(label["value"].is_null());
assert_eq!(row(&list, "width")["unit"], "in");
assert_eq!(row(&list, "width")["value"], 1.0);
assert_eq!(s.doc.param_values().0["width"].v, 25.4);
}
// Export still uses the canonical marker and round-trips the unquoted text.
let exported = run(&mut s, "parameters.export", json!({"format": "csv"}));
assert!(exported["text"].as_str().unwrap().contains("verID,text,REV-B,,quoted label,"), "{exported}");
let mut reopened = Session::default();
run(&mut reopened, "parameters.import", json!({"text": exported["text"]}));
assert_eq!(reopened.doc.text_param("verID").unwrap().text, "REV-B");
}
}
}
#[test]
fn text_parameter_imports_keep_unknown_units_atomic() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "verID", "unit": "text", "expression": "original"}));
run(&mut s, "parameters.add", json!({"name": "width", "unit": "mm", "expression": "20"}));
let before = s.doc.to_json();
for unit in ["Textual", "MM"] {
let csv = format!("name,unit,expression\nverID,Text,replacement\nwidth,mm,30\nbad,{unit},1\n");
let json_text = json!([
{"name": "verID", "unit": "Text", "expression": "replacement"},
{"name": "width", "unit": "mm", "expression": "30"},
{"name": "bad", "unit": unit, "expression": "1"}
])
.to_string();
for text in [csv, json_text] {
let why = err(&mut s, "parameters.import", json!({"text": text}));
assert!(why.contains(&format!("unknown unit `{unit}`")), "{why}");
assert_eq!(s.doc.to_json(), before, "a rejected row must roll back the entire import");
}
}
}
#[test]
fn text_parameter_commands_accept_mixed_case_units() {
let mut s = Session::default();
let r = run(&mut s, "parameters.add", json!({"name": "Label", "unit": "Text", "expression": "\"TAG-A\""}));
assert_eq!(r["unit"], "text");
assert_eq!(r["text"], "TAG-A");
run(&mut s, "parameters.change", json!({"name": "Label", "unit": "TEXT", "expression": "'TAG-B'"}));
assert_eq!(s.doc.text_param("Label").unwrap().text, "TAG-B");
let r = run(&mut s, "expr.evaluate", json!({"unit": " tExT ", "expression": "\"TAG-C\""}));
assert_eq!(r["ok"], true);
assert_eq!(r["kind"], "text");
assert_eq!(r["text"], "TAG-C");
}
/// Two triangles joined by three links (a b c, d e f; links a–d, b–e, c–f), a on the origin,
/// a–b horizontal, every distance a dimension: the construction leaves it to the iteration.
/// Returns the session, the sketch feature and the nine dimensions' parameters.
@@ -887,69 +812,6 @@ fn a_defined_length_takes_the_design_unit() {
assert!(rel(volume(&mut s), 50.8 * 25.4 * 25.4) < 1e-9);
}
/// A parameter added without a unit takes the unit of its value, a length in the design's units
/// as a typed length would be (#8865): `40/2` in an inch design is 20 in, as the Parameters
/// dialog makes it. A unit given, an angle and a unit-less value keep their own.
#[test]
fn a_parameter_added_without_a_unit_takes_the_design_unit() {
let added = |s: &mut Session, p: Value| {
let r = run(s, "parameters.add", p);
(r["unit"].as_str().unwrap_or("?").to_string(), r["value"].as_f64().unwrap_or(f64::NAN), r["display_value"].as_f64().unwrap_or(f64::NAN))
};
let close = |got: (String, f64, f64), unit: &str, mm: f64, shown: f64| {
assert!(got.0 == unit && rel(got.1, mm) < 1e-9 && rel(got.2, shown) < 1e-9, "{got:?}, expected {unit} {mm} mm ({shown})");
};
// A millimetre design is as it was.
let mut s = Session::default();
close(added(&mut s, json!({"name": "v", "expression": "40/2"})), "mm", 20.0, 20.0);
close(added(&mut s, json!({"name": "w", "expression": "v + 1"})), "mm", 21.0, 21.0);
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
close(added(&mut s, json!({"name": "v", "expression": "40/2"})), "in", 508.0, 20.0);
close(added(&mut s, json!({"name": "given", "expression": "40/2", "unit": "in"})), "in", 508.0, 20.0);
close(added(&mut s, json!({"name": "metric", "expression": "40/2", "unit": "mm"})), "mm", 20.0, 20.0);
// A value with a unit keeps its size and shows in the design's units.
close(added(&mut s, json!({"name": "plate", "expression": "25.4 mm"})), "in", 25.4, 1.0);
// One that refers to another parameter: its bare number is an inch too.
close(added(&mut s, json!({"name": "more", "expression": "v + 1"})), "in", 533.4, 21.0);
close(added(&mut s, json!({"name": "half", "expression": "v / 2"})), "in", 254.0, 10.0);
// An angle stays in degrees, a unit-less count stays unit-less.
close(added(&mut s, json!({"name": "turn", "expression": "30 deg"})), "deg", 30f64.to_radians(), 30.0);
close(added(&mut s, json!({"name": "n", "expression": "4", "unit": ""})), "", 4.0, 4.0);
close(added(&mut s, json!({"name": "twice", "expression": "n * 2"})), "", 8.0, 8.0);
// parameters.change and parameters.import make a new parameter the same way.
run(&mut s, "parameters.change", json!({"name": "c", "expression": "3"}));
assert_eq!(s.doc.param("c").map(|p| p.unit.as_str()), Some("in"));
run(&mut s, "parameters.import", json!({"text": "name,expression\nimported,2\n"}));
assert_eq!(s.doc.param("imported").map(|p| p.unit.as_str()), Some("in"));
let (vals, _) = s.doc.param_values();
assert!(vals.get("imported").is_some_and(|v| rel(v.v, 50.8) < 1e-9), "{:?}", vals.get("imported"));
// An existing parameter changed without a unit keeps its own.
run(&mut s, "parameters.change", json!({"name": "metric", "expression": "30"}));
assert_eq!(s.doc.param("metric").map(|p| p.unit.as_str()), Some("mm"));
// A centimetre design works the same way.
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "cm"}));
close(added(&mut s, json!({"name": "v", "expression": "3"})), "cm", 30.0, 3.0);
}
/// Hostile parameters.add input in an inch design is refused with a reason and adds nothing.
#[test]
fn a_hostile_parameter_in_an_inch_design_is_refused() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
// 1e308 inches is past any finite millimetre value.
for (name, e) in [("huge", "1e308"), ("inf", "1e308 * 1e308"), ("nan", "0/0"), ("bad", "2 furlong"), ("empty", " "), ("self_ref", "self_ref + 1")]
{
let why = err(&mut s, "parameters.add", json!({"name": name, "expression": e}));
assert!(!why.is_empty() && s.doc.param(name).is_none(), "{name}: {why}");
}
let why = err(&mut s, "parameters.add", json!({"name": "u", "expression": "1", "unit": "furlong"}));
assert!(why.contains("unknown unit"), "{why}");
assert!(s.doc.params.is_empty());
}
/// A definition that cannot be made fails the command and leaves the design as it was: a taken,
/// reserved or malformed name, no value, a value that names itself, two different values for one
/// name, and a parameter's or configuration cell's own expression.
@@ -1033,18 +895,6 @@ fn expr_of_now(s: &Session, name: &str) -> String {
s.doc.param(name).map(|p| p.expr.clone()).unwrap_or_default()
}
/// #9015: `expr.evaluate` of a length with a bare offset uses the design's units.
#[test]
fn expr_evaluate_bare_offsets_follow_design_units() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
run(&mut s, "parameters.add", json!({"name": "baseLength", "expression": "76"}));
let r = run(&mut s, "expr.evaluate", json!({"expression": "baseLength - 1", "kind": "length"}));
assert_eq!(r["ok"], true, "{r}");
// 75 in in millimetres (without the fix this was 76 in − 1 mm).
assert!((r["value"].as_f64().unwrap_or(0.0) - 75.0 * 25.4).abs() < 1e-9, "{r}");
}
/// A dimension made as `w = 20` shows `w`; typing `w = 30` over it sets `w` rather than being
/// refused as a taken name (#4071).
#[test]
+8 -128
View File
@@ -22,7 +22,7 @@ pub static COMMANDS: &[CommandSpec] = &[
"the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?",
),
CommandSpec::new("parts.insert", "Insert Part", insert).icon("fastener").params(
"family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing); size (\"M6\", or \"608\" for bearings); \
"family (socket_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing); size (\"M6\", or \"608\" for bearings); \
length? (mm; screws, bolts, set screws, pins; default a standard length near 2.5 d); \
at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name?",
),
@@ -33,7 +33,6 @@ pub static COMMANDS: &[CommandSpec] = &[
/// A family: (id, name, standard).
const FAMILIES: &[(&str, &str, &str)] = &[
("socket_head_cap_screw", "Socket head cap screw", "ISO 4762"),
("button_head_cap_screw", "Button head cap screw", "ISO 7380-1"),
("hex_bolt", "Hex head bolt / screw", "ISO 4014 / ISO 4017"),
("hex_nut", "Hex nut", "ISO 4032"),
("washer", "Plain washer", "ISO 7089"),
@@ -78,33 +77,6 @@ const SHCS: [(&str, f64, f64, f64, f64); 14] = [
("M30", 45.0, 30.0, 22.0, 15.5),
];
/// ISO 7380-1: (size, head diameter dk, head height k, socket s, socket depth t, the last being
/// the key engagement depth, which is 0.59 to 0.63 k throughout). The standard runs M3 to M16:
/// the M2.5 and M14 some suppliers list are not in it.
const BHCS: [(&str, f64, f64, f64, f64); 8] = [
("M3", 5.7, 1.65, 2.0, 1.04),
("M4", 7.6, 2.2, 2.5, 1.3),
("M5", 9.5, 2.75, 3.0, 1.56),
("M6", 10.5, 3.3, 4.0, 2.08),
("M8", 14.0, 4.4, 5.0, 2.6),
("M10", 17.5, 5.5, 6.0, 3.12),
("M12", 21.0, 6.6, 8.0, 4.16),
("M16", 28.0, 8.8, 10.0, 5.2),
];
/// A button head's cylindrical flank, as a fraction of the head height k, and the flat top it
/// keeps around its socket, as a fraction of the socket's across-flats s. The flat clears the
/// socket's corners (0.577 s) at every size.
///
/// ISO 7380-1 draws neither, and a real button head has no flat at all: its crown curves on and
/// the socket's corners break through it. The flat is ours, so that the socket is a plain cut on
/// a plane. It costs us the standard's crown radius r1, which the head's own dk and k then fix:
/// the result is inside r1's tolerance at six of the eight sizes, 0.08 under it at M3 and 0.12
/// over it at M12. No one pair of fractions is inside it at all eight, and taking r1 as given
/// instead leaves no flat clear of the socket below M10, so dk, k, s and t are what we keep exact.
const BUTTON_FLANK: f64 = 0.15;
const BUTTON_FLAT: f64 = 0.7;
/// ISO 4014/4017 hex head: (size, across flats s, head height k).
const HEX_BOLT: [(&str, f64, f64); 14] = [
("M2", 4.0, 1.4),
@@ -198,7 +170,7 @@ fn default_length(d: f64) -> f64 {
/// One part's shape, in its own frame.
#[derive(Clone, Debug, PartialEq)]
enum Shape {
/// A head (round, domed or hex), a shank down −z, an optional hex socket in the head's top.
/// A head (round or hex), a shank down −z, an optional hex socket in the head's top.
Screw { d: f64, pitch: f64, len: f64, head: Head, socket: Option<(f64, f64)> },
/// A hex prism with a through hole (nut), z 0…m.
Nut { d: f64, pitch: f64, s: f64, m: f64 },
@@ -210,21 +182,8 @@ enum Shape {
#[derive(Clone, Copy, Debug, PartialEq)]
enum Head {
Round {
dk: f64,
k: f64,
},
/// A button head: a short cylindrical flank, a crown domed over it, and a flat top of
/// radius `flat` around the socket, at z = k.
Dome {
dk: f64,
k: f64,
flat: f64,
},
Hex {
s: f64,
k: f64,
},
Round { dk: f64, k: f64 },
Hex { s: f64, k: f64 },
}
fn shape(family: &str, size: &str, length: Option<f64>) -> std::result::Result<Shape, String> {
@@ -236,11 +195,6 @@ fn shape(family: &str, size: &str, length: Option<f64>) -> std::result::Result<S
let (_, dk, k, s, t) = SHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4762"))?;
Shape::Screw { d, pitch, len: len(d), head: Head::Round { dk, k }, socket: Some((s, t)) }
}
"button_head_cap_screw" => {
let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?;
let (_, dk, k, s, t) = BHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 7380-1"))?;
Shape::Screw { d, pitch, len: len(d), head: Head::Dome { dk, k, flat: BUTTON_FLAT * s }, socket: Some((s, t)) }
}
"hex_bolt" => {
let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?;
let (_, s, k) = HEX_BOLT.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4014"))?;
@@ -306,41 +260,15 @@ fn cyl(s: &mut Session, d: f64, z0: f64, z1: f64, op: &str) -> Result<()> {
/// A solid of revolution about z from a closed (r, z) outline, as one body or joined.
fn revolve(s: &mut Session, pts: &[(f64, f64)], op: &str) -> Result<()> {
revolve_outline(s, pts, None, op)
}
/// The same, with the outline closed from its last point back to its first by an arc through
/// `through`: a button head's domed crown.
fn revolve_domed(s: &mut Session, pts: &[(f64, f64)], through: (f64, f64), op: &str) -> Result<()> {
revolve_outline(s, pts, Some(through), op)
}
fn revolve_outline(s: &mut Session, pts: &[(f64, f64)], arc: Option<(f64, f64)>, op: &str) -> Result<()> {
run(s, "sketch.create", json!({"plane": "XZ"}))?;
let xz = |(r, z): &(f64, f64)| [*r, -*z];
let points: Vec<[f64; 2]> = pts.iter().map(xz).collect();
run(s, "sketch.line", json!({"points": points, "closed": arc.is_none()}))?;
if let (Some(through), Some(first), Some(last)) = (arc, pts.first(), pts.last()) {
run(s, "sketch.arc.three_point", json!({"start": xz(last), "through": xz(&through), "end": xz(first)}))?;
}
let points: Vec<[f64; 2]> = pts.iter().map(|(r, z)| [*r, -*z]).collect();
run(s, "sketch.line", json!({"points": points, "closed": true}))?;
fix_all(s)?;
run(s, "sketch.finish", json!({}))?;
run(s, "solid.revolve", json!({"axis": "y", "operation": op}))?;
Ok(())
}
/// A point halfway along a button head's crown: on the circle centred on the axis that runs
/// from the top of the flank (a, c) to the rim of the flat top (b, k).
fn crown(a: f64, c: f64, b: f64, k: f64) -> (f64, f64) {
// The centre on the axis, equidistant from both, and the radius from it.
let zc = (b * b + k * k - a * a - c * c) / (2.0 * (k - c));
let r = (b * b + (k - zc) * (k - zc)).sqrt();
// Halfway between the directions to the two ends.
let (x, z) = ((a + b) / r, (c - zc + k - zc) / r);
let n = x.hypot(z);
if n.is_finite() && n > 0.0 { (r * x / n, zc + r * z / n) } else { ((a + b) / 2.0, (c + k) / 2.0) }
}
/// Fix every point and curve of the sketch being drawn: a standard part's outline is its size, so
/// its sketches are fully defined and a check of the design finds nothing left free in them.
fn fix_all(s: &mut Session) -> Result<()> {
@@ -369,14 +297,6 @@ fn build(s: &mut Session, sh: &Shape) -> Result<()> {
revolve(s, &[(0.0, -len), (d / 2.0, -len), (d / 2.0, 0.0), (dk / 2.0, 0.0), (dk / 2.0, k), (0.0, k)], "new")?;
k
}
// The same outline up to the head's rim, then a short flank, and the arc of the
// crown closing it back to the flat top.
Head::Dome { dk, k, flat } => {
let (a, c) = (dk / 2.0, BUTTON_FLANK * k);
let outline = [(flat, k), (0.0, k), (0.0, -len), (d / 2.0, -len), (d / 2.0, 0.0), (a, 0.0), (a, c)];
revolve_domed(s, &outline, crown(a, c, flat, k), "new")?;
k
}
// A hex head joined over a shank that runs up into it.
Head::Hex { s: af, k } => {
hex(s, af, 0.0, k, "new")?;
@@ -414,7 +334,6 @@ fn library(_s: &mut Session, p: &Value) -> Result<Value> {
let fam = |id: &str| -> Value {
let mut sizes: Vec<Value> = match id {
"socket_head_cap_screw" => SHCS.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "head_diameter": r.1, "head_height": r.2, "socket": r.3, "socket_depth": r.4})).collect(),
"button_head_cap_screw" => BHCS.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "head_diameter": r.1, "head_height": r.2, "socket": r.3, "socket_depth": r.4})).collect(),
"hex_bolt" => HEX_BOLT.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "across_flats": r.1, "head_height": r.2})).collect(),
"hex_nut" => HEX_NUT.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "across_flats": r.1, "height": r.2})).collect(),
"washer" => WASHER.iter().map(|r| json!({"size": r.0, "inner": r.1, "outer": r.2, "thickness": r.3})).collect(),
@@ -424,8 +343,7 @@ fn library(_s: &mut Session, p: &Value) -> Result<Value> {
_ => Vec::new(),
};
let (_, name, standard) = FAMILIES.iter().find(|f| f.0 == id).copied().unwrap_or(("", "", ""));
let lengths =
matches!(id, "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin").then_some(LENGTHS.to_vec());
let lengths = matches!(id, "socket_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin").then_some(LENGTHS.to_vec());
if lengths.is_some() {
for row in &mut sizes {
let Some(size) = row.get("size").and_then(Value::as_str).map(str::to_string) else { continue };
@@ -460,7 +378,6 @@ fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) {
};
let standard = match family {
"socket_head_cap_screw" => "ISO 4762",
"button_head_cap_screw" => "ISO 7380-1",
"hex_bolt" => "ISO 4017",
"hex_nut" => "ISO 4032",
"washer" => "ISO 7089",
@@ -494,7 +411,6 @@ fn set_identity(s: &mut Session, comp: u64, now: (String, String), was: Option<(
fn label(family: &str) -> &'static str {
match family {
"socket_head_cap_screw" => "SHCS",
"button_head_cap_screw" => "BHCS",
"hex_bolt" => "Hex Bolt",
"hex_nut" => "Hex Nut",
"washer" => "Washer",
@@ -717,40 +633,6 @@ mod tests {
}
}
/// #7692: a button head cap screw (ISO 7380-1) takes the same parameters as a socket head
/// cap screw, with a domed crown in place of the cylindrical head.
#[test]
fn a_button_head_is_domed_over_the_shank() {
let l = run(&mut Session::default(), "parts.library", json!({"family": "button_head_cap_screw"}));
let m6 = l["sizes"].as_array().and_then(|a| a.iter().find(|x| x["size"] == "M6")).cloned().unwrap_or_default();
assert_eq!((m6["head_diameter"].as_f64(), m6["head_height"].as_f64(), m6["socket"].as_f64()), (Some(10.5), Some(3.3), Some(4.0)));
// ISO 7380-1 has no M2, M2.5, M14 or larger than M16; the lengths are a screw's.
let sizes: Vec<&str> = l["sizes"].as_array().map(|a| a.iter().filter_map(|x| x["size"].as_str()).collect()).unwrap_or_default();
assert_eq!(sizes, ["M3", "M4", "M5", "M6", "M8", "M10", "M12", "M16"]);
assert!(l["lengths"].as_array().is_some_and(|a| !a.is_empty()), "{l}");
// An M6 x 20 button head: head Ø10.5, 3.3 high over the seating plane, shank 20 long.
let mut s = Session::default();
run(&mut s, "parts.insert", json!({"family": "button_head_cap_screw", "size": "M6", "length": 20}));
let (lo, hi) = bbox(&s, "BHCS M6x20");
assert!((hi.x - lo.x - 10.5).abs() < 1e-3 && (lo.z + 20.0).abs() < 1e-6 && (hi.z - 3.3).abs() < 1e-3, "{lo:?} {hi:?}");
assert!(s.model.state().threads.iter().any(|t| t.designation.starts_with("M6")), "{:?}", s.model.state().threads);
// The profile: full width at the rim and up the flank (0.15 k = 0.50 high), drawing in
// over the crown (r = 4.62 halfway up the head), and a flat top of 0.7 s = 2.8, which
// leaves a ring of material around the socket's corners at r = 2.31.
let st = s.world_state();
let widest = |above: f64| {
st.bodies.iter().flat_map(|b| b.mesh().positions.clone()).filter(|p| p.z > above).map(|p| p.x.hypot(p.y)).fold(0.0, f64::max)
};
assert!((5.2..5.26).contains(&widest(-0.1)), "the rim: {}", widest(-0.1));
assert!((5.2..5.26).contains(&widest(0.3)), "the flank: {}", widest(0.3));
assert!((3.5..4.7).contains(&widest(1.65)), "the crown halfway up: {}", widest(1.65));
assert!((2.6..2.9).contains(&widest(3.29)), "the flat top: {}", widest(3.29));
// Its part number is the standard and size, as the other families' are.
let comp = s.doc.components.iter().find(|c| c.name.starts_with("BHCS")).map(|c| c.id).unwrap_or(0);
let number = s.doc.components.iter().find(|c| c.id == comp).and_then(|c| c.metadata.text(solidcraft_doc::metadata::PART_NUMBER));
assert_eq!(number, Some("ISO 7380-1 M6x20"));
}
/// #2091: the second and larger ISO sizes, M2, M2.5, M14, M24 and M30, are in the screw, bolt,
/// nut and washer tables (they stopped at M3 and M20).
#[test]
@@ -804,7 +686,6 @@ mod tests {
fn every_sketch_of_a_standard_part_is_fully_defined() {
for (family, size, resized) in [
("socket_head_cap_screw", "M6", "M8"),
("button_head_cap_screw", "M6", "M8"),
("hex_bolt", "M6", "M8"),
("hex_nut", "M6", "M8"),
("washer", "M6", "M8"),
@@ -829,7 +710,6 @@ mod tests {
fn resizing_placed_parts_uses_local_geometry_and_millimetres_in_every_design_unit() {
for (family, initial, resized, prefix) in [
("socket_head_cap_screw", "M6", "M8", "SHCS"),
("button_head_cap_screw", "M6", "M8", "BHCS"),
("hex_bolt", "M6", "M8", "Hex Bolt"),
("hex_nut", "M6", "M8", "Hex Nut"),
("washer", "M6", "M8", "Washer"),
@@ -846,7 +726,7 @@ mod tests {
assert!(s.model.results.iter().all(|r| r.error.is_none()), "{family} {units}");
let b = bbox(&s, prefix);
assert!(b.0.x < b.1.x && b.0.y < b.1.y && b.0.z < b.1.z, "{family} {units}: {b:?}");
if matches!(family, "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "hex_nut" | "set_screw") {
if matches!(family, "socket_head_cap_screw" | "hex_bolt" | "hex_nut" | "set_screw") {
assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9), "{family} {units}");
}
if family == "dowel_pin" {
-54
View File
@@ -1006,22 +1006,6 @@ fn pattern_count_units_explain_how_to_use_a_parameter() -> Result<(), Box<dyn st
Ok(())
}
/// #9015: in an inch design, pattern spacing `baseLength - 1` subtracts one inch, not one mm.
#[test]
fn pattern_spacing_bare_offsets_follow_design_units() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
run(&mut s, "parameters.add", json!({"name": "baseLength", "expression": "4"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Seed"}));
run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["Seed"], "dir1": [1, 0, 0], "count1": 2, "spacing1": "baseLength - 1"}));
assert_eq!(s.model.state().bodies.len(), 2);
// Spacing is 3 in = 76.2 mm (not 3 mm): the seed is 10 in, so the copy starts at x = 76.2.
let m = run(&mut s, "inspect.measure", json!({}));
let bodies = m["bodies"].as_array().expect("bodies");
let xmin = |b: &Value| b["bbox"]["min"][0].as_f64().unwrap_or(0.0);
assert!(bodies.iter().any(|b| (xmin(b) - 76.2).abs() < 1e-6), "expected a copy spaced 3 in apart, got {m}");
}
#[test]
fn pattern_count_fractions_are_refused() -> Result<(), Box<dyn std::error::Error>> {
let mut s = Session::default();
@@ -1065,41 +1049,3 @@ fn pattern_count_integer_parameters_survive_save_and_reject_fractional_edits() -
assert!(invalid.model.results.iter().any(|r| r.error.as_ref().is_some_and(|e| e.contains("a count must be a whole number;"))));
Ok(())
}
/// Editing a pattern behind the history marker (double-clicking its greyed-out item and pressing
/// OK) changes nothing in the model: the reply says so, where the edit used to look as if it had
/// silently failed, and it still carries what building the copies met (#8100).
#[test]
fn editing_a_rolled_back_pattern_says_it_is_not_built() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length":40,"width":30,"height":10,"corner":[0,0,0],"body_name":"Plate"}));
run(&mut s, "solid.cylinder", json!({"radius":2,"height":20,"base":[10,15,-5],"operation":"cut","targets":["Plate"],"name":"Cut"}));
let pattern = |count: u32, origin: [f64; 3]| json!({"features":["Cut"],"axis":{"origin":origin,"dir":[0,0,1]},"count":count});
let redefine = |count, origin| json!({"feature":"Pattern","command":"solid.pattern.circular","params":pattern(count, origin)});
let centre = [20.0, 15.0, 0.0];
let hole = PI * 4.0 * 10.0;
let mut first = pattern(2, centre);
first["name"] = json!("Pattern");
let id = run(&mut s, "solid.pattern.circular", first)["feature"].as_u64().unwrap();
assert!(rel(volume(&mut s), 12000.0 - 2.0 * hole) < 1e-4);
// A pattern that is built: the edit is built at once, with nothing to say.
let reply = run(&mut s, "timeline.redefine", redefine(3, centre));
assert_eq!(reply["rolled_back"], json!(false), "{reply}");
assert!(reply.get("note").is_none(), "{reply}");
assert!(rel(volume(&mut s), 12000.0 - 3.0 * hole) < 1e-4);
// Behind the marker: the edit is kept but not built, and the reply says why nothing changed.
run(&mut s, "timeline.roll_to", json!({"position": 2}));
let reply = run(&mut s, "timeline.redefine", redefine(4, centre));
assert_eq!(reply["rolled_back"], json!(true), "{reply}");
assert_eq!(reply["note"], "Pattern is after the history marker, so it is not built: move the marker past it to build it");
assert!(reply.get("warning").is_none(), "{reply}");
assert!(rel(volume(&mut s), 12000.0 - hole) < 1e-4);
assert!(s.model.result(id).is_some_and(|r| r.skipped && r.error.is_none()));
run(&mut s, "timeline.roll_to", json!({}));
assert!(rel(volume(&mut s), 12000.0 - 4.0 * hole) < 1e-4);
// What building the rolled-back copies met still reaches the reply: here a copy that misses.
run(&mut s, "timeline.roll_to", json!({"position": 2}));
let reply = run(&mut s, "timeline.redefine", redefine(2, [0.0, 0.0, 0.0]));
assert_eq!(reply["rolled_back"], json!(true), "{reply}");
assert_eq!(reply["warning"], "1 of 1 cut copies remove no material", "{reply}");
}
+441 -420
View File
@@ -1,420 +1,441 @@
//! Render capability discovery and persistent intent. No rendering or host probing.
use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use solidcraft_doc::render_settings::{RenderSettings, RenderSetup};
use super::CommandSpec;
use crate::params::bad;
use crate::{Result, Session};
mod clear_coat;
mod effects;
mod environment;
mod jobs;
mod library;
mod library_data;
#[cfg(test)]
mod light_union_tests;
mod lights;
mod optical_bindings;
mod physical_library;
mod resources;
mod shots;
mod staging;
mod studio_presets;
mod surface_bindings;
mod textures;
mod transmission;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.environment.set", "Set Render Environment", crate::checked!("render.environment.set", environment::set)).icon("settings").doc_only()
.contract(&environment::CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render::EnvironmentResult>)
.params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU or 0..100 GPU. Edits the existing HDR, sky or constant environment in one undo, without selecting a source, moving the camera or starting a render. Absent environments and raster refuse."),
CommandSpec::new("render.lights.set", "Set Render Light", crate::checked!("render.lights.set", lights::set))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.add", "Add Light", crate::checked!("render.lights.add", lights::add))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.duplicate", "Duplicate Render Light", crate::checked!("render.lights.duplicate", lights::duplicate))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.remove", "Remove Render Light", crate::checked!("render.lights.remove", lights::remove))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.list", "List Render Lights", crate::checked!("render.lights.list", lights::list))
.icon("list").noundo().doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::ListParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::ListResult>)
.params("setup?: saved setup name OR settings?: complete RenderSetup snapshot; neither uses defaults. Returns {lights:[{id,kind,name,name_key,number,implicit,intensity,colour,...spatial fields}]}. IDs are kind:zero-based-source-slot, stable across numerical edits but not family changes/reordering/removal/rig replacement; point and spot share punctual slots. Includes implicit default/preset lights. GPU RGB radiance is factored as colour * intensity; area edges are full world-mm vectors. Read-only, no host, camera change, save, render, model evaluation or undo. See docs/render-settings.md."),
CommandSpec::new("render.aging.describe","Layered Surface Aging",effects::aging).icon("appearance").noundo().doc_only()
.params("Empty object. Read-only original Rust/patina/dust/grime/scratch/chip/fading presets and exact GPU aging contract. UI activation opens the shared Aging tab; edits remain a saved render draft, never engineering geometry or material-property mutation."),
CommandSpec::new("render.effects.describe","Lens and Creative Effects",effects::presentation).icon("camera").noundo().doc_only()
.params("Empty object. Read-only original photographic/creative filter defaults and constraints. UI activation opens shared Effects controls. Saved finishing and exact-master regrading preserve raw EXR bytes; no physical lens or branded-film calibration is implied."),
CommandSpec::new("render.optics.bind","Save Optical Binding",optical_bindings::bind).icon("appearance")
.params("name: 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. 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()
.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; 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."),
CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only()
.params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."),
CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo()
.params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."),
CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo()
.params("No parameters. Fits the current camera to the visible product bounds through the shared Camera::fit contract; changes only view state, not a saved setup, rendering job, stage or engineering geometry."),
CommandSpec::new("render.preset.resolve", "Review Native Studio", studio_presets::resolve).icon("render_scene").noundo()
.params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."),
CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::apply).icon("render_scene")
.params("Same reviewed input as render.preset.resolve, expected_revision required, replace_lighting_and_environment:true and replace_stage:true when an existing stage would change. Re-resolves the complete candidate and publishes one undo or no mutation; camera, optical bindings, geometry and engineering materials are preserved."),
CommandSpec::new("render.quality.prepare", "Review Fixed Sampling Budget", studio_presets::quality).icon("settings").noundo().doc_only()
.params("id: Q-*; variant:fixed_samples_png; acknowledge_omissions:true. Read-only bounded GPU still-budget projection, not full adaptive/convergence/linear-master quality acceptance. Returns dimensions/samples/depth/seed/denoise and explicit omissions. Never switches executor or mutates a shot."),
CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", shots::duplicate).icon("copy").doc_only()
.params("name, new_name, expected_revision:u64. Copies exact saved setup and resource references in one undo. Existing destinations refuse; captured jobs and camera navigation are unchanged."),
CommandSpec::new("render.shot.rename", "Rename Render Shot", shots::rename).icon("settings").doc_only()
.params("name, new_name, expected_revision:u64. Renames exact saved setup in one undo; an existing destination or stale review refuses."),
CommandSpec::new("render.shot.remove", "Remove Render Shot", shots::remove).icon("delete").doc_only()
.params("name, expected_revision:u64. Removes only that saved setup in one undo; retains resources, geometry and captured results."),
CommandSpec::new("render.library.preview", "Inspect Original Surface Map", library::preview).icon("appearance").noundo().doc_only()
.params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."),
CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only()
.params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."),
CommandSpec::new("render.stage.ground", "Save Render Ground", staging::ground).icon("render_scene")
.params("name: typed raytrace setup, set?: setup patch, margin_fraction?:0.25, gap_mm?:0.1, reflectance_linear?:[0.18,0.18,0.18], replace_stage?:false. Fits one finite passive ground below the visible product once and saves its physical transforms in one undo. Product AABB separation is rechecked on every render."),
CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", staging::backdrop).icon("render_scene").doc_only()
.params("name: typed raytrace setup, set?: setup patch, kind: floor_wall or cyclorama, reflectance_linear?: [0.18,0.18,0.18], expected_revision: reviewed revision, replace_stage?:false. Fits a finite floor/wall or a 24-strip polygonal cyclorama behind the visible subject using the saved camera azimuth; world +Z up and a minimum one-mm stage envelope. Preserves subject geometry, lighting, output, pose and engineering materials; one undo and rechecked product separation. Not an infinite/analytically smooth/terrain background."),
CommandSpec::new("render.stage.clear", "Remove Render Stage", staging::clear).icon("render_scene").doc_only()
.params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."),
CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance")
.params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."),
CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only()
.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, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo()
.params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."),
CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only()
.params("kind?: surfaces, selene_appearances, hdr, rigs, scenes, materials, lighting, environments, quality, native_scenes, selene_shots or capabilities; query?: bounded search; availability?: all/usable/specification/blocked; offset?:0; limit?:48 (1..128). Returns source status and explicit implemented projections separately. No device, file IO or design change."),
CommandSpec::new("render.library.describe", "Inspect Render Library Resource", library::describe).icon("inspect").noundo().doc_only()
.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")
.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()
.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()
.params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1. Returns an explicit GPU planar map binding 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()
.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 to GPU lighting. 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")
.params("rig: render.library.studio.prepare parameters; name; set?: typed GPU setup patch; 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", resources::inspect).icon("inspect").noundo().doc_only()
.params("path: scoped Radiance HDR file; validates the complete bounded source and returns sha256, width, height, encoded_bytes and primaries without saving or rendering"),
CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", resources::capture_settings).icon("settings").doc_only()
.params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"),
CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only()
.params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace and transient studio_weights may accompany it. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.budget?: compact (legacy default), studio or workstation; see docs/render-cpu-resource-profiles.md for explicit image/geometry/memory/work limits. CPU raytrace.progressive?: {samples_per_pixel:1..profile limit, seed:u32}; requires primary_samples:1 and selected reflections.samples:1; no area/LED, anisotropy or dielectrics in this initial mode. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"),
CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image")
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only()
.params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."),
CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only()
.params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."),
CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only()
.params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."),
CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only()
.params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"),
CommandSpec::new("render.backends", "Render Backends", backends).icon("list")
.noundo()
.doc_only()
.params("No parameters. Returns {schema_version: 1, default_backend: builtin, backends: [{id, label, availability, executors: [{id, availability, profiles, limits, scratch}]}]}. Metadata only; does not start rendering or probe a GPU. See docs/render-backends.md"),
CommandSpec::new("render.settings.get", "Render Settings", get_settings).icon("settings").noundo().doc_only()
.params("name?: saved setup. Without name returns {setups, defaults}; with name returns {name, setup}. Does not evaluate the model or apply a camera. See docs/render-settings.md"),
CommandSpec::new("render.settings.set", "Save Render Settings", set_settings).icon("settings").doc_only()
.params("name: setup name, set: object of fields to replace (backend, mode, camera, width, height, format, exposure_ev, environment_rotation, environment_intensity, background, job, surfaces, stage). job?: typed active raster/cpu_raytrace/gpu_path configuration with optional validated embedded HDR reference; omitted preserves, null clears, object replaces the complete job. Creates from defaults and saves without a host, validates atomically, one undo step; identical edits are no-ops. See docs/render-settings.md"),
CommandSpec::new("render.scene", "Inspect Render Scene", scene).noundo().at("RENDER", "SCENE").icon("render_scene")
.params("No parameters. Authoritative product-scene metadata, without modelling overlays or mesh payloads. Explicitly settles stale geometry; does not render an image. See docs/render-workspace.md"),
CommandSpec::new("render.settings.apply", "Apply Render Camera", apply_settings).icon("camera").noundo().doc_only()
.params("name: saved setup. Applies its existing Camera snapshot including roll/up as view state, without modifying the document or starting a render."),
];
fn set_camera(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.camera.set";
if !params.as_object().is_some_and(|p| p.len() == 1 && p.contains_key("camera")) {
return Err(bad(cmd, "expected exactly one camera snapshot"));
}
// Reuse strict saved-camera decoding and its numeric limits, without saving a setup.
let setup: RenderSetup = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
s.camera = Some(setup.camera);
Ok(json!({"camera":setup.camera,"document_changed":false}))
}
fn get_camera(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.camera.get", "expected an empty parameter object"));
}
Ok(json!({"camera":s.camera,"explicit_view":s.camera.is_some(),"document_changed":false}))
}
fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.camera.fit", "expected an empty parameter object"));
}
let scene = crate::product_scene::extract(s)?;
let mut camera = s.camera.unwrap_or_default();
if !scene.bounds.is_empty() {
camera.fit(&scene.bounds);
}
s.camera = Some(camera);
Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false}))
}
fn scene(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.scene", "expected an empty parameter object"));
}
let scene = crate::product_scene::extract(s)?;
let mut stable = std::collections::BTreeMap::new();
for (target, name) in surface_bindings::targets(s, "render.scene")? {
if stable.insert(name, target).is_some() {
return Err(bad("render.scene", "ambiguous stable occurrence name"));
}
}
let bodies: Vec<_> = scene
.meshes
.iter()
.enumerate()
.map(|(ordinal,m)| json!({"ordinal":ordinal,"name":m.name,"stable_target":stable.get(&m.name),"triangles":m.mesh.triangles.len(),"color":m.color,"opacity":m.opacity,"face_appearances":m.faces.len(),"bounds":{"min":m.mesh.bounds().min,"max":m.mesh.bounds().max}}))
.collect();
Ok(
json!({"bodies":bodies,"bounds":if scene.bounds.is_empty() { Value::Null } else { json!({"min":scene.bounds.min,"max":scene.bounds.max}) },"overlays":false}),
)
}
fn apply_settings(s: &mut Session, params: &Value) -> Result<Value> {
let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad("render.settings.apply", e.to_string()))?;
let name = request.name.ok_or_else(|| bad("render.settings.apply", "`name` is required"))?;
RenderSettings::validate_name(&name).map_err(|e| bad("render.settings.apply", e.to_string()))?;
let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad("render.settings.apply", "no saved render setup with that name"))?;
setup.validate().map_err(|e| bad("render.settings.apply", e.to_string()))?;
s.camera = Some(setup.camera);
Ok(json!({"name":name,"camera":setup.camera}))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GetSettings {
name: Option<String>,
}
fn get_settings(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.settings.get";
let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
match request.name {
None => Ok(json!({"setups": s.doc.render.setups, "defaults": RenderSetup::default()})),
Some(name) => {
RenderSettings::validate_name(&name).map_err(|e| bad(cmd, e.to_string()))?;
let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad(cmd, "no saved render setup with that name"))?;
Ok(json!({"name": name, "setup": setup}))
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetSettings {
name: String,
set: Value,
}
fn set_settings(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.settings.set";
let request: SetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
let setup = patched_settings(s, &request.name, &request.set, cmd)?;
let reply = json!({"name": request.name, "setup": setup});
if s.doc.render.setups.get(&request.name) == Some(&setup) {
return Ok(reply);
}
let mut settings = (*s.doc.render).clone();
settings.setups.insert(request.name, setup);
settings.validate().map_err(|e| bad(cmd, e.to_string()))?;
s.doc_mut().render = Arc::new(settings);
Ok(reply)
}
fn patched_settings(s: &Session, name: &str, set: &Value, cmd: &str) -> Result<RenderSetup> {
RenderSettings::validate_name(name).map_err(|e| bad(cmd, e.to_string()))?;
let patch = set.as_object().filter(|p| p.len() <= 13).ok_or_else(|| bad(cmd, "`set` must be an object with at most 13 fields"))?;
let current = s.doc.render.setups.get(name).cloned().unwrap_or_default();
let mut value = serde_json::to_value(&current).map_err(|e| bad(cmd, e.to_string()))?;
let object = value.as_object_mut().ok_or_else(|| bad(cmd, "invalid render setup"))?;
for (key, value) in patch {
object.insert(key.clone(), value.clone());
}
let setup: RenderSetup = serde_json::from_value(value).map_err(|e| bad(cmd, e.to_string()))?;
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
Ok(setup)
}
fn backends(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.backends", "expected an empty parameter object"));
}
Ok(json!({"schema_version": 1, "default_backend": "builtin", "backends": [s.render_backend()],
"cpu_resource_profiles": solidcraft_render::job::CpuBudget::ALL.map(|budget| json!({"id":budget,"limits":budget.limits()}))}))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
fn assert_unchanged(s: &mut Session, params: Value) -> Result<Value> {
let doc = s.doc.clone();
let before = (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale());
let camera = s.camera;
let undo = s.undo.clone();
let redo = s.redo.clone();
let result = s.execute("render.backends", &params);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale()));
assert_eq!(camera, s.camera);
for (before, after) in [(&undo, &s.undo), (&redo, &s.redo)] {
assert_eq!(before.len(), after.len());
for (a, b) in before.iter().zip(after.iter()) {
assert!(Arc::ptr_eq(&a.doc, &b.doc));
assert_eq!((&a.label, a.active_sketch, &a.pending_moves), (&b.label, b.active_sketch, &b.pending_moves));
}
}
result
}
#[test]
fn discovery_preserves_clean_dirty_and_undo_redo_state() {
let mut s = Session::default();
let r = assert_unchanged(&mut s, Value::Null).unwrap();
assert_eq!(r["schema_version"], 1);
assert_eq!(r["default_backend"], "builtin");
assert_eq!(r["backends"].as_array().unwrap().len(), 1);
let descriptor: crate::render::BackendDescriptor = serde_json::from_value(r["backends"][0].clone()).unwrap();
assert_eq!(descriptor, crate::render::builtin_backend());
s.execute("solid.box", &json!({"length": 10, "width": 20, "height": 5})).unwrap();
s.execute("view.apply", &json!({"view": "top"})).unwrap();
assert!(s.is_dirty());
assert_unchanged(&mut s, json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.redo.is_empty());
assert_unchanged(&mut s, json!({})).unwrap();
for p in [json!([]), json!(3), json!({"backend": "missing"}), json!({"width": "bad"})] {
assert!(assert_unchanged(&mut s, p).is_err());
}
}
#[test]
fn cooperative_host_never_discovers_cpu_raytracing_or_accepts_its_reserved_viewport_id() {
use solidcraft_render::job::CpuHost;
let mut s = Session::default();
s.set_render_job_host(Some(CpuHost::cooperative())).unwrap();
let reply = assert_unchanged(&mut s, json!({})).unwrap();
let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap();
assert!(backend.executors.iter().any(|d| d.id.as_str() == "cpu-product"));
assert!(!backend.executors.iter().any(|d| d.id.as_str() == "cpu-raytrace"));
let mut viewport = CpuHost::cooperative().descriptor().unwrap();
viewport.id = solidcraft_render::ExecutorId::new("cpu-raytrace").unwrap();
viewport.profiles[0].operation = solidcraft_render::RenderOperation::Viewport;
viewport.profiles[0].formats.clear();
assert!(s.set_render_viewport(Some(viewport)).unwrap_err().to_string().contains("reserved"));
assert_eq!(s.render_backend(), backend);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn native_cpu_discovery_matches_installed_features_and_preserves_raster_default() {
use solidcraft_render::job::{CpuHost, Integrator};
use solidcraft_render::{RenderFeature, RenderFormat, RenderMode, RenderOperation, RenderRequest};
let host = CpuHost::for_platform().unwrap();
// Query the host so the same test covers feature-off builds and workspace
// feature unification without assuming the engine's own cfg is sufficient.
let raytrace = host.validate_integrator(Integrator::Raytrace).is_ok();
let mut s = Session::default();
let doc = s.doc.clone();
s.set_render_job_host(Some(host.clone())).unwrap();
let reply = assert_unchanged(&mut s, json!({})).unwrap();
assert!(Arc::ptr_eq(&doc, &s.doc));
assert!(!s.is_dirty());
assert!(s.undo.is_empty());
let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap();
let descriptors: Vec<_> = backend.executors.iter().filter(|d| d.id.as_str() == "cpu-raytrace").collect();
assert_eq!(descriptors.len(), usize::from(raytrace));
if let Some(descriptor) = descriptors.first() {
assert_eq!(descriptor.availability, solidcraft_render::Availability::Available);
assert_eq!(*descriptor, &host.descriptor_for(Integrator::Raytrace).unwrap());
assert!(!descriptor.profiles.iter().any(|p| p.features.contains(&RenderFeature::Progressive)));
}
let request = RenderRequest {
backend: None,
mode: RenderMode::Preview,
operation: RenderOperation::Image,
width: 16,
height: 16,
format: Some(RenderFormat::Png),
features: vec![RenderFeature::Pbr],
policy: Default::default(),
};
assert_eq!(solidcraft_render::resolve_request(std::slice::from_ref(&backend), &request).unwrap().executor.as_str(), "cpu-product");
assert_eq!(s.scratch().render_backend(), backend);
s.set_render_job_host(Some(host)).unwrap();
assert_eq!(s.render_backend(), backend, "reinstalling the same host cannot duplicate method descriptors");
s.set_render_job_host(Some(CpuHost::cooperative())).unwrap();
assert!(!s.render_backend().executors.iter().any(|d| d.id.as_str() == "cpu-raytrace"));
s.set_render_job_host(None).unwrap();
assert_eq!(s.render_backend(), solidcraft_render::builtin_backend());
assert_unchanged(&mut s, json!({})).unwrap();
assert!(Arc::ptr_eq(&doc, &s.doc));
assert!(!s.is_dirty());
assert!(s.undo.is_empty());
}
#[test]
fn discovery_does_not_settle_a_live_drag_or_rebuild_geometry() {
let mut s = Session::default();
for (id, p) in [
("sketch.create", json!({"plane": "XY"})),
("sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [25, 20]})),
("sketch.dimension", json!({"entities": ["l1"], "value": 20})),
("sketch.dimension", json!({"entities": ["l2"], "value": 15})),
("sketch.finish", json!({})),
("solid.extrude", json!({"distance": 5})),
("sketch.edit", json!({"sketch": "Sketch1"})),
("sketch.drag", json!({"entity": "l1.start", "from": [5, 5], "to": [4, 5], "live": true})),
] {
s.execute(id, &p).unwrap();
}
assert!(s.model.is_stale());
s.evaluations = 0;
let model = s.model.state();
assert_unchanged(&mut s, json!({})).unwrap();
assert_unchanged(&mut s, json!({"unexpected": true})).unwrap_err();
assert!(Arc::ptr_eq(&model, &s.model.state()));
assert_eq!(s.evaluations, 0);
}
}
#[cfg(test)]
mod settings_tests;
#[cfg(test)]
mod job_tests;
//! Render capability discovery and persistent intent. No rendering or host probing.
use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use solidcraft_doc::render_settings::{RenderSettings, RenderSetup};
use super::CommandSpec;
use crate::params::bad;
use crate::{Result, Session};
mod clear_coat;
mod effects;
mod environment;
mod jobs;
mod library;
mod library_data;
#[cfg(test)]
mod light_union_tests;
mod lights;
mod optical_bindings;
mod physical_library;
mod resources;
mod shots;
mod staging;
mod studio_presets;
mod surface_bindings;
mod textures;
mod transmission;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.environment.set", "Set Render Environment", crate::checked!("render.environment.set", environment::set)).icon("settings").doc_only()
.contract(&environment::CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render::EnvironmentResult>)
.params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU or 0..100 GPU. Edits the existing HDR, sky or constant environment in one undo, without selecting a source, moving the camera or starting a render. Absent environments and raster refuse."),
CommandSpec::new("render.lights.set", "Set Render Light", crate::checked!("render.lights.set", lights::set))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.add", "Add Light", crate::checked!("render.lights.add", lights::add))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.duplicate", "Duplicate Render Light", crate::checked!("render.lights.duplicate", lights::duplicate))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.remove", "Remove Render Light", crate::checked!("render.lights.remove", lights::remove))
.icon("render_scene").doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::EditParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::EditResult>)
.params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, intensity_ev, temperature_k, softness, azimuth_deg, elevation_deg, distance_mm, size_mm, aim_at, width_mm, height_mm, position_mm, direction, edge_u_mm, edge_v_mm, radiance, colour, reference_distance_mm, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."),
CommandSpec::new("render.lights.list", "List Render Lights", crate::checked!("render.lights.list", lights::list))
.icon("list").noundo().doc_only()
.contract(&crate::schema::TypedContract::<crate::schema::render_lights::ListParams>::new())
.output(crate::schema::output_schema_for::<crate::schema::render_lights::ListResult>)
.params("setup?: saved setup name OR settings?: complete RenderSetup snapshot; neither uses defaults. Returns {lights:[{id,kind,name,name_key,number,implicit,intensity,colour,...spatial fields}]}. IDs are kind:zero-based-source-slot, stable across numerical edits but not family changes/reordering/removal/rig replacement; point and spot share punctual slots. Includes implicit default/preset lights. GPU RGB radiance is factored as colour * intensity; area edges are full world-mm vectors. Read-only, no host, camera change, save, render, model evaluation or undo. See docs/render-settings.md."),
CommandSpec::new("render.aging.describe","Layered Surface Aging",effects::aging).icon("appearance").noundo().doc_only()
.params("Empty object. Read-only original Rust/patina/dust/grime/scratch/chip/fading presets and exact GPU aging contract. UI activation opens the shared Aging tab; edits remain a saved render draft, never engineering geometry or material-property mutation."),
CommandSpec::new("render.effects.describe","Lens and Creative Effects",effects::presentation).icon("camera").noundo().doc_only()
.params("Empty object. Read-only original photographic/creative filter defaults and constraints. UI activation opens shared Effects controls. Saved finishing and exact-master regrading preserve raw EXR bytes; no physical lens or branded-film calibration is implied."),
CommandSpec::new("render.optics.bind","Save Optical Binding",optical_bindings::bind).icon("appearance")
.params("name: 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. 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()
.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; 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."),
CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only()
.params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."),
CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo()
.params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."),
CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo()
.params("No parameters. Fits the current camera to the visible product bounds through the shared Camera::fit contract; changes only view state, not a saved setup, rendering job, stage or engineering geometry."),
CommandSpec::new("render.preset.resolve", "Review Native Studio", studio_presets::resolve).icon("render_scene").noundo()
.params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."),
CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::apply).icon("render_scene")
.params("Same reviewed input as render.preset.resolve, expected_revision required, replace_lighting_and_environment:true and replace_stage:true when an existing stage would change. Re-resolves the complete candidate and publishes one undo or no mutation; camera, optical bindings, geometry and engineering materials are preserved."),
CommandSpec::new("render.quality.prepare", "Review Fixed Sampling Budget", studio_presets::quality).icon("settings").noundo().doc_only()
.params("id: Q-*; variant:fixed_samples_png; acknowledge_omissions:true. Read-only bounded GPU still-budget projection, not full adaptive/convergence/linear-master quality acceptance. Returns dimensions/samples/depth/seed/denoise and explicit omissions. Never switches executor or mutates a shot."),
CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", shots::duplicate).icon("copy").doc_only()
.params("name, new_name, expected_revision:u64. Copies exact saved setup and resource references in one undo. Existing destinations refuse; captured jobs and camera navigation are unchanged."),
CommandSpec::new("render.shot.rename", "Rename Render Shot", shots::rename).icon("settings").doc_only()
.params("name, new_name, expected_revision:u64. Renames exact saved setup in one undo; an existing destination or stale review refuses."),
CommandSpec::new("render.shot.remove", "Remove Render Shot", shots::remove).icon("delete").doc_only()
.params("name, expected_revision:u64. Removes only that saved setup in one undo; retains resources, geometry and captured results."),
CommandSpec::new("render.library.preview", "Inspect Original Surface Map", library::preview).icon("appearance").noundo().doc_only()
.params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."),
CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only()
.params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."),
CommandSpec::new("render.stage.ground", "Save Render Ground", staging::ground).icon("render_scene")
.params("name: typed raytrace setup, set?: setup patch, margin_fraction?:0.25, gap_mm?:0.1, reflectance_linear?:[0.18,0.18,0.18], replace_stage?:false. Fits one finite passive ground below the visible product once and saves its physical transforms in one undo. Product AABB separation is rechecked on every render."),
CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", staging::backdrop).icon("render_scene").doc_only()
.params("name: typed raytrace setup, set?: setup patch, kind: floor_wall or cyclorama, reflectance_linear?: [0.18,0.18,0.18], expected_revision: reviewed revision, replace_stage?:false. Fits a finite floor/wall or a 24-strip polygonal cyclorama behind the visible subject using the saved camera azimuth; world +Z up and a minimum one-mm stage envelope. Preserves subject geometry, lighting, output, pose and engineering materials; one undo and rechecked product separation. Not an infinite/analytically smooth/terrain background."),
CommandSpec::new("render.stage.clear", "Remove Render Stage", staging::clear).icon("render_scene").doc_only()
.params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."),
CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance")
.params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."),
CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only()
.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, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo()
.params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."),
CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only()
.params("kind?: surfaces, selene_appearances, hdr, rigs, scenes, materials, lighting, environments, quality, native_scenes, selene_shots or capabilities; query?: bounded search; availability?: all/usable/specification/blocked; offset?:0; limit?:48 (1..128). Returns source status and explicit implemented projections separately. No device, file IO or design change."),
CommandSpec::new("render.library.describe", "Inspect Render Library Resource", library::describe).icon("inspect").noundo().doc_only()
.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")
.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()
.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()
.params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1. Returns an explicit GPU planar map binding 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()
.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 to GPU lighting. 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")
.params("rig: render.library.studio.prepare parameters; name; set?: typed GPU setup patch; 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", resources::inspect).icon("inspect").noundo().doc_only()
.params("path: scoped Radiance HDR file; validates the complete bounded source and returns sha256, width, height, encoded_bytes and primaries without saving or rendering"),
CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", resources::capture_settings).icon("settings").doc_only()
.params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"),
CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only()
.params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace, transient studio_weights, raster_lights and progressive_feedback may accompany it. raster_lights?: transient null (legacy studio) or 0..8 directional sources {direction:[x,y,z],color:[linear r,g,b],intensity:0..64}; empty array is dark direct lighting. Requires builtin Raster without studio_weights, raytrace, HDR, transmission or other method controls; existing RenderSetup.exposure_ev is captured for Raster within -32..32. Directions are finite/nonzero and bounded by 1e9; RGB is 0..1. Not saved; no shadows or physical glass. raster_punctual_lights?: transient null or 0..8 shared point/spot sources {position_mm:[x,y,z],color:[linear r,g,b],intensity:0..64,reference_distance_mm:0.001..1000000,minimum_distance_mm:0.001..reference_distance_mm,cone?:{emitted_axis:[x,y,z],inner_half_angle_radians,outer_half_angle_radians}}. Spot angles require 0<=inner<outer<=pi/2 and a finite nonzero emitted axis. raster_area_lights?: transient null or 0..4 rectangles {center_mm:[x,y,z],edge_u_mm:[x,y,z],edge_v_mm:[x,y,z],color:[linear r,g,b],intensity:0..64}; full perpendicular side lengths 0.000001..1000000mm, corners within +/-1000000000mm, U cross V emits. Local sources require a runtime request with settings.job:null or an untyped setup; saved typed jobs refuse them. All three absent/null collections preserve the legacy studio; any explicit local array, even empty, disables implicit sources, and absent raster_lights then means no directionals. Local images use unshadowed point/spot falloff and a one-point projected-area rectangle approximation; no finite footprint, soft shadows, environment, area_samples, softness or seed. Local light evaluations count within the existing projected-work limit; caps are 8directional+8shared point/spot+4rectangle, with the existing Raster memory envelope and one captured exposure. Positions and spot-axis components are finite and bounded by1e9; RGB0..1. No saved/UI local-light authoring yet. progressive_feedback?: false; transient protected display updates during CPU progressive rendering only; true refuses raster, GPU and fixed CPU requests. Omission preserves legacy admission/submission. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.budget?: compact (legacy default), studio or workstation; see docs/render-cpu-resource-profiles.md for explicit image/geometry/memory/work limits. CPU raytrace.progressive?: {samples_per_pixel:1..profile limit, seed:u32}; requires primary_samples:1 and selected reflections.samples:1; bounded area/LED direct lights retain their existing source and emitter-sample limits; anisotropy requires fixed sampling; certified smooth thin-sheet/box dielectrics support fixed or progressive sampling under the same certificates and bounded optical transport. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption. nested_media?: false is the existing JobOptions opt-in; fixed or progressive CPU images admit only strictly nested certified closed_box boundaries with an exterior camera, while touching/partial overlaps, sheets within volumes and clearcoat combinations refuse. Other nondefault JobOptions remain unsupported on CPU; progressive/Interactive optics retain primary_samples:1 and selected reflections.samples:1 limits and never drop unsupported intent. GPU progressive uses the same nested_media field with its own certified-media contract; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/ Line truncated
CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image")
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only()
.params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."),
CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only()
.params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."),
CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only()
.params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."),
CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only()
.params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"),
CommandSpec::new("render.backends", "Render Backends", backends).icon("list")
.noundo()
.doc_only()
.params("No parameters. Returns {schema_version: 1, default_backend: builtin, backends: [{id, label, availability, executors: [{id, availability, profiles, limits, scratch}]}]}. Metadata only; does not start rendering or probe a GPU. See docs/render-backends.md"),
CommandSpec::new("render.settings.get", "Render Settings", get_settings).icon("settings").noundo().doc_only()
.params("name?: saved setup. Without name returns {setups, defaults}; with name returns {name, setup}. Does not evaluate the model or apply a camera. See docs/render-settings.md"),
CommandSpec::new("render.settings.set", "Save Render Settings", set_settings).icon("settings").doc_only()
.params("name: setup name, set: object of fields to replace (backend, mode, camera, width, height, format, exposure_ev, environment_rotation, environment_intensity, background, job, surfaces, stage). job?: typed active raster/cpu_raytrace/gpu_path configuration with optional validated embedded HDR reference; omitted preserves, null clears, object replaces the complete job. Creates from defaults and saves without a host, validates atomically, one undo step; identical edits are no-ops. See docs/render-settings.md"),
CommandSpec::new("render.scene", "Inspect Render Scene", scene).noundo().at("RENDER", "SCENE").icon("render_scene")
.params("No parameters. Authoritative product-scene metadata, without modelling overlays or mesh payloads. Explicitly settles stale geometry; does not render an image. See docs/render-workspace.md"),
CommandSpec::new("render.settings.apply", "Apply Render Camera", apply_settings).icon("camera").noundo().doc_only()
.params("name: saved setup. Applies its existing Camera snapshot including roll/up as view state, without modifying the document or starting a render."),
];
fn set_camera(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.camera.set";
if !params.as_object().is_some_and(|p| p.len() == 1 && p.contains_key("camera")) {
return Err(bad(cmd, "expected exactly one camera snapshot"));
}
// Reuse strict saved-camera decoding and its numeric limits, without saving a setup.
let setup: RenderSetup = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
s.camera = Some(setup.camera);
Ok(json!({"camera":setup.camera,"document_changed":false}))
}
fn get_camera(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.camera.get", "expected an empty parameter object"));
}
Ok(json!({"camera":s.camera,"explicit_view":s.camera.is_some(),"document_changed":false}))
}
fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.camera.fit", "expected an empty parameter object"));
}
let scene = crate::product_scene::extract(s)?;
let mut camera = s.camera.unwrap_or_default();
if !scene.bounds.is_empty() {
camera.fit(&scene.bounds);
}
s.camera = Some(camera);
Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false}))
}
fn scene(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.scene", "expected an empty parameter object"));
}
let scene = crate::product_scene::extract(s)?;
let mut stable = std::collections::BTreeMap::new();
for (target, name) in surface_bindings::targets(s, "render.scene")? {
if stable.insert(name, target).is_some() {
return Err(bad("render.scene", "ambiguous stable occurrence name"));
}
}
let bodies: Vec<_> = scene
.meshes
.iter()
.enumerate()
.map(|(ordinal,m)| json!({"ordinal":ordinal,"name":m.name,"stable_target":stable.get(&m.name),"triangles":m.mesh.triangles.len(),"color":m.color,"opacity":m.opacity,"face_appearances":m.faces.len(),"bounds":{"min":m.mesh.bounds().min,"max":m.mesh.bounds().max}}))
.collect();
Ok(
json!({"bodies":bodies,"bounds":if scene.bounds.is_empty() { Value::Null } else { json!({"min":scene.bounds.min,"max":scene.bounds.max}) },"overlays":false}),
)
}
fn apply_settings(s: &mut Session, params: &Value) -> Result<Value> {
let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad("render.settings.apply", e.to_string()))?;
let name = request.name.ok_or_else(|| bad("render.settings.apply", "`name` is required"))?;
RenderSettings::validate_name(&name).map_err(|e| bad("render.settings.apply", e.to_string()))?;
let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad("render.settings.apply", "no saved render setup with that name"))?;
setup.validate().map_err(|e| bad("render.settings.apply", e.to_string()))?;
s.camera = Some(setup.camera);
Ok(json!({"name":name,"camera":setup.camera}))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GetSettings {
name: Option<String>,
}
fn get_settings(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.settings.get";
let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
match request.name {
None => Ok(json!({"setups": s.doc.render.setups, "defaults": RenderSetup::default()})),
Some(name) => {
RenderSettings::validate_name(&name).map_err(|e| bad(cmd, e.to_string()))?;
let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad(cmd, "no saved render setup with that name"))?;
Ok(json!({"name": name, "setup": setup}))
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetSettings {
name: String,
set: Value,
}
fn set_settings(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.settings.set";
if let Some(set) = params.get("set") {
validate_saved_raster_lights(set, cmd)?;
}
let request: SetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
let setup = patched_settings(s, &request.name, &request.set, cmd)?;
let reply = json!({"name": request.name, "setup": setup});
if s.doc.render.setups.get(&request.name) == Some(&setup) {
return Ok(reply);
}
let mut settings = (*s.doc.render).clone();
settings.setups.insert(request.name, setup);
settings.validate().map_err(|e| bad(cmd, e.to_string()))?;
s.doc_mut().render = Arc::new(settings);
Ok(reply)
}
fn patched_settings(s: &Session, name: &str, set: &Value, cmd: &str) -> Result<RenderSetup> {
validate_saved_raster_lights(set, cmd)?;
RenderSettings::validate_name(name).map_err(|e| bad(cmd, e.to_string()))?;
let patch = set.as_object().filter(|p| p.len() <= 13).ok_or_else(|| bad(cmd, "`set` must be an object with at most 13 fields"))?;
if let Some(current) = s.doc.render.setups.get(name)
&& let Some(solidcraft_doc::render_settings::RenderJob::Raster { lights, .. }) = &current.job
{
solidcraft_render::job::validate_raster_lights(lights).map_err(|e| bad(cmd, e.to_string()))?;
}
let current = s.doc.render.setups.get(name).cloned().unwrap_or_default();
let mut value = serde_json::to_value(&current).map_err(|e| bad(cmd, e.to_string()))?;
let object = value.as_object_mut().ok_or_else(|| bad(cmd, "invalid render setup"))?;
for (key, value) in patch {
object.insert(key.clone(), value.clone());
}
let setup: RenderSetup = serde_json::from_value(value).map_err(|e| bad(cmd, e.to_string()))?;
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
Ok(setup)
}
/// The new saved array is checked by reference before raw Value patch copies.
fn validate_saved_raster_lights(settings: &Value, command: &str) -> Result<()> {
if let Some(lights) = settings.get("job").and_then(|job| job.get("lights")) {
let _ = solidcraft_render::job::deserialize_raster_lights(lights).map_err(|e| bad(command, e.to_string()))?;
}
Ok(())
}
fn backends(s: &mut Session, params: &Value) -> Result<Value> {
if !params.as_object().is_some_and(|p| p.is_empty()) {
return Err(bad("render.backends", "expected an empty parameter object"));
}
Ok(json!({"schema_version": 1, "default_backend": "builtin", "backends": [s.render_backend()],
"cpu_resource_profiles": solidcraft_render::job::CpuBudget::ALL.map(|budget| json!({"id":budget,"limits":budget.limits()}))}))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
fn assert_unchanged(s: &mut Session, params: Value) -> Result<Value> {
let doc = s.doc.clone();
let before = (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale());
let camera = s.camera;
let undo = s.undo.clone();
let redo = s.redo.clone();
let result = s.execute("render.backends", &params);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale()));
assert_eq!(camera, s.camera);
for (before, after) in [(&undo, &s.undo), (&redo, &s.redo)] {
assert_eq!(before.len(), after.len());
for (a, b) in before.iter().zip(after.iter()) {
assert!(Arc::ptr_eq(&a.doc, &b.doc));
assert_eq!((&a.label, a.active_sketch, &a.pending_moves), (&b.label, b.active_sketch, &b.pending_moves));
}
}
result
}
#[test]
fn discovery_preserves_clean_dirty_and_undo_redo_state() {
let mut s = Session::default();
let r = assert_unchanged(&mut s, Value::Null).unwrap();
assert_eq!(r["schema_version"], 1);
assert_eq!(r["default_backend"], "builtin");
assert_eq!(r["backends"].as_array().unwrap().len(), 1);
let descriptor: crate::render::BackendDescriptor = serde_json::from_value(r["backends"][0].clone()).unwrap();
assert_eq!(descriptor, crate::render::builtin_backend());
s.execute("solid.box", &json!({"length": 10, "width": 20, "height": 5})).unwrap();
s.execute("view.apply", &json!({"view": "top"})).unwrap();
assert!(s.is_dirty());
assert_unchanged(&mut s, json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.redo.is_empty());
assert_unchanged(&mut s, json!({})).unwrap();
for p in [json!([]), json!(3), json!({"backend": "missing"}), json!({"width": "bad"})] {
assert!(assert_unchanged(&mut s, p).is_err());
}
}
#[test]
fn cooperative_host_never_discovers_cpu_raytracing_or_accepts_its_reserved_viewport_id() {
use solidcraft_render::job::CpuHost;
let mut s = Session::default();
s.set_render_job_host(Some(CpuHost::cooperative())).unwrap();
let reply = assert_unchanged(&mut s, json!({})).unwrap();
let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap();
assert!(backend.executors.iter().any(|d| d.id.as_str() == "cpu-product"));
assert!(!backend.executors.iter().any(|d| d.id.as_str() == "cpu-raytrace"));
let mut viewport = CpuHost::cooperative().descriptor().unwrap();
viewport.id = solidcraft_render::ExecutorId::new("cpu-raytrace").unwrap();
viewport.profiles[0].operation = solidcraft_render::RenderOperation::Viewport;
viewport.profiles[0].formats.clear();
assert!(s.set_render_viewport(Some(viewport)).unwrap_err().to_string().contains("reserved"));
assert_eq!(s.render_backend(), backend);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn native_cpu_discovery_matches_installed_features_and_preserves_raster_default() {
use solidcraft_render::job::{CpuHost, Integrator};
use solidcraft_render::{RenderFeature, RenderFormat, RenderMode, RenderOperation, RenderRequest};
let host = CpuHost::for_platform().unwrap();
// Query the host so the same test covers feature-off builds and workspace
// feature unification without assuming the engine's own cfg is sufficient.
let raytrace = host.validate_integrator(Integrator::Raytrace).is_ok();
let mut s = Session::default();
let doc = s.doc.clone();
s.set_render_job_host(Some(host.clone())).unwrap();
let reply = assert_unchanged(&mut s, json!({})).unwrap();
assert!(Arc::ptr_eq(&doc, &s.doc));
assert!(!s.is_dirty());
assert!(s.undo.is_empty());
let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap();
let descriptors: Vec<_> = backend.executors.iter().filter(|d| d.id.as_str() == "cpu-raytrace").collect();
assert_eq!(descriptors.len(), usize::from(raytrace));
if let Some(descriptor) = descriptors.first() {
assert_eq!(descriptor.availability, solidcraft_render::Availability::Available);
assert_eq!(*descriptor, &host.descriptor_for(Integrator::Raytrace).unwrap());
assert!(!descriptor.profiles.iter().any(|p| p.features.contains(&RenderFeature::Progressive)));
}
let request = RenderRequest {
backend: None,
mode: RenderMode::Preview,
operation: RenderOperation::Image,
width: 16,
height: 16,
format: Some(RenderFormat::Png),
features: vec![RenderFeature::Pbr],
policy: Default::default(),
};
assert_eq!(solidcraft_render::resolve_request(std::slice::from_ref(&backend), &request).unwrap().executor.as_str(), "cpu-product");
assert_eq!(s.scratch().render_backend(), backend);
s.set_render_job_host(Some(host)).unwrap();
assert_eq!(s.render_backend(), backend, "reinstalling the same host cannot duplicate method descriptors");
s.set_render_job_host(Some(CpuHost::cooperative())).unwrap();
assert!(!s.render_backend().executors.iter().any(|d| d.id.as_str() == "cpu-raytrace"));
s.set_render_job_host(None).unwrap();
assert_eq!(s.render_backend(), solidcraft_render::builtin_backend());
assert_unchanged(&mut s, json!({})).unwrap();
assert!(Arc::ptr_eq(&doc, &s.doc));
assert!(!s.is_dirty());
assert!(s.undo.is_empty());
}
#[test]
fn discovery_does_not_settle_a_live_drag_or_rebuild_geometry() {
let mut s = Session::default();
for (id, p) in [
("sketch.create", json!({"plane": "XY"})),
("sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [25, 20]})),
("sketch.dimension", json!({"entities": ["l1"], "value": 20})),
("sketch.dimension", json!({"entities": ["l2"], "value": 15})),
("sketch.finish", json!({})),
("solid.extrude", json!({"distance": 5})),
("sketch.edit", json!({"sketch": "Sketch1"})),
("sketch.drag", json!({"entity": "l1.start", "from": [5, 5], "to": [4, 5], "live": true})),
] {
s.execute(id, &p).unwrap();
}
assert!(s.model.is_stale());
s.evaluations = 0;
let model = s.model.state();
assert_unchanged(&mut s, json!({})).unwrap();
assert_unchanged(&mut s, json!({"unexpected": true})).unwrap_err();
assert!(Arc::ptr_eq(&model, &s.model.state()));
assert_eq!(s.evaluations, 0);
}
}
#[cfg(test)]
mod settings_tests;
#[cfg(test)]
mod job_tests;
pub(super) fn prepare_interactive(s: &crate::Session, params: &serde_json::Value) -> crate::Result<crate::render_interactive::Prepared> {
jobs::interactive(s, params)
}
+273 -3
View File
@@ -1,6 +1,205 @@
use super::*;
use solidcraft_render::job::{CpuHost, JobId};
#[test]
fn raster_saved_ev_reopens_captures_check_start_and_changes_real_png_with_one_authority() {
let mut offline = Session::default();
offline.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap();
for (name, ev) in [("Minus", -1.0), ("Zero", 0.0), ("Plus", 1.0)] {
offline
.execute("render.settings.set", &json!({"name":name,"set":{"width":32,"height":32,"exposure_ev":ev,"job":{"method":"raster"}}}))
.unwrap();
}
let mut s = Session::new(solidcraft_doc::Document::from_json(&offline.doc.to_json()).unwrap());
let host = CpuHost::cooperative();
s.set_render_job_host(Some(host.clone())).unwrap();
s.execute("render.scene", &json!({})).unwrap();
let doc = s.doc.clone();
let mut images = Vec::new();
for (name, ev) in [("Minus", -1.0), ("Zero", 0.0), ("Plus", 1.0)] {
let checked = s.execute("render.preflight", &json!({"setup":name})).unwrap();
assert_eq!(checked["ignored_controls"], json!([]));
assert_eq!(checked["request"]["integrator"], "raster");
assert_eq!(checked["request"].get("raster_exposure_ev").and_then(Value::as_f64).unwrap_or(0.0), ev);
let started = s.execute("render.start", &json!({"setup":name})).unwrap();
let job: JobId = serde_json::from_value(started["job"].clone()).unwrap();
finish(&host);
let handle = s.render_job_handle(job).unwrap();
assert_eq!(json!(handle.status().unwrap().request), checked["request"]);
images.push(handle.frame().unwrap().unwrap().png().to_vec());
}
assert_ne!(images[0], images[1]);
assert_ne!(images[1], images[2]);
let explicit = s
.execute(
"render.preflight",
&json!({"settings":{"width":16,"height":16,"exposure_ev":1,
"job":{"method":"raster","lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":2}]}}}),
)
.unwrap();
assert_eq!(explicit["request"]["raster_exposure_ev"], 1.0);
assert_eq!(explicit["request"]["raster_lights"].as_array().unwrap().len(), 1);
assert!(Arc::ptr_eq(&doc, &s.doc));
for ev in [-33.0, 33.0] {
assert!(s.execute("render.settings.set", &json!({"name":"Zero","set":{"exposure_ev":ev}})).is_err());
assert!(Arc::ptr_eq(&doc, &s.doc));
}
assert!(s.execute("render.preflight", &json!({"raster_exposure_ev":1})).is_err());
}
#[test]
fn saved_raster_directional_rig_reopens_and_reaches_check_start_status_png_without_cpu_switch() {
let mut offline = Session::default();
offline.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap();
offline
.execute(
"render.settings.set",
&json!({"name":"SavedRig","set":{"width":32,"height":32,"job":{"method":"raster",
"lights":[{"direction":[3,-4,0],"color":[1,0,0],"intensity":2}]}}}),
)
.unwrap();
let document = solidcraft_doc::Document::from_json(&offline.doc.to_json()).unwrap();
let mut s = Session::new(document);
let host = CpuHost::cooperative();
s.set_render_job_host(Some(host.clone())).unwrap();
s.execute("render.scene", &json!({})).unwrap();
let doc = s.doc.clone();
let checked = s.execute("render.preflight", &json!({"setup":"SavedRig"})).unwrap();
assert_eq!(checked["request"]["integrator"], "raster");
assert!(checked["request"].get("raytrace").is_none());
assert_eq!(checked["request"]["raster_lights"][0]["direction"][0].as_f64().unwrap(), 3.0);
let started = s.execute("render.start", &json!({"setup":"SavedRig"})).unwrap();
let job: JobId = serde_json::from_value(started["job"].clone()).unwrap();
finish(&host);
let handle = s.render_job_handle(job).unwrap();
assert_eq!(json!(handle.status().unwrap().request), checked["request"]);
let lit_png = handle.frame().unwrap().unwrap().png().to_vec();
assert!(lit_png.starts_with(b"\x89PNG\r\n\x1a\n"));
let mut dark = serde_json::to_value(&s.doc.render.setups["SavedRig"]).unwrap();
dark["job"]["lights"] = json!([]);
let dark_started = s.execute("render.start", &json!({"settings":dark})).unwrap();
let dark_job: JobId = serde_json::from_value(dark_started["job"].clone()).unwrap();
finish(&host);
assert_ne!(s.render_job_handle(dark_job).unwrap().frame().unwrap().unwrap().png(), lit_png.as_slice());
for runtime in [Value::Null, json!([])] {
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &json!({"setup":"SavedRig","raster_lights":runtime})).unwrap_err().to_string();
assert!(error.contains("authoritative"), "{error}");
}
}
assert!(Arc::ptr_eq(&doc, &s.doc));
}
#[test]
fn raster_json_is_bounded_before_saved_normalization_and_preserves_null_empty_semantics() {
let (mut s, host) = session();
s.execute(
"render.settings.set",
&json!({"name":"Bounded","set":{"width":16,"height":16,"job":{"method":"raster","transparent_background":false}}}),
)
.unwrap();
let light = json!({"direction":[0,0,1],"color":[1,1,1],"intensity":1});
let mut unknown = light.clone();
unknown["unexpected"] = json!({"nested":vec![0;32]});
let doc = s.doc.clone();
for rig in [json!(vec![light; 9]), json!([unknown])] {
for saved in [false, true] {
let mut params = json!({"raster_lights":rig});
if saved {
params["setup"] = json!("Bounded");
}
let before = params.clone(); // deliberately small adversarial fixture, not production lowering
for command in ["render.preflight", "render.start"] {
assert!(s.execute(command, &params).is_err());
assert_eq!(params, before);
assert_eq!(host.admitted_bytes(), 0);
assert!(Arc::ptr_eq(&doc, &s.doc));
}
}
}
for saved in [false, true] {
for rig in [None, Some(Value::Null), Some(json!([]))] {
let empty = rig.as_ref().is_some_and(Value::is_array);
let mut params = json!({});
if saved {
params["setup"] = json!("Bounded");
}
if let Some(rig) = rig {
params["raster_lights"] = rig;
}
let checked = s.execute("render.preflight", &params).unwrap();
if empty {
assert_eq!(checked["request"]["raster_lights"], json!([]));
} else {
assert!(checked["request"].get("raster_lights").is_none());
}
}
}
// Source inspection, not this outcome test, proves the raw new array was
// borrowed/validated before materialization. No real OOM test is claimed.
}
#[test]
fn transient_raster_rig_survives_saved_normalization_check_start_status_and_png() {
let (mut s, host) = session();
s.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap();
s.execute("render.settings.set", &json!({"name":"Rig","set":{"width":32,"height":32,"job":{"method":"raster","transparent_background":false}}}))
.unwrap();
let doc = s.doc.clone();
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations);
let legacy = s.execute("render.start", &json!({"setup":"Rig"})).unwrap();
let legacy_id: JobId = serde_json::from_value(legacy["job"].clone()).unwrap();
finish(&host);
let legacy_png = s.render_job_handle(legacy_id).unwrap().frame().unwrap().unwrap().png().to_vec();
for rig in [json!([]), json!([{"direction":[0,-1,1],"color":[1,0,0],"intensity":2}])] {
let params = json!({"setup":"Rig","raster_lights":rig});
let checked = s.execute("render.preflight", &params).unwrap();
assert_eq!(checked["request"]["raster_lights"].as_array().unwrap().len(), params["raster_lights"].as_array().unwrap().len());
assert_eq!(checked["retained_request_bytes"].as_u64().unwrap() > 0, !params["raster_lights"].as_array().unwrap().is_empty());
let started = s.execute("render.start", &params).unwrap();
let job: JobId = serde_json::from_value(started["job"].clone()).unwrap();
finish(&host);
let status = s.execute("render.status", &json!({"job":job})).unwrap();
assert_eq!(status["request"], checked["request"]);
assert_eq!(status["progress"]["phase"], "completed");
let handle = s.render_job_handle(job).unwrap();
let frame = handle.frame().unwrap().unwrap();
assert!(frame.png().starts_with(b"\x89PNG\r\n\x1a\n"));
assert_ne!(frame.png(), legacy_png.as_slice());
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations));
assert!(!s.doc.to_json().contains("raster_lights"));
}
}
#[test]
fn raster_rig_rejects_foreign_intent_and_unsupported_setup_controls_without_reserving() {
let (mut s, host) = session();
s.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap();
s.execute("render.preflight", &json!({"raster_lights":[]})).unwrap();
let doc = s.doc.clone();
for command in ["render.preflight", "render.start"] {
for extra in [
json!({"integrator":"raytrace"}),
json!({"progressive":true}),
json!({"studio_weights":[1,1,1]}),
json!({"raytrace":{}}),
json!({"nested_media":true}),
json!({"progressive_feedback":true}),
json!({"settings":{"exposure_ev":33}}),
json!({"settings":{"environment_rotation":1}}),
] {
let mut params = json!({"raster_lights":[]});
for (key, value) in extra.as_object().unwrap() {
params[key] = value.clone();
}
assert!(s.execute(command, &params).is_err(), "{command}: {params}");
assert_eq!(host.admitted_bytes(), 0);
assert!(Arc::ptr_eq(&doc, &s.doc));
}
}
}
fn session() -> (Session, CpuHost) {
let host = CpuHost::cooperative();
let mut s = Session::default();
@@ -1182,17 +1381,18 @@ fn explicit_render_camera_preserves_orientation_and_refuses_invalid_state_atomic
}
/// #5089: a setup saved with exposure (the render workspace and the other executors use it)
/// renders on the raster executor, which has no exposure, and the reply says what it left out.
/// now renders with captured Raster exposure; only unsupported environment controls remain ignored.
#[test]
fn a_setup_saved_with_exposure_renders_and_names_the_controls_it_leaves_out() {
let (mut s, host) = session();
s.execute("render.settings.set", &json!({"name":"x","set":{"mode":"preview","width":16,"height":16,"exposure_ev":0.3}})).unwrap();
let reply = s.execute("render.preflight", &json!({"setup":"x"})).unwrap();
assert_eq!(reply["ignored_controls"], json!(["exposure_ev"]));
assert_eq!(reply["ignored_controls"], json!([]));
assert_eq!(reply["request"]["raster_exposure_ev"], 0.3);
let plain = s.execute("render.preflight", &request()).unwrap();
assert_eq!(plain["ignored_controls"], json!([]));
let started = s.execute("render.start", &json!({"setup":"x"})).unwrap();
assert_eq!(started["ignored_controls"], json!(["exposure_ev"]));
assert_eq!(started["ignored_controls"], json!([]));
finish(&host);
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
assert_eq!(s.execute("render.status", &json!({"job":id})).unwrap()["progress"]["phase"], "completed");
@@ -1216,3 +1416,73 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads
assert!(Arc::ptr_eq(&document, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), host.admitted_bytes()));
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn cpu_exposure_full_saved_range_check_start_preserves_fixed_and_progressive_capture() {
let host = CpuHost::for_platform().unwrap();
assert_eq!(host.kind(), solidcraft_render::job::HostKind::NativeWorker);
host.validate_integrator(solidcraft_render::job::Integrator::Raytrace).unwrap();
eprintln!("CPU_EXPOSURE_RANGE_BRANCH cpu_supported=true");
for ev in [-32.0, -17.0, 17.0, 32.0] {
for progressive in [false, true] {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap();
let mut options = json!({"lights":[],"shadows":false,"primary_samples":1});
if progressive {
options["progressive"] = json!({"samples_per_pixel":3,"seed":31});
}
s.execute(
"render.settings.set",
&json!({"name":"EV","set":{"width":4,"height":4,"exposure_ev":ev,
"job":{"method":"cpu_raytrace","options":options}}}),
)
.unwrap();
let saved = s.doc.render.setups["EV"].clone();
s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
s.set_render_job_host(Some(host.clone())).unwrap();
s.execute("render.scene", &json!({})).unwrap();
let doc = s.doc.clone();
let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty());
let named = json!({"setup":"EV"});
let checked = s.execute("render.preflight", &named).unwrap();
assert_eq!(checked, s.execute("render.preflight", &json!({"settings":saved})).unwrap());
assert_eq!(checked["resolved"]["executor"], "cpu-raytrace");
assert_eq!(checked["request"]["raytrace"]["exposure_ev"], ev);
let started = s.execute("render.start", &named).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let handle = s.render_job_handle(id).unwrap();
let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error);
assert_eq!(json!(status.request), checked["request"]);
let captured = status.request.raytrace.as_ref().unwrap();
assert_eq!(captured.exposure_ev, ev);
assert_eq!(captured.progressive.is_some(), progressive);
assert_eq!(captured.budget, solidcraft_render::job::CpuBudget::Compact);
assert_eq!(status.options.exposure_ev, 0.0, "no second GPU exposure authority");
assert!(handle.frame().unwrap().is_some());
assert_eq!(s.doc.render.setups["EV"], saved);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty()));
}
}
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn cpu_exposure_outside_expanded_range_fails_check_and_start_before_missing_hdr_input() {
let mut s = Session::default();
s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap();
for ev in [-33.0, 33.0, -32.01, 32.01] {
let params = json!({"integrator":"raytrace","settings":{"width":1,"height":1},
"raytrace":{"exposure_ev":ev},"environment":{"path":"never-read-exposure-boundary.hdr"}});
let doc = s.doc.clone();
let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty());
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &params).unwrap_err().to_string();
assert!(error.contains("raytrace exposure_ev must be finite and within -32..32"), "{error}");
}
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty()));
}
}
+762 -34
View File
@@ -11,6 +11,14 @@ use solidcraft_render::{
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct Start {
#[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_lights")]
raster_lights: Option<Vec<solidcraft_render::job::DirectionalLightOptions>>,
#[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_punctual_lights")]
raster_punctual_lights: Option<Vec<solidcraft_render::job::PunctualLightOptions>>,
#[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_area_lights")]
raster_area_lights: Option<Vec<solidcraft_render::job::RectangleLightOptions>>,
progressive_feedback: bool,
nested_media: bool,
studio_weights: Option<[f64; 3]>,
progressive: bool,
denoise: bool,
@@ -47,6 +55,7 @@ impl Default for EnvironmentRequest {
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ProgressiveStart {
progressive_feedback: bool,
studio_weights: Option<[f64; 3]>,
aging: solidcraft_doc::render_aging::SavedAgingStack,
#[serde(default)]
@@ -75,6 +84,7 @@ struct ProgressiveStart {
}
struct Prepared {
progressive_feedback: bool,
replace: bool,
scene: solidcraft_render::ProductScene,
request: ImageRequest,
@@ -99,8 +109,207 @@ fn lower_led(input: &mut Start, command: &str) -> Result<()> {
Ok(())
}
/// Pure preview lowering. Parse the existing CPU wire before changing its sampling;
/// unsupported effects remain errors rather than disappearing from the request.
fn interactive_params(params: &Value) -> Result<Value> {
let command = "render.interactive";
let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?;
let object = params.as_object().ok_or_else(|| bad(command, "Interactive requires an explicit CPU request object"))?;
if object.contains_key("setup") || object.contains_key("replace") {
return Err(bad(command, "Interactive requires an explicit settings snapshot without setup or replace"));
}
if input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some() {
return Err(bad(command, "Interactive does not accept explicit Raster lights"));
}
if input.integrator != Integrator::Raytrace || input.progressive || input.transparent_background {
return Err(bad(command, "Interactive requires opaque CPU ray tracing, not GPU progressive or raster rendering"));
}
if input.studio_weights.is_some() || input.denoise || input.samples.is_some() || input.max_depth.is_some() || input.seed.is_some() {
return Err(bad(command, "Interactive cannot accept GPU studio, denoise or sampling controls"));
}
let mut settings = input.settings.take().ok_or_else(|| bad(command, "Interactive requires explicit settings"))?;
if settings.job.is_some() {
return Err(bad(command, "Interactive requires a lowered CPU runtime request with settings.job: null"));
}
if settings.mode != solidcraft_render::RenderMode::Preview || settings.format != solidcraft_render::RenderFormat::Png {
return Err(bad(command, "Interactive CPU requires the existing Preview/Image/PNG profile"));
}
// Keep the existing CPU runtime exposure authority; never silently neutralize
// saved/common controls in order to make a request acceptable.
if settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 {
return Err(bad(command, "Interactive CPU exposure belongs to raytrace.exposure_ev; environment controls belong to the captured input"));
}
lower_led(&mut input, command)?;
if let Some(environment) = &input.environment {
// Same numerical controls as EnvironmentInput::new, checked before a path
// can be read. Resource bytes and primaries remain prepare's responsibility.
if !environment.rotation_radians.is_finite()
|| !environment.intensity.is_finite()
|| !(0.0..=64.0).contains(&environment.intensity)
|| !matches!(environment.samples, 1 | 4 | 16 | 64)
{
return Err(bad(command, "invalid Interactive environment controls"));
}
if input.raytrace.as_ref().is_some_and(|options| options.environment.is_some()) {
return Err(bad(command, "choose either captured HDR or constant CPU environment"));
}
}
let final_request = ImageRequest {
raster_punctual_lights: None,
raster_area_lights: None,
raster_exposure_ev: 0.0,
raster_lights: None,
camera: settings.camera,
width: settings.width,
height: settings.height,
background: settings.background,
transparent_background: input.transparent_background,
integrator: input.integrator,
raytrace: input.raytrace,
studio_weights: input.studio_weights,
environment: None,
textures: None,
};
let preview = solidcraft_render::job::interactive::cpu_request(&final_request).map_err(job_error)?;
settings.width = preview.width;
settings.height = preview.height;
let budget = preview.raytrace.as_ref().map_or(solidcraft_render::job::CpuBudget::Compact, |options| options.budget);
settings.validate_for_cpu(budget).map_err(|e| bad(command, e.to_string()))?;
// Preserve every original field after strict deserialization. Only the LED
// recipe has been consumed into real area lights; do not lower it twice.
let mut lowered = object.clone();
lowered.remove("led_strip");
lowered.remove("led_samples");
lowered.insert("settings".into(), serde_json::to_value(settings).map_err(|e| bad(command, e.to_string()))?);
lowered.insert("raytrace".into(), serde_json::to_value(preview.raytrace).map_err(|e| bad(command, e.to_string()))?);
Ok(Value::Object(lowered))
}
/// Capture/admit only. The engine's Interactive owner submits outside the final
/// registry; this helper never starts, replaces, cancels or exports a job.
pub(super) fn interactive(s: &Session, params: &Value) -> Result<crate::render_interactive::Prepared> {
let params = interactive_params(params)?;
let prepared = prepare(s, &params, "render.interactive")?;
if prepared.executor.as_str() != "cpu-raytrace" {
return Err(bad("render.interactive", "Interactive requires the installed cpu-raytrace executor"));
}
Ok(crate::render_interactive::Prepared {
scene: prepared.scene,
request: prepared.request,
options: prepared.options,
environment: prepared.environment,
})
}
#[cfg(test)]
mod union_lowering_tests {
#[cfg(not(target_arch = "wasm32"))]
fn raster_local_command_fixture() -> (Session, Value) {
let mut s = Session::default();
s.execute(
"solid.box",
&json!({"length":20,"width":20,"height":4,"center":[0,0,0],"operation":"new","body_name":"Raster local command fixture"}),
)
.unwrap();
s.execute("render.scene", &json!({})).unwrap();
s.set_render_job_host(Some(solidcraft_render::job::CpuHost::for_platform().unwrap())).unwrap();
let mut camera = solidcraft_render::Camera { distance: 50.0, ..Default::default() };
camera.set_view(solidcraft_render::StandardView::Top);
let wire = json!({"settings":{"width":8,"height":8,"camera":camera,"background":[20,40,60],"exposure_ev":1.25,"job":null},
"raster_punctual_lights":[{"position_mm":[0.0,0.0,20.0],"color":[0.25,0.5,1.0],"intensity":2.0,"reference_distance_mm":20.0,"minimum_distance_mm":0.001}],
"raster_area_lights":[{"center_mm":[0.0,0.0,20.0],"edge_u_mm":[4.0,0.0,0.0],"edge_v_mm":[0.0,-4.0,0.0],"color":[1.0,0.5,0.25],"intensity":2.0}]});
(s, wire)
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn raster_local_public_preflight_start_status_and_real_png_keep_both_sources_and_one_ev() {
use solidcraft_render::job::{JobId, Phase};
let (mut s, wire) = raster_local_command_fixture();
let original = wire.clone();
let checked = s.execute("render.preflight", &wire).unwrap();
assert_eq!(checked["request"]["raster_punctual_lights"], wire["raster_punctual_lights"]);
assert_eq!(checked["request"]["raster_area_lights"], wire["raster_area_lights"]);
assert_eq!(checked["request"]["raster_exposure_ev"], 1.25);
assert!(checked["request"].get("raster_lights").is_none(), "no implicit directionals added");
let started = s.execute("render.start", &wire).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let handle = s.render_job_handle(id).unwrap();
let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
assert_eq!(status.request.raster_exposure_ev, 1.25);
assert_eq!(serde_json::to_value(&status.request.raster_punctual_lights).unwrap(), wire["raster_punctual_lights"]);
assert_eq!(serde_json::to_value(&status.request.raster_area_lights).unwrap(), wire["raster_area_lights"]);
let frame = handle.frame().unwrap().unwrap();
let bright = image::load_from_memory(frame.png()).unwrap().to_rgba8();
assert_eq!(bright.dimensions(), (8, 8));
let mut empty = wire.clone();
empty["raster_punctual_lights"] = json!([]);
empty["raster_area_lights"] = json!([]);
let started = s.execute("render.start", &empty).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let dark_handle = s.render_job_handle(id).unwrap();
assert_eq!(dark_handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed);
let dark_frame = dark_handle.frame().unwrap().unwrap();
let dark = image::load_from_memory(dark_frame.png()).unwrap().to_rgba8();
assert_ne!(bright, dark, "actual local lights must change the real producer output");
assert_eq!(wire, original, "input intent is immutable");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn raster_local_public_commands_refuse_saved_and_foreign_controls_without_reservation() {
let (mut s, wire) = raster_local_command_fixture();
let before_revision = s.revision;
let mut saved = wire.clone();
saved["settings"]["job"] = serde_json::to_value(RenderJob::Raster { transparent_background: false, lights: None }).unwrap();
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &saved).unwrap_err().to_string();
assert!(error.contains("saved local-light authoring"), "{error}");
}
for (key, value) in [
("integrator", json!("raytrace")),
("studio_weights", json!([1, 1, 1])),
("raytrace", json!({})),
("environment", json!({"path":"must-not-be-opened.hdr"})),
("nested_media", json!(true)),
("progressive_feedback", json!(true)),
("progressive", json!(true)),
("samples", json!(1)),
("seed", json!(0)),
("denoise", json!(true)),
] {
let mut invalid = wire.clone();
invalid[key] = value;
for command in ["render.preflight", "render.start"] {
assert!(s.execute(command, &invalid).is_err(), "{command} accepted {key}");
assert_eq!(s.render_job_host().unwrap().admitted_bytes(), 0, "no failed request reserved work");
}
}
let mut interactive = wire;
interactive["integrator"] = json!("raytrace");
assert!(interactive_params(&interactive).is_err());
assert_eq!(s.revision, before_revision);
}
#[test]
fn raster_local_public_command_caps_refuse_before_host_lookup_or_scene_capture() {
let point = json!({"position_mm":[0,0,20],"color":[1,1,1],"intensity":1,"reference_distance_mm":20,"minimum_distance_mm":0.001});
let area = json!({"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,-4,0],"color":[1,1,1],"intensity":1});
let mut s = Session::default();
for (key, value, reason) in
[("raster_punctual_lights", json!(vec![point; 9]), "at most eight"), ("raster_area_lights", json!(vec![area; 5]), "at most four")]
{
let mut wire = json!({});
wire[key] = value;
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &wire).unwrap_err().to_string();
assert!(error.contains(reason), "bound must fail before absent host: {error}");
}
}
}
use super::*;
#[test]
fn led_lowering_keeps_hdr_reflection_aa_and_anisotropy_inputs_without_reading_hdr() {
@@ -123,6 +332,361 @@ mod union_lowering_tests {
assert!(input.led_strip.is_none() && input.led_samples.is_none());
assert_eq!(wire["environment"]["path"], json!("unopened.hdr"));
}
fn interactive_final_wire() -> Value {
let camera = solidcraft_render::Camera { fov: 0.8, ..Default::default() };
json!({"integrator":"raytrace","settings":{
"width":3840,"height":2160,"camera":camera,"background":[20,40,60],"job":null,
"stage":[{"id":"floor","center_mm":[0.0,0.0,-5.0],"half_u_mm":[40.0,0.0,0.0],
"half_v_mm":[0.0,40.0,0.0],"reflectance_linear":[0.1,0.2,0.3]}]},
"raytrace":{"primary_samples":4,"shadows":false,"exposure_ev":1.25,"lights":[],
"reflections":{"bodies":[{"body":"receiver","mode":"mirror"}],"samples":16,"max_bounces":3},
"punctual_lights":[{"position_mm":[0.0,0.0,20.0],"color":[1.0,0.5,0.25],"intensity":2.0,
"reference_distance_mm":20.0,"minimum_distance_mm":0.01}],
"emissions":[{"body_index":0,"body":"receiver","color":[0.2,0.4,0.8],"strength":3.0}],
"surface_effects":[{"body":"receiver","repeat_mm":[2.0,3.0,4.0],"roughness_amplitude":0.1,"bump_amplitude_mm":0.01}]},
"environment":{"path":"unopened-original.hdr","expected_sha256":"a".repeat(64),
"rotation_radians":0.75,"intensity":2.0,"samples":16}})
}
#[test]
fn interactive_fits_4k_before_admission_and_preserves_final_wire_and_transport() {
let wire = interactive_final_wire();
let original = wire.clone();
let lowered = interactive_params(&wire).unwrap();
let before: Start = serde_json::from_value(wire.clone()).unwrap();
let after: Start = serde_json::from_value(lowered.clone()).unwrap();
let final_settings = before.settings.unwrap();
let preview_settings = after.settings.unwrap();
assert_eq!((final_settings.width, final_settings.height), (3840, 2160));
assert_eq!((preview_settings.width, preview_settings.height), (1024, 576));
assert!(before.raytrace.as_ref().unwrap().budget.validate_image(3840, 2160, None).is_err(), "Compact final exceeds pixel cap");
let mut expected_settings = final_settings;
expected_settings.width = 1024;
expected_settings.height = 576;
assert_eq!(preview_settings, expected_settings, "camera, stage, background and other settings remain exact");
let mut expected_options = before.raytrace.unwrap();
expected_options.primary_samples = 1;
expected_options.progressive = Some(Default::default());
expected_options.reflections.as_mut().unwrap().samples = 1;
assert_eq!(after.raytrace.unwrap(), expected_options, "no lighting, emission, shading effect or EV is discarded");
assert_eq!(lowered["environment"], wire["environment"], "unopened HDR path and expected digest stay pinned");
assert_eq!(lowered["raytrace"]["progressive"], json!({"samples_per_pixel":16,"seed":0}));
assert_eq!(wire, original);
}
#[test]
fn interactive_small_and_extreme_aspects_fit_without_enlarging_or_zero_dimensions() {
for (width, height, expected) in [(320, 200, (320, 200)), (4096, 1, (1024, 1)), (1, 4096, (1, 1024))] {
let wire = json!({"integrator":"raytrace","settings":{"width":width,"height":height}});
let output = interactive_params(&wire).unwrap();
assert_eq!((output["settings"]["width"].as_u64().unwrap(), output["settings"]["height"].as_u64().unwrap()), (expected.0, expected.1));
}
}
#[test]
fn interactive_refuses_alternate_authorities_and_unknown_fields_without_io() {
let s = Session::default();
let base = interactive_final_wire();
for (key, value) in [
("setup", json!(null)),
("setup", json!("Saved")),
("replace", json!(false)),
("replace", json!(true)),
("integrator", json!("raster")),
("progressive", json!(true)),
("transparent_background", json!(true)),
("denoise", json!(true)),
("samples", json!(1)),
("max_depth", json!(2)),
("seed", json!(0)),
("studio_weights", json!([1, 1, 1])),
("unknown", json!(true)),
("lens", json!(null)),
] {
let mut wire = base.clone();
wire[key] = value;
let error = match interactive(&s, &wire) {
Err(error) => error.to_string(),
Ok(_) => panic!("Interactive accepted conflicting input {key}"),
};
assert!(!error.contains("could not read") && !error.contains("no image host"), "refuse before host/IO: {key}: {error}");
}
for settings in [
json!(null),
json!({"job":{"method":"cpu_raytrace"}}),
json!({"job":{"method":"gpu_path"}}),
json!({"exposure_ev":1.0}),
json!({"environment_rotation":1.0}),
json!({"width":0}),
json!({"mode":"final"}),
json!({"format":"exr"}),
] {
let mut wire = base.clone();
wire["settings"] = settings;
assert!(interactive_params(&wire).is_err());
}
let mut missing = base.clone();
missing.as_object_mut().unwrap().remove("settings");
assert!(interactive_params(&missing).is_err());
for wire in [json!(null), json!([]), json!(false)] {
assert!(interactive_params(&wire).is_err());
}
assert!(s.render_job_host().is_none());
}
#[test]
fn interactive_refuses_invalid_or_unsupported_effects_before_unopened_hdr() {
let base = interactive_final_wire();
// Retain numerically valid dielectric intent for capture-time certification.
// This fixture still mixes same-body mirror, emission and nonidentity effects;
// successful lowering is not scene or job admission.
let mut authored = base.clone();
authored["raytrace"]["dielectrics"] = json!([{"body_index":0,"body_name":"receiver","ior":1.5,"absorption_per_mm":[0,0,0],
"boundary":"closed_box","thickness_mm":0}]);
let original = authored.clone();
let authored_options: RaytraceOptions = serde_json::from_value(original["raytrace"].clone()).unwrap();
let mut expected_options = authored_options.clone();
expected_options.primary_samples = 1;
expected_options.progressive = Some(solidcraft_render::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 });
expected_options.reflections.as_mut().unwrap().samples = 1;
let mut expected_settings: RenderSetup = serde_json::from_value(original["settings"].clone()).unwrap();
expected_settings.width = 1024;
expected_settings.height = 576;
let mut expected_wire = original.clone();
expected_wire["settings"] = serde_json::to_value(&expected_settings).unwrap();
expected_wire["raytrace"] = serde_json::to_value(&expected_options).unwrap();
let lowered = interactive_params(&authored).unwrap();
let lowered_options: RaytraceOptions = serde_json::from_value(lowered["raytrace"].clone()).unwrap();
let lowered_settings: RenderSetup = serde_json::from_value(lowered["settings"].clone()).unwrap();
assert_eq!(lowered_options.dielectrics, authored_options.dielectrics, "the exact original dielectric selector is retained");
assert_eq!(lowered_options.surface_effects, authored_options.surface_effects, "shading intent is not removed");
assert_eq!(lowered_options.emissions, authored_options.emissions, "surface emission is not removed");
assert_eq!(lowered_options.reflections, expected_options.reflections, "only the selected reflection sample count changes");
assert_eq!(lowered_options, expected_options, "only documented Interactive sampling is normalized");
assert_eq!(lowered_settings, expected_settings, "camera, stage, background and other settings remain exact");
assert_eq!(lowered["environment"], original["environment"], "unopened HDR path and expected digest remain exact");
assert_eq!(lowered, expected_wire, "no other request field changes");
assert_eq!(authored, original, "the authored final wire remains unchanged");
for (key, value) in [
("primary_samples", json!(0)),
("exposure_ev", json!(33.0)),
(
"anisotropic_faces",
json!([{"body_index":0,"body_name":"receiver","face":0,"tangent":[1,0,0],
"orientation":"zero","roughness_x":0.2,"roughness_y":0.4},null]),
),
("textures", json!([])),
] {
let mut wire = base.clone();
wire["raytrace"][key] = value;
assert!(interactive_params(&wire).is_err(), "unsupported {key} must not disappear");
}
for (key, value) in [("thickness_mm", json!(1.0)), ("ior", json!(0.5))] {
let mut wire = authored.clone();
wire["raytrace"]["dielectrics"][0][key] = value;
assert!(interactive_params(&wire).is_err(), "invalid dielectric {key} must refuse before unopened HDR");
}
for (key, value) in [("intensity", json!(-1.0)), ("samples", json!(3))] {
let mut wire = base.clone();
wire["environment"][key] = value;
assert!(interactive_params(&wire).is_err());
}
let mut ambiguous = base.clone();
ambiguous["raytrace"]["environment"] = json!({"color":[1.0,1.0,1.0],"intensity":1.0});
assert!(interactive_params(&ambiguous).is_err());
let mut orphaned_led_samples = base;
orphaned_led_samples["led_samples"] = json!(16);
assert!(interactive_params(&orphaned_led_samples).is_err());
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn interactive_capture_reuses_cpu_scene_stage_and_admission_without_starting_a_job() {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":10,"width":8,"height":4,"body_name":"receiver"})).unwrap();
s.execute(
"appearance.assign",
&json!({"bodies":["receiver"],"color":"#4080c0",
"pbr":{"metallic":1.0,"roughness":0.25,"dielectric_ior":1.5}}),
)
.unwrap();
s.execute("render.scene", &json!({})).unwrap();
let subject = crate::product_scene::extract(&s).unwrap();
let host = solidcraft_render::job::CpuHost::for_platform().unwrap();
s.set_render_job_host(Some(host.clone())).unwrap();
let mut wire = interactive_final_wire();
wire.as_object_mut().unwrap().remove("environment");
let document = s.doc.clone();
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
let captured = interactive(&s, &wire).unwrap();
assert_eq!((captured.request.width, captured.request.height), (1024, 576));
assert_eq!(captured.request.integrator, Integrator::Raytrace);
assert_eq!(captured.request.raytrace.as_ref().unwrap().exposure_ev, 1.25);
let body = captured.scene.meshes.iter().find(|mesh| mesh.name == "receiver").unwrap();
assert_eq!(body.surface, subject.meshes[0].surface);
assert_eq!(body.faces, subject.meshes[0].faces);
assert!(std::sync::Arc::ptr_eq(&body.mesh, &subject.meshes[0].mesh));
assert_eq!(captured.scene.meshes.len(), 2, "subject and render-only floor are both captured");
assert!(captured.scene.meshes.iter().any(|mesh| mesh.name == "__render_stage__/floor"));
assert_eq!(captured.options, solidcraft_render::job::JobOptions::default());
assert!(captured.environment.is_none());
assert_eq!(host.admitted_bytes(), 0, "capture validates but does not submit/reserve a job");
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
assert_eq!(wire["settings"]["width"], 3840);
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
fn nested_command_fixture() -> (Session, Value) {
let mut s = Session::default();
for (name, length, width, height) in [("Outer", 20, 20, 4), ("Inner", 10, 10, 2)] {
s.execute(
"solid.box",
&json!({
"length":length,"width":width,"height":height,"center":[0,0,2],
"operation":"new","body_name":name,
}),
)
.unwrap();
}
s.execute("render.scene", &json!({})).unwrap();
let scene = crate::product_scene::extract(&s).unwrap();
assert_eq!(scene.meshes.len(), 2);
let dielectrics: Vec<_> = scene
.meshes
.iter()
.enumerate()
.map(|(index, body)| {
assert!(matches!(body.name.as_str(), "Outer" | "Inner"));
json!({
"body_index":index,"body_name":body.name,"boundary":"closed_box","ior":1.0,
"absorption_per_mm":if body.name == "Outer" { [0.1,0.2,0.0] } else { [0.3,0.4,0.0] },
"thickness_mm":0.0,
})
})
.collect();
let mut camera = solidcraft_render::Camera { distance: 50.0, fov: 0.0, ..Default::default() };
camera.set_view(solidcraft_render::StandardView::Top);
camera.target = solidcraft_geom::Vec3::new(0.0, 0.0, 2.0);
let host = solidcraft_render::job::CpuHost::for_platform().unwrap();
assert_eq!(host.kind(), solidcraft_render::job::HostKind::NativeWorker);
assert!(host.is_available(), "this native test requires an available real CPU worker");
s.set_render_job_host(Some(host)).unwrap();
let wire = json!({
"integrator":"raytrace","nested_media":true,
"settings":{"width":1,"height":1,"camera":camera,"background":[255,255,255],"job":null},
"raytrace":{"dielectrics":dielectrics,"lights":[],"shadows":false,
"environment":{"color":[1,1,1],"intensity":1}},
});
(s, wire)
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn command_nested_opt_in_reaches_retained_job_options_and_real_beer_transport() {
use solidcraft_render::job::{JobId, Phase};
let (mut s, wire) = nested_command_fixture();
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
let document = s.doc.clone();
for value in [None, Some(false)] {
let mut default = wire.clone();
if let Some(value) = value {
default["nested_media"] = json!(value);
} else {
default.as_object_mut().unwrap().remove("nested_media");
}
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &default).unwrap_err().to_string();
assert!(error.contains("nested, touching or overlapping dielectric volumes are unsupported"), "{command}: {error}");
}
}
let checked = s.execute("render.preflight", &wire).unwrap();
assert_eq!(checked["resolved"]["executor"], "cpu-raytrace");
assert_eq!(checked["request"]["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]);
let started = s.execute("render.start", &wire).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let handle = s.render_job_handle(id).unwrap();
let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
assert_eq!(status.options, solidcraft_render::job::JobOptions { nested_media: true, ..Default::default() });
let retained = s.execute("render.status", &json!({"job":id})).unwrap();
assert_eq!(retained["options"]["nested_media"], true);
let frame = handle.frame().unwrap().unwrap();
let image = image::load_from_memory(frame.png()).unwrap().to_rgba8();
// Independent Beer oracle: outer2mm + inner2mm, replacing the parent
// interval, yields exp(-.8), exp(-1.2),1 -> Reinhard+sRGB [151,132,188].
assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]);
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn command_nesting_keeps_default_false_rejects_gpu_controls_and_captures_progressive_glass() {
use solidcraft_render::job::{JobId, JobOptions, Phase};
let (mut s, wire) = nested_command_fixture();
for (key, value) in [("samples", json!(2)), ("max_depth", json!(2)), ("seed", json!(7)), ("denoise", json!(true)), ("lens", json!({}))] {
let mut invalid = wire.clone();
invalid[key] = value;
for command in ["render.preflight", "render.start"] {
assert!(s.execute(command, &invalid).is_err(), "{command} accepted unrelated control {key}");
}
}
let mut progressive = wire.clone();
progressive["raytrace"]["progressive"] = json!({"samples_per_pixel":2,"seed":0});
// Original narrow perspective fixture: every possible pixel jitter ray
// enters both boxes, rather than allowing primary misses/background.
progressive["settings"]["camera"]["fov"] = json!(1.0e-6);
// This previously blanket-negative branch is now an actual supported
// progressive transport/capture case. GPU-only control refusals above
// and the default nesting assertions below are unchanged.
let checked = s.execute("render.preflight", &progressive).unwrap();
assert_eq!(checked["resolved"]["executor"], "cpu-raytrace");
assert_eq!(checked["request"]["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]);
assert_eq!(checked["request"]["raytrace"]["progressive"], progressive["raytrace"]["progressive"]);
let started = s.execute("render.start", &progressive).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let handle = s.render_job_handle(id).unwrap();
let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
assert!(status.options.nested_media);
let captured = status.request.raytrace.as_ref().unwrap();
assert_eq!(captured.progressive.unwrap().samples_per_pixel, 2);
assert_eq!(captured.progressive.unwrap().seed, 0);
assert_eq!(serde_json::to_value(&captured.dielectrics).unwrap(), wire["raytrace"]["dielectrics"]);
let frame = handle.frame().unwrap().unwrap();
let image = image::load_from_memory(frame.png()).unwrap().to_rgba8();
assert_eq!(image.dimensions(), (1, 1));
// Camera is exterior at z52. At every box face its full jitter cone
// lies within52*tan(1e-6) < 0.000053mm of the axis, far inside the
// inner +/-5mm face. Even using twice the actual half-angle bounds,
// cos(theta)>1-2e-12. Parent-only and child lengths are each2/cos mm.
// IOR1 removes Fresnel/refraction; scalar Beer is exp(-.8/cos),
// exp(-1.2/cos),1. Their bounded variation is far below the nearest
// integer thresholds of existing Reinhard/sRGB: [151,132,188].
// Actual primary-background pixels would be255 and fail this oracle.
// This remains a command-route smoke, not a Fresnel/TIR quality case.
assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]);
let interactive = interactive_params(&wire).unwrap();
assert_eq!(interactive["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]);
assert_eq!(interactive["nested_media"], true);
assert!(interactive["raytrace"]["progressive"].is_object());
// Ordinary CPU requests retain the exact default JobOptions; omission is
// not silently promoted to nesting by adding this explicit opt-in.
let mut opaque = wire;
opaque.as_object_mut().unwrap().remove("nested_media");
opaque["raytrace"].as_object_mut().unwrap().remove("dielectrics");
s.execute("render.preflight", &opaque).unwrap();
let started = s.execute("render.start", &opaque).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let status = s.render_job_handle(id).unwrap().wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
assert_eq!(status.options, JobOptions::default());
let retained = s.execute("render.status", &json!({"job":id})).unwrap();
assert_eq!(retained["options"]["nested_media"], false);
}
}
/// Resolve portable intent before choosing an executor. Legacy requests are left intact;
@@ -140,6 +704,27 @@ struct Normalized {
}
fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result<Option<Normalized>> {
// Validate the new payload by reference even if this turns out to be an
// unsaved request. Never clone an unbounded caller-owned light array.
let raster_override = params
.get("raster_lights")
.map(|value| solidcraft_render::job::deserialize_raster_lights(value).map_err(|e| bad(command, e.to_string())))
.transpose()?;
// Validate both local arrays by reference before any saved setup or JSON clone.
if let Some(value) = params.get("raster_punctual_lights") {
let _ = solidcraft_render::job::deserialize_raster_punctual_lights(value).map_err(|e| bad(command, e.to_string()))?;
}
if let Some(value) = params.get("raster_area_lights") {
let _ = solidcraft_render::job::deserialize_raster_area_lights(value).map_err(|e| bad(command, e.to_string()))?;
}
let local_intent = ["raster_punctual_lights", "raster_area_lights"].into_iter().any(|key| params.get(key).is_some_and(|v| !v.is_null()));
if local_intent {
let inline_saved = params.get("settings").and_then(|v| v.get("job")).is_some_and(|v| !v.is_null());
let named_saved = params.get("setup").and_then(Value::as_str).and_then(|name| s.doc.render.setups.get(name)).is_some_and(|v| v.job.is_some());
if inline_saved || named_saved {
return Err(bad(command, "runtime Raster local lights require settings.job: null; saved local-light authoring is not supported yet"));
}
}
let Some(object) = params.as_object() else {
return Ok(None);
};
@@ -152,16 +737,29 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result<Opt
if value.get("job").is_none_or(Value::is_null) {
return Ok(None);
}
serde_json::from_value::<RenderSetup>(value.clone()).map_err(|e| bad(command, e.to_string()))?
RenderSetup::deserialize(value).map_err(|e| bad(command, e.to_string()))?
} else if let Some(settings) = named.and_then(Value::as_str).and_then(|name| s.doc.render.setups.get(name)) {
if settings.job.is_none() {
return Ok(None);
}
settings.validate().map_err(|e| bad(command, e.to_string()))?;
settings.clone()
} else {
return Ok(None);
};
if let Some(key) = object.keys().find(|key| !matches!(key.as_str(), "setup" | "settings" | "replace" | "studio_weights")) {
if let Some(key) = object.keys().find(|key| {
!matches!(
key.as_str(),
"setup"
| "settings"
| "replace"
| "studio_weights"
| "progressive_feedback"
| "raster_lights"
| "raster_punctual_lights"
| "raster_area_lights"
)
}) {
return Err(bad(
command,
format!(
@@ -178,7 +776,16 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result<Opt
let surfaces = std::mem::take(&mut settings.surfaces);
let mut hdr = None;
let mut lowered = match job {
RenderJob::Raster { transparent_background } => json!({"transparent_background":transparent_background}),
RenderJob::Raster { transparent_background, lights } => {
if lights.is_some() && object.contains_key("raster_lights") {
return Err(bad(command, "saved Raster lights are authoritative; remove the runtime raster_lights override"));
}
let mut request = json!({"transparent_background":transparent_background});
if lights.is_some() {
request["raster_lights"] = serde_json::to_value(lights).map_err(|e| bad(command, e.to_string()))?;
}
request
}
RenderJob::CpuRaytrace { options } => {
hdr = options.hdr.map(SavedHdr::Cpu);
let raytrace = options.to_runtime(settings.exposure_ev).map_err(|e| bad(command, e.to_string()))?;
@@ -200,12 +807,19 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result<Opt
}
};
lowered["settings"] = serde_json::to_value(settings).map_err(|e| bad(command, e.to_string()))?;
if let Some(lights) = raster_override {
// Only the already validated, bounded representation is materialized.
lowered["raster_lights"] = serde_json::to_value(lights).map_err(|e| bad(command, e.to_string()))?;
}
if let Some(weights) = object.get("studio_weights") {
lowered["studio_weights"] = weights.clone();
}
if let Some(replace) = object.get("replace") {
lowered["replace"] = replace.clone();
}
if let Some(feedback) = object.get("progressive_feedback") {
lowered["progressive_feedback"] = feedback.clone();
}
Ok(Some(Normalized { params: lowered, hdr, surfaces, optics }))
}
@@ -241,7 +855,26 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
"runtime GPU transmission, texture, lens, environment, lighting, tone-map and denoise controls require progressive rendering",
));
}
let mut input: Start = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?;
solidcraft_render::job::validate_raster_lights(&input.raster_lights).map_err(job_error)?;
solidcraft_render::job::validate_raster_punctual_lights(&input.raster_punctual_lights).map_err(job_error)?;
solidcraft_render::job::validate_raster_area_lights(&input.raster_area_lights).map_err(job_error)?;
if (input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some())
&& (input.integrator != Integrator::Raster
|| input.progressive
|| input.progressive_feedback
|| input.nested_media
|| input.raytrace.is_some()
|| input.studio_weights.is_some()
|| input.environment.is_some())
{
return Err(bad(command, "explicit Raster lights require Raster without CPU/GPU controls, environment or studio_weights"));
}
if input.progressive_feedback
&& (input.integrator != Integrator::Raytrace || input.raytrace.as_ref().and_then(|options| options.progressive).is_none())
{
return Err(bad(command, "progressive_feedback requires CPU progressive raytracing"));
}
validate_studio_weights(input.studio_weights, command)?;
if input.integrator == Integrator::Raytrace && input.studio_weights.is_some() {
return Err(bad(command, "studio_weights apply to raster or the implicit GPU studio; use explicit CPU light intensities"));
@@ -274,6 +907,14 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
}
if let Some(options) = &input.raytrace {
options.retained_bytes().map_err(job_error)?;
if options.directional_shadow_transmission {
if input.nested_media {
return Err(bad(command, "directional shadow transmission does not support nested media"));
}
if saved_hdr.is_some() || input.environment.is_some() {
return Err(bad(command, "directional shadow transmission does not support HDR environments"));
}
}
options.budget.validate_execution().map_err(job_error)?;
// Check the complete image envelope before any source file is read.
let dimensions = if let Some(name) = &input.setup {
@@ -364,10 +1005,13 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
} else {
settings.validate().map_err(|e| bad(command, e.to_string()))?;
}
// The raster image executor has no exposure or environment controls. A setup saved with them
// (the render workspace and the other executors use them) still renders here, and the reply
// names what this render leaves out (#5089). The raytrace path takes them only through a
// saved job, so a raytrace request with them is still refused.
// Raster captures the existing exposure authority. Legacy environment controls
// still have no transport here and are reported/refused under their old policy.
if (input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some())
&& (settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0)
{
return Err(bad(command, "explicit Raster lights do not implement environment controls"));
}
let ignored = if input.integrator == Integrator::Raster { ignored_controls(&settings) } else { Vec::new() };
if input.integrator != Integrator::Raster
&& (settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0)
@@ -408,6 +1052,10 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
return Err(bad(command, "resolved executor is not installed as an image job host"));
}
let request = ImageRequest {
raster_punctual_lights: input.raster_punctual_lights.take(),
raster_area_lights: input.raster_area_lights.take(),
raster_exposure_ev: if input.integrator == Integrator::Raster { settings.exposure_ev } else { 0.0 },
raster_lights: input.raster_lights.take(),
studio_weights: validate_studio_weights(input.studio_weights, command)?,
environment: None,
textures: None,
@@ -419,28 +1067,47 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
background: settings.background,
transparent_background: input.transparent_background,
};
let mut admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?;
let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?;
let options = solidcraft_render::job::JobOptions { nested_media: input.nested_media, ..Default::default() };
let mut admission = if input.progressive_feedback {
host.admit_cpu_protected_partial_with_environment_and_options(&scene, &request, options, environment.as_ref()).map_err(job_error)?
} else {
host.admit(&scene, &request, options).map_err(job_error)?
};
let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?;
let retained_lights = retained_lights
.checked_add(request.raster_lights_retained_bytes().map_err(job_error)?)
.ok_or_else(|| bad(command, "retained light metadata overflow"))?;
let retained_environment =
if environment_info.is_some() { std::mem::size_of::<solidcraft_render::lighting::environment_input::EnvironmentInfo>() as u64 } else { 0 };
let retained_request_bytes = retained_lights.checked_add(retained_environment).ok_or_else(|| bad(command, "request metadata overflow"))?;
admission.estimated_total_bytes = admission
.estimated_total_bytes
.checked_add(environment_bytes)
.and_then(|v| v.checked_add(retained_request_bytes))
.filter(|v| *v <= budget.limits().max_job_bytes)
.ok_or_else(|| bad(command, "environment job exceeds per-job memory limit"))?;
admission.preparation_bytes =
admission.preparation_bytes.checked_add(environment_bytes).ok_or_else(|| bad(command, "environment admission overflow"))?;
if !input.progressive_feedback {
let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?;
admission.estimated_total_bytes = admission
.estimated_total_bytes
.checked_add(environment_bytes)
.and_then(|v| v.checked_add(retained_request_bytes))
.filter(|v| *v <= budget.limits().max_job_bytes)
.ok_or_else(|| bad(command, "environment job exceeds per-job memory limit"))?;
admission.preparation_bytes =
admission.preparation_bytes.checked_add(environment_bytes).ok_or_else(|| bad(command, "environment admission overflow"))?;
}
let transparency = match input.integrator {
Integrator::Raster => "sorted_alpha_approximation",
Integrator::Raytrace if refraction => "physical_transmission",
Integrator::Raytrace => "opaque_only",
};
let reply = json!({"ignored_controls":ignored,"stage_panels":settings.stage.len(),"stage_transport":"CPU direct/specular only; no diffuse interreflection", "cpu_budget":budget,"cpu_limits":budget.limits(),"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":refraction,"dielectric_boundaries":if refraction {vec!["thin_sheet","closed_box"]} else {Vec::<&str>::new()}});
Ok(Prepared { replace: input.replace, scene, request, reply, environment, executor: resolved.executor, options: Default::default() })
Ok(Prepared {
progressive_feedback: input.progressive_feedback,
replace: input.replace,
scene,
request,
reply,
environment,
executor: resolved.executor,
options,
})
}
fn prepare_progressive(
@@ -465,6 +1132,9 @@ fn prepare_progressive(
return Err(bad(command, "progressive rendering does not accept CPU raytrace, environment or LED options"));
}
let mut input: ProgressiveStart = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
if input.progressive_feedback {
return Err(bad(command, "progressive_feedback requires CPU progressive raytracing, not GPU progressive rendering"));
}
validate_studio_weights(input.studio_weights, command)?;
if input.studio_weights.is_some() && (input.lighting.is_some() || input.environment.is_some() || saved_hdr.is_some()) {
return Err(bad(command, "studio_weights require the implicit GPU studio without environment lighting"));
@@ -615,6 +1285,10 @@ fn prepare_progressive(
return Err(bad(command, "image host is unavailable"));
}
let request = ImageRequest {
raster_punctual_lights: None,
raster_area_lights: None,
raster_exposure_ev: 0.0,
raster_lights: None,
studio_weights: validate_studio_weights(input.studio_weights, command)?,
integrator: Default::default(),
raytrace: None,
@@ -644,15 +1318,21 @@ fn prepare_progressive(
"raw_linear_accumulator_preserved":true, "output_stage":"linear_before_tone_map"
});
}
Ok(Prepared { replace: input.replace, scene, request, reply, executor: resolved.executor, options, environment: None })
Ok(Prepared {
progressive_feedback: false,
replace: input.replace,
scene,
request,
reply,
executor: resolved.executor,
options,
environment: None,
})
}
/// The setup's controls the raster image executor doesn't apply: those not at their neutral value.
/// Nonneutral environment controls the Raster image executor still cannot apply.
fn ignored_controls(settings: &RenderSetup) -> Vec<&'static str> {
let mut ignored = Vec::new();
if settings.exposure_ev != 0.0 {
ignored.push("exposure_ev");
}
if settings.environment_rotation != 0.0 {
ignored.push("environment_rotation");
}
@@ -668,16 +1348,13 @@ pub(super) fn preflight(s: &mut Session, params: &Value) -> Result<Value> {
pub(super) fn start(s: &mut Session, params: &Value) -> Result<Value> {
let p = prepare(s, params, "render.start")?;
let status = s
.render_jobs
.start_with_environment(
s.revision,
p.scene,
p.request,
p.replace,
crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment },
)
.map_err(job_error)?;
let execution = crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment };
let status = if p.progressive_feedback {
s.render_jobs.start_with_environment_and_feedback(s.revision, p.scene, p.request, p.replace, execution, true)
} else {
s.render_jobs.start_with_environment(s.revision, p.scene, p.request, p.replace, execution)
}
.map_err(job_error)?;
let mut status = json!(status);
if let (Some(out), Some(ignored)) = (status.as_object_mut(), p.reply.get("ignored_controls")) {
out.insert("ignored_controls".into(), ignored.clone());
@@ -807,3 +1484,54 @@ fn validate_studio_weights(weights: Option<[f64; 3]>, command: &str) -> Result<O
}
Ok(weights)
}
#[cfg(test)]
mod directional_shadow_guard_tests {
use super::*;
fn wire() -> Value {
json!({"integrator":"raytrace","settings":{"width":1,"height":1,"job":null},
"raytrace":{"directional_shadow_transmission":true,"shadows":true,"lights":[],
"dielectrics":[{"body_index":0,"body_name":"guard-only target","boundary":"thin_sheet",
"ior":1.0,"absorption_per_mm":[0.0,0.0,0.0],"thickness_mm":1.0}]}})
}
#[test]
fn interactive_lowering_preserves_real_directional_mode_without_selecting_it_by_default() {
for enabled in [false, true] {
let mut input = wire();
input["raytrace"]["directional_shadow_transmission"] = json!(enabled);
let lowered = interactive_params(&input).unwrap();
let after: Start = serde_json::from_value(lowered.clone()).unwrap();
assert_eq!(after.raytrace.unwrap().directional_shadow_transmission, enabled);
assert_eq!(lowered["raytrace"].get("directional_shadow_transmission").and_then(Value::as_bool), enabled.then_some(true));
}
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn directional_context_refusals_precede_unopened_hdr_and_product_capture() {
let mut session = Session::default();
let host = solidcraft_render::job::CpuHost::for_platform().unwrap();
session.set_render_job_host(Some(host)).unwrap();
for nested in [false, true] {
let mut input = wire();
if nested {
input["nested_media"] = json!(true);
} else {
input["environment"] = json!({"path":"must-not-open-original-directional.hdr","samples":4});
}
let error = prepare(&session, &input, "render.start").err().unwrap().to_string();
assert!(
error.contains(if nested {
"directional shadow transmission does not support nested media"
} else {
"directional shadow transmission does not support HDR environments"
}),
"{error}"
);
assert!(!error.contains("could not read"));
assert_eq!(session.render_job_host().unwrap().admitted_bytes(), 0);
}
}
}
+167 -146
View File
@@ -1,146 +1,167 @@
//! Read-only light inspection. No host, geometry evaluation, camera or design mutation.
use serde_json::Value;
use solidcraft_doc::render_settings::{RenderSettings, RenderSetup};
use crate::params::bad;
use crate::schema::render_lights::{EditParams, EditResult, Geometry, Light};
use crate::schema::render_lights::{ListParams, ListResult};
use crate::{Result, Session};
pub(super) fn list(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.lights.list";
if !params.is_object() {
return Err(bad(cmd, "expected an object"));
}
let request: ListParams = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
if params.get("setup").is_some_and(Value::is_null) || params.get("settings").is_some_and(Value::is_null) {
return Err(bad(cmd, "setup and settings cannot be null"));
}
let setup = match (request.setup, request.settings) {
(Some(_), Some(_)) => return Err(bad(cmd, "choose setup or settings, not both")),
(Some(name), None) => {
RenderSettings::validate_name(&name).map_err(|e| bad(cmd, e.to_string()))?;
s.doc.render.setups.get(&name).cloned().ok_or_else(|| bad(cmd, "no saved render setup with that name"))?
}
(None, Some(settings)) => {
if !settings.is_object() {
return Err(bad(cmd, "settings must be an object"));
}
serde_json::from_value(settings).map_err(|e| bad(cmd, e.to_string()))?
}
(None, None) => RenderSetup::default(),
};
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
serde_json::to_value(ListResult { lights: crate::render_lights::inspect(&setup).map_err(|e| bad(cmd, e))? }).map_err(|e| bad(cmd, e.to_string()))
}
fn change(s: &mut Session, params: &Value, operation: &str) -> Result<Value> {
let command = format!("render.lights.{operation}");
if !params.is_object() {
return Err(bad(&command, "expected an object"));
}
let input: EditParams = serde_json::from_value(params.clone()).map_err(|e| bad(&command, e.to_string()))?;
RenderSettings::validate_name(&input.name).map_err(|e| bad(&command, e.to_string()))?;
if input.expected_revision.is_some_and(|revision| revision != s.revision) {
return Err(bad(&command, "light settings changed; refresh before editing"));
}
let mut setup = match input.settings {
Some(value) if value.is_object() => serde_json::from_value::<RenderSetup>(value).map_err(|e| bad(&command, e.to_string()))?,
Some(_) => return Err(bad(&command, "settings must be an object")),
None => s.doc.render.setups.get(&input.name).cloned().unwrap_or_default(),
};
let mut lights = crate::render_lights::inspect(&setup).map_err(|e| bad(&command, e))?;
let target = [setup.camera.target.x, setup.camera.target.y, setup.camera.target.z];
let mut selected = None;
match operation {
"add" => {
if input.id.is_some() {
return Err(bad(&command, "add does not accept an id"));
}
let mut patch = input.set.unwrap_or_default();
if patch.kind.is_none() {
patch.kind = Some("area".into());
}
let [x, y, z] = target;
let mut light = Light {
id: String::new(),
name: String::new(),
name_key: String::new(),
number: 0,
implicit: false,
intensity: 1.0,
colour: [1.0; 3],
geometry: Geometry::Area { position_mm: [x, y - 100.0, z + 100.0], edge_u_mm: [10.0, 0.0, 0.0], edge_v_mm: [0.0, -10.0, 0.0] },
};
crate::render_lights::patch(&mut light, &patch, target, setup.camera.distance).map_err(|e| bad(&command, e))?;
lights.push(light);
selected = lights.len().checked_sub(1);
}
"set" | "duplicate" | "remove" => {
let id = input.id.as_deref().ok_or_else(|| bad(&command, "id is required"))?;
crate::render_lights::parse_id(id).map_err(|e| bad(&command, e))?;
let index = lights.iter().position(|light| light.id == id).ok_or_else(|| bad(&command, "light no longer exists"))?;
if operation == "remove" {
if input.set.is_some() {
return Err(bad(&command, "remove does not accept set"));
}
lights.retain(|light| light.id != id);
} else if operation == "duplicate" {
if input.set.is_some() {
return Err(bad(&command, "duplicate does not accept set"));
}
let light = lights.get(index).cloned().ok_or_else(|| bad(&command, "missing light"))?;
lights.push(light);
selected = lights.len().checked_sub(1);
} else {
let patch = input.set.ok_or_else(|| bad(&command, "set is required"))?;
let light = lights.get_mut(index).ok_or_else(|| bad(&command, "missing light"))?;
if matches!(setup.job, Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { .. }))
&& light.geometry.kind() == "directional"
&& patch.softness.is_some()
{
return Err(bad(&command, "CPU directional lights have hard shadows; softness is not supported"));
}
crate::render_lights::patch(light, &patch, target, setup.camera.distance).map_err(|e| bad(&command, e))?;
selected = Some(index);
}
}
_ => return Err(bad(&command, "unknown light operation")),
}
let id = selected.and_then(|index| {
lights.get(index).map(|light| {
let kind = light.geometry.kind();
let slot = lights
.iter()
.take(index)
.filter(|prior| {
if matches!(kind, "point" | "spot") { matches!(prior.geometry.kind(), "point" | "spot") } else { prior.geometry.kind() == kind }
})
.count();
format!("{kind}:{slot}")
})
});
crate::render_lights::write(&mut setup, &lights).map_err(|e| bad(&command, e))?;
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()))?;
if *s.doc.render != settings {
s.doc_mut().render = std::sync::Arc::new(settings);
}
serde_json::to_value(EditResult { id, name: input.name, setup: serde_json::to_value(setup).map_err(|e| bad(&command, e.to_string()))? })
.map_err(|e| bad(&command, e.to_string()))
}
pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "set")
}
pub(super) fn add(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "add")
}
pub(super) fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "duplicate")
}
pub(super) fn remove(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "remove")
}
//! Read-only light inspection. No host, geometry evaluation, camera or design mutation.
use serde_json::Value;
use solidcraft_doc::render_settings::{RenderSettings, RenderSetup};
use crate::params::bad;
use crate::schema::render_lights::{EditParams, EditResult, Geometry, Light};
use crate::schema::render_lights::{ListParams, ListResult};
use crate::{Result, Session};
pub(super) fn list(s: &mut Session, params: &Value) -> Result<Value> {
let cmd = "render.lights.list";
if let Some(settings) = params.get("settings") {
super::validate_saved_raster_lights(settings, cmd)?;
}
if !params.is_object() {
return Err(bad(cmd, "expected an object"));
}
let request: ListParams = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?;
if params.get("setup").is_some_and(Value::is_null) || params.get("settings").is_some_and(Value::is_null) {
return Err(bad(cmd, "setup and settings cannot be null"));
}
let setup = match (request.setup, request.settings) {
(Some(_), Some(_)) => return Err(bad(cmd, "choose setup or settings, not both")),
(Some(name), None) => {
RenderSettings::validate_name(&name).map_err(|e| bad(cmd, e.to_string()))?;
let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad(cmd, "no saved render setup with that name"))?;
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
setup.clone()
}
(None, Some(settings)) => {
if !settings.is_object() {
return Err(bad(cmd, "settings must be an object"));
}
serde_json::from_value(settings).map_err(|e| bad(cmd, e.to_string()))?
}
(None, None) => RenderSetup::default(),
};
setup.validate().map_err(|e| bad(cmd, e.to_string()))?;
serde_json::to_value(ListResult { lights: crate::render_lights::inspect(&setup).map_err(|e| bad(cmd, e))? }).map_err(|e| bad(cmd, e.to_string()))
}
fn change(s: &mut Session, params: &Value, operation: &str) -> Result<Value> {
let command = format!("render.lights.{operation}");
if let Some(settings) = params.get("settings") {
super::validate_saved_raster_lights(settings, &command)?;
}
if !params.is_object() {
return Err(bad(&command, "expected an object"));
}
let input: EditParams = serde_json::from_value(params.clone()).map_err(|e| bad(&command, e.to_string()))?;
RenderSettings::validate_name(&input.name).map_err(|e| bad(&command, e.to_string()))?;
if input.expected_revision.is_some_and(|revision| revision != s.revision) {
return Err(bad(&command, "light settings changed; refresh before editing"));
}
let mut setup = match input.settings {
Some(value) if value.is_object() => serde_json::from_value::<RenderSetup>(value).map_err(|e| bad(&command, e.to_string()))?,
Some(_) => return Err(bad(&command, "settings must be an object")),
None => {
if let Some(setup) = s.doc.render.setups.get(&input.name) {
setup.validate().map_err(|e| bad(&command, e.to_string()))?;
}
s.doc.render.setups.get(&input.name).cloned().unwrap_or_default()
}
};
let mut lights = crate::render_lights::inspect(&setup).map_err(|e| bad(&command, e))?;
if matches!(&setup.job, Some(solidcraft_doc::render_settings::RenderJob::Raster { .. })) {
if matches!(operation, "add" | "duplicate") && lights.len() == 8 {
return Err(bad(&command, "at most eight saved Raster directional lights"));
}
if let Some(patch) = &input.set {
crate::render_lights::validate_raster_patch(patch).map_err(|e| bad(&command, e))?;
}
}
let target = [setup.camera.target.x, setup.camera.target.y, setup.camera.target.z];
let mut selected = None;
match operation {
"add" => {
if input.id.is_some() {
return Err(bad(&command, "add does not accept an id"));
}
let mut patch = input.set.unwrap_or_default();
if patch.kind.is_none() {
patch.kind = Some("area".into());
}
let [x, y, z] = target;
let mut light = Light {
id: String::new(),
name: String::new(),
name_key: String::new(),
number: 0,
implicit: false,
intensity: 1.0,
colour: [1.0; 3],
geometry: Geometry::Area { position_mm: [x, y - 100.0, z + 100.0], edge_u_mm: [10.0, 0.0, 0.0], edge_v_mm: [0.0, -10.0, 0.0] },
};
crate::render_lights::patch(&mut light, &patch, target, setup.camera.distance).map_err(|e| bad(&command, e))?;
lights.push(light);
selected = lights.len().checked_sub(1);
}
"set" | "duplicate" | "remove" => {
let id = input.id.as_deref().ok_or_else(|| bad(&command, "id is required"))?;
crate::render_lights::parse_id(id).map_err(|e| bad(&command, e))?;
let index = lights.iter().position(|light| light.id == id).ok_or_else(|| bad(&command, "light no longer exists"))?;
if operation == "remove" {
if input.set.is_some() {
return Err(bad(&command, "remove does not accept set"));
}
lights.retain(|light| light.id != id);
} else if operation == "duplicate" {
if input.set.is_some() {
return Err(bad(&command, "duplicate does not accept set"));
}
let light = lights.get(index).cloned().ok_or_else(|| bad(&command, "missing light"))?;
lights.push(light);
selected = lights.len().checked_sub(1);
} else {
let patch = input.set.ok_or_else(|| bad(&command, "set is required"))?;
let light = lights.get_mut(index).ok_or_else(|| bad(&command, "missing light"))?;
if matches!(setup.job, Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { .. }))
&& light.geometry.kind() == "directional"
&& patch.softness.is_some()
{
return Err(bad(&command, "CPU directional lights have hard shadows; softness is not supported"));
}
crate::render_lights::patch(light, &patch, target, setup.camera.distance).map_err(|e| bad(&command, e))?;
selected = Some(index);
}
}
_ => return Err(bad(&command, "unknown light operation")),
}
let id = selected.and_then(|index| {
lights.get(index).map(|light| {
let kind = light.geometry.kind();
let slot = lights
.iter()
.take(index)
.filter(|prior| {
if matches!(kind, "point" | "spot") { matches!(prior.geometry.kind(), "point" | "spot") } else { prior.geometry.kind() == kind }
})
.count();
format!("{kind}:{slot}")
})
});
crate::render_lights::write(&mut setup, &lights).map_err(|e| bad(&command, e))?;
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()))?;
if *s.doc.render != settings {
s.doc_mut().render = std::sync::Arc::new(settings);
}
serde_json::to_value(EditResult { id, name: input.name, setup: serde_json::to_value(setup).map_err(|e| bad(&command, e.to_string()))? })
.map_err(|e| bad(&command, e.to_string()))
}
pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "set")
}
pub(super) fn add(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "add")
}
pub(super) fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "duplicate")
}
pub(super) fn remove(s: &mut Session, p: &Value) -> Result<Value> {
change(s, p, "remove")
}
+89 -2
View File
@@ -1,6 +1,93 @@
use super::*;
use solidcraft_doc::render_settings::RenderJob;
#[test]
fn offline_raster_directional_edit_persists_with_one_undo_and_exact_reopen() {
let mut s = Session::default();
save(&mut s, json!({"width":16,"height":16,"job":{"method":"raster"}}));
let before = s.doc.clone();
let undo = s.undo.len();
let reply = s
.execute(
"render.lights.set",
&json!({"name":"Studio","id":"directional:0","expected_revision":s.revision,
"set":{"direction":[3,-4,0],"colour":[0.25,0.5,1],"intensity_ev":1}}),
)
.unwrap();
assert_eq!(reply["setup"]["job"]["method"], "raster");
let light = &reply["setup"]["job"]["lights"][0];
assert_eq!(light["direction"][0].as_f64().unwrap(), 3.0);
assert_eq!(light["direction"][1].as_f64().unwrap(), -4.0);
assert_eq!(light["intensity"].as_f64().unwrap(), 2.0);
assert_eq!(reply["setup"]["job"]["lights"].as_array().unwrap().len(), 3);
assert_eq!(s.undo.len(), undo + 1);
let after = s.doc.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc, after);
let loaded = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(loaded.render, s.doc.render);
let listed = s.execute("render.lights.list", &json!({"setup":"Studio"})).unwrap();
assert_eq!(listed["lights"][0]["implicit"], false);
assert_eq!(listed["lights"][0]["direction"][0].as_f64().unwrap(), 3.0);
}
#[test]
fn saved_raster_remove_all_and_visibility_preserve_explicit_darkness_and_authored_values() {
let mut s = Session::default();
save(&mut s, json!({"job":{"method":"raster","lights":[{"direction":[0,0,1],"color":[0.25,0.5,1],"intensity":2}]}}));
let authored = s.doc.render.setups["Studio"].clone();
let mut filtered = authored.clone();
let visibility = crate::schema::render_lights::Visibility { solo: None, muted: ["directional:0".into()].into_iter().collect() };
assert_eq!(crate::render_lights::filter(&mut filtered, &visibility).unwrap(), None);
let Some(RenderJob::Raster { lights: Some(lights), .. }) = &filtered.job else { panic!("lost rig") };
assert_eq!(lights[0].intensity, 0.0);
assert_eq!(s.doc.render.setups["Studio"], authored);
s.execute("render.lights.remove", &json!({"name":"Studio","id":"directional:0"})).unwrap();
let Some(RenderJob::Raster { lights: Some(lights), .. }) = &s.doc.render.setups["Studio"].job else { panic!("empty rig became legacy") };
assert!(lights.is_empty());
let loaded = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
assert_eq!(loaded.render, s.doc.render);
assert_eq!(s.execute("render.lights.list", &json!({"setup":"Studio"})).unwrap()["lights"], json!([]));
}
#[test]
fn saved_raster_unsupported_families_and_controls_refuse_atomically() {
let mut s = Session::default();
save(&mut s, json!({"job":{"method":"raster"}}));
let before = s.doc.clone();
let state = (s.revision, s.undo.len(), s.redo.len());
for patch in [
json!({"kind":"point"}),
json!({"kind":"spot"}),
json!({"kind":"area"}),
json!({"softness":0}),
json!({"intensity_ev":7}),
json!({"distance_mm":10}),
json!({"radiance":[1,1,1]}),
json!({"direction":[0,0,1],"azimuth_deg":0}),
] {
assert!(s.execute("render.lights.set", &json!({"name":"Studio","id":"directional:0","set":patch})).is_err());
assert!(Arc::ptr_eq(&before, &s.doc));
assert_eq!(state, (s.revision, s.undo.len(), s.redo.len()));
}
}
#[test]
fn saved_raster_array_is_bounded_before_settings_merge_and_inline_light_edit() {
let mut s = Session::default();
save(&mut s, json!({"job":{"method":"raster"}}));
let before = s.doc.clone();
let light = json!({"direction":[0,0,1],"color":[1,1,1],"intensity":1});
let invalid = json!({"job":{"method":"raster","lights":vec![light;9]}});
assert!(s.execute("render.settings.set", &json!({"name":"Studio","set":invalid})).is_err());
assert!(s.execute("render.lights.set", &json!({"name":"Studio","id":"directional:0","settings":invalid,"set":{"intensity_ev":1}})).is_err());
assert!(s.execute("render.lights.list", &json!({"settings":invalid})).is_err());
assert!(Arc::ptr_eq(&before, &s.doc));
// The small refusal fixture is not an OOM test; source order proves pre-copy admission.
}
fn save(s: &mut Session, patch: Value) {
s.execute("render.settings.set", &json!({"name":"Studio", "set":patch})).unwrap();
}
@@ -625,7 +712,7 @@ fn embedded_hdr_capture_rejects_parameters_scope_and_cpu_primaries_without_mutat
assert_eq!(state, (s.revision, s.undo.len(), s.redo.len()));
}
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-hdr-scope-{}-{nonce}", std::process::id()));
let dir = std::env::temp_dir().join(format!("solidcraft-hdr-scope-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let allowed = dir.join("allowed");
std::fs::create_dir(&allowed).unwrap();
@@ -725,7 +812,7 @@ fn invalid_saved_jobs_never_partially_replace_a_setup() {
json!({"job":{"method":"gpu_path","options":{"samples":4097}}}),
json!({"job":{"method":"cpu_raytrace","options":{"emissions":[]}}}),
json!({"job":{"method":"gpu_path","options":{"environment":{"kind":"hdr","path":"not-opened.hdr"}}}}),
json!({"job":{"method":"raster"}}),
json!({"job":{"method":"raster"},"exposure_ev":33}),
json!({"job":{"method":"gpu_path"},"environment_intensity":2}),
json!({"job":{"options":{"samples":4}}}),
] {
+127 -1
View File
@@ -1,7 +1,10 @@
//! Planned Render interactions, with explicit non-mutating refusals.
use super::CommandSpec;
use crate::schema::render_lights::{MuteParams, SoloParams};
use crate::schema::{TypedContract, output_schema_for, render_ui::CheckReport};
use crate::schema::{
TypedContract, output_schema_for,
render_ui::{CheckReport, InteractiveParams},
};
use crate::{Result, Session, params::bad};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -48,8 +51,16 @@ macro_rules! waiting {
}
const CHECK_REPORT: TypedContract<CheckReport> = TypedContract::new();
const INTERACTIVE: TypedContract<InteractiveParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.interactive", "Interactive Render", crate::checked!("render.interactive", interactive))
.icon("render_image")
.contract(&INTERACTIVE)
.output(output_schema_for::<InteractiveParams>)
.noundo()
.doc_only()
.params("action: on|off|pause|resume. Validates and echoes an explicit CPU Interactive preview request for the UI adapter. Headless calls never start, pause or cancel a render job, open UI, or change the design, final render settings or exportable images."),
CommandSpec::new("render.preflight.copy", "Copy Render Check Report", crate::checked!("render.preflight.copy", copy_check))
.icon("copy")
.contract(&CHECK_REPORT)
@@ -210,3 +221,118 @@ fn output_sections_copy_report_validates_without_design_history_or_job_changes()
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
}
/// The UI adapter owns provisional preview actions; headless execution only echoes.
fn interactive(_: &mut Session, params: &Value) -> Result<Value> {
let command = "render.interactive";
if !params.is_object() {
return Err(bad(command, "expected an object"));
}
let request: InteractiveParams = serde_json::from_value(params.clone()).map_err(|error| bad(command, error.to_string()))?;
serde_json::to_value(request).map_err(|error| bad(command, error.to_string()))
}
#[cfg(test)]
#[test]
fn interactive_contract_describes_exact_actions_and_a_nonmutating_echo() {
use crate::schema::{input_schema_for, render_ui::Action};
let command = super::find_command("render.interactive").unwrap();
assert!(!command.undoable);
assert!(!command.reads_model);
assert!(command.planned.is_none());
assert_eq!(command.icon, "render_image");
let contract = command.contract.unwrap();
assert_eq!(contract.allowed_keys().iter().map(String::as_str).collect::<Vec<_>>(), ["action"]);
assert!(command.output.is_some());
let action_schema = serde_json::to_value(input_schema_for::<Action>()).unwrap();
assert_eq!(action_schema["enum"], json!(["on", "off", "pause", "resume"]));
let request_schema = serde_json::to_value(input_schema_for::<InteractiveParams>()).unwrap();
assert_eq!(request_schema["additionalProperties"], false);
assert_eq!(request_schema["required"], json!(["action"]));
let reply_schema = serde_json::to_value(output_schema_for::<InteractiveParams>()).unwrap();
assert_eq!(reply_schema["required"], json!(["action"]));
assert_eq!(reply_schema["properties"].as_object().unwrap().keys().map(String::as_str).collect::<Vec<_>>(), ["action"]);
}
#[cfg(test)]
#[test]
fn interactive_valid_and_hostile_requests_preserve_headless_document_history_and_host() {
use crate::schema::ParamCheck;
let mut session = Session::default();
session.execute("render.settings.set", &json!({"name":"Original","set":{"width":800}})).unwrap();
session.execute("render.settings.set", &json!({"name":"Original","set":{"width":900}})).unwrap();
session.execute("edit.undo", &json!({})).unwrap();
let document = session.doc.clone();
let before = (session.revision, session.undo.len(), session.redo.len(), session.evaluations, session.is_dirty());
assert!(session.render_job_host().is_none());
for level in [ParamCheck::Off, ParamCheck::Warn, ParamCheck::Strict] {
session.param_check = level;
for action in ["on", "off", "pause", "resume"] {
let params = json!({"action":action});
assert_eq!(session.execute("render.interactive", &params).unwrap(), params);
}
for hostile in [
json!(null),
json!(true),
json!(0),
json!("on"),
json!([]),
json!(["on"]),
json!({}),
json!({"action":null}),
json!({"action":true}),
json!({"action":1e300}),
json!({"action":["on"]}),
json!({"action":{"on":true}}),
json!({"action":"start"}),
json!({"action":"On"}),
json!({"action":" on"}),
json!({"action":"on\n"}),
json!({"action":"x".repeat(65536)}),
json!({"action":"on","slot":0}),
json!({"action":"off","job":{"session":1,"serial":1,"generation":1}}),
json!({"action":"pause","replace":true}),
json!({"action":"resume","settings":{}}),
json!({"action":"on","path":"must-not-be-read.hdr"}),
] {
assert!(session.execute("render.interactive", &hostile).is_err(), "{level:?}: {hostile}");
}
assert!(std::sync::Arc::ptr_eq(&document, &session.doc));
assert_eq!(before, (session.revision, session.undo.len(), session.redo.len(), session.evaluations, session.is_dirty()));
assert!(session.render_job_host().is_none());
}
}
#[cfg(test)]
#[test]
fn interactive_echo_preserves_a_queued_final_job_and_its_resource_lease() {
use solidcraft_render::job::{CpuHost, JobId};
let host = CpuHost::cooperative();
let mut session = Session::default();
session.set_render_job_host(Some(host.clone())).unwrap();
// Queue a tiny raster job without pumping the cooperative host or opening a device.
let started = session.execute("render.start", &json!({"settings":{"width":16,"height":16}})).unwrap();
let first_id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let first = session.render_job_handle(first_id).unwrap();
let status = serde_json::to_value(first.status().unwrap()).unwrap();
let admitted = host.admitted_bytes();
assert!(admitted > 0);
let document = session.doc.clone();
let before = (session.revision, session.undo.len(), session.redo.len(), session.evaluations, session.is_dirty());
for action in ["on", "pause", "resume", "off"] {
let params = json!({"action":action});
assert_eq!(session.execute("render.interactive", &params).unwrap(), params);
assert_eq!(serde_json::to_value(first.status().unwrap()).unwrap(), status);
assert_eq!(host.admitted_bytes(), admitted);
assert!(session.render_job_host().unwrap().same_host(&host));
assert!(std::sync::Arc::ptr_eq(&document, &session.doc));
assert_eq!(before, (session.revision, session.undo.len(), session.redo.len(), session.evaluations, session.is_dirty()));
}
assert!(session.execute("render.interactive", &json!({"action":"off","job":first_id})).is_err());
assert_eq!(serde_json::to_value(first.status().unwrap()).unwrap(), status);
assert_eq!(host.admitted_bytes(), admitted);
let next = session.execute("render.start", &json!({"settings":{"width":16,"height":16}})).unwrap();
let next_id: JobId = serde_json::from_value(next["job"].clone()).unwrap();
assert_eq!(next_id.session, first_id.session);
assert_eq!(next_id.serial, first_id.serial + 1, "echo actions must not allocate or replace final job identities");
}
-2
View File
@@ -19,7 +19,6 @@ fn section(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.section";
if bool_(p, "clear").unwrap_or(false) {
s.section = None;
s.status_slot(crate::status_items::StatusId::Section, false);
s.revision += 1;
return Ok(json!({"section": null}));
}
@@ -76,7 +75,6 @@ fn section(s: &mut Session, p: &Value) -> Result<Value> {
let origin = origin + normal * offset * if bool_(p, "flip").unwrap_or(false) { -1.0 } else { 1.0 };
s.section = Some((origin, normal));
s.section_hatch = bool_(p, "hatch").unwrap_or(true);
s.status_slot(crate::status_items::StatusId::Section, true);
s.revision += 1;
let mut section = json!({"origin": origin, "normal": normal, "hatch": s.section_hatch});
if let Some(i) = axis {
-166
View File
@@ -1,166 +0,0 @@
//! Settings profiles (#6237): named sets of the input and interface preferences, kept by the
//! app. The engine holds no preferences, so these commands only check and echo their
//! parameters; the desktop and web apps act on the echo (`settings_profiles` in the UI crate).
//! Run without an app (CLI, scripts), they do nothing else.
use serde_json::{Map, Value, json};
use super::CommandSpec;
use crate::params::{bad, str_};
use crate::{Result, Session};
/// Most characters in a profile's name.
pub const MAX_PROFILE_NAME: usize = 64;
/// Most bytes in a path given to Export or Import.
const MAX_PATH: usize = 4096;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("settings.profile.list", "Settings Profiles", list)
.icon("list")
.noundo()
.doc_only()
.params("→ profiles: [name], active: name|null; handled by the app"),
CommandSpec::new("settings.profile.save", "Save Settings Profile", save)
.icon("save")
.noundo()
.doc_only()
.params("name: 1..64 characters → name; keeps the current input and interface settings under `name` (replacing a profile of that name) and makes it the active one"),
CommandSpec::new("settings.profile.apply", "Apply Settings Profile", apply)
.icon("settings")
.noundo()
.doc_only()
.params("name → name, applied, skipped: [preference]; switches every setting the profile holds at once"),
CommandSpec::new("settings.profile.rename", "Rename Settings Profile", rename)
.icon("rename")
.noundo()
.doc_only()
.params("name, to: 1..64 characters → name"),
CommandSpec::new("settings.profile.delete", "Delete Settings Profile", delete)
.icon("delete")
.noundo()
.doc_only()
.params("name → deleted"),
CommandSpec::new("settings.profile.export", "Export Settings Profile", export)
.icon("export")
.noundo()
.doc_only()
.params("name, path?: file → profile (a `solidcraft-profile/1` document), written to `path` when given; never opens a dialog"),
CommandSpec::new("settings.profile.import", "Import Settings Profile", import)
.icon("import")
.noundo()
.doc_only()
.params("path: file | profile: `solidcraft-profile/1` document, name?: 1..64 characters → name; adds the profile without switching to it"),
];
/// A profile name as given: trimmed, 1 to [`MAX_PROFILE_NAME`] characters, no control characters.
pub fn profile_name(name: &str) -> Option<&str> {
let name = name.trim();
(!name.is_empty() && name.chars().count() <= MAX_PROFILE_NAME && !name.chars().any(char::is_control)).then_some(name)
}
fn name_param<'a>(cmd: &str, p: &'a Value, key: &str) -> Result<&'a str> {
str_(p, key)
.and_then(profile_name)
.ok_or_else(|| bad(cmd, format!("`{key}` must be 1 to {MAX_PROFILE_NAME} characters, without control characters")))
}
fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<Option<&'a str>> {
match p.get("path") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(path)) if !path.trim().is_empty() && path.len() <= MAX_PATH => Ok(Some(path)),
Some(_) => Err(bad(cmd, format!("`path` must be a file path of at most {MAX_PATH} bytes"))),
}
}
fn list(_s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({}))
}
fn save(_s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": name_param("settings.profile.save", p, "name")? }))
}
fn apply(_s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": name_param("settings.profile.apply", p, "name")? }))
}
fn rename(_s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "settings.profile.rename";
Ok(json!({ "name": name_param(cmd, p, "name")?, "to": name_param(cmd, p, "to")? }))
}
fn delete(_s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": name_param("settings.profile.delete", p, "name")? }))
}
fn export(_s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "settings.profile.export";
let mut out = Map::new();
out.insert("name".into(), json!(name_param(cmd, p, "name")?));
if let Some(path) = path_param(cmd, p)? {
out.insert("path".into(), json!(path));
}
Ok(Value::Object(out))
}
fn import(_s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "settings.profile.import";
let mut out = Map::new();
let (key, value) = match (path_param(cmd, p)?, p.get("profile")) {
(Some(path), None) => ("path", json!(path)),
(None, Some(profile)) if profile.is_object() => ("profile", profile.clone()),
_ => return Err(bad(cmd, "give either `path` or `profile` (a `solidcraft-profile/1` document)")),
};
out.insert(key.into(), value);
if p.get("name").is_some_and(|name| !name.is_null()) {
out.insert("name".into(), json!(name_param(cmd, p, "name")?));
}
Ok(Value::Object(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn run(id: &str, p: Value) -> std::result::Result<Value, String> {
let mut s = Session::default();
s.execute(id, &p).map_err(|e| e.to_string())
}
#[test]
fn names_are_trimmed_and_bounded() {
assert_eq!(run("settings.profile.save", json!({"name":" Laptop "})).unwrap(), json!({"name":"Laptop"}));
for name in [json!(""), json!(" "), json!("a\nb"), json!("x".repeat(65)), json!(3), Value::Null] {
assert!(run("settings.profile.save", json!({ "name": name })).is_err(), "{name}");
}
assert!(run("settings.profile.save", json!({"name":"é".repeat(64)})).is_ok());
assert!(run("settings.profile.rename", json!({"name":"A"})).is_err());
}
#[test]
fn import_takes_a_path_or_a_document_but_not_both() {
assert_eq!(run("settings.profile.import", json!({"path":"/tmp/p.json"})).unwrap(), json!({"path":"/tmp/p.json"}));
let doc = json!({"format":"solidcraft-profile/1"});
assert_eq!(run("settings.profile.import", json!({"profile":doc, "name":"B"})).unwrap(), json!({"profile":doc, "name":"B"}));
assert!(run("settings.profile.import", json!({"path":"/tmp/p.json", "profile":doc})).is_err());
assert!(run("settings.profile.import", json!({"profile":"text"})).is_err());
assert!(run("settings.profile.import", json!({})).is_err());
assert!(run("settings.profile.export", json!({"name":"A", "path":"x".repeat(5000)})).is_err());
}
#[test]
fn profile_commands_leave_the_design_and_its_history_alone() {
let mut s = Session::default();
let doc = s.doc.to_json();
for (id, p) in [
("settings.profile.save", json!({"name":"A"})),
("settings.profile.apply", json!({"name":"A"})),
("settings.profile.list", json!({})),
("settings.profile.delete", json!({"name":"A"})),
] {
s.execute(id, &p).unwrap();
}
assert_eq!(s.doc.to_json(), doc);
assert!(s.undo.is_empty());
}
}
+3 -64
View File
@@ -128,7 +128,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
"entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
"entities: [refs] (a line midpoint is \"mid:line_id\"), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
),
CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)
.at("SKETCH", "CONSTRAINTS")
@@ -333,63 +333,12 @@ fn settle(strict: bool, rep: SolveReport, sk: &mut Sketch, unsolved: Sketch) ->
if strict && !rep.keeps_orientation() {
return Err(EngineError::Other(rep.failure(|f| format!("that would over-constrain the sketch (conflicts with {f})"))));
}
// A solve that throws points far beyond the sketch found a far solution of its constraints,
// not the one the edit means (a line squeezed to a point under a direction constraint, an
// angle between sides that can't take it): it counts as one that fails.
let far = flung(&unsolved, sk);
if strict && far {
return Err(EngineError::Other(
"that would throw points of the sketch far away: its constraints have no solution near the sketch as it is".into(),
));
}
// A solve that shrinks a line or circle to a point met its constraints only by squeezing
// that curve away (a corner made the midpoint of the opposite side of its rectangle).
let gone = shrunk(&unsolved, sk);
if strict && let Some(curve) = &gone {
return Err(EngineError::Other(format!("that would shrink {curve} to a point: its constraints can only be met without it")));
}
if !rep.keeps_orientation() || far || gone.is_some() {
if !rep.keeps_orientation() {
*sk = unsolved;
}
Ok(rep)
}
/// The first line or circle that solving `before` into `after` shrank to a point: longer (or
/// wider) than 1e-3 before and shorter than 1e-5 after. A length a dimension asks for is never
/// that short. 1e-6 let a side squeezed to 1.2e-6 by one solve through, and the next solve
/// took it the rest of the way.
fn shrunk(before: &Sketch, after: &Sketch) -> Option<String> {
let size = |sk: &Sketch, i: usize| match sk.curves.get(i).map(|c| &c.kind) {
Some(CurveKind::Line { .. }) => line_pts(sk, i).map(|(a, b)| a.dist(b)),
Some(CurveKind::Arc { .. } | CurveKind::Circle { .. }) => sk.radius(i),
_ => None,
};
(0..before.curves.len().min(after.curves.len()))
.find(|&i| matches!((size(before, i), size(after, i)), (Some(b), Some(a)) if b > 1e-3 && a < 1e-5))
.and_then(|i| after.curves.get(i).map(|c| c.id.clone()))
}
/// A solve moving some point further than this many times the sketch's size (and its largest
/// dimension value) has thrown the geometry to a far solution.
const FLUNG: f64 = 1000.0;
/// Did solving `before` into `after` throw some point further than [`FLUNG`] times the sketch's
/// size, or to no number at all?
fn flung(before: &Sketch, after: &Sketch) -> bool {
let (lo, hi) = before
.points
.iter()
.map(|p| p.pos)
.filter(|p| p.x.is_finite() && p.y.is_finite())
.fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
});
let size = if lo.x <= hi.x { lo.dist(hi) } else { 0.0 };
let longest = after.driving_values().values().map(|v| v.abs()).filter(|v| v.is_finite()).fold(0.0, f64::max);
let reach = FLUNG * (size + longest).max(1.0);
after.points.iter().zip(&before.points).any(|(a, b)| !(a.pos.dist(b.pos) <= reach))
}
/// The sketch solves of `edit` and drags, counted in tests (see [`solve_with`]).
pub(super) fn counted_solve(
sk: &mut Sketch,
@@ -1787,7 +1736,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
}));
let ok = solve_with(&mut trial, &h, None, Analysis::StatusOnly, None).ok();
trial.constraints.retain(|c| c.id != TEMP);
if ok && !collapsed(sk, &trial) && !flung(sk, &trial) {
if ok && !collapsed(sk, &trial) {
*sk = trial;
return Ok(());
}
@@ -1799,12 +1748,6 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
if first_movable && !second_locked {
let mut trial = sk.clone();
if solve_with(&mut trial, &Hold::default(), None, Analysis::StatusOnly, None).ok() {
if flung(sk, &trial) {
return Err(bad(cmd, "that would throw points of the sketch far away: its constraints have no solution near the sketch as it is"));
}
if let Some(curve) = shrunk(sk, &trial) {
return Err(bad(cmd, format!("that would shrink {curve} to a point: its constraints can only be met without it")));
}
*sk = trial;
return Ok(());
}
@@ -2492,10 +2435,6 @@ pub(super) fn line_pts(sk: &Sketch, l: usize) -> Option<(Vec2, Vec2)> {
fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.dimension";
// A dimension may measure model geometry (#7912): an `{edge: [x,y,z], body?}` or a
// `{vertex: [x,y,z], body?}` among its entities is projected into the sketch first, as
// `sketch.project` does, and stands for the projected curve (or point) there.
let p = &super::sketch_project::project_entities(s, p, cmd)?;
let ents = string_list(cmd, p, "entities")?;
if ents.is_empty() || ents.len() > 2 {
return Err(bad(cmd, "`entities` must list one or two sketch entities"));
@@ -1232,94 +1232,6 @@ fn coincident_refuses_a_lines_two_ends() {
run(&mut s, "sketch.constraint.coincident", json!({"a":"l1.end","b":"l2.end"}));
}
/// A constraint whose solve finds only a far solution is not allowed to throw points far away:
/// the held solve is tried without it, or the constraint is refused. Here a centre that is
/// already the midpoint of two lines is made the midpoint of a third, and the solve threw two
/// line ends to x = -2.2e8 mm while the sketch said solved (found by a local sketch fuzzer).
#[test]
fn a_constraint_never_throws_the_sketch_far_away() {
let mut s = Session::default();
for (id, p) in [
("sketch.create", json!({"plane": "XY"})),
("sketch.arc.three_point", json!({"end": [-15, 6], "start": [-24, -21], "through": [-12, -1]})),
("sketch.arc.three_point", json!({"end": [-18, -27], "start": [3, 13], "through": [22, 21]})),
("sketch.dimension", json!({"entities": ["a1.start", "a2.center"], "value": 29})),
("sketch.dimension", json!({"entities": ["a2.end", "a1.start"], "value": 38})),
("sketch.circle.center", json!({"center": [-23, -10], "radius": 7})),
("sketch.constraint.coincident", json!({"a": "a2.start", "b": "a1.end"})),
("sketch.rectangle.two_point", json!({"p0": [22, -9], "p1": [19, -10]})),
("sketch.line", json!({"ids": ["l16"], "points": [[-14, -29], [-5, 5]]})),
("sketch.circle.center", json!({"center": [-14, 19], "radius": 14})),
("sketch.constraint.fix", json!({"entity": "c1.center"})),
("sketch.rectangle.two_point", json!({"p0": [-10, 23], "p1": [16, 13]})),
("sketch.line", json!({"ids": ["l22"], "points": [[-8, 21], [25, 14]]})),
("sketch.circle.center", json!({"center": [6, 10], "radius": 10})),
("sketch.circle.center", json!({"center": [8, -12], "radius": 11})),
("sketch.rectangle.two_point", json!({"p0": [-4, -7], "p1": [-5, -27]})),
("sketch.constraint.concentric", json!({"a": "a1", "b": "c4"})),
("sketch.rectangle.two_point", json!({"p0": [-12, -14], "p1": [-1, -17]})),
("sketch.constraint.midpoint", json!({"line": "l12", "point": "c4.center"})),
("sketch.constraint.midpoint", json!({"line": "l14", "point": "c4.center"})),
("sketch.rectangle.two_point", json!({"p0": [23, 22], "p1": [-28, 8]})),
("sketch.constraint.fix", json!({"entity": "p15"})),
("sketch.dimension", json!({"entities": ["p17", "a1.start"], "value": 35})),
("sketch.constraint.coincident", json!({"a": "p19", "b": "p12"})),
("sketch.constraint.tangent", json!({"a": "c1", "b": "l11"})),
("sketch.line", json!({"closed": true, "points": [[8, -29], [-5, 24], [-9, -6], [26, -8]]})),
("sketch.constraint.perpendicular", json!({"a": "l15", "b": "l17"})),
("sketch.dimension", json!({"entities": ["l12"], "value": 13})),
("sketch.dimension", json!({"entities": ["l26", "l17"], "type": "angle", "value": 14})),
("sketch.constraint.fix", json!({"entity": "p18"})),
("sketch.constraint.tangent", json!({"a": "l23", "b": "c4"})),
("sketch.constraint.coincident", json!({"a": "origin", "b": "l23.start"})),
("sketch.constraint.midpoint", json!({"line": "l18", "point": "c4.center"})),
] {
let _ = s.execute(id, &p);
}
let sk = sketch(&s);
let far = sk.points.iter().map(|p| p.pos.len()).fold(0.0_f64, f64::max);
assert!(far < 1e4, "a point went {far} mm away");
}
/// A constraint that can only be met by shrinking curves to a point is refused, as one that
/// throws the sketch far away is: making a rectangle's corner the midpoint of the opposite side,
/// or two opposite corners coincident, squeezed the whole rectangle to a point while the sketch
/// said solved (found by a local sketch fuzzer).
#[test]
fn a_constraint_that_would_shrink_a_rectangle_to_a_point_is_refused() {
for (id, p) in
[("sketch.constraint.midpoint", json!({"line": "l4", "point": "p2"})), ("sketch.constraint.coincident", json!({"a": "p1", "b": "p3"}))]
{
let mut s = new_sketch();
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-30, 4], "p1": [11, 27]}));
let before = sketch(&s);
let e = s.execute(id, &p).unwrap_err().to_string();
assert!(e.contains("shrink") && e.contains("to a point"), "{id} {p}: {e}");
assert_eq!(sketch(&s), before, "{id} {p}");
}
}
/// Two rectangles, a corner of one made coincident with a corner of the other and then a second
/// pair of corners made coincident: one solve squeezed a 49 mm side to about 1.2e-6 mm, just
/// longer than the check took for a point, and the next took it the rest of the way, so the
/// constraint was taken (found by a local sketch fuzzer).
#[test]
fn a_constraint_that_squeezes_a_side_to_a_hair_is_refused() {
let mut s = new_sketch();
for (id, p) in [
("sketch.rectangle.two_point", json!({"p0": [27, 29], "p1": [1, 19]})),
("sketch.rectangle.two_point", json!({"p0": [23, -8], "p1": [-21, -20]})),
("sketch.constraint.perpendicular", json!({"a": "l5", "b": "l4"})),
("sketch.constraint.coincident", json!({"a": "p5", "b": "p1"})),
] {
run(&mut s, id, p);
}
let before = sketch(&s);
let e = s.execute("sketch.constraint.coincident", &json!({"a": "p6", "b": "p3"})).unwrap_err().to_string();
assert!(e.contains("shrink") && e.contains("to a point"), "{e}");
assert_eq!(sketch(&s), before);
}
#[test]
fn coincident_circles_lie_on_each_other() {
let mut s = new_sketch();
-159
View File
@@ -1,159 +0,0 @@
//! Equation curves (#8352): a sketch curve drawn from formulas, x(t) and y(t) over a range of t
//! or y = f(x) over a range of x, in the design's expression language and parameters. The curve
//! is a fit point spline through points worked out from the formulas, as many as keep it within
//! a tolerance of them; it keeps its formulas, so it follows the parameters and can be edited.
use serde_json::{Value, json};
use solidcraft_doc::sketch_equation::{self, DEFAULT_TOLERANCE, EquationFit};
use solidcraft_sketch::{EquationCurve, Sketch};
use super::sketch::{edit, mark_construction};
use super::{CommandSpec, in_sketch};
use crate::params::bad;
use crate::schema::sketch_equation::{EquationCurveParams, EquationCurveResult, EquationEditParams, EquationEditResult};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
#[cfg(test)]
#[path = "sketch_equation_tests.rs"]
mod tests;
const CREATE_CONTRACT: TypedContract<EquationCurveParams> = TypedContract::new();
const EDIT_CONTRACT: TypedContract<EquationEditParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.equation_curve", "Equation Curve", crate::checked!("sketch.equation_curve", create))
.at("SKETCH", "CREATE")
.icon("equation_curve")
.enabled(in_sketch)
.contract(&CREATE_CONTRACT)
.output(output_schema_for::<EquationCurveResult>)
.params(concat!(
"x: x(t), y: y(t): formulas of t in the design's expression language and parameters (\"r * (cos(t) + t * sin(t))\"); or explicit: true and y: f(x) alone (no x); \
start, end: the range of t (or of x): a number or an expression (\"2 * pi\", \"360 deg\" is 2·pi, a length is in the design's unit); \
tolerance?: mm (default 0.01): how far the curve may stray from the formulas (0.0001 to 10); construction?: bool. \
The variable is a plain number: sin(t) reads it in radians; a result without a unit is in the design's length unit. \
Makes a fit point spline through fixed points, as many as the tolerance needs (up to 500), closed smoothly when it ends where it starts; \
the points are placed again from the formulas whenever the parameters change. Returns curve, points (how many), closed, deviation (mm)",
created_doc!()
)),
CommandSpec::new("sketch.equation_curve.edit", "Edit Equation Curve", crate::checked!("sketch.equation_curve.edit", edit_curve))
.icon("equation_curve")
.enabled(in_sketch)
.contract(&EDIT_CONTRACT)
.output(output_schema_for::<EquationEditResult>)
.params(
"curve: an equation curve's id; x?, y?, explicit?, start?, end?, tolerance?: as in sketch.equation_curve, each kept when left out (explicit: true drops x; false needs x). \
The points are chosen again for the new formulas; the curve's start point (and the end point of an open curve) keeps its id, so geometry joined there stays joined. Returns curve, points, closed, deviation",
),
];
/// A formula or range parameter: a string (an expression) or a number.
fn text(p: &Value, cmd: &str, key: &str) -> Result<Option<String>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(s.trim().to_string())),
Some(Value::Number(n)) => n
.as_f64()
.and_then(crate::params::finite)
.map(|v| Some(format!("{v}")))
.ok_or_else(|| bad(cmd, format!("`{key}` must be a finite number"))),
Some(_) => Err(bad(cmd, format!("`{key}` must be a formula (a string) or a number"))),
}
}
fn tolerance(p: &Value, cmd: &str) -> Result<Option<f64>> {
match p.get("tolerance") {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_f64()
.filter(|t| t.is_finite() && (sketch_equation::MIN_TOLERANCE..=sketch_equation::MAX_TOLERANCE).contains(t))
.map(Some)
.ok_or_else(|| bad(cmd, "`tolerance` must be a number of mm from 0.0001 to 10")),
}
}
fn explicit(p: &Value, cmd: &str) -> Result<Option<bool>> {
match p.get("explicit") {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(_) => Err(bad(cmd, "`explicit` must be true or false")),
}
}
/// The equation a command's parameters give, over `old` (each left out kept).
fn equation(p: &Value, cmd: &str, old: Option<&EquationCurve>) -> Result<EquationCurve> {
let x = text(p, cmd, "x")?;
let explicit = explicit(p, cmd)?;
let x = match (explicit, x) {
(Some(true), Some(_)) => return Err(bad(cmd, "an explicit curve takes y = f(x) alone: leave out `x`")),
(Some(true), None) => None,
(_, Some(x)) => Some(x),
(Some(false), None) => match old.and_then(|o| o.x.clone()) {
Some(x) => Some(x),
None => return Err(bad(cmd, "a parametric curve needs `x`, a formula of t")),
},
(None, None) => match old {
Some(o) => o.x.clone(),
None => return Err(bad(cmd, "needs `x` and `y` (formulas of t), or explicit: true and `y` (a formula of x)")),
},
};
let pick = |key: &str, kept: Option<&String>| -> Result<String> {
match text(p, cmd, key)? {
Some(v) => Ok(v),
None => kept.cloned().ok_or_else(|| bad(cmd, format!("missing `{key}`"))),
}
};
let eq = EquationCurve {
curve: old.map(|o| o.curve.clone()).unwrap_or_default(),
x,
y: pick("y", old.map(|o| &o.y))?,
start: pick("start", old.map(|o| &o.start))?,
end: pick("end", old.map(|o| &o.end))?,
tolerance: tolerance(p, cmd)?.or(old.map(|o| o.tolerance)).unwrap_or(DEFAULT_TOLERANCE),
};
sketch_equation::check(&eq).map_err(|e| bad(cmd, e.to_string()))?;
Ok(eq)
}
/// The points of an equation, over the design's parameters as features are evaluated with them.
fn fit(doc: &solidcraft_doc::Document, eq: &EquationCurve, cmd: &str) -> Result<EquationFit> {
sketch_equation::fit(&doc.evaluation_values(), eq).map_err(|e| bad(cmd, e.to_string()))
}
fn reply(curve: String, fit: &EquationFit, info: Value) -> Value {
// A closed curve's last point is its first one.
let points = fit.points.len().saturating_sub(usize::from(fit.closed));
json!({"curves": [curve.clone()], "curve": curve, "points": points, "closed": fit.closed, "deviation": fit.deviation, "sketch": info})
}
fn create(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.equation_curve";
let eq = equation(p, cmd, None)?;
let ((curve, fit), info) = edit(s, p, cmd, false, |sk: &mut Sketch, doc| {
let fit = fit(doc, &eq, cmd)?;
let c = sk.add_equation_curve(&fit.points, fit.closed, eq.clone()).map_err(|e| bad(cmd, e.to_string()))?;
mark_construction(sk, &[c], p);
let id = sk.curves.get(c).map(|c| c.id.clone()).ok_or_else(|| bad(cmd, "the new curve is missing"))?;
Ok((id, fit))
})?;
Ok(reply(curve, &fit, info))
}
fn edit_curve(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.equation_curve.edit";
let id = p.get("curve").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`curve` must be an equation curve's id"))?.to_string();
let (fit, info) = edit(s, p, cmd, false, |sk: &mut Sketch, doc| {
let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?;
let old = sk.equation_of(&id).cloned().ok_or_else(|| bad(cmd, format!("`{id}` is not an equation curve")))?;
let eq = equation(p, cmd, Some(&old))?;
let fit = fit(doc, &eq, cmd)?;
sk.replace_equation_curve(c, &fit.points, fit.closed, eq).map_err(|e| bad(cmd, e.to_string()))?;
Ok(fit)
})?;
let mut out = reply(id, &fit, info);
if let Some(o) = out.as_object_mut() {
o.remove("curves");
}
Ok(out)
}
@@ -1,256 +0,0 @@
//! Equation curves (#8352): a fit point spline from formulas over the design's parameters.
use serde_json::{Value, json};
use solidcraft_geom::Vec2;
use solidcraft_sketch::CurveKind;
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn volume(s: &mut Session) -> f64 {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
}
fn no_trouble(s: &Session) {
for r in &s.model.results {
assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning);
}
}
fn near(got: f64, want: f64, rel: f64) {
assert!((got - want).abs() <= want.abs() * rel, "got {got}, want {want}");
}
/// The evaluated sketch `S`.
fn solved(s: &Session) -> solidcraft_sketch::Sketch {
let f = s.doc.find_feature("S").unwrap().id;
s.model.state().sketch(f).unwrap().sketch.clone()
}
/// The positions of curve `id`'s points in the evaluated sketch `S`.
fn curve_points(s: &Session, id: &str) -> Vec<Vec2> {
let sk = solved(s);
let c = sk.curves.iter().find(|c| c.id == id).unwrap();
c.kind.point_ids().iter().map(|i| sk.points[*i].pos).collect()
}
/// A wave over a strip: y = h + 5 sin(2 pi x / 100) over x from 0 to 100, closed by three
/// lines down to the x axis. Its area is 100 h (the sine adds as much as it takes away).
fn wave(s: &mut Session) -> String {
run(s, "parameters.add", json!({"name": "h", "expression": "10 mm"}));
run(s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(s, "sketch.equation_curve", json!({"explicit": true, "y": "h + 5 * sin(2 * pi * x / 100)", "start": 0, "end": "100 mm"}));
let id = r["curve"].as_str().unwrap().to_string();
assert_eq!(r["closed"], false, "{r}");
assert!(r["deviation"].as_f64().unwrap() <= 0.01, "{r}");
run(s, "sketch.line", json!({"points": [format!("{id}.end"), [100, 0], [0, 0], format!("{id}.start")]}));
run(s, "sketch.finish", json!({}));
id
}
#[test]
fn a_wave_from_a_formula_extrudes_and_follows_its_parameter() {
let mut s = Session::default();
let id = wave(&mut s);
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10}));
no_trouble(&s);
near(volume(&mut s), 100.0 * 10.0 * 10.0, 1e-4);
let before = curve_points(&s, &id);
assert!(before.iter().all(|p| (p.y - (10.0 + 5.0 * (2.0 * std::f64::consts::PI * p.x / 100.0).sin())).abs() < 1e-9), "{before:?}");
// The curve follows the parameter: the strip is twice as tall.
run(&mut s, "parameters.change", json!({"name": "h", "expression": "20 mm"}));
no_trouble(&s);
near(volume(&mut s), 100.0 * 20.0 * 10.0, 1e-4);
let after = curve_points(&s, &id);
assert_eq!(before.len(), after.len());
assert!(before.iter().zip(&after).all(|(a, b)| (b.y - a.y - 10.0).abs() < 1e-9 && (a.x - b.x).abs() < 1e-9));
// The parameter knows the curve uses it, and a rename reaches the formula.
let users = run(&mut s, "parameters.users", json!({"name": "h"}));
assert!(users.to_string().contains("Curve Y"), "{users}");
run(&mut s, "parameters.rename", json!({"name": "h", "new_name": "height"}));
let f = s.doc.find_feature("S").unwrap().id;
assert_eq!(s.doc.sketch(f).unwrap().equation_of(&id).unwrap().y, "height + 5 * sin(2 * pi * x / 100)");
no_trouble(&s);
near(volume(&mut s), 100.0 * 20.0 * 10.0, 1e-4);
// The design file keeps the formulas, and a reopened design follows them.
assert!(s.doc.to_json().contains("\"equations\""));
let mut r = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
no_trouble(&r);
near(volume(&mut r), 100.0 * 20.0 * 10.0, 1e-4);
}
#[test]
fn the_variable_hides_a_parameter_of_its_name_and_a_rename_leaves_it_alone() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "t", "expression": "1000 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "t * t", "start": -2, "end": 2}));
let id = r["curve"].as_str().unwrap().to_string();
run(&mut s, "sketch.finish", json!({}));
no_trouble(&s);
let pts = curve_points(&s, &id);
assert!(pts.iter().all(|p| (p.y - p.x * p.x).abs() < 1e-9 && p.x.abs() <= 2.0 + 1e-9), "{pts:?}");
run(&mut s, "parameters.rename", json!({"name": "t", "new_name": "u"}));
let f = s.doc.find_feature("S").unwrap().id;
let eq = s.doc.sketch(f).unwrap().equation_of(&id).unwrap().clone();
assert_eq!((eq.x.as_deref(), eq.y.as_str()), (Some("t"), "t * t"));
}
#[test]
fn a_full_turn_closes_smoothly_and_extrudes_as_a_disc() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.equation_curve", json!({"x": "20 * cos(t)", "y": "20 * sin(t)", "start": 0, "end": "360 deg"}));
assert_eq!(r["closed"], true, "{r}");
let id = r["curve"].as_str().unwrap().to_string();
run(&mut s, "sketch.finish", json!({}));
let f = s.doc.find_feature("S").unwrap().id;
let sk = s.doc.sketch(f).unwrap();
let Some(CurveKind::Spline { pts, periodic: true, control: false, .. }) = sk.curves.iter().find(|c| c.id == id).map(|c| &c.kind) else {
panic!("not a closed fit spline: {:?}", sk.curves)
};
assert_eq!(pts.first(), pts.last());
assert!(pts.iter().all(|p| sk.points[*p].fixed));
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 5}));
no_trouble(&s);
near(volume(&mut s), std::f64::consts::PI * 400.0 * 5.0, 1e-3);
}
#[test]
fn a_profile_under_a_curve_revolves() {
// y = 5 + 2 sin(x / 5) over x from 0 to 30, revolved about the x axis:
// V = pi * integral of (5 + 2 sin(x/5))^2 = pi * (25 * 30 + 20 * 5 (1 - cos 6) + 4 (15 - 5/4 sin 12)).
let want = std::f64::consts::PI * (750.0 + 100.0 * (1.0 - 6f64.cos()) + 4.0 * (15.0 - 1.25 * 12f64.sin()));
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.equation_curve", json!({"explicit": true, "y": "5 + 2 * sin(x / 5)", "start": 0, "end": 30}));
let id = r["curve"].as_str().unwrap().to_string();
run(&mut s, "sketch.line", json!({"points": [format!("{id}.end"), [30, 0], [0, 0], format!("{id}.start")]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.revolve", json!({"sketch": "S", "axis": "x"}));
no_trouble(&s);
near(volume(&mut s), want, 2e-3);
}
#[test]
fn an_edit_changes_the_formulas_and_keeps_the_joined_ends() {
let mut s = Session::default();
let id = wave(&mut s);
run(&mut s, "sketch.edit", json!({"sketch": "S"}));
let f = s.doc.find_feature("S").unwrap().id;
let before = s.doc.sketch(f).unwrap().clone();
let ends = |sk: &solidcraft_sketch::Sketch| {
let c = sk.curves.iter().find(|c| c.id == id).unwrap();
let (a, b) = c.kind.ends().unwrap();
(sk.points[a].id.clone(), sk.points[b].id.clone())
};
// A tighter tolerance and a bigger wave: more points, the same ends.
let r = run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "y": "h + 8 * sin(2 * pi * x / 100)", "tolerance": 0.002}));
assert!(r["deviation"].as_f64().unwrap() <= 0.002, "{r}");
let after = s.doc.sketch(f).unwrap().clone();
assert_eq!(ends(&before), ends(&after));
let count = |sk: &solidcraft_sketch::Sketch| sk.curves.iter().find(|c| c.id == id).unwrap().kind.point_ids().len();
assert!(count(&after) > count(&before), "{} vs {}", count(&after), count(&before));
assert_eq!(r["points"].as_u64(), Some(count(&after) as u64));
let eq = after.equation_of(&id).unwrap();
assert_eq!((eq.y.as_str(), eq.start.as_str(), eq.tolerance), ("h + 8 * sin(2 * pi * x / 100)", "0", 0.002));
// No points left behind: the old in-between points went.
assert_eq!(after.points.len(), before.points.len() - count(&before) + count(&after));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10}));
no_trouble(&s);
near(volume(&mut s), 100.0 * 10.0 * 10.0, 1e-4);
// Undo puts the old formulas back.
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.sketch(f).unwrap().equation_of(&id).unwrap().y, "h + 5 * sin(2 * pi * x / 100)");
}
#[test]
fn an_edit_can_switch_between_the_two_forms() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.equation_curve", json!({"explicit": true, "y": "x / 2", "start": 0, "end": 10}));
let id = r["curve"].as_str().unwrap().to_string();
// To a closed parametric curve: the old end point goes, the start stays.
let r = run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "x": "10 * cos(t)", "y": "10 * sin(t)", "start": 0, "end": "2 * pi"}));
assert_eq!(r["closed"], true, "{r}");
let f = s.doc.find_feature("S").unwrap().id;
let sk = s.doc.sketch(f).unwrap();
assert_eq!(sk.points.len(), 1 + r["points"].as_u64().unwrap() as usize, "the origin and the curve's own points");
// Back to the explicit form, open again.
let r = run(&mut s, "sketch.equation_curve.edit", json!({"curve": id, "explicit": true, "y": "x * x / 10", "start": -10, "end": 10}));
assert_eq!(r["closed"], false, "{r}");
let sk = s.doc.sketch(f).unwrap();
assert!(sk.equation_of(&id).unwrap().x.is_none());
let (a, b) = sk.curves.iter().find(|c| c.id == id).unwrap().kind.ends().unwrap();
assert_eq!((sk.points[a].pos, sk.points[b].pos), (Vec2::new(-10.0, 10.0), Vec2::new(10.0, 10.0)));
}
#[test]
fn deleting_the_curve_forgets_its_formulas() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let r = run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "sin(t)", "start": 0, "end": 6}));
let id = r["curve"].as_str().unwrap().to_string();
run(&mut s, "sketch.delete", json!({"entities": [id]}));
let f = s.doc.find_feature("S").unwrap().id;
let sk = s.doc.sketch(f).unwrap();
assert!(sk.equations.is_empty() && sk.curves.is_empty() && sk.points.len() == 1, "{sk:?}");
}
#[test]
fn bad_formulas_ranges_and_values_are_refused_and_change_nothing() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
let before = s.doc.to_json();
for p in [
json!({}),
json!({"y": "t", "start": 0, "end": 1}),
json!({"x": "t", "y": "t", "start": 0}),
json!({"x": "t", "explicit": true, "y": "x", "start": 0, "end": 1}),
json!({"x": "t", "y": "sqrt(t)", "start": -1, "end": 1}),
json!({"x": "t", "y": "1 / t", "start": -1, "end": 1}),
json!({"x": "t", "y": "t", "start": 1, "end": 1}),
json!({"x": "t", "y": "t", "start": 0, "end": "1e12"}),
json!({"x": "t * 1 deg", "y": "t", "start": 0, "end": 1}),
json!({"x": "nope", "y": "t", "start": 0, "end": 1}),
json!({"x": "t", "y": "t", "start": 0, "end": 1, "tolerance": 0}),
json!({"x": "t", "y": "t", "start": 0, "end": 1, "tolerance": "big"}),
json!({"x": 5, "y": 5, "start": 0, "end": 1}),
json!({"x": ["t"], "y": "t", "start": 0, "end": 1}),
json!({"x": "t", "y": "sin(1e5 * t)", "start": 0, "end": 1000, "tolerance": 0.0001}),
json!({"x": "1e300 * t", "y": "t", "start": 0, "end": 1}),
] {
assert!(s.execute("sketch.equation_curve", &p).is_err(), "{p} should be refused");
assert_eq!(s.doc.to_json(), before, "{p} changed the design");
}
for p in [json!({"curve": "nope", "y": "t"}), json!({"y": "t"}), json!({"curve": 7})] {
assert!(s.execute("sketch.equation_curve.edit", &p).is_err(), "{p} should be refused");
}
let line = run(&mut s, "sketch.line", json!({"points": [[0, 0], [5, 5]]}))["curves"][0].as_str().unwrap().to_string();
assert!(s.execute("sketch.equation_curve.edit", &json!({"curve": line, "y": "t"})).is_err());
}
#[test]
fn a_curve_its_parameters_break_is_an_error_not_a_crash() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "k", "expression": "1 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.equation_curve", json!({"x": "t", "y": "sqrt(k / 1 mm - t)", "start": 0, "end": 0.5}));
run(&mut s, "sketch.finish", json!({}));
no_trouble(&s);
// Now the square root goes negative inside the range: the sketch reports it.
run(&mut s, "parameters.change", json!({"name": "k", "expression": "0.25 mm"}));
let r = s.model.results.iter().find(|r| r.name == "S").unwrap();
assert!(r.error.as_deref().is_some_and(|e| e.contains("equation curve")), "{:?}", r.error);
run(&mut s, "parameters.change", json!({"name": "k", "expression": "1 mm"}));
no_trouble(&s);
}
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more