Compare commits
111
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f5894683c | ||
|
|
a6c0e8a959 | ||
|
|
46438b14a7 | ||
|
|
3900dc742c | ||
|
|
6b235ff0d1 | ||
|
|
4774efe1ee | ||
|
|
4f687454fc | ||
|
|
7f257866d9 | ||
|
|
feeac232f0 | ||
|
|
4f77836834 | ||
|
|
af21f2aa13 | ||
|
|
142285bff3 | ||
|
|
ea4513728b | ||
|
|
9325e3ac8c | ||
|
|
8c32875160 | ||
|
|
871014f955 | ||
|
|
684a4f4285 | ||
|
|
73e188df52 | ||
|
|
c571a133dc | ||
|
|
a2218e8a8d | ||
|
|
c36860e773 | ||
|
|
5faacb55d6 | ||
|
|
6c2ac96a09 | ||
|
|
cccef6dccd | ||
|
|
5a630606a4 | ||
|
|
7139ee9d20 | ||
|
|
5818c3eb3b | ||
|
|
9c2b888b40 | ||
|
|
0678ec98c3 | ||
|
|
b8aa83c6d9 | ||
|
|
8ad0cce768 | ||
|
|
3bcd93e2ca | ||
|
|
3a70b43708 | ||
|
|
1bbb18494e | ||
|
|
8e55033d9a | ||
|
|
a1d2b6d05b | ||
|
|
89191a1278 | ||
|
|
dad363980b | ||
|
|
55d07a258c | ||
|
|
1589e18f2a | ||
|
|
ee43b7d478 | ||
|
|
ed30a59795 | ||
|
|
c66752e8d3 | ||
|
|
429520088a | ||
|
|
54b4bb3f44 | ||
|
|
d8bf4c9bed | ||
|
|
d68970dd97 | ||
|
|
a6644ef0d2 | ||
|
|
48bab1a65a | ||
|
|
25d7a6b0c3 | ||
|
|
8505c77f5b | ||
|
|
7ecb3934a6 | ||
|
|
b5a5412d48 | ||
|
|
c4e1a3a756 | ||
|
|
b432b4484b | ||
|
|
068c46cf8b | ||
|
|
d7cad1005a | ||
|
|
8564006ffb | ||
|
|
708d5a149d | ||
|
|
0c094142d3 | ||
|
|
1939adba6b | ||
|
|
207679e261 | ||
|
|
4cbbccb935 | ||
|
|
22f8da2689 | ||
|
|
51d8842e8a | ||
|
|
95fd121bb3 | ||
|
|
1444801d96 | ||
|
|
28dcbbc862 | ||
|
|
7e96aabd6d | ||
|
|
52893744a5 | ||
|
|
4699b9cc89 | ||
|
|
4eb0c6f5ec | ||
|
|
a07b60cd81 | ||
|
|
bd3053f57b | ||
|
|
49ab9179a7 | ||
|
|
8c4caf9372 | ||
|
|
202b775de4 | ||
|
|
2c35a027f5 | ||
|
|
146a43f38e | ||
|
|
e04bc060f6 | ||
|
|
464da90238 | ||
|
|
0b32d3619d | ||
|
|
eb10552c61 | ||
|
|
e95f65fd54 | ||
|
|
1fdc56835b | ||
|
|
3fde538320 | ||
|
|
283ccd0b21 | ||
|
|
6b222aedf7 | ||
|
|
bcdbb91f26 | ||
|
|
21a1269d5c | ||
|
|
d580c4256c | ||
|
|
1b52186524 | ||
|
|
3e6eadc118 | ||
|
|
87358ef724 | ||
|
|
3d73822442 | ||
|
|
51f4074506 | ||
|
|
796b7c40d3 | ||
|
|
9cdee588f2 | ||
|
|
90d9c6488a | ||
|
|
edb7882815 | ||
|
|
db3558d820 | ||
|
|
b2f5da6ca7 | ||
|
|
f1159a5d51 | ||
|
|
ffc84dbe2e | ||
|
|
942e1540db | ||
|
|
6500c42c9f | ||
|
|
655c1f3336 | ||
|
|
9f2e117934 | ||
|
|
c6fe613d32 | ||
|
|
d5e953871b | ||
|
|
c7dcab172f |
No files matched your search
@@ -33,6 +33,12 @@ slow-timeout = { period = "60s" }
|
||||
[profile.ci.junit]
|
||||
path = "junit.xml"
|
||||
|
||||
# Bound the whole test process, including Vulkan host initialization and teardown.
|
||||
# Cold runs can warm multiple pipelines before the first image starts rendering.
|
||||
[[profile.ci.overrides]]
|
||||
filter = "package(=solidcraft-ui-egui) & test(=render_workspace::tests::progressive_image_controls_route_to_the_registered_host)"
|
||||
slow-timeout = { period = "60s", terminate-after = 20 }
|
||||
|
||||
# The action matrix sample runs its designs in parallel workers (ACTION_MATRIX_JOBS, set to match in
|
||||
# ci.yml). Its workers reserve that many of nextest's threads, so the cores are not oversubscribed
|
||||
# (a pi-case hole that takes 8 s alone went past the matrix's 90 s action limit when they were),
|
||||
|
||||
+16
-2
@@ -82,7 +82,6 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf | IBM Corp. (IBM Plex Mono) | https://github.com/IBM/plex (via google/fonts), unmodified; licence text in assets/fonts/ibm-plex-mono/OFL.txt; the interface monospace font | SIL OFL 1.1 |
|
||||
| assets/fonts/ibm-plex-sans/IBMPlexSans-Variable.ttf | IBM Corp. (IBM Plex Sans, variable wdth and wght) | https://github.com/IBM/plex (via google/fonts), unmodified; licence text in assets/fonts/ibm-plex-sans/OFL.txt; the default interface font | SIL OFL 1.1 |
|
||||
| docs/book/src/generated/tool-preview.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/tool-preview.json`; gitignored) | MIT OR Apache-2.0 |
|
||||
| assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 |
|
||||
| assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf | The BIZ UDGothic Project Authors | https://github.com/googlefonts/morisawa-biz-ud-gothic (Google Fonts), unmodified; licence text in assets/fonts/biz-udp-gothic/OFL.txt; used for web UI Japanese font | SIL OFL 1.1 |
|
||||
| assets/fonts/craft-ui-sc/CraftUI-SC.otf | Adobe / Google Inc. (Noto Sans SC); SolidCraft subset | https://github.com/notofonts/noto-cjk Sans/SubsetOTF/SC Regular, glyph-subset for assets/locales/zh.json and renamed Craft UI SC (OFL reserved-name); licence text in assets/fonts/craft-ui-sc/OFL.txt; web UI Simplified Chinese | SIL OFL 1.1 |
|
||||
| assets/fonts/craft-ui-tc/CraftUI-TC.otf | Adobe / Google Inc. (Noto Sans TC); SolidCraft subset | https://github.com/notofonts/noto-cjk Sans/SubsetOTF/TC Regular, glyph-subset for assets/locales/zh-TW.json and renamed Craft UI TC (OFL reserved-name); licence text in assets/fonts/craft-ui-tc/OFL.txt; web UI Traditional Chinese | SIL OFL 1.1 |
|
||||
@@ -147,7 +146,6 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/fonts/craft-ui-tc/OFL.txt | Adobe / Google Inc. (Noto CJK); SolidCraft header | Accompanying OFL for CraftUI-TC.otf | SIL OFL 1.1 |
|
||||
| assets/fonts/ibm-plex-mono/OFL.txt | IBM Corp. | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/fonts/ibm-plex-sans/OFL.txt | IBM Corp. | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/fonts/liberation-sans/OFL.txt | Red Hat, Inc.; Liberation Fonts contributors | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/icons/app/linux/exports/hicolor/128x128/apps/io.tangencylabs.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/linux/exports/hicolor/16x16/apps/io.tangencylabs.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/linux/exports/hicolor/24x24/apps/io.tangencylabs.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
@@ -215,6 +213,7 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/styles/ui/themes/one-dark.json | SolidCraft contributors | original SolidCraft theme file with colours adapted from the One Dark palette (Atom One Dark by GitHub Atom, https://github.com/atom/atom, MIT) | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/tokyo-night.json | SolidCraft contributors | original SolidCraft theme file adapting the colours of a published palette (Tokyo Night by enkia, https://github.com/enkia/tokyo-night-vscode-theme, MIT) | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/solarized-light.json | SolidCraft contributors | original SolidCraft theme file adapting the colours of a published palette (Solarized by Ethan Schoonover, https://github.com/altercation/solarized, MIT) | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/solarized-dark.json | SolidCraft contributors | original SolidCraft theme file adapting the colours of a published palette (Solarized by Ethan Schoonover, https://github.com/altercation/solarized, MIT) | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/nord.json | SolidCraft contributors | original SolidCraft theme file adapting the colours of a published palette (Nord by Sven Greb and the Nord contributors, https://github.com/nordtheme/nord, MIT) | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/high-contrast.json | SolidCraft contributors | original SolidCraft theme file | MIT OR Apache-2.0 |
|
||||
| assets/styles/ui/themes/graphite.json | SolidCraft contributors | original SolidCraft theme file | MIT OR Apache-2.0 |
|
||||
@@ -828,6 +827,21 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments.
|
||||
| docs/book/src/media/sketching/offset.mp4 | SolidCraft contributors | original screen recording of the actual SolidCraft 0.29.0 English desktop UI (default dark theme, software renderer) offsetting a sketch outline, with the original drawn pointer of examples/demo/overlay.py and labels set in DejaVu Sans Bold, captured with examples/demo/doc_shots.py | MIT OR Apache-2.0 |
|
||||
| docs/book/src/media/sketching/trim.mp4 | SolidCraft contributors | original screen recording of the actual SolidCraft 0.29.0 English desktop UI (default dark theme, software renderer) trimming a notch in a sketch, with the original drawn pointer of examples/demo/overlay.py and labels set in DejaVu Sans Bold, captured with examples/demo/doc_shots.py | MIT OR Apache-2.0 |
|
||||
| assets/locales/ca.json | carlymx | Catalan translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/pending/sketch-mirror-auto-line.json | SolidCraft contributors | Original Mirror preference label and translations | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-01-extrude5-edge-frame.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-04-preview-outer-l11.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-05-preview-inner-l8.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-06-result-outer-120.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-07-preview-360.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-08-cancelled.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-13-colliding-id.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-14-surface-l1.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-15-surface-result.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/revolve-selected-edge.mp4 | SamD98 | screen recording of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| assets/locales/bg.json | Yasen-55 | Original translation | MIT OR Apache-2.0 |
|
||||
| crates/sketch/assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in crates/sketch/assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 |
|
||||
| crates/sketch/assets/fonts/liberation-sans/OFL.txt | Red Hat, Inc.; Liberation Fonts contributors | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/locales/pending/drag-to-zoom.json | SolidCraft contributors | Original drag-to-zoom labels and translations | MIT OR Apache-2.0 |
|
||||
|
||||
## Code adapted from sibling projects
|
||||
|
||||
|
||||
Generated
+2
@@ -4283,9 +4283,11 @@ dependencies = [
|
||||
name = "solidcraft-render"
|
||||
version = "0.40.0-rc.2"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
"moxcms",
|
||||
"png",
|
||||
"robust",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
|
||||
@@ -16198,7 +16198,7 @@ spirv 0.4.0+sdk-1.4.341.0: Apache-2.0 (https://github.com/gfx-rs/rspirv)
|
||||
Bundled fonts (SIL Open Font License, Version 1.1)
|
||||
================================================================================
|
||||
|
||||
- LiberationSans-Regular.ttf (assets/fonts/liberation-sans/LiberationSans-Regular.ttf)
|
||||
- LiberationSans-Regular.ttf (crates/sketch/assets/fonts/liberation-sans/LiberationSans-Regular.ttf)
|
||||
Copyright 2012 Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google)
|
||||
Source: https://github.com/liberationfonts
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `kernel-cases --export=DIR`: one kernel rig case as a corpus entry for solidcore's rig. The
|
||||
//! case's commands run as the rig runs them while the kernel's operations are traced
|
||||
//! (`smlib_trace`); the entry holds the operation (or the chain of operations) that made the
|
||||
//! bodies the case ends with, each operand that came in as a record given as that record (the
|
||||
//! (`smlib_trace`); the entry holds every operation in execution order, including discarded
|
||||
//! tool construction and handled refusals, each operand that came in as a record (the
|
||||
//! B-rep record, solidcore-record's JSON), the fix set, the case's expected values and the rig's
|
||||
//! own result. A case whose result no kernel operation alone accounts for is written too, with
|
||||
//! the reasons, so nothing is dropped silently.
|
||||
@@ -98,32 +98,6 @@ impl<'a> Trace<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The operations `ends` need, in the order they ran: each body's maker, and its operands' makers
|
||||
/// in turn, back to bodies made from records. Operands made by nothing traced are listed in
|
||||
/// `unknown`.
|
||||
fn chain(t: &Trace<'_>, ends: &[u64], unknown: &mut BTreeSet<u64>) -> Vec<usize> {
|
||||
let mut need = BTreeSet::new();
|
||||
let mut todo: Vec<u64> = ends.to_vec();
|
||||
while let Some(id) = todo.pop() {
|
||||
if t.imports.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
match t.producer.get(&id) {
|
||||
Some(&i) => {
|
||||
if need.insert(i)
|
||||
&& let Some(c) = t.calls.get(i)
|
||||
{
|
||||
todo.extend(c.1.iter().copied());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
unknown.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
need.into_iter().collect()
|
||||
}
|
||||
|
||||
/// The entry of case `dir`, run with result `out`, into `root/<area>/<id>.json`, and the fix set
|
||||
/// into `root/fixes.json`.
|
||||
pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<(), String> {
|
||||
@@ -220,14 +194,18 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()
|
||||
}
|
||||
|
||||
let mut unknown = BTreeSet::new();
|
||||
let mut order = chain(&t, &ends, &mut unknown);
|
||||
let mut available: BTreeSet<u64> = t.imports.keys().copied().collect();
|
||||
for (_, inputs, _, outputs) in &t.calls {
|
||||
unknown.extend(inputs.iter().filter(|id| !available.contains(id)).copied());
|
||||
if let Ok(made) = outputs {
|
||||
available.extend(made.iter().copied());
|
||||
}
|
||||
}
|
||||
unknown.extend(ends.iter().filter(|id| !available.contains(id)).copied());
|
||||
if !unknown.is_empty() {
|
||||
why_not.push(format!("operands made by nothing traced: {unknown:?}"));
|
||||
}
|
||||
if let Some(i) = failed_call.filter(|i| !order.contains(i)) {
|
||||
order.push(i);
|
||||
}
|
||||
// Operand records: every body the chain takes, or the case ends with, that came in as a record.
|
||||
// Operand records: every body a call takes, or the case ends with, that came in as a record.
|
||||
let mut bodies = BTreeMap::new();
|
||||
let given = |id: u64, bodies: &mut BTreeMap<String, Value>| {
|
||||
if let Some((record, trusted, splines)) = t.imports.get(&id) {
|
||||
@@ -235,14 +213,21 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()
|
||||
}
|
||||
};
|
||||
let mut calls: Vec<Value> = Vec::new();
|
||||
for (op, inputs, params, outputs) in order.iter().filter_map(|&i| t.calls.get(i)) {
|
||||
for (i, (op, inputs, params, outputs)) in t.calls.iter().enumerate() {
|
||||
for &id in inputs.iter() {
|
||||
given(id, &mut bodies);
|
||||
}
|
||||
let mut c = json!({"op": op, "inputs": inputs.iter().map(|i| format!("b{i}")).collect::<Vec<_>>(), "params": params});
|
||||
match outputs {
|
||||
Ok(made) => c["outputs"] = json!(made.iter().map(|i| format!("b{i}")).collect::<Vec<_>>()),
|
||||
Err(e) => c["error"] = json!(e),
|
||||
Err(e) => {
|
||||
c["error"] = json!(e);
|
||||
// The application handled this refusal. Replay must continue to any later
|
||||
// calls and grade the final bodies, even when this was the last attempt.
|
||||
if failed_call != Some(i) {
|
||||
c["continued"] = json!(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
calls.push(c);
|
||||
}
|
||||
@@ -290,6 +275,134 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn empty_record() -> Brep {
|
||||
Brep { version: 4, tolerance: 1e-6, regions: Vec::new(), shells: Vec::new(), faces: Vec::new(), edges: Vec::new(), vertices: Vec::new() }
|
||||
}
|
||||
|
||||
fn call(op: &'static str, inputs: &[u64], outputs: Result<Vec<u64>, String>) -> Event {
|
||||
Event::Call { op, inputs: inputs.to_vec(), params: json!({}), outputs }
|
||||
}
|
||||
|
||||
fn exported_case(name: &str, events: Vec<Event>, ran: Result<Vec<(String, Brep)>, String>) -> Value {
|
||||
let root = std::env::temp_dir().join(format!("solidcraft-export-{}-{name}", std::process::id()));
|
||||
let dir = root.join("tests/kernel-cases/traces").join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("expected.json"), "{}").unwrap();
|
||||
let output = root.join("export");
|
||||
write(&output, dir.to_str().unwrap(), &json!({"status": "pass"}), Capture { events, ran: Some(ran) }).unwrap();
|
||||
let entry = output.join("traces").join(format!("{name}.json"));
|
||||
serde_json::from_str(&std::fs::read_to_string(entry).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarded_tool_construction_is_exported_in_execution_order() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"discarded-tool",
|
||||
vec![call("extrude", &[], Ok(vec![1])), call("extrude", &[], Ok(vec![2])), Event::Export { id: 1, record: Box::new(record.clone()) }],
|
||||
Ok(vec![("Part".into(), record)]),
|
||||
);
|
||||
assert_eq!(e["calls"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(e["calls"][0]["outputs"], json!(["b1"]));
|
||||
assert_eq!(e["calls"][1]["outputs"], json!(["b2"]));
|
||||
assert_eq!(e["traced_ops"], json!(["extrude", "extrude"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handled_refusals_are_exported_without_becoming_terminal() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"handled-refusal",
|
||||
vec![
|
||||
call("extrude", &[], Ok(vec![1])),
|
||||
call("fillet", &[1], Err("too large".into())),
|
||||
call("fillet", &[1], Ok(vec![2])),
|
||||
Event::Export { id: 2, record: Box::new(record.clone()) },
|
||||
],
|
||||
Ok(vec![("Part".into(), record)]),
|
||||
);
|
||||
assert_eq!(e["calls"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(e["calls"][1]["error"], "too large");
|
||||
assert_eq!(e["calls"][1]["continued"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handled_last_attempt_keeps_the_retained_body_as_the_result() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"handled-last-attempt",
|
||||
vec![
|
||||
call("extrude", &[], Ok(vec![1])),
|
||||
call("fillet", &[1], Err("too large".into())),
|
||||
Event::Export { id: 1, record: Box::new(record.clone()) },
|
||||
],
|
||||
Ok(vec![("Part".into(), record)]),
|
||||
);
|
||||
assert_eq!(e["calls"][1]["continued"], true);
|
||||
assert_eq!(e["result"], json!([{"body": "Part", "made": "b1"}]));
|
||||
assert_eq!(e["operation_expressible"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_final_refusal_still_ends_replay() {
|
||||
let e = exported_case(
|
||||
"terminal-refusal",
|
||||
vec![
|
||||
call("extrude", &[], Ok(vec![1])),
|
||||
call("fillet", &[1], Err("too large".into())),
|
||||
call("fillet", &[1], Err("no room".into())),
|
||||
call("copy", &[1], Ok(vec![2])),
|
||||
],
|
||||
Err("no room".into()),
|
||||
);
|
||||
assert_eq!(e["calls"].as_array().unwrap().len(), 4);
|
||||
assert_eq!(e["calls"][1]["continued"], true);
|
||||
assert!(e["calls"][2].get("continued").is_none());
|
||||
assert_eq!(e["outcome"]["kernel_error"], "no room");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarded_operations_still_require_their_operand_records() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"missing-tool-operand",
|
||||
vec![call("extrude", &[], Ok(vec![1])), call("copy", &[99], Ok(vec![2])), Event::Export { id: 1, record: Box::new(record.clone()) }],
|
||||
Ok(vec![("Part".into(), record)]),
|
||||
);
|
||||
assert_eq!(e["operation_expressible"], false);
|
||||
assert!(e["why_not"].as_array().unwrap().iter().any(|why| why.as_str().unwrap().contains("99")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarded_operations_keep_their_imported_operands() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"imported-tool-operand",
|
||||
vec![
|
||||
call("extrude", &[], Ok(vec![1])),
|
||||
Event::Import { id: 9, record: Box::new(record.clone()), trusted: false, keeping_splines: true },
|
||||
call("copy", &[9], Ok(vec![2])),
|
||||
Event::Export { id: 1, record: Box::new(record.clone()) },
|
||||
],
|
||||
Ok(vec![("Part".into(), record.clone())]),
|
||||
);
|
||||
assert_eq!(e["bodies"]["b9"], json!({"record": record, "trusted": false, "keeping_splines": true}));
|
||||
assert_eq!(e["calls"][1]["inputs"], json!(["b9"]));
|
||||
assert_eq!(e["operation_expressible"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_output_cannot_supply_an_earlier_discarded_operation() {
|
||||
let record = empty_record();
|
||||
let e = exported_case(
|
||||
"future-tool-operand",
|
||||
vec![call("copy", &[9], Ok(vec![2])), call("extrude", &[], Ok(vec![9])), Event::Export { id: 9, record: Box::new(record.clone()) }],
|
||||
Ok(vec![("Part".into(), record)]),
|
||||
);
|
||||
assert_eq!(e["operation_expressible"], false);
|
||||
assert!(e["why_not"].as_array().unwrap().iter().any(|why| why.as_str().unwrap().contains("9")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_area_is_the_path_under_kernel_cases() {
|
||||
assert_eq!(area_and_id("tests/kernel-cases/booleans/1894-x").unwrap(), ("booleans".into(), "1894-x".into()));
|
||||
|
||||
@@ -62,9 +62,9 @@ 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] [--profile-out trace.json] [--json-out FILE] [--allow-errors] [--validation each_step|each_feature|off]\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 (--validation: when SMLib's full check runs on the features computed (diagnostics.validation), default each_feature)\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 (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\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] [--profile-out trace.json] [--json-out FILE] [--allow-errors] [--validation each_step|each_feature|off]\n [--param-check off|warn|strict] [--quality standard|fine|finest]\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 (--quality: how closely an STL, OBJ or 3MF --out follows curved faces, as file.export's quality: a chord of\n 2e-4, 5e-5 or 1e-5 of each body's size, never under 1 µm, default standard)\n (--validation: when SMLib's full check runs on the features computed (diagnostics.validation), default each_feature)\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 (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\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] [--profile] [--profile-out trace.json] (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 (--profile and --profile-out as for run)\n";
|
||||
const USAGE_EVAL: &str = " solidcraft-cli eval <script.json|design.sc|part.step> [--in design.sc|part.step] [--json-out FILE] [--profile] [--profile-out trace.json] [--validation each_step|each_feature|off] (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 (--profile, --profile-out and --validation as for run)\n";
|
||||
/// `script`'s lines in the usage.
|
||||
const USAGE_SCRIPT: &str = " solidcraft-cli script <design.sc|script.json> [--out script.json]\n (the design's history as a command script that eval and run replay)\n";
|
||||
/// `bench-open`'s lines in the usage.
|
||||
@@ -451,11 +451,12 @@ fn cmd_run(args: &[String]) -> Result<(), String> {
|
||||
known_args(
|
||||
"run",
|
||||
args,
|
||||
&["--in", "--out", "--save", "--json-out", "--param-check", "--profile-out", "--validation"],
|
||||
&["--in", "--out", "--save", "--json-out", "--param-check", "--profile-out", "--validation", "--quality"],
|
||||
&["--quiet", "--results", "--timings", "--profile", "--allow-errors"],
|
||||
true,
|
||||
)?;
|
||||
let validation = validation_flag("run", args)?;
|
||||
let quality = export_quality("run", args)?;
|
||||
let base = flag(args, "--in");
|
||||
let path = positional(args);
|
||||
if path.is_none() && base.is_none() {
|
||||
@@ -503,7 +504,11 @@ fn cmd_run(args: &[String]) -> Result<(), String> {
|
||||
timeline_ok(&s, flags(args, "--out").is_empty())?;
|
||||
}
|
||||
for out in flags(args, "--out") {
|
||||
s.execute("file.export", &json!({"path": out})).map_err(|e| e.to_string())?;
|
||||
let mut params = json!({"path": out});
|
||||
if let Some(q) = quality {
|
||||
params["quality"] = json!(q);
|
||||
}
|
||||
s.execute("file.export", ¶ms).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if let Some(p) = flag(args, "--save") {
|
||||
s.execute("file.save_as", &json!({"path": p})).map_err(|e| e.to_string())?;
|
||||
@@ -544,6 +549,20 @@ fn open_validating(
|
||||
}
|
||||
}
|
||||
|
||||
/// `--quality standard|fine|finest`: how closely the meshes `--out` writes (STL, OBJ, 3MF)
|
||||
/// follow curved faces, as `file.export`'s `quality` (#12270). Checked before anything runs;
|
||||
/// given twice it is refused, since only one quality can apply.
|
||||
fn export_quality<'a>(cmd: &str, args: &'a [String]) -> Result<Option<&'a str>, String> {
|
||||
if flags(args, "--quality").len() > 1 {
|
||||
return Err(format!("{cmd}: --quality is given more than once"));
|
||||
}
|
||||
match flag(args, "--quality") {
|
||||
Some(q) if solidcraft_engine::io::MeshQuality::from_name(q).is_some() => Ok(Some(q)),
|
||||
Some(q) => Err(format!("{cmd}: --quality must be standard, fine or finest, not `{q}`")),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// `--validation MODE` (`diagnostics.validation`): the default, each_feature, when not given.
|
||||
fn validation_flag(cmd: &str, args: &[String]) -> Result<solidcraft_engine::kernel::Validation, String> {
|
||||
match flag(args, "--validation") {
|
||||
@@ -592,10 +611,12 @@ fn timeline_ok(s: &Session, skip_newer_features: bool) -> Result<(), String> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Runs `solidcraft-cli eval` (and its `inspect` alias), opening the input design or script with the requested `--validation` mode and reporting both `inspect.measure` and `document.inspect`.
|
||||
fn cmd_eval(args: &[String]) -> Result<(), String> {
|
||||
let json_out = json_out(args)?;
|
||||
known_args("eval", args, &["--in", "--json-out", "--profile-out"], &["--profile"], true)?;
|
||||
let mut s = open(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off)?;
|
||||
known_args("eval", args, &["--in", "--json-out", "--profile-out", "--validation"], &["--profile"], true)?;
|
||||
let validation = validation_flag("eval", args)?;
|
||||
let mut s = open_validating(flag(args, "--in"), positional(args), solidcraft_engine::schema::ParamCheck::Off, validation)?;
|
||||
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 mut out = json!({
|
||||
|
||||
@@ -67,6 +67,9 @@ fn run_rejects_invalid_options_before_script_execution_or_output_writes() {
|
||||
(&["--out", "--quiet"][..], "--out needs a value"),
|
||||
(&["--ouut", "part.step"][..], "doesn't take --ouut"),
|
||||
(&["--unknown"][..], "doesn't take --unknown"),
|
||||
(&["--quality"][..], "--quality needs a value"),
|
||||
(&["--quality", "best"][..], "--quality must be standard, fine or finest, not `best`"),
|
||||
(&["--quality", "standard", "--quality", "best"][..], "--quality is given more than once"),
|
||||
];
|
||||
for existing in [false, true] {
|
||||
let saved = dir.0.join(format!("{existing}.solidcraft"));
|
||||
@@ -288,6 +291,38 @@ fn results_still_save_and_export_the_script_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The triangles of a binary STL: the count after its 80-byte header.
|
||||
fn stl_triangles(path: &Path) -> u32 {
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
u32::from_le_bytes(bytes[80..84].try_into().unwrap())
|
||||
}
|
||||
|
||||
/// #12270: `run --out part.stl --quality fine` writes the mesh at that quality, as
|
||||
/// `file.export`'s `quality` does, without a script to say so.
|
||||
#[test]
|
||||
fn run_exports_meshes_at_the_quality_asked_for() {
|
||||
let dir = Scratch::new();
|
||||
let script = dir.0.join("cylinder.json");
|
||||
std::fs::write(&script, json!({"commands": [{"command": "solid.cylinder", "params": {"diameter": 40, "height": 10}}]}).to_string()).unwrap();
|
||||
let export = |name: &str, quality: Option<&str>| {
|
||||
let stl = dir.0.join(name);
|
||||
let mut command = cli();
|
||||
command.arg("run").arg(&script).arg("--quiet").arg("--out").arg(&stl);
|
||||
if let Some(q) = quality {
|
||||
command.args(["--quality", q]);
|
||||
}
|
||||
let output = command.output().unwrap();
|
||||
assert!(output.status.success(), "{quality:?}: {}", String::from_utf8_lossy(&output.stderr));
|
||||
stl_triangles(&stl)
|
||||
};
|
||||
let default = export("default.stl", None);
|
||||
let standard = export("standard.stl", Some("standard"));
|
||||
let fine = export("fine.stl", Some("fine"));
|
||||
let finest = export("finest.stl", Some("finest"));
|
||||
assert_eq!(default, standard);
|
||||
assert!(standard < fine && fine < finest, "standard {standard}, fine {fine}, finest {finest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_with_base_design_and_quiet_still_report_and_save() {
|
||||
let dir = Scratch::new();
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<meta property="og:site_name" content="SolidCraft">
|
||||
<meta property="og:title" content="SolidCraft: try it in your browser">
|
||||
<meta property="og:description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
|
||||
<meta property="og:url" content="https://solidcraft.ai/">
|
||||
<meta property="og:url" content="https://app.solidcraft.io/">
|
||||
<meta property="og:image" content="https://docs.solidcraft.io/og.png">
|
||||
<meta property="og:image:width" content="1280">
|
||||
<meta property="og:image:height" content="640">
|
||||
|
||||
@@ -676,7 +676,7 @@ pub fn take_drops(files: &Rc<Files>, raw: &mut egui::RawInput, theme: bool) {
|
||||
/// any later page.
|
||||
fn hold_page_lock(page: &str) {
|
||||
let Some(locks) = web_locks() else { return };
|
||||
let Ok(request) = Reflect::get(&locks, &"request".into()).and_then(|f| f.dyn_into::<Function>().map_err(JsValue::from)) else { return };
|
||||
let Ok(request) = Reflect::get(&locks, &"request".into()).and_then(|f| f.dyn_into::<Function>()) else { return };
|
||||
// A promise that never settles: the lock is let go only when the page goes.
|
||||
let hold = Closure::<dyn FnMut(JsValue) -> js_sys::Promise>::new(|_lock: JsValue| js_sys::Promise::new(&mut |_, _| {}));
|
||||
let name = format!("{}{page}", keep::LOCK_PREFIX);
|
||||
|
||||
@@ -23,9 +23,9 @@ fn prompt() {
|
||||
let _ = js_sys::Reflect::set(&window, &OFFER.into(), &JsValue::NULL);
|
||||
}
|
||||
let shown = js_sys::Reflect::get(&offer, &"prompt".into())
|
||||
.and_then(|f| f.dyn_into::<js_sys::Function>().map_err(JsValue::from))
|
||||
.and_then(|f| f.dyn_into::<js_sys::Function>())
|
||||
.and_then(|f| f.call0(&offer))
|
||||
.and_then(|p| p.dyn_into::<js_sys::Promise>().map_err(JsValue::from));
|
||||
.and_then(|p| p.dyn_into::<js_sys::Promise>());
|
||||
match shown {
|
||||
// Accepted or dismissed, the browser handles it; a refusal is only logged.
|
||||
Ok(p) => wasm_bindgen_futures::spawn_local(async move {
|
||||
|
||||
@@ -376,6 +376,7 @@ mod web {
|
||||
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,
|
||||
prefs_warning: Option<String>,
|
||||
other_tab_prefs: PrefsInbox,
|
||||
/// The open designs followed for their kept copy, by `Session::uid` (#10220).
|
||||
keep_track: std::collections::HashMap<u64, Track>,
|
||||
@@ -386,14 +387,33 @@ mod web {
|
||||
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 {
|
||||
fn persisted_prefs(&mut self, previous: impl FnOnce() -> Result<Option<String>, String>) -> Option<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();
|
||||
let (prefs, warning) = match self.app.try_prefs() {
|
||||
Ok(prefs) => (Some(prefs), None),
|
||||
Err(reason) => match previous().and_then(|previous| self.app.prefs_with_stored_panel_layout(previous.as_deref())) {
|
||||
Ok(prefs) => (Some(prefs), Some(format!("Panel layout changes were not saved: {reason}"))),
|
||||
Err(error) => (None, Some(format!("Settings were not written: {error}; panel layout: {reason}"))),
|
||||
},
|
||||
};
|
||||
if self.prefs_warning != warning {
|
||||
if let Some(warning) = &warning {
|
||||
log::warn!("{warning}");
|
||||
}
|
||||
self.prefs_warning = warning;
|
||||
}
|
||||
self.app.preferences.language = live;
|
||||
prefs
|
||||
}
|
||||
|
||||
fn stored_prefs() -> Result<Option<String>, String> {
|
||||
let storage = web_sys::window()
|
||||
.and_then(|window| window.local_storage().ok().flatten())
|
||||
.ok_or_else(|| "browser settings storage is unavailable".to_owned())?;
|
||||
storage.get_item(&crate::prefs_key()).map_err(|_| "browser settings could not be read".to_owned())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -401,7 +421,7 @@ mod web {
|
||||
if !self.launch.persists() || ctx.input(|i| i.events.is_empty()) {
|
||||
return;
|
||||
}
|
||||
let prefs = self.persisted_prefs();
|
||||
let Some(prefs) = self.persisted_prefs(Self::stored_prefs) else { return };
|
||||
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(&crate::prefs_key(), &prefs));
|
||||
if !matches!(stored, Some(Ok(()))) {
|
||||
@@ -415,8 +435,9 @@ mod web {
|
||||
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);
|
||||
if let Some(held) = self.persisted_prefs(Self::stored_prefs) {
|
||||
self.prefs_writer.loaded(held);
|
||||
}
|
||||
}
|
||||
|
||||
/// Files from the computer, writes to store, messages and the autosave.
|
||||
@@ -828,7 +849,9 @@ mod web {
|
||||
self.files.panel.set(false);
|
||||
}
|
||||
"insert" => {
|
||||
self.app.insert_path(&path);
|
||||
if !solidcraft_ui_egui::mesh_units::ask(&mut self.app, &path, true) {
|
||||
self.app.insert_path(&path);
|
||||
}
|
||||
self.files.panel.set(false);
|
||||
}
|
||||
"download" => match vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES) {
|
||||
@@ -873,10 +896,16 @@ mod web {
|
||||
*r = new.clone();
|
||||
}
|
||||
}
|
||||
if let Some(at) = self.app.home.opened_at.remove(&old) {
|
||||
self.app.home.opened_at.insert(new.clone(), at);
|
||||
}
|
||||
// A forgotten design follows its new name.
|
||||
if self.app.home.forgotten.remove(&old) {
|
||||
self.app.home.forgotten.insert(new);
|
||||
self.app.home.forgotten.insert(new.clone());
|
||||
}
|
||||
// An open tab of that file keeps its path and, when the name came
|
||||
// from the file, the title that matches the file list (#11375).
|
||||
solidcraft_ui_egui::documents::follow_file_rename(&mut self.app, &old, &new);
|
||||
}
|
||||
Err(e) => self.app.set_status(e, true),
|
||||
}
|
||||
@@ -1096,7 +1125,7 @@ mod web {
|
||||
if !self.launch.persists() {
|
||||
return;
|
||||
}
|
||||
let prefs = self.persisted_prefs();
|
||||
let Some(prefs) = self.persisted_prefs(|| Ok(storage.get_string(&crate::prefs_key()))) else { return };
|
||||
storage.set_string(&crate::prefs_key(), prefs);
|
||||
}
|
||||
}
|
||||
@@ -1273,6 +1302,7 @@ mod web {
|
||||
space_mouse: SpaceMouse::default(),
|
||||
wheel_gestures: solidcraft_ui_egui::WebWheelGestures::default(),
|
||||
prefs_writer: crate::PrefsWriter::default(),
|
||||
prefs_warning: None,
|
||||
other_tab_prefs,
|
||||
keep_track: Default::default(),
|
||||
all_kept: false,
|
||||
|
||||
@@ -282,13 +282,20 @@ impl eframe::App for App {
|
||||
let now = std::time::Instant::now();
|
||||
if self.prefs_writer.due(ui.input(|i| i.events.iter().any(changes_settings)), now)
|
||||
&& let Some(storage) = frame.storage_mut()
|
||||
&& let Some(wait) = self.prefs_writer.store(storage, self.solve.prefs(), now)
|
||||
&& let Ok(prefs) = self.prefs_for_storage(storage)
|
||||
&& let Some(wait) = self.prefs_writer.store(storage, prefs, now)
|
||||
{
|
||||
ui.ctx().request_repaint_after(wait);
|
||||
}
|
||||
}
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
let prefs = self.solve.prefs();
|
||||
let prefs = match self.prefs_for_storage(storage) {
|
||||
Ok(prefs) => prefs,
|
||||
Err(reason) => {
|
||||
log::warn!("Settings were not written: {reason}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
storage.set_string(solidcraft_ui_egui::prefs::STORAGE_KEY, prefs.clone());
|
||||
self.prefs_writer.written = Some(prefs);
|
||||
}
|
||||
@@ -361,6 +368,14 @@ struct LostWatch {
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn prefs_for_storage(&self, storage: &dyn eframe::Storage) -> Result<String, String> {
|
||||
self.solve.try_prefs().or_else(|reason| {
|
||||
log::warn!("Panel layout changes were not saved: {reason}");
|
||||
let previous = solidcraft_ui_egui::prefs::stored(|key| storage.get_string(key));
|
||||
self.solve.prefs_with_stored_panel_layout(previous.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// The graphics device was lost (#4172): the window can't draw again, so close, keeping
|
||||
/// unsaved changes for recovery as a forced quit does (the window can't ask about them), and
|
||||
/// start again once closed ([`device_lost::restart`]).
|
||||
|
||||
+4
-2
@@ -23,7 +23,7 @@ assets/
|
||||
appearances/library.rs # built-in visual presets
|
||||
materials/library.rs # physical defaults and colours
|
||||
shaders/viewport.wgsl # original viewport shader
|
||||
fonts/{liberation-sans,biz-udp-gothic}/ # unmodified fonts and OFL licences
|
||||
fonts/biz-udp-gothic/ # unmodified font and OFL licence
|
||||
locales/{en,de,ja,ko}.json # shared offline catalogs
|
||||
platforms/{macos,linux,windows}/ # bundle, freedesktop and WiX templates
|
||||
platforms/macos/dmg/ # disk image window: layout, dmgbuild settings, background art
|
||||
@@ -87,7 +87,9 @@ The CLI still supports arbitrary PNG/ICO exports with `solidcraft-cli icon`.
|
||||
|
||||
Resources remain compiled by their owning layer through existing APIs:
|
||||
`ui-egui::icons::paint_icon` and `Tokens` at L5, model presets in L2 `doc`, and sketch
|
||||
fonts at L1. State, projection, interaction, commands and GPU bindings stay in
|
||||
fonts at L1. The sketch crate owns its built-in Liberation Sans font and OFL
|
||||
licence under `crates/sketch/assets/fonts/liberation-sans/`, so Cargo source
|
||||
packages and vendored builds include both files. State, projection, interaction, commands and GPU bindings stay in
|
||||
their current modules. Embedded data uses `CARGO_MANIFEST_DIR`; application code
|
||||
needs no runtime resource registry or repository lookup.
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ pub(crate) fn glyph_icon(name: &str) -> Option<&'static str> {
|
||||
"Smooth" => "c_smooth",
|
||||
"Equal" => "c_equal",
|
||||
"Concentric" => "c_concentric",
|
||||
"MidPoint" => "c_midpoint",
|
||||
"MidPoint" | "PointAlong" => "c_midpoint",
|
||||
"Symmetry" => "c_symmetry",
|
||||
"Fix" => "c_fix",
|
||||
_ => return None,
|
||||
|
||||
+487
-32
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+351
-175
File diff suppressed because it is too large.
Load diff
+275
-20
@@ -264,8 +264,8 @@
|
||||
"Flat size": "Abwicklungsgröße",
|
||||
"Flat size X": "Abwicklungsmaß X",
|
||||
"Flat size Y": "Abwicklungsmaß Y",
|
||||
"Follow camera (Look At sketches)": "Kamera folgen (Skizzen ansehen)",
|
||||
"Follow the camera (Look At sketches)": "Der Kamera folgen (Skizzen ansehen)",
|
||||
"Follow camera (Look At sketches)": "Kamera folgen (senkrecht auf Skizzen)",
|
||||
"Follow the camera (Look At sketches)": "Der Kamera folgen (senkrecht auf Skizzen)",
|
||||
"Font": "Schriftart",
|
||||
"Free Move": "Frei verschieben",
|
||||
"From": "Von",
|
||||
@@ -568,6 +568,7 @@
|
||||
"Select edges": "Kanten auswählen",
|
||||
"Select points of the sketch being edited": "Punkte der bearbeiteten Skizze auswählen",
|
||||
"Select the centre the pattern turns around first": "Zuerst den Mittelpunkt auswählen, um den sich das Muster dreht",
|
||||
"Select the curves to divide first": "Zuerst die zu teilenden Kurven auswählen",
|
||||
"Select the curves to offset first": "Zuerst die zu versetzenden Kurven auswählen",
|
||||
"Select the mirror line": "Die Spiegellinie auswählen",
|
||||
"Select the sketch curves or points to mirror first": "Zuerst die zu spiegelnden Skizzenkurven oder -punkte auswählen",
|
||||
@@ -693,6 +694,7 @@
|
||||
"Unsuppress Selected Folders": "Unterdrückung der ausgewählten Ordner aufheben",
|
||||
"Updating the preview": "Vorschau wird aktualisiert",
|
||||
"Use active author placement": "Aktive Autorplatzierung verwenden",
|
||||
"Use axis direction only": "Nur Achsenrichtung verwenden",
|
||||
"Use fixed plane": "Feste Ebene verwenden",
|
||||
"Use saved fixed plane": "Gespeicherte feste Ebene verwenden",
|
||||
"Use selected face as fixed plane": "Ausgewählte Fläche als feste Ebene verwenden",
|
||||
@@ -1035,6 +1037,7 @@
|
||||
"cmd.occurrence_move": "Instanz verschieben",
|
||||
"cmd.occurrence_properties": "Physikalische Eigenschaften der Instanz",
|
||||
"cmd.occurrence_reparent": "In andere Komponente verschieben",
|
||||
"cmd.panel.action": "Panelaktion ausführen",
|
||||
"cmd.panel.activate": "Panel-Registerkarte aktivieren",
|
||||
"cmd.panel.close": "Panel schließen",
|
||||
"cmd.panel.collapse": "Panel-Bereich einklappen",
|
||||
@@ -1078,6 +1081,9 @@
|
||||
"cmd.pointcloud_edit": "Punktwolke bearbeiten",
|
||||
"cmd.pointcloud_insert": "Punktwolke einfügen",
|
||||
"cmd.pointcloud_list": "Punktwolken",
|
||||
"cmd.pointcloud_reload": "Punktwolke neu laden",
|
||||
"cmd.render.coat.bind": "Klarlack speichern",
|
||||
"cmd.render.coat.unbind": "Klarlack entfernen",
|
||||
"cmd.render.compare.divider": "Render-Vergleichstrenner verschieben",
|
||||
"cmd.render.result.discard": "Renderergebnis verwerfen",
|
||||
"cmd.render.result.select": "Renderergebnis auswählen",
|
||||
@@ -1226,6 +1232,7 @@
|
||||
"cmd.sketch_options": "Skizzenpalettenoptionen",
|
||||
"cmd.sketch_paste": "Skizzenelemente einfügen",
|
||||
"cmd.sketch_point3d": "3D-Punkt",
|
||||
"cmd.sketch_point_divide": "Kurve teilen",
|
||||
"cmd.sketch_polygon_circumscribed": "Umgeschriebenes Polygon",
|
||||
"cmd.sketch_polygon_edge": "Polygon über eine Kante",
|
||||
"cmd.sketch_polygon_inscribed": "Eingeschriebenes Polygon",
|
||||
@@ -1303,6 +1310,7 @@
|
||||
"cmd.view.render_browser": "Render-Browser",
|
||||
"cmd.view.render_dock": "Render-Panel verschieben",
|
||||
"cmd.view.render_focus": "Render-Fokusansicht",
|
||||
"cmd.view.render_live": "Live-Rendering pausieren oder fortsetzen",
|
||||
"cmd.view.status_details": "Statusdetails des Ansichtsfensters",
|
||||
"cmd.view.status_items": "Ansichtsstatus-Elemente",
|
||||
"cmd.view_ambient_occlusion": "Umgebungsverdeckung",
|
||||
@@ -1332,6 +1340,7 @@
|
||||
"cmd.view_shots_strip": "Aufnahmenleiste",
|
||||
"cmd.view_spin": "Ansicht kontinuierlich drehen",
|
||||
"cmd.view_tool": "Navigationswerkzeug",
|
||||
"cmd.view_tool_zoom": "Durch Ziehen zoomen",
|
||||
"cmd.view_top": "Draufsicht",
|
||||
"cmd.view_visual_style": "Darstellungsstil",
|
||||
"color.blue": "Blau",
|
||||
@@ -1469,6 +1478,7 @@
|
||||
"file_load.reading_percent": "Datei wird gelesen... {percent} %",
|
||||
"file_load.rebuilding": "Merkmal {done} von {total} wird neu aufgebaut",
|
||||
"file_load.recovering": "Design wird wiederhergestellt",
|
||||
"file_load.reloading_cloud": "Punktwolke wird neu geladen",
|
||||
"file_load.step_build": "Modell wird aufgebaut",
|
||||
"file_load.step_feature": "Merkmal {done} von {total}",
|
||||
"file_load.step_part": "Teil {done} von {total}",
|
||||
@@ -1708,6 +1718,7 @@
|
||||
"help.sketch.pattern.circular": "Kopiert Skizzengeometrie um einen Mittelpunkt, über einen vollen Kreis oder einen festen Winkel. Für Lochkreise, Speichen und Zähne.",
|
||||
"help.sketch.pattern.rectangular": "Kopiert Skizzengeometrie in Reihen und Spalten mit festen Abständen. Für Raster aus Bohrungen, Schlitzen oder Lüftungsöffnungen.",
|
||||
"help.sketch.point": "Setzt einen Skizzenpunkt. Als Bezug für Maße, Bedingungen, Bohrungsmitten oder spätere Elemente.",
|
||||
"help.sketch.point.divide": "Setzt Punkte, die die gewählten Kurven in gleich lange Abschnitte teilen. Die Punkte bleiben auf jeder Kurve und behalten ihren Abstand, wenn sie sich ändert.",
|
||||
"help.sketch.point3d": "Setzt bei eingeschalteter 3D-Skizze einen Punkt im Raum. Als Bezug für 3D-Kurven und Pfade.",
|
||||
"help.sketch.polygon.circumscribed": "Zeichnet ein regelmäßiges Polygon um einen Kreis, bemessen vom Mittelpunkt zur Mitte einer Seite. Wenn die Schlüsselweite bekannt ist, etwa bei einer Sechskantmutter.",
|
||||
"help.sketch.polygon.edge": "Zeichnet ein regelmäßiges Polygon aus den beiden Enden einer Seite. Wenn Länge und Lage einer Seite bekannt sind.",
|
||||
@@ -2136,7 +2147,7 @@
|
||||
"navbar.ground_shadow": "Bodenschatten",
|
||||
"navbar.home": "Start",
|
||||
"navbar.later": "Später",
|
||||
"navbar.look_at": "Ansehen",
|
||||
"navbar.look_at": "Senkrecht auf",
|
||||
"navbar.more": "Mehr",
|
||||
"navbar.orbit": "Drehen",
|
||||
"navbar.orthographic": "Orthografisch",
|
||||
@@ -2156,6 +2167,7 @@
|
||||
"navbar.value_tip": "{name} · {value}",
|
||||
"navbar.visual_style": "Darstellung",
|
||||
"navbar.zoom": "Zoomen",
|
||||
"navbar.zoom_hold_tip": "Zoomen (Tastenkürzel gedrückt halten)",
|
||||
"needs two joints": "benötigt zwei Gelenke",
|
||||
"network.allow_once": "Einmalig erlauben",
|
||||
"network.always_allow": "Diesen Server immer erlauben",
|
||||
@@ -2353,6 +2365,8 @@
|
||||
"prefs.edges": "Kanten und Schattierung",
|
||||
"prefs.extend": "Erweitern",
|
||||
"prefs.extra_navigation": "Mit Strg und gedrückter linker Maustaste auf einer freien Fläche drehen. Leertaste gedrückt halten, um die Ansicht zu verschieben.",
|
||||
"prefs.extrude_arrow_face_stops": "Extrusionspfeil hält an Flächen",
|
||||
"prefs.extrude_arrow_face_stops_note": "Beim Ziehen des Abstandspfeils von Extrusion hält er an ebenen Flächen parallel zum Profil, etwa an der Rückseite eines Blocks, in den geschnitten wird, und hebt die Fläche hervor. Aus: Der Pfeil bewegt sich nur in runden Schritten.",
|
||||
"prefs.extrude_view_isometric": "Beim Öffnen von Extrudieren isometrisch ausrichten",
|
||||
"prefs.extrude_view_return": "Beim Schließen von Extrudieren zur vorigen Ansicht zurück",
|
||||
"prefs.follows_os": "Wie im Betriebssystem",
|
||||
@@ -2407,6 +2421,10 @@
|
||||
"prefs.hide_constraint_glyphs_zoomed_out": "Bindungssymbole bei starkem Herauszoomen ausblenden",
|
||||
"prefs.hide_constraint_glyphs_zoomed_out_note": "Bindungssymbole verschwinden, wenn die Skizze so weit herausgezoomt ist, dass sie sie überladen würden. Aus: sie behalten bei jedem Zoom eine feste Bildschirmgröße.",
|
||||
"prefs.history": "Verlauf",
|
||||
"prefs.history_bar_groups": "Verlaufsleiste in Gruppen falten",
|
||||
"prefs.history_bar_groups_note": "In einem langen Verlauf wird eine Folge von Features einer Komponente zu einem Chip gefaltet, und Merkmalsordner beginnen gefaltet. Eine eingefügte STEP-Baugruppe kommt in einen Group-Ordner. Aus zeigt jedes Feature, öffnet Ordner und legt keinen Ordner an.",
|
||||
"prefs.history_group_joints": "Gelenke im Verlauf gruppieren",
|
||||
"prefs.history_group_joints_note": "Zwei oder mehr Gelenke erscheinen als eine Schaltfläche mit ihrer Anzahl; ein Klick zeigt jedes einzeln. Aus zeigt jedes Gelenk einzeln.",
|
||||
"prefs.history_origin_bodies": "Ursprung und Körper oben zeigen",
|
||||
"prefs.history_origin_bodies_note": "Der Verlauf links oder unter dem Browser beginnt mit dem Körper-Ordner der aktiven Komponente und dem Ursprung, mit Augen und Menüs wie im Browser. Der Verlauf unten bleibt unverändert.",
|
||||
"prefs.history_play_button": "Schaltfläche „Verlauf abspielen“ in den Verlaufssteuerelementen",
|
||||
@@ -2504,6 +2522,7 @@
|
||||
"prefs.origin_plane_names": "Namen der Ursprungsebenen",
|
||||
"prefs.origin_plane_names_note": "Namen in Browser, Dialogen und Listen. {top} ist XY, {front} ist XZ und {right} ist YZ, mit Z nach oben. Befehle, Skripte und gespeicherte Konstruktionen behalten XY, XZ und YZ.",
|
||||
"prefs.overall_speed": "Gesamtgeschwindigkeit",
|
||||
"prefs.panel_layout.recovery": "Gespeicherte Panel-Layouts konnten nicht wiederhergestellt werden. Die gespeicherten Daten bleiben erhalten; Klassisch bleibt verfügbar.",
|
||||
"prefs.parameter_list_rows": "Zeilen der Parameterliste",
|
||||
"prefs.parameter_list_rows_tip": "Maximale Anzahl der Parameter, die Pfeil abwärts in einem leeren Ausdrucksfeld auflistet.",
|
||||
"prefs.persistent_ribbon_pressed": "Aktive Menübandbefehle hervorheben",
|
||||
@@ -2547,6 +2566,8 @@
|
||||
"prefs.quick_measure_note": "Zeigt unten rechts in der Ansicht die Größe der Auswahl an: bei einer Kante die Länge, bei einer kreisförmigen Kante zusätzlich Durchmesser (Ø) und Radius (R), bei einer Fläche den Flächeninhalt, bei einem Punkt die Position, bei zwei Elementen Abstand und Winkel sowie bei mehreren Kanten oder Flächen die Gesamtlänge bzw. Gesamtfläche. Ein Klick kopiert den Messwert.",
|
||||
"prefs.remember_dialog_values": "Befehlsdialogwerte merken",
|
||||
"prefs.remember_dialog_values.help": "Standardmäßig aus. Wenn aktiviert, werden nach erfolgreicher Ausführung eines Befehls seine sicheren Werte und Optionen beim nächsten Öffnen desselben Befehls wiederverwendet, bis SolidCraft geschlossen wird.",
|
||||
"prefs.render_legacy_image_defaults": "Bisherige Render-Bildvorgaben verwenden",
|
||||
"prefs.render_legacy_image_defaults_help": "Den bisherigen manuellen Ablauf beibehalten: neue Setups mit CPU-Raster, feste Abtastung beim CPU-Raytracing und manuell geöffnete Ergebnisse. Beim Wechsel zu Render die Ansicht neu einpassen, Aufnahmen ohne Wiederherstellung ihrer Kamera wechseln und die bisherige Bildausrichtung und Navigation verwenden. Automatische Live-Bildrückmeldungen deaktivieren. Gespeicherte Setups bleiben unverändert.",
|
||||
"prefs.render_previous_geometry_budget": "Bisheriges Geometriebudget für die Render-Vorschau verwenden",
|
||||
"prefs.render_previous_geometry_budget_help": "Stellt die bisherige feste Obergrenze für die Geometrie wieder her (512 MiB auf 64-Bit-Desktop-Systemen, andernfalls 128 MiB) anstelle des geräteabhängigen Budgets.",
|
||||
"prefs.reports_saved": "{n} gespeichert",
|
||||
@@ -2623,8 +2644,9 @@
|
||||
"prefs.sketch_exit_view_note": "Legt fest, zu welcher Ansicht nach „Skizze beenden“, „Abbrechen“ oder zweimaligem Drücken der Esc-Taste gewechselt wird.",
|
||||
"prefs.sketch_face_activates_part": "Skizzieren auf der Fläche eines Teils aktiviert dieses Teil",
|
||||
"prefs.sketch_face_activates_part_note": "Eine Skizze, die auf einer Fläche am Körper einer anderen Komponente begonnen wird, aktiviert zuerst diese Komponente, sodass die Skizze zu ihr gehört und im Browser bei diesem Teil bleibt. Das Teil bleibt danach aktiv. Aus: Die Skizze gehört zur aktiven Komponente.",
|
||||
"prefs.sketch_mirror_auto_line": "Vorausgewählte Konstruktionslinie zum Spiegeln verwenden",
|
||||
"prefs.sketch_open_look_at": "Beim Öffnen einer Skizze auf sie ausrichten",
|
||||
"prefs.sketch_open_look_at_note": "Aus: Beim Erstellen oder Bearbeiten einer Skizze bleibt die Ansicht, wie sie ist. „Ansehen“ richtet die Ansicht bei Bedarf auf die Skizze aus.",
|
||||
"prefs.sketch_open_look_at_note": "Aus: Beim Erstellen oder Bearbeiten einer Skizze bleibt die Ansicht, wie sie ist. „Senkrecht auf“ richtet die Ansicht bei Bedarf auf die Skizze aus.",
|
||||
"prefs.sketch_recent_snap": "Automatisch an zuletzt verwendete Mittelpunkte fangen",
|
||||
"prefs.sketch_recent_snap_note": "Fängt den Zeiger beim Zeichnen dort ein, wo sich die Hilfslinien der beiden zuletzt verwendeten Kreismittelpunkte oder Kantenmitten kreuzen. Aus: die Hilfslinien bleiben sichtbar und der Zeiger bewegt sich nicht.",
|
||||
"prefs.sketch_selection": "Skizzen und Auswahl",
|
||||
@@ -2674,6 +2696,8 @@
|
||||
"prefs.structure.work": "Arbeit",
|
||||
"prefs.supersampling_brief": "Rendert die Ansicht größer und verkleinert sie dann: sehr scharf, aber rechenintensiver.",
|
||||
"prefs.tab_accent_note": "Die Akzentfarbe richtet sich nach dem aktiven Tab.",
|
||||
"prefs.tab_double_click_renames": "Entwurfsregisterkarte per Doppelklick umbenennen",
|
||||
"prefs.tab_double_click_renames_note": "Geben Sie den neuen Namen ein und drücken Sie Enter oder klicken Sie woanders hin, um ihn zu übernehmen, oder Esc zum Abbrechen. Aus: Ein Doppelklick auf eine Registerkarte maximiert das Fenster, wie auf dem leeren Teil der Leiste.",
|
||||
"prefs.theme_file": "Designdatei",
|
||||
"prefs.theme_file_or_paste": "Datei oder Einfügen",
|
||||
"prefs.theme_follow": "Einer Designdatei folgen",
|
||||
@@ -2770,12 +2794,15 @@
|
||||
"refused.join": "Konnte nicht mit {body} vereinigt werden.",
|
||||
"refused.repair": "Teil reparieren",
|
||||
"refused.show_face": "Fläche zeigen",
|
||||
"render.adaptive.pilot_progress": "Adaptive Pilotphase · {current}/{target} Durchgänge",
|
||||
"render.adaptive.preview_help": "Pilotbilder bestimmen die Verteilung und sind vom Endbild ausgeschlossen. Produktionsiterationen nutzen ein eigenes Budget pro Pixel; die Iterationszahl ist keine einheitliche Samplezahl pro Pixel.",
|
||||
"render.adaptive.production_progress": "Adaptive Produktion · {current}/{target} Iterationen",
|
||||
"render.adaptive_absolute": "Absolute RGB-Fehleruntergrenze",
|
||||
"render.adaptive_coverage": "Zielwert für den Abdeckungsfehler",
|
||||
"render.adaptive_enable": "Samples mithilfe unabhängiger Pilot-Samples zuteilen",
|
||||
"render.adaptive_help": "Nur GPU. Unabhängige Pilot-Samples werden verworfen. Anschließend werden pro Pixel 16 oder mehr Produktions-Samples zugeteilt, bis zu den Samples pro Pixel. Die Zuteilung richtet sich nach der RGB- und Abdeckungsvarianz; seltene Pfade können übersehen werden, und Pixel, die ihr Limit erreicht haben, können verrauscht bleiben. Der Abschlussbericht zählt den tatsächlichen Aufwand. Keine zertifizierte Garantie für ein bestimmtes Rauschniveau oder eine bestimmte Renderzeit.",
|
||||
"render.adaptive_help": "Unabhängige Pilotsamples werden verworfen und bestimmen dann mindestens 16 Produktionssamples pro Pixel bis zum Wert Samples pro Pixel. CPU-Ressourcengrenzen umfassen beide Phasen. RGB- und Abdeckungsvarianz steuern die Verteilung; Pixel am Limit können verrauscht bleiben. Der Abschlussbericht zählt die tatsächlichen Samples.",
|
||||
"render.adaptive_minimum": "Minimale Produktions-Samples",
|
||||
"render.adaptive_pending": "Die adaptive Zuteilung mit unabhängigen GPU-Pilot-Samples und bedingte Fresnel-Schichten sind verfügbar. Zertifizierte Konvergenz, Garantien für seltene Ereignisse und adaptiver Lichttransport auf der CPU bleiben nicht verfügbar.",
|
||||
"render.adaptive_pending": "Adaptive Verteilung mit unabhängigen Pilotsamples ist für CPU und GPU verfügbar. Bedingte Fresnel-Schichten erfordern die GPU. Die statistische Verteilung bestätigt keine Konvergenz.",
|
||||
"render.adaptive_pilots": "Pilot-Samples pro Pixel",
|
||||
"render.adaptive_relative": "Zielwert für den relativen RGB-Fehler",
|
||||
"render.add_ground": "Add fitted ground to setup",
|
||||
@@ -2798,6 +2825,7 @@
|
||||
"render.aging_metallic": "Metallanteil der Schicht",
|
||||
"render.aging_origin": "Feldursprung · Weltkoordinaten (mm)",
|
||||
"render.aging_patina": "Kupfergrüne Patina",
|
||||
"render.aging_raytrace_help": "Alterung wird beim CPU-Raytracing und GPU-Pathtracing angewendet. Raster bleibt eine schematische Darstellung.",
|
||||
"render.aging_refresh_targets": "Aktuelle Körper prüfen",
|
||||
"render.aging_roughness": "Rauheit der Schicht",
|
||||
"render.aging_rust": "Oxidiertes Eisen / Rost",
|
||||
@@ -2818,6 +2846,7 @@
|
||||
"render.appearance_editor.closed": "Geschlossener Körper",
|
||||
"render.appearance_editor.coat": "Klarlack",
|
||||
"render.appearance_editor.cpu_reason": "Benötigt CPU-Strahlverfolgung.",
|
||||
"render.appearance_editor.discard_saved_edit": "Ungespeicherte Optikänderungen verwerfen",
|
||||
"render.appearance_editor.glass": "Glas und Absorption",
|
||||
"render.appearance_editor.glass_enable": "Physikalisches Glas für diesen Körper verwenden",
|
||||
"render.appearance_editor.glass_note": "Geschlossenes Glas verwendet geometrische Abstände. Es kann nicht mit Klarlack oder Texturen auf demselben Körper kombiniert werden.",
|
||||
@@ -2836,7 +2865,7 @@
|
||||
"render.appearance_editor.replace": "Gespeicherte Optik dieses Körpers ersetzen",
|
||||
"render.appearance_editor.revalidate": "Diesen Körper erneut prüfen",
|
||||
"render.appearance_editor.save": "Diese Optik speichern",
|
||||
"render.appearance_editor.save_reason": "Zum Speichern wird physikalisches Glas auf einem aktuellen GPU-Körper benötigt. Klarlack und lokale Bildtexturen bleiben vorübergehend.",
|
||||
"render.appearance_editor.save_reason": "Zum Speichern Glas an einem aktuellen CPU- oder GPU-Körper aktivieren. Für Klarlack „Klarlack in Aufnahme speichern“ verwenden. Lokale Bilddateien bleiben temporär.",
|
||||
"render.appearance_editor.saved": "Mit dieser Aufnahme gespeichert",
|
||||
"render.appearance_editor.saved_state": "Diese Optik ist mit dieser Aufnahme gespeichert.",
|
||||
"render.appearance_editor.scatter_reason": "Innere Streuung benötigt einen geschlossenen Körper.",
|
||||
@@ -2882,9 +2911,13 @@
|
||||
"render.base_metallic": "Metallanteil",
|
||||
"render.base_opaque_only": "Dieser Editor lässt Körper undurchsichtig. Für optische Transmission verwenden Sie die gesonderten Glaseinstellungen.",
|
||||
"render.batch_all_shots": "Alle Ansichten ({count})",
|
||||
"render.batch_current_settings_help": "Verwendet die aktuellen Bildeinstellungen mit jeder gespeicherten Aufnahmekamera, eine Aufnahme nach der anderen.",
|
||||
"render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.",
|
||||
"render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.",
|
||||
"render.batch_owner_limit": "Es können höchstens 32 Dokument-Bildfolgen vorgehalten werden. Schließen Sie zuerst eine vorhandene Folge ab oder brechen Sie sie ab.",
|
||||
"render.batch_preparing": "Nächste Aufnahme wird vorbereitet",
|
||||
"render.batch_status": "{running} läuft · {waiting} warten",
|
||||
"render.batch_waiting_worker": "Warten auf die Rendering-Vorbereitung",
|
||||
"render.bloom_enable": "Darstellungs-Bloom",
|
||||
"render.bloom_help": "Kreativer Ausgabeglanz aus linearen Glanzlichtern mit drei normierten Durchläufen. Radius in Ausgabepixeln; Addition vor sRGB. Keine Linsen-, Volumen- oder Konvergenzsimulation. Das rohe EXR bleibt unverändert.",
|
||||
"render.bloom_opaque": "Bloom benötigt eine deckende Ausgabe. Transparentes PNG wird abgelehnt, nicht still abgeflacht.",
|
||||
@@ -2914,6 +2947,16 @@
|
||||
"render.category_paint": "Lack",
|
||||
"render.category_plastic": "Kunststoff",
|
||||
"render.category_wood": "Holz",
|
||||
"render.caustics_depth": "Kaustik-Pfadtiefe",
|
||||
"render.caustics_enable": "Glaskaustiken durch Punkt- und Richtungslichter",
|
||||
"render.caustics_help": "Die Photonenzahl bestimmt Rauschen und Aufwand. Der Sammelradius tauscht scharfe Details gegen eine glattere Schätzung. CPU benötigt indirekte Beleuchtung.",
|
||||
"render.caustics_path_required": "CPU-Kaustiken benötigen indirekte Beleuchtung.",
|
||||
"render.caustics_photons": "Photonen",
|
||||
"render.caustics_radius": "Sammelradius",
|
||||
"render.check_glass_cpu": "Die CPU unterstützt geprüfte ebene Glasscheiben und achsenparallele Boxen. Allgemeine geschlossene Netze, Verschachtelung und innere Streuung erfordern indirekte Beleuchtung. Durch geschlossenes Glas übertragene Schatten bleiben nicht unterstützt.",
|
||||
"render.check_glass_gpu": "Die GPU unterstützt geprüfte getrennte Glasmedien oder ausdrücklich aktivierte geprüfte Verschachtelung. Dafür müssen die äußeren Körper konvex und die inneren streng enthalten sein; Grenzen dürfen sich nicht berühren.",
|
||||
"render.check_media_remaining": "Dichtegitter, Displacement, vollständige spektrale Integration und fortgeführte Polarisation bleiben nicht verfügbar.",
|
||||
"render.check_media_scope": "Aktive innere Streuung benötigt ein geschlossenes Glasmedium ohne gerade Schattenübertragung und ohne Rauschreduzierung. Die GPU benötigt außerdem eine Fresnel-Schicht. Aktive äußere Atmosphäre kann nicht mit Glas oder Oberflächen-Rauschreduzierung kombiniert werden.",
|
||||
"render.check_opaque": "Transparenz: nur undurchsichtige Oberflächen; Hintergrund-Alpha wird unterstützt.",
|
||||
"render.check_sorted_alpha": "Transparenz: Näherung mit sortiertem Alpha.",
|
||||
"render.check_transmission": "Transparenz: physikalische Transmission.",
|
||||
@@ -2932,7 +2975,7 @@
|
||||
"render.children.copy_request": "Anfrage-JSON kopieren",
|
||||
"render.children.coverage_error": "Abdeckungsfehler",
|
||||
"render.children.cpu": "CPU-Raytracing",
|
||||
"render.children.denoise": "Rauschen im fertigen Bild reduzieren",
|
||||
"render.children.denoise": "Bildrauschen reduzieren",
|
||||
"render.children.depth": "Pfadtiefe",
|
||||
"render.children.distortion": "Verzeichnung",
|
||||
"render.children.edge_samples": "Kanten-Samples",
|
||||
@@ -2995,6 +3038,14 @@
|
||||
"render.choose_look": "Zuerst einen Look in der Bibliothek wählen",
|
||||
"render.chromatic_offset": "Chromatischer Kantenversatz",
|
||||
"render.clear_stage": "Remove saved stage",
|
||||
"render.coat_discard": "Klarlackänderung verwerfen",
|
||||
"render.coat_pending_edit": "Diese Klarlackänderung ist ungespeichert. Mit der Aufnahme speichern oder verwerfen.",
|
||||
"render.coat_remove": "Gespeicherten Klarlack entfernen",
|
||||
"render.coat_remove_note": "Entfernt den Klarlack dieses Ziels aus der Aufnahme. Geometrie, Aussehen und physikalische Materialien bleiben unverändert.",
|
||||
"render.coat_remove_title": "Gespeicherten Klarlack entfernen?",
|
||||
"render.coat_revalidate_saved": "Der gespeicherte Klarlack wurde geändert. Diese Änderung verwerfen und das Ziel vor der nächsten Bearbeitung erneut öffnen.",
|
||||
"render.coat_save": "Klarlack in Aufnahme speichern",
|
||||
"render.coat_saved_help": "Klarlack fügt undurchsichtigen Flächen eine glänzende Schicht hinzu. Mit der Aufnahme speichern. Glas kann nicht dasselbe Ziel verwenden. Auf der CPU dürfen auch benutzerdefinierte Reflexions- und Anisotropieüberschreibungen dieses Ziel nicht verwenden.",
|
||||
"render.compare_divider": "Vergleichstrenner",
|
||||
"render.compare_live": "Live",
|
||||
"render.compare_live_preview": "Live-Vorschau",
|
||||
@@ -3028,10 +3079,18 @@
|
||||
"render.cpu_budget_triangles": "Dreiecksobergrenze",
|
||||
"render.cpu_budget_workstation": "Workstation (komplexe Szenen)",
|
||||
"render.cpu_captured_hdr": "Für dieses Bild erfasstes HDR",
|
||||
"render.cpu_celestial_adopt": "CPU-Raytracing mit indirekter Beleuchtung · Pfadtiefe {depth} · {spp} SPP · verfolgte Schatten · Seed {seed} · 1 Primärsample",
|
||||
"render.cpu_celestial_adopt_label": "CPU-Raytracing mit indirekter Beleuchtung",
|
||||
"render.cpu_celestial_path_required": "Endliche Sonne und Verlaufshimmel verwenden indirekte CPU-Beleuchtung.",
|
||||
"render.cpu_celestial_switch": "Wähle CPU-Raytracing mit indirekter Beleuchtung, um diese Sonne oder diesen Himmel beizubehalten.",
|
||||
"render.cpu_celestial_unportable": "Behalte GPU-Pathtracing für die aktuellen Transmissions-Sample-Einstellungen bei.",
|
||||
"render.cpu_check_capture_help": "Prüfen und Starten verifizieren dieselbe Datei-Prüfsumme oder verwenden das eingebettete HDR. Jedes Bild behält seine erfasste Quelle.",
|
||||
"render.cpu_check_changed": "Die Einstellungen oder das Modell haben sich nach dieser Prüfung geändert. Prüfen Sie erneut, bevor Sie rendern.",
|
||||
"render.cpu_constant_direct_help": "Ohne indirekte Beleuchtung kann diese konstante Quelle in Reflexionen und durch Glas sichtbar sein. Sie beleuchtet keine undurchsichtigen Flächen. Schalte indirekte Beleuchtung ein, um sie als Szenenlicht zu nutzen.",
|
||||
"render.cpu_constant_enable_indirect_plan": "Pfadtiefe {depth}; progressives Sampling mit {spp} Samples/Pixel (Seed {seed}); ein Primärstrahl pro Sample; Raytracing-Schatten. Bildgröße, CPU-Budget und andere Einstellungen bleiben erhalten.",
|
||||
"render.cpu_constant_help": "Konstante Strahldichte ist für reflektierte oder durchgelassene Strahlen sichtbar. Sie liefert keine direkte diffuse Beleuchtung.",
|
||||
"render.cpu_custom_directions": "Vorgabe durch eigene Richtungslichter ersetzen",
|
||||
"render.cpu_denoise_help": "Verringert das Rauschen bei jeder Bildaktualisierung. Feine Details und Übergänge der Tiefenschärfe können weicher werden. Die EXR-Rohdaten bleiben unverändert. Nachträgliche Anpassungen eines fertigen Bildes verwenden dessen Rohbild und wenden die Rauschreduzierung nicht erneut an.",
|
||||
"render.cpu_direction": "Richtung zum Licht (X, Y, Z)",
|
||||
"render.cpu_directional": "Richtungslicht",
|
||||
"render.cpu_directional_add": "Richtungslicht hinzufügen",
|
||||
@@ -3043,8 +3102,11 @@
|
||||
"render.cpu_environment_samples": "HDR-Beleuchtungs-Samples",
|
||||
"render.cpu_exposure_help": "Die CPU-Belichtung muss zwischen −16 und 16 EV liegen. Eine GPU-Belichtung außerhalb dieses Bereichs bleibt erhalten, bis Sie sie ändern.",
|
||||
"render.cpu_fixed": "Einzelbild",
|
||||
"render.cpu_fixed_retained": "Feste Abtastung beibehalten",
|
||||
"render.cpu_glass_enable_path": "Indirekte Beleuchtung einschalten",
|
||||
"render.cpu_hdr_help": "Radiance-HDR-Datei (.hdr), Panorama im Format 2:1, bis zu 2048 × 1024 Pixel und 16 MiB. Für die CPU müssen die sRGB/D65-Primärfarben ausdrücklich in der Datei angegeben sein. Dateien ohne Angabe der Primärfarben sowie EXR-Dateien werden abgelehnt.",
|
||||
"render.cpu_hdr_reflection_help": "Raue HDR-Reflexionen erfordern vollständig metallische Körper- und Flächenoberflächen. Die Prüfung meldet nicht unterstützte Kombinationen.",
|
||||
"render.cpu_indirect_method_required": "Wähle CPU-Raytracing, um diesen Modus für indirekte Beleuchtung einzuschalten.",
|
||||
"render.cpu_key_rim": "Haupt- und Konturlicht",
|
||||
"render.cpu_last_check": "Letzte CPU-Prüfung",
|
||||
"render.cpu_light_help": "Bis zu acht Richtungslichter. Eine leere eigene Liste schaltet sie aus; die Wahl einer Vorgabe stellt deren Lichter wieder her. Farben sind lineares RGB, und die Intensität ist ein relativer Wert, keine Leistungsangabe in Watt.",
|
||||
@@ -3056,18 +3118,32 @@
|
||||
"render.cpu_lighting": "Beleuchtungsvorgabe",
|
||||
"render.cpu_lights": "CPU-Lichter",
|
||||
"render.cpu_linear_color": "Lineare Farbe (R, G, B)",
|
||||
"render.cpu_maps_saved_help": "CPU-Renderings können gespeicherte Karten undurchsichtiger Flächen verwenden: Oberfläche wählen und die Karten in der Aufnahme speichern. Mit indirekter Beleuchtung darf ein anderer Körper Glas verwenden; der Körper mit Karten darf kein Glas sein. Ausgewählte Reflexionen, Anisotropie und prozedurale Effekte ausschalten. Temporäre Kartendateipfade verwenden die GPU.",
|
||||
"render.cpu_material_certification": "Die CPU-Prüfung validiert unterstützte Glasgeometrie vor dem Rendern. Geschlossenes Glas verwendet geometrische Abstände.",
|
||||
"render.cpu_neutral": "Neutral",
|
||||
"render.cpu_opaque_hint": "CPU-Raytracing verwendet einen undurchsichtigen Hintergrund.",
|
||||
"render.cpu_opaque_required": "CPU-Raytracing benötigt einen undurchsichtigen Hintergrund. Entfernen Sie das Häkchen bei „Transparenter Hintergrund“, um fortzufahren.",
|
||||
"render.cpu_options_pending": "Dieses CPU-Bedienfeld kann Emission, Oberflächeneffekte, Glas oder Anisotropie noch nicht bearbeiten. Entfernen Sie diese API-Optionen, bevor Sie es verwenden.",
|
||||
"render.cpu_path_depth": "Pfadtiefe",
|
||||
"render.cpu_path_help": "Berechnet Licht, das zwischen undurchsichtigen Flächen und durch unterstützte Glasformen läuft. Erfordert progressives Rendern und Raytracing-Schatten. Die Pfadtiefe zählt beleuchtete Flächen, Glasgrenzen und Streuereignisse ab dem ersten Treffer (1–16). Tiefe 1 liefert direkte Beleuchtung auf undurchsichtigen Flächen; höhere Werte erlauben mehr Reflexionen oder Glasdurchgänge und können länger dauern. Für eigene Reflexionen oder Anisotropie die indirekte Beleuchtung ausschalten.",
|
||||
"render.cpu_path_lighting": "Indirekte Beleuchtung",
|
||||
"render.cpu_path_optics_reason": "Die Einstellungen bleiben erhalten. Für eigene Reflexionen oder Anisotropie die indirekte Beleuchtung ausschalten.",
|
||||
"render.cpu_point": "Punktlicht",
|
||||
"render.cpu_point_add": "Punktlicht hinzufügen",
|
||||
"render.cpu_point_help": "Bis zu acht Punktlichter, zusätzlich zur gewählten Richtungsbeleuchtung. Abstände in mm; der Mindestabstand darf den Referenzabstand nicht überschreiten.",
|
||||
"render.cpu_primary_samples": "Kanten-Samples pro Pixel",
|
||||
"render.cpu_progressive": "CPU progressiv",
|
||||
"render.cpu_progressive_help": "Den vorhandenen CPU-Integrator in Durchgängen mit je einem Primär-Sample akkumulieren. Ausgewählte Reflexionen erfordern ein Sample; Flächenlichter, Dielektrika und Anisotropie erfordern „Einzelbild“.",
|
||||
"render.cpu_progressive_adopt": "Progressive Abtastung verwenden",
|
||||
"render.cpu_progressive_adopt_help": "Die progressive Abtastung verwendet ein Kamerasample pro Durchlauf. Bildgröße, Lichtquellen und Reflexionseinstellungen bleiben unverändert.",
|
||||
"render.cpu_progressive_always": "Progressive Abtastung ist immer aktiv",
|
||||
"render.cpu_progressive_help": "Neue CPU-Kamerasamples sammeln und jeden vollständigen Durchgang zeigen. Ausgewählte Reflexionen verwenden einen Versuch pro Kamerasample; zertifiziertes Glas und planare Anisotropie behalten ihre bisherigen Grenzen. Adaptive Pilot- und Produktionssamples teilen sich das CPU-Profilbudget.",
|
||||
"render.cpu_progressive_limits": "Höchstens 1.048.576 Pixel und 16.777.216 Auswertungen von Pixel × Sample. Das Ändern der Samples passt die Bildgröße nie automatisch an.",
|
||||
"render.cpu_progressive_reflection_adopt": "Setzen Sie die Reflexionsversuche ausgewählter Körper auf 1, bevor Sie die progressive Abtastung übernehmen.",
|
||||
"render.cpu_progressive_seed": "Startwert für das CPU-Sampling",
|
||||
"render.cpu_progressive_spp": "Samples pro Pixel",
|
||||
"render.cpu_quality_budget_help": "Ändert Größe, Obergrenze der Produktionssamples, Startwert und CPU-Ressourcenprofil. Kamera, Objektiv, Beleuchtung, GI-Tiefe und Effekte bleiben erhalten.",
|
||||
"render.cpu_quality_progressive_required": "Aktiviere unten progressive Samples, bevor du ein CPU-Budget auswählst.",
|
||||
"render.cpu_quality_summary": "{width} × {height} · Sample-Grenze {samples} · Startwert {seed} · {profile}",
|
||||
"render.cpu_reflection_add": "Raue Reflexion hinzufügen",
|
||||
"render.cpu_reflection_depth": "Reflexionstiefe (1–8)",
|
||||
"render.cpu_reflection_empty": "Keine Körper ausgewählt: Szenenreflexionen sind aus.",
|
||||
@@ -3081,7 +3157,21 @@
|
||||
"render.cpu_runtime_help": "Numerische Licht- und Umgebungseinstellungen werden mit dem Setup gespeichert. Körperreflexionen und HDR-Dateien bleiben vorübergehend. Vorhandene Werte für Flächenlicht und Spotkegel bleiben erhalten.",
|
||||
"render.cpu_sampling_mode": "CPU-Sampling-Modus",
|
||||
"render.cpu_shadows": "Schatten werfen",
|
||||
"render.cpu_sky_bounds": "Die Himmelsrotation muss endlich innerhalb ±1.000.000 Radiant liegen; die Intensität muss 0–100 sein.",
|
||||
"render.cpu_studio_enable": "Indirekte Beleuchtung für dieses Lichtset aktivieren",
|
||||
"render.cpu_studio_enable_apply": "Indirekte Beleuchtung aktivieren und anwenden",
|
||||
"render.cpu_studio_indirect_help": "Dieses Sonnen-Lichtset benötigt indirekte Beleuchtung mit Tiefe 8, verfolgte Schatten und eine Kamerastichprobe pro Durchlauf. Ist progressives Rendern ausgeschaltet, beginnt es mit 16 Stichproben pro Pixel und Startwert 0. Vorhandene progressive Einstellungen und das Ressourcenprofil bleiben erhalten. Unvereinbare Einstellungen verhindern die Anwendung, ohne sie zu ändern.",
|
||||
"render.cpu_studio_radiance_limit": "Dieses Lichtset hat eine Flächenstrahldichte von {radiance}, über der CPU-Grenze von 64. Die vorgegebene Beleuchtung bleibt erhalten; wählen Sie ein anderes Lichtset oder GPU.",
|
||||
"render.cpu_subsurface_denoise_reason": "Streuung im Glas auf der CPU benötigt ausgeschaltete Rauschreduzierung. Die Einstellungen bleiben erhalten.",
|
||||
"render.cpu_subsurface_help": "Streuung lenkt Licht im Inneren geschlossenen Glases um. Positive Raten benötigen indirekte Beleuchtung ohne Rauschreduzierung. Die Rate zählt Kollisionen pro mm; 0 fügt keine Streuung hinzu. Positive Richtungswerte bevorzugen vorwärts, negative rückwärts.",
|
||||
"render.cpu_summary": "CPU-Raytracing · Reflexionen · HDR · Richtungs- und Punktlichter",
|
||||
"render.cpu_transparent_help": "Transparentes PNG entfernt den Hintergrund und erhält die Kantenabdeckung. Körper- und Flächendeckkraft müssen 100 % bleiben.",
|
||||
"render.cpu_volume_enable_path": "Indirekte Beleuchtung einschalten",
|
||||
"render.cpu_volume_enable_path_plan": "CPU-Raytracing · Pfadtiefe {depth} · {spp} Samples/Pixel · Seed {seed} · Raytracing-Schatten. Atmosphäre und Bildbudget bleiben erhalten.",
|
||||
"render.cpu_volume_help": "CPU-Atmosphäre nutzt indirekte Beleuchtung. Bei Extinktion null bleibt die gespeicherte Box ohne Nebel erhalten.",
|
||||
"render.cpu_volume_method_adopt": "CPU-Raytracing mit indirekter Beleuchtung",
|
||||
"render.cpu_volume_method_incompatible": "Diese Licht-, Sampling- oder Atmosphäreinstellungen lassen sich nicht auf diese Methode übertragen. Die Einstellungen bleiben erhalten.",
|
||||
"render.cpu_volume_path_required": "Indirekte Beleuchtung einschalten, um CPU-Atmosphäre zu nutzen.",
|
||||
"render.cpu_warm_cool": "Warm und kühl",
|
||||
"render.diag_bodies": "Sichtbare Körper",
|
||||
"render.diag_job_details": "Erfasste Auftragsdetails",
|
||||
@@ -3091,6 +3181,7 @@
|
||||
"render.diag_preflight_details": "Details der Vorabprüfung",
|
||||
"render.diag_request": "Aktuelle Anfrage im Wortlaut",
|
||||
"render.diag_triangles": "Dreiecke",
|
||||
"render.directional_sun_limit": "Die GPU unterstützt insgesamt acht gerichtete Lichtquellen, darunter höchstens eine weiche Sonne. Dupliziere ein hartes gerichtetes Licht für eine weitere entfernte Quelle.",
|
||||
"render.discard_continue": "Entwurf verwerfen und fortfahren",
|
||||
"render.draft_confirm_help": "Der aktuelle Render-Entwurf enthält nicht angewendete Änderungen. Speichern Sie sie vor dem Wechsel, verwerfen Sie sie ausdrücklich oder bearbeiten Sie weiter.",
|
||||
"render.draft_confirm_title": "Bearbeitete Rendereinstellungen beibehalten",
|
||||
@@ -3240,7 +3331,7 @@
|
||||
"render.export_display": "Export: Anzeige-PNG",
|
||||
"render.export_image_label": "Bild exportieren",
|
||||
"render.export_linear": "Export: lineares Roh-EXR",
|
||||
"render.exr_pending": "Die GPU kann rohe lineare EXR-Dateien behalten. Kompression, mehrschichtige Bilder und zusätzliche Renderpässe bleiben nicht verfügbar.",
|
||||
"render.exr_pending": "CPU-Raytracing und GPU-Pathtracing können rohe lineare EXR-Dateien behalten. Kompression, mehrschichtige Bilder und zusätzliche Renderpässe bleiben nicht verfügbar.",
|
||||
"render.film_grain": "Fotografisches Korn",
|
||||
"render.fit": "Produkt einpassen",
|
||||
"render.fixed_camera": "Kamera",
|
||||
@@ -3278,11 +3369,21 @@
|
||||
"render.frame_tall": "9:16 · Vertikal",
|
||||
"render.frame_thirds": "Drittellinien",
|
||||
"render.frame_wide": "16:9 · Breitbild",
|
||||
"render.glass_abbe": "Abbe-Zahl",
|
||||
"render.glass_dispersion": "Chromatische Dispersion",
|
||||
"render.glass_film": "Dünnschichtinterferenz",
|
||||
"render.glass_film_ior": "Brechungsindex der Schicht",
|
||||
"render.glass_film_thickness": "Schichtdicke",
|
||||
"render.glass_model_enable": "Erweitertes Glasmodell",
|
||||
"render.glass_model_help": "Glasrauheit streut durchgelassene Strahlen. Dispersion und Schichtfarbe verwenden drei Wellenlängenbänder. Raue Scheiben benötigen ausgeschaltete gerade Schattenübertragung.",
|
||||
"render.glass_roughness": "Glasrauheit",
|
||||
"render.gpu_depth": "Maximale Pfadtiefe",
|
||||
"render.gpu_job_shader_wait": "Shader-Vorbereitung kann Minuten dauern",
|
||||
"render.gpu_options_help": "Samples, Tiefe, Startwert und Belichtung werden mit diesem Setup gespeichert. Es wird nur die aktive Bildmethode gespeichert.",
|
||||
"render.gpu_path_crashed": "SolidCraft wurde beim letzten Einrichten auf diesem Grafikadapter beendet, wahrscheinlich im Grafiktreiber, und richtet ihn deshalb nicht von selbst erneut ein. Verwenden Sie stattdessen Raytracing auf der CPU oder versuchen Sie es erneut (nach einem Treiberupdate wird es ebenfalls erneut versucht).",
|
||||
"render.gpu_path_failed": "GPU-Pathtracer nicht verfügbar",
|
||||
"render.gpu_path_first_setup": "Das erste Setup auf dieser GPU kann mehrere Minuten dauern; SolidCraft bleibt währenddessen bedienbar. Spätere Starts verwenden die kompilierten Shader erneut, sofern der Treiber sie behält.",
|
||||
"render.gpu_path_not_started": "Die Einrichtung des GPU-Pfadtracers wurde noch nicht gestartet.",
|
||||
"render.gpu_path_preparing": "GPU-Pathtracer: Shader werden kompiliert…",
|
||||
"render.gpu_path_retry": "Erneut versuchen",
|
||||
"render.gpu_seed": "Zufallsstartwert",
|
||||
@@ -3478,6 +3579,8 @@
|
||||
"render.light_product_centre": "Produktmitte",
|
||||
"render.light_size": "Größe",
|
||||
"render.light_softness": "Weichheit",
|
||||
"render.light_space_world": "Lichter in Weltkoordinaten",
|
||||
"render.light_space_world_help": "Lichtpositionen und -richtungen verwenden Weltkoordinaten. Beim Umkreisen mit der Kamera bleiben die Lichter an ihrer Position.",
|
||||
"render.light_temperature": "Farbtemperatur",
|
||||
"render.light_temperature_help": "Angenäherte Schwarzkörperfarbe; als lineares RGB gespeichert.",
|
||||
"render.light_type": "Typ",
|
||||
@@ -3534,6 +3637,25 @@
|
||||
"render.linear_help": "Behält ein lineares 32-Bit-Gleitkomma-RGBA-Rohbild vor Entrauschen, Belichtung, Tone-Mapping, Filtern und Hintergrund. Lineares sRGB/D65; Abdeckung vormultipliziert. Zusätzlicher Speicher wird ausdrücklich zugelassen. Keine Komprimierung und keine zusätzlichen Durchgänge.",
|
||||
"render.linear_retain": "Lineares Roh-EXR behalten",
|
||||
"render.linear_unavailable": "Für das gewählte fertige Bild wurde kein EXR behalten. Aktivieren Sie das Behalten vor dem Rendern; ein älteres PNG kann die rohe Strahldichte nicht wiederherstellen.",
|
||||
"render.live.adaptive": "Live · {width} × {height} · {progress}",
|
||||
"render.live.final_changed": "Die Render-Anfrage hat sich beim Anhalten des Live-Renderings geändert. Starten Sie das finale Bild erneut.",
|
||||
"render.live.final_waiting": "Finales Bild vorbereiten · Live-Render-Ressourcen freigeben",
|
||||
"render.live.invalid_size": "Live-Rendering benötigt eine positive Ausgabebreite und -höhe.",
|
||||
"render.live.pause": "Live pausieren",
|
||||
"render.live.paused": "Live · Pausiert",
|
||||
"render.live.paused_outdated": "Live · Pausiert · Veraltet",
|
||||
"render.live.quality_help": "Interaktive Qualität: höchstens 512 Pixel an der längsten Kante. Verwendet den gewählten Renderer und seine unterstützten Effekte. Endauflösung, Einstellungen und Export bleiben getrennt.",
|
||||
"render.live.refused": "Live nicht verfügbar: {reason}",
|
||||
"render.live.resume": "Live fortsetzen",
|
||||
"render.live.samples": "Live · {width} × {height} · {current}/{target} Samples",
|
||||
"render.live.source_current": "{method} · Live",
|
||||
"render.live.source_outdated": "{method} · Vorheriges Bild",
|
||||
"render.live.source_outdated_help": "Zeigt das zuletzt aufgenommene Bild, während das Live-Rendering aktualisiert wird oder nicht verfügbar ist. Es kann von der aktuellen Szene oder den Bildeinstellungen abweichen.",
|
||||
"render.live.source_settings_help": "Ausgabe öffnen, um Renderer und Bildeinstellungen zu bearbeiten.",
|
||||
"render.live.stopped": "Live-Rendering angehalten",
|
||||
"render.live.updating": "Live · Interaktive Qualität (bis 512 px) · Aktualisierung",
|
||||
"render.live.waiting_canvas": "Warten auf die Render-Ansicht",
|
||||
"render.live.worker_stopped": "Der Aufnahmeprozess für das Live-Rendering wurde vor der Rückgabe eines Ergebnisses beendet",
|
||||
"render.look_add": "Farblook hinzufügen",
|
||||
"render.look_applied": "{name} angewendet",
|
||||
"render.look_bleach": "Von Bleach-Bypass inspiriert",
|
||||
@@ -3563,6 +3685,9 @@
|
||||
"render.material_coat_help": "Illustrative dielektrische Beschichtung über dem vorhandenen undurchsichtigen Erscheinungsbild. Gewicht null lässt das Grundmaterial unverändert.",
|
||||
"render.material_color_map": "Grundfarbentextur (sRGB)",
|
||||
"render.material_color_replace": "Basismap ersetzt Körperfarbe",
|
||||
"render.material_cpu_glass_only": "Temporäre Bilddatei-Karten benötigen die GPU. Die CPU kann gespeicherte integrierte Oberflächenkarten verwenden.",
|
||||
"render.material_cpu_optics_limits": "Indirekte Beleuchtung für unterstützte geschlossene Glasformen, geprüfte Verschachtelung und Streuung im Inneren einschalten. Dünne Scheiben können Licht für Schatten durchlassen. Sonst eine ebene Scheibe oder achsenparallele Box verwenden. Berührende Formen und durch geschlossenes Glas übertragene Schatten werden weiterhin nicht unterstützt. Die Werte bleiben erhalten.",
|
||||
"render.material_cpu_saved_runtime_conflict": "Gespeicherte CPU-Optik kann nicht mit temporären optischen Bindungen kombiniert werden. Geprüfte Optik speichern oder die temporäre Bindung entfernen.",
|
||||
"render.material_custom": "Eigene illustrative Optik",
|
||||
"render.material_enable": "Diese GPU-Materialüberschreibungen verwenden",
|
||||
"render.material_filter": "Szenenkörper filtern…",
|
||||
@@ -3583,6 +3708,7 @@
|
||||
"render.material_normal_map": "Normalenbild (OpenGL, +Y)",
|
||||
"render.material_normal_strength": "Normalenstärke (0–1)",
|
||||
"render.material_origin": "Texturursprung X · Y · Z (mm)",
|
||||
"render.material_raytrace_required": "Physikalisches Glas benötigt CPU-Raytracing oder GPU-Pathtracing.",
|
||||
"render.material_refresh": "Szenenkörper aktualisieren",
|
||||
"render.material_refresh_needed": "Die Szene hat sich geändert. Aktualisieren Sie die Körperliste, bevor Sie ein Ziel hinzufügen.",
|
||||
"render.material_remove": "Diese Zuweisung entfernen",
|
||||
@@ -3592,6 +3718,7 @@
|
||||
"render.material_revalidate_needed": "Diese Zuweisung gehört zu einer früheren Szenenrevision. Prüfen Sie die genaue Körperidentität erneut, bevor Sie rendern.",
|
||||
"render.material_roughness": "Rauheit des Klarlacks (0,045–1)",
|
||||
"render.material_roughness_map": "Rauheitsmap (linear)",
|
||||
"render.material_saved_edit_pending": "Diese Optikänderungen sind ungespeichert. Geprüfte Werte speichern, die gespeicherte Zuordnung entfernen oder Änderungen verwerfen. Temporäre Bindungen und nicht unterstützte Effekte können das gespeicherte Ziel nicht überschreiben.",
|
||||
"render.material_shadow": "Gerade Schattenstrahlen durchlassen",
|
||||
"render.material_target_missing": "Ordnungsnummer und Name des Körpers stimmen nicht mehr überein. Entfernen Sie diese Zuweisung und wählen Sie den gewünschten Körper ausdrücklich erneut.",
|
||||
"render.material_thickness": "Dicke der dünnen Schicht (mm)",
|
||||
@@ -3603,7 +3730,7 @@
|
||||
"render.method_cpu": "CPU-Raytracing",
|
||||
"render.method_gpu": "GPU-Pathtracing",
|
||||
"render.method_limit_raster": "Die Rasterung verwendet die feste undurchsichtige Studiovorschau. Wählen Sie ausdrücklich eine Raytracing-Methode für die unterstützten optischen Einstellungen.",
|
||||
"render.method_raster": "CPU-Rasterung",
|
||||
"render.method_raster": "CPU-Rasterung (schematisch)",
|
||||
"render.navigation_help": "Die Kamera bewegt sich wie im Konstruieren (Einstellungen › Navigation). Setup speichern übernimmt die aktuelle Kamera.",
|
||||
"render.nested_enable": "Zertifizierte verschachtelte Dielektrika",
|
||||
"render.nested_help": "Bis zu 16 umschließende Schichten; jedes übergeordnete Element muss konvex und jedes untergeordnete strikt darin enthalten sein. Überschneidungen, sich berührende Flächen, dünne Schichten und die Transmission gerader Schattenstrahlen werden abgelehnt. Der Zustand „Kamera im Inneren“ folgt der zertifizierten Hierarchie. Erzeugt keine Flüssigkeitsoberfläche und verschmilzt keine sich berührenden CAD-Grenzflächen.",
|
||||
@@ -3631,16 +3758,19 @@
|
||||
"render.output_exr_unavailable": "EXR-Ausgabeeinstellungen sind hier nicht verfügbar. Linearer EXR-Export erfordert ein fertiges GPU-Bild mit gespeichertem linearem Original.",
|
||||
"render.output_fit": "Einpassen",
|
||||
"render.output_format": "Format",
|
||||
"render.output_format_status": "PNG enthält das exakte fertige Anzeigebild. Optionales GPU-EXR bewahrt rohe lineare FLOAT32-Strahldichte vor Filtern. Export ersetzt nie durch Vorschaucache oder anderen Auftrag.",
|
||||
"render.output_format_status": "PNG enthält das exakte fertige Anzeigebild. Optionales CPU/GPU-EXR bewahrt rohe lineare FLOAT32-Strahldichte vor Anzeigefiltern. Der Export verwendet nie den Vorschaucache oder einen anderen Auftrag.",
|
||||
"render.output_grading": "Farbkorrektur",
|
||||
"render.output_image": "Bild",
|
||||
"render.output_largest": "{width} × {height} max.",
|
||||
"render.output_lock_ratio": "Seitenverhältnis sperren",
|
||||
"render.output_master_unavailable": "Zum EXR-Export ein fertiges Bild mit EXR-Rohdaten auswählen. EXR-Rohdaten vor dem Rendern neuer Bilder aktivieren.",
|
||||
"render.output_over_budget": "Das angeforderte Bild überschreitet den gewählten Ressourcenrahmen. Wählen Sie ausdrücklich eine passende Größe oder ein passendes Profil; es erfolgt keine automatische Herabstufung.",
|
||||
"render.output_presentation_limits": "CPU-Bildeffekte und EXR-Ausgabe unterstützen Bilder mit bis zu 8192 Pixeln Breite oder Höhe und insgesamt höchstens 16.777.216 Pixeln.",
|
||||
"render.output_presets_help": "Format, Qualität und Prüfliste befinden sich im Ausgabeeditor.",
|
||||
"render.output_quality": "Qualität",
|
||||
"render.output_quality_waiting": "Qualitätsdefinition steht noch aus",
|
||||
"render.output_ratio_refused": "Die verknüpfte Abmessung überschreitet das Größenlimit dieser Methode. Die vorherige Größe bleibt erhalten; entsperren Sie das Verhältnis oder wählen Sie einen kleineren Wert.",
|
||||
"render.output_raytrace_only": "Bildeffekte erfordern CPU-Raytracing oder GPU-Pathtracing.",
|
||||
"render.output_ready": "Bereit zum Rendern",
|
||||
"render.output_run_check": "Prüfung starten",
|
||||
"render.output_size_limit": "{method}: bis zu {dimension} px pro Seite und {pixels} Pixel. Größte passende Größe: {width} × {height}.",
|
||||
@@ -3695,6 +3825,12 @@
|
||||
"render.post_saturation": "Sättigung",
|
||||
"render.post_title": "Darstellungsfilter",
|
||||
"render.post_vignette": "Vignettierung",
|
||||
"render.preparation_cancelled": "Rendering-Vorbereitung abgebrochen",
|
||||
"render.preparation_checking": "Rendering wird geprüft",
|
||||
"render.preparation_retirement_failed": "Die Bereinigung der Rendering-Vorbereitung ist fehlgeschlagen. Dieses Fenster kann kein weiteres Bild vorbereiten.",
|
||||
"render.preparation_retiring": "Rendering-Vorbereitung wird abgeschlossen",
|
||||
"render.preparation_unavailable": "Rendering-Vorbereitung nicht verfügbar",
|
||||
"render.presentation_banner": "Bildeffekte funktionieren mit CPU- und GPU-Raytracing. Das Öffnen dieser Seite ändert die Methode nicht.",
|
||||
"render.preview": "Integrierte Vorschau",
|
||||
"render.preview_help": "Rasterdarstellung mit gemischter Transparenz. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.",
|
||||
"render.preview_image_settings_help": "Die Live-Vorschau behält eine feste Studiobeleuchtung. Belichtung und Bildbeleuchtung gelten für den Bildauftrag, wenn Sie „Prüfen“ oder „Start“ verwenden.",
|
||||
@@ -3713,11 +3849,15 @@
|
||||
"render.quality_ack": "Die Projektion mit festem Budget und ihre Auslassungen bestätigen",
|
||||
"render.quality_apply": "Dieses feste Sampling-Budget verwenden",
|
||||
"render.quality_balanced": "Ausgewogen",
|
||||
"render.quality_budget_help": "Legt Größe, Samples, Tiefe, Startwert und Rauschreduzierung fest. Andere Bildeinstellungen bleiben erhalten.",
|
||||
"render.quality_custom": "Benutzerdefiniert",
|
||||
"render.quality_denoise_off": "Rauschreduzierung: Aus",
|
||||
"render.quality_denoise_on": "Rauschreduzierung: Ein",
|
||||
"render.quality_draft": "Entwurf",
|
||||
"render.quality_high": "Hoch",
|
||||
"render.quality_projection_help": "Q-Vorgaben enthalten künftige Anforderungen. Diese Aktion projiziert nur ein unterstütztes PNG-Budget mit festen Samples und lässt adaptives Stoppen, rohe lineare Ausgabe und unabhängige Transmissionslimits ausdrücklich aus.",
|
||||
"render.quality_projection_help": "Diese Prüfung ändert nur Auflösung, Abtastbudget, Pfadtiefe, Startwert und Rauschreduzierung. Andere Einstellungen bleiben erhalten; das Budget garantiert keine Konvergenz.",
|
||||
"render.quality_review": "Sampling-Budget prüfen",
|
||||
"render.quality_summary": "{width} × {height} · {samples} Samples · Tiefe {depth} · Startwert {seed} · {denoise}",
|
||||
"render.queue_pending": "In dieser Oberfläche gibt es keine automatische Produktionswarteschlange und keinen Animations-Renderer. Fertige Einzelbilder bleiben separat exportierbar.",
|
||||
"render.radial_assign": "Erscheinungsbild zuweisen",
|
||||
"render.radial_compare": "Vergleichen",
|
||||
@@ -3747,7 +3887,7 @@
|
||||
"render.result_navigation": "Verschieben und Zoomen folgen den Navigationseinstellungen. Leertaste + Ziehen verschiebt.",
|
||||
"render.result_open": "Das fertige Bild in der Hauptansicht öffnen.",
|
||||
"render.result_preview": "Live-Vorschau",
|
||||
"render.result_provisional": "Vorläufiges CPU-Bild",
|
||||
"render.result_provisional": "Vorläufiges Bild",
|
||||
"render.result_provisional_help": "Dieser Zwischenstand ist nicht exportierbar. Der Export behält das letzte fertige Ergebnis; ein Abbruch kehrt zu diesem Ergebnis zurück.",
|
||||
"render.result_reduced_display": "Anzeigevorschau auf die Geräte-/Cachegrenze reduziert. PNG und Export behalten die volle Auflösung; native 100%-Ansicht ist hier nicht verfügbar.",
|
||||
"render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.",
|
||||
@@ -3836,9 +3976,11 @@
|
||||
"render.shot_frame_subject": "Motiv einpassen",
|
||||
"render.shot_invalid_camera": "Kamerawerte müssen endlich und im gültigen Bereich sein.",
|
||||
"render.shot_lens": "Objektiv",
|
||||
"render.shot_lens_cpu_progressive_reason": "Vor der CPU-Schärfentiefe unter Sampling die progressive Abtastung übernehmen.",
|
||||
"render.shot_lens_enable_reason": "Schärfentiefe aktivieren, um Blende und Fokusabstand zu bearbeiten.",
|
||||
"render.shot_lens_gpu_reason": "Schärfentiefe benötigt GPU-Pfadverfolgung.",
|
||||
"render.shot_lens_perspective_reason": "Schärfentiefe benötigt perspektivische Projektion.",
|
||||
"render.shot_lens_raytrace_reason": "Schärfentiefe ist für CPU-Raytracing und GPU-Pathtracing verfügbar.",
|
||||
"render.shot_look_selection": "Auswahl anvisieren",
|
||||
"render.shot_manager": "Gespeicherte Aufnahmen",
|
||||
"render.shot_new_name": "Neuer Aufnahmename",
|
||||
@@ -3872,7 +4014,12 @@
|
||||
"render.sky_horizon": "Horizont · lineares RGB",
|
||||
"render.sky_zenith": "Zenit · lineares RGB",
|
||||
"render.soft_focus": "Weichzeichnung",
|
||||
"render.spot_axis": "Abstrahlrichtung",
|
||||
"render.spot_cone": "Spotkegel",
|
||||
"render.spot_gpu_help": "Die Winkel werden von der Abstrahlrichtung aus gemessen. Zwischen innerem und äußerem Winkel wird das Licht schwächer. Sehr schmale Übergänge erfordern CPU-Rendering.",
|
||||
"render.spot_help": "Die Winkel werden von der Abstrahlrichtung aus gemessen. Zwischen innerem und äußerem Winkel wird das Licht schwächer.",
|
||||
"render.spot_inner": "Innerer Halbwinkel",
|
||||
"render.spot_outer": "Äußerer Halbwinkel",
|
||||
"render.stage_frame": "Bildausschnitt",
|
||||
"render.stage_layout.appearance_note": "Zum Anwenden auf die Auswahl klicken.",
|
||||
"render.stage_layout.studio_note": "Vor dem Anwenden zur Prüfung klicken.",
|
||||
@@ -3912,7 +4059,7 @@
|
||||
"render.stage_panels.prepare_plan": "Erstellungsplan vorbereiten",
|
||||
"render.stage_panels.projects": "Projiziert",
|
||||
"render.stage_panels.quality_ack": "Ich bestätige das feste Budget und seine Auslassungen",
|
||||
"render.stage_panels.quality_omissions": "Adaptives Stoppen und Fehlerziele, separate Transmissionstiefe, Russian-Roulette-Regeln, lineare Rohausgabe, EXR-Master und Konvergenznachweis.",
|
||||
"render.stage_panels.quality_omissions": "Dieses Budget legt keine adaptiven Fehlerziele, eigenen Transmissionsgrenzen, Russian-Roulette-Regeln oder Speicherung des linearen Masters fest und garantiert keine Konvergenz.",
|
||||
"render.stage_panels.reference": "Referenz",
|
||||
"render.stage_panels.references": "Referenzen",
|
||||
"render.stage_panels.remove_optics": "Optik entfernen",
|
||||
@@ -3956,7 +4103,7 @@
|
||||
"render.stage_panels.subtitle_environment": "Originale HDR-Umgebung · gesamte Szene",
|
||||
"render.stage_panels.subtitle_maps": "Erstellte räumliche Texturen · temporäre Vorschau",
|
||||
"render.stage_panels.subtitle_physical": "Schreibgeschützter Plan · kein Material erstellt oder zugewiesen",
|
||||
"render.stage_panels.subtitle_quality": "Festes GPU-Budget · zukünftige Anforderungen ausgelassen",
|
||||
"render.stage_panels.subtitle_quality": "GPU-Abtastbudget · nur aufgeführte Einstellungen",
|
||||
"render.stage_panels.subtitle_rig": "Erstellter Lichtaufbau · Lichtquellen und passive Flächen",
|
||||
"render.stage_panels.subtitle_saved_maps": "Erstellte Texturen · mit dieser Aufnahme gespeichert",
|
||||
"render.stage_panels.subtitle_stage": "Physischer Boden und Bühne · an das Produkt angepasst",
|
||||
@@ -3981,7 +4128,7 @@
|
||||
"render.studio_area_help": "Bis zu vier einseitige Rechtecke. Orthogonale Halbkanten U und V bestimmen die Größe; U × V zeigt zur beleuchteten Seite. Die Koordinaten sind Weltmillimeter.",
|
||||
"render.studio_center": "Mittelpunkt X, Y, Z (mm)",
|
||||
"render.studio_denoise": "Rauschen im fertigen Bild reduzieren",
|
||||
"render.studio_denoise_help": "Abschließender kantenerhaltender Filter; feine Details können weicher werden. Glas und scharfe spiegelnde Oberflächen umgehen den Filter.",
|
||||
"render.studio_denoise_help": "Kantenerhaltender Filter für progressive und fertige Bilder; feine Details können weicher werden. Glas und scharfe spiegelnde Oberflächen umgehen den Filter.",
|
||||
"render.studio_direction": "Richtung zur Sonne (X, Y, Z)",
|
||||
"render.studio_environment": "Umgebung",
|
||||
"render.studio_environment_bounds": "Die Umgebungsdrehung muss endlich und innerhalb von ±1.000.000 Radiant liegen, die Intensität zwischen 0 und 100.",
|
||||
@@ -4074,11 +4221,15 @@
|
||||
"render.use_preview": "Integrierte Vorschau verwenden",
|
||||
"render.volume_albedo": "Streualbedo · lineares RGB",
|
||||
"render.volume_anisotropy": "Mittlerer Phasenkosinus",
|
||||
"render.volume_denoise_required": "Für Atmosphäre die Rauschreduzierung ausschalten.",
|
||||
"render.volume_enable": "Teilnehmendes Medium aktivieren",
|
||||
"render.volume_extinction": "Extinktionskoeffizient",
|
||||
"render.volume_glass_required": "Atmosphäre und Glas können in dieser Einstellung nicht kombiniert werden.",
|
||||
"render.volume_help": "GPU-Transport innerhalb einer endlichen Box, mit Beer-Lambert-Abschwächung und HG-Streuung auf Kamera- und indirekten Pfaden. Verwendet ausdrückliche Studio-, HDR- und Himmelsbeleuchtung einschließlich Schattenabschwächung. Ein positiver Phasenkosinus streut nach vorn. Glasgrenzflächen und Oberflächenentrauschen müssen ausdrücklich deaktiviert werden. Extinktion null lässt den Transport unverändert. Keine physikalische Mondatmosphäre, kein Dichtegitter, keine Volumenemission, kein spektraler Transport und keine zertifizierte Materialeigenschaft.",
|
||||
"render.volume_lighting_required": "Für Atmosphäre eine Umgebung oder ein eigenes Lichtrig wählen.",
|
||||
"render.volume_max": "Obere Grenzen · Weltkoordinaten (mm)",
|
||||
"render.volume_min": "Untere Grenzen · Weltkoordinaten (mm)",
|
||||
"render.volume_single_stratum_required": "Für Atmosphäre ein Transmissionssample verwenden.",
|
||||
"render.volume_title": "Begrenztes homogenes Volumen",
|
||||
"render.wait_add_light": "Noch nicht unterstützt: benannte Lichtquellen erstellen",
|
||||
"render.wait_batch": "Noch nicht unterstützt: Renderwarteschlange gespeicherter Aufnahmen",
|
||||
@@ -4195,6 +4346,7 @@
|
||||
"sketch.dimension_applied": "Maß angewendet",
|
||||
"sketch.dimension_applied_defined": "Maß angewendet; Parameter `{name}` definiert",
|
||||
"sketch.dimension_applied_renamed": "Maß angewendet; der Parameter heißt jetzt `{name}`",
|
||||
"sketch.divide_hint": "Punkte teilen jede Kurve in gleich lange Abschnitte und behalten sie bei, wenn sie sich ändert.",
|
||||
"sketch.dof_left": "{count} Freiheitsgrade übrig",
|
||||
"sketch.dof_left_one": "{count} Freiheitsgrad übrig",
|
||||
"sketch.draw_curves": "Als {linetype} zeichnen",
|
||||
@@ -5051,6 +5203,7 @@
|
||||
"ui.heading_custom_view_navigator": "EIGENER ANSICHTSNAVIGATOR",
|
||||
"ui.heading_cylinder": "ZYLINDER",
|
||||
"ui.heading_design": "DESIGN",
|
||||
"ui.heading_divide_curve": "KURVE TEILEN",
|
||||
"ui.heading_draft": "ABZIEHEN",
|
||||
"ui.heading_edit": "BEARBEITEN",
|
||||
"ui.heading_equation_curve": "GLEICHUNGSKURVE",
|
||||
@@ -5131,6 +5284,11 @@
|
||||
"ui.history_play_button_show": "Wiedergabe-Schaltfläche einblenden",
|
||||
"ui.history_play_finish_action": "Die aktuelle Aktion abschließen, bevor der Verlauf abgespielt wird",
|
||||
"ui.history_play_roll_back": "Die Verlaufsmarkierung vor dem Abspielen zurücksetzen",
|
||||
"ui.history_scope_all": "Features des ganzen Designs zeigen",
|
||||
"ui.history_scope_all_shown": "Die Features des ganzen Designs",
|
||||
"ui.history_scope_pick": "Eine Komponente bearbeiten oder im Browser wählen, um nur ihre Features zu zeigen",
|
||||
"ui.history_scope_show": "Nur die Features von {name} und der Komponenten darin zeigen",
|
||||
"ui.history_scope_shown": "Die Features von {name} und der Komponenten darin",
|
||||
"ui.history_show_names": "Namen anzeigen",
|
||||
"ui.history_sketch_listed_under": "Aufgeführt unter {feature}",
|
||||
"ui.history_title": "Verlauf",
|
||||
@@ -5175,8 +5333,8 @@
|
||||
"ui.link_copies_text": "Diese Komponenten erzeugen dieselben Körper wie {name}. Sollen sie zu Platzierungen seiner Verknüpfung werden?",
|
||||
"ui.lock": "Sperren",
|
||||
"ui.loft": "Loft",
|
||||
"ui.look_at": "Ansehen",
|
||||
"ui.look_at_anim_desc": "Achsenansicht, Ansehen, Home und Einpassen",
|
||||
"ui.look_at": "Senkrecht auf",
|
||||
"ui.look_at_anim_desc": "Achsenansicht, Senkrecht auf, Home und Einpassen",
|
||||
"ui.major_radius": "Großer Radius",
|
||||
"ui.manipulator_free_alt": "Freies Ziehen des Manipulators auch mit Alt/Option",
|
||||
"ui.manipulator_free_alt_tip": "An: Alt/Option oder Strg/Cmd auf Extrusions-/Gizmo-Pfeilen deaktiviert das Einrasten von Werten. Aus: nur Strg/Cmd.",
|
||||
@@ -5256,6 +5414,101 @@
|
||||
"ui.palette_sketch_options": "Skizzenoptionen",
|
||||
"ui.pan": "Verschieben",
|
||||
"ui.pan_zoom_orbit": "Verschieben, zoomen, umkreisen",
|
||||
"ui.panel_fixture.apply": "Anwenden",
|
||||
"ui.panel_fixture.cancel": "Abbrechen",
|
||||
"ui.panel_fixture.caption": "Synthetisches Panelmuster",
|
||||
"ui.panel_fixture.draft": "Beibehaltener Entwurf",
|
||||
"ui.panel_fixture.editor": "Mustereditor",
|
||||
"ui.panel_fixture.explanation": "Dieser synthetische Inhalt behält seinen Entwurf beim Ausblenden oder Verschieben.",
|
||||
"ui.panel_fixture.fill": "Füllendes Muster",
|
||||
"ui.panel_fixture.finish": "Abschließen",
|
||||
"ui.panel_fixture.finished": "Synthetische Transaktion beendet",
|
||||
"ui.panel_fixture.footer": "Musteraktionen lassen den Entwurf unverändert.",
|
||||
"ui.panel_fixture.guard": "Abbruch bei laufender Transaktion verweigern",
|
||||
"ui.panel_fixture.inline": "Einzeiliges Muster",
|
||||
"ui.panel_fixture.live": "Synthetische Transaktion läuft",
|
||||
"ui.panel_fixture.log": "Musterprotokoll",
|
||||
"ui.panel_fixture.pin": "Angeheftetes Muster",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "Dienstaktualisierungen: {count}",
|
||||
"ui.panel_host.attention": "Aufmerksamkeit erforderlich",
|
||||
"ui.panel_host.bottom": "Unten",
|
||||
"ui.panel_host.close": "Panel schließen",
|
||||
"ui.panel_host.collapse": "Panel einklappen",
|
||||
"ui.panel_host.expand": "Panel ausklappen",
|
||||
"ui.panel_host.floating": "Schwebend",
|
||||
"ui.panel_host.focus": "Panel fokussieren",
|
||||
"ui.panel_host.focus_target": "{title} fokussieren",
|
||||
"ui.panel_host.header": "Panelkopf",
|
||||
"ui.panel_host.join": "Tabs verbinden",
|
||||
"ui.panel_host.join_target": "Tabs mit {title} verbinden",
|
||||
"ui.panel_host.left": "Links",
|
||||
"ui.panel_host.menu": "Panelaktionen",
|
||||
"ui.panel_host.move": "Verschieben nach",
|
||||
"ui.panel_host.overflow": "Weitere Panels",
|
||||
"ui.panel_host.popout": "In einem Fenster öffnen",
|
||||
"ui.panel_host.resize": "Panelgröße ändern",
|
||||
"ui.panel_host.right": "Rechts",
|
||||
"ui.panel_host.rule.availability": "Dieses Panel ist nicht verfügbar.",
|
||||
"ui.panel_host.rule.bounds": "Die Panels passen nicht in ihre Größenbegrenzungen.",
|
||||
"ui.panel_host.rule.capability": "Dieser Host unterstützt diese Aktion nicht.",
|
||||
"ui.panel_host.rule.collection_limit": "Das Panellayout hat seine Grenze erreicht.",
|
||||
"ui.panel_host.rule.duplicate_id": "Diese Panelkennung wird bereits verwendet.",
|
||||
"ui.panel_host.rule.exactly_once": "Jedes Panel muss einmal erscheinen.",
|
||||
"ui.panel_host.rule.feature_disabled": "Diese Aktion ist für dieses Panel deaktiviert.",
|
||||
"ui.panel_host.rule.id": "Die Panelkennung ist ungültig.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "Diese Panels können keine Tabgruppe teilen.",
|
||||
"ui.panel_host.rule.lifecycle": "Das Panel konnte diese Aktion nicht abschließen.",
|
||||
"ui.panel_host.rule.missing_target": "Dieses Panelziel ist nicht mehr verfügbar.",
|
||||
"ui.panel_host.rule.no_space": "Für dieses Panellayout ist kein Platz.",
|
||||
"ui.panel_host.rule.pin_conflict": "An dieser Kante ist bereits ein anderes Panel angeheftet.",
|
||||
"ui.panel_host.rule.pin_order": "Ein angeheftetes Panel muss an seiner Kante zuerst bleiben.",
|
||||
"ui.panel_host.rule.placement": "Dieses Panel kann nicht an diese Position verschoben werden.",
|
||||
"ui.panel_host.rule.revision": "Das Layout wurde geändert. Versuchen Sie die Aktion erneut.",
|
||||
"ui.panel_host.rule.schema": "Die Panelanfrage ist ungültig.",
|
||||
"ui.panel_host.rule.version": "Diese Panellayoutversion wird nicht unterstützt.",
|
||||
"ui.panel_host.sash": "Benachbarte Panels skalieren",
|
||||
"ui.panel_host.scroll_horizontal": "Panelspalten scrollen",
|
||||
"ui.panel_host.scroll_vertical": "Panelstapel scrollen",
|
||||
"ui.panel_host.surface": "Panel",
|
||||
"ui.panel_host.tab": "Paneltab",
|
||||
"ui.panel_host.tabs": "Alle Tabs",
|
||||
"ui.panel_layout.applied": "{name} auf {workspace} angewendet",
|
||||
"ui.panel_layout.cancel": "Abbrechen",
|
||||
"ui.panel_layout.confirm_replace": "„{name}“ ersetzen?",
|
||||
"ui.panel_layout.copy": "Kopieren",
|
||||
"ui.panel_layout.current": "Aktuelles Layout",
|
||||
"ui.panel_layout.custom": "Benutzerdefiniert",
|
||||
"ui.panel_layout.custom_hint": "Panels wurden seit {name} verschoben.",
|
||||
"ui.panel_layout.details": "Details",
|
||||
"ui.panel_layout.layout_workspace": "Layout-Arbeitsbereich",
|
||||
"ui.panel_layout.page_defaults_hint": "Setzt die Einstellungen dieser Seite zurück. Panel-Anordnungen und gespeicherte Layouts bleiben erhalten.",
|
||||
"ui.panel_layout.panel_layout": "Panel-Layout",
|
||||
"ui.panel_layout.panel_style": "Panel-Stil",
|
||||
"ui.panel_layout.replace": "Layout ersetzen",
|
||||
"ui.panel_layout.replace_current": "Durch aktuelle Anordnung ersetzen",
|
||||
"ui.panel_layout.replace_short": "Ersetzen",
|
||||
"ui.panel_layout.reset": "Arbeitsbereich zurücksetzen",
|
||||
"ui.panel_layout.reset_hint": "{workspace} auf die Standardanordnung zurücksetzen. Gespeicherte Layouts bleiben erhalten.",
|
||||
"ui.panel_layout.reset_short": "Zurücksetzen",
|
||||
"ui.panel_layout.restore_failed": "Das Layout konnte nicht wiederhergestellt werden",
|
||||
"ui.panel_layout.save": "Layout speichern",
|
||||
"ui.panel_layout.save_as": "Speichern unter",
|
||||
"ui.panel_layout.save_as_tile": "Speichern unter…",
|
||||
"ui.panel_layout.selected": "ausgewählt",
|
||||
"ui.panel_layout.suggested_name": "Layout {n}",
|
||||
"ui.panel_layout.try_again": "Erneut versuchen",
|
||||
"ui.panel_layout.validation.builtin": "Integrierte Layouts können nicht geändert werden",
|
||||
"ui.panel_layout.validation.duplicate": "Dieser Name ist bereits vorhanden",
|
||||
"ui.panel_layout.validation.empty": "Namen eingeben",
|
||||
"ui.panel_layout.validation.full": "64 von 64 gespeichert. Ein Layout zum Ersetzen wählen.",
|
||||
"ui.panel_layout.validation.invalid": "1–64 Zeichen ohne Steuerzeichen verwenden",
|
||||
"ui.panel_layout.workspace.classic": "Klassisch",
|
||||
"ui.panel_layout.workspace.modelling": "Modellierung",
|
||||
"ui.panel_layout.workspace.render": "Rendern",
|
||||
"ui.panel_layout.workspace.review": "Prüfung",
|
||||
"ui.panel_layout.workspace.sketch": "Skizze",
|
||||
"ui.panel_layout.your_layout": "Eigenes Layout",
|
||||
"ui.parallel": "Parallel",
|
||||
"ui.parameters": "Parameter",
|
||||
"ui.part_size_needs_a_part": "Wählen Sie ein eingefügtes Standardbauteil (Schraube, Mutter, Scheibe oder Stift) aus, um seine Größe zu ändern. Einen Körper vergrößern oder verkleinern Sie mit Skalieren.",
|
||||
@@ -5302,6 +5555,7 @@
|
||||
"ui.point_cloud_no_file_colors": "Die Datei hat keine Farben",
|
||||
"ui.point_cloud_pause": "Pause",
|
||||
"ui.point_cloud_play": "Abspielen",
|
||||
"ui.point_cloud_reload": "Aus Datei neu laden",
|
||||
"ui.point_cloud_single_color": "Einheitliche Farbe",
|
||||
"ui.point_cloud_size": "Punktgröße",
|
||||
"ui.point_cloud_units": "Einheit der Datei",
|
||||
@@ -5396,6 +5650,7 @@
|
||||
"ui.second_rail": "Zweite Leitkurve",
|
||||
"ui.section_analysis": "Querschnittsanalyse",
|
||||
"ui.section_size": "Querschnittsgröße",
|
||||
"ui.segments": "Segmente",
|
||||
"ui.select": "Auswählen",
|
||||
"ui.selectOther": "Andere auswählen…",
|
||||
"ui.selectTangentChain": "Tangentialkette auswählen",
|
||||
@@ -5535,7 +5790,7 @@
|
||||
"ui.unsuppress": "Unterdrückung aufheben",
|
||||
"ui.untied_ends_tip": "Berührt nur nach Position",
|
||||
"ui.untitled": "Ohne Titel",
|
||||
"ui.up_axis_note": "Welche Achse in den Ansichten nach oben zeigt (Achsenansicht, Home, Ansehen). Designs bleiben unverändert.",
|
||||
"ui.up_axis_note": "Welche Achse in den Ansichten nach oben zeigt (Achsenansicht, Home, Senkrecht auf). Designs bleiben unverändert.",
|
||||
"ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren",
|
||||
"ui.upload": "Hochladen",
|
||||
"ui.vertical_constraint": "Vertikale Bedingung",
|
||||
|
||||
@@ -134,6 +134,7 @@
|
||||
"render.aging_metallic": "Layer metallic fraction",
|
||||
"render.aging_origin": "Field origin · world mm",
|
||||
"render.aging_patina": "Copper-green patina",
|
||||
"render.aging_raytrace_help": "Ageing is applied by CPU ray tracing and GPU path tracing. Raster keeps schematic rendering.",
|
||||
"render.aging_refresh_targets": "Inspect current bodies",
|
||||
"render.aging_roughness": "Layer roughness",
|
||||
"render.aging_rust": "Oxidized iron / rust",
|
||||
@@ -159,6 +160,7 @@
|
||||
"render.background_workflow": "Choose the background you intend: a camera-only colour/gradient, a physical stage that receives light, or HDR illumination. They are independent. Live Preview is a modelling view; render a new image or regrade a retained master to see camera finishing.",
|
||||
"render.base_color": "Base colour · sRGB",
|
||||
"render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalised box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.",
|
||||
"render.check_media_remaining": "Density grids, displacement, full spectral integration and propagated polarisation remain unavailable.",
|
||||
"render.chromatic_offset": "Chromatic edge offset",
|
||||
"render.cpu_area_editor_help": "Full side vectors in millimeters; U cross V points towards the emitting side. This differs from GPU half-edge vectors.",
|
||||
"render.cpu_light_help": "Up to eight directional lights. An empty custom list turns them off; selecting a preset restores its lights. Colours are linear RGB and intensity is relative, not watts.",
|
||||
@@ -178,6 +180,7 @@
|
||||
"render.flare_strength": "Highlight flare strength",
|
||||
"render.flare_threshold": "Scene-linear flare threshold",
|
||||
"render.frame_centre_mark": "Centre mark",
|
||||
"render.glass_model_help": "Glass roughness scatters transmitted rays. Dispersion and film colour use three wavelength bands. Rough sheets require straight transmitted shadows off.",
|
||||
"render.hdr_primaries_declared": "The source declares its colour primaries.",
|
||||
"render.hdr_primaries_srgb": "Colour primaries: sRGB/D65",
|
||||
"render.hdr_primaries_undeclared": "The source does not declare primaries; review the renderer colour requirements.",
|
||||
@@ -269,6 +272,7 @@
|
||||
"ui.layout_floating": "Floating",
|
||||
"ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.",
|
||||
"ui.organize": "Organise",
|
||||
"ui.panel_layout.workspace.modelling": "Modelling",
|
||||
"ui.point_cloud_color_by": "Colour By",
|
||||
"ui.point_cloud_file_colors": "File Colours",
|
||||
"ui.point_cloud_no_file_colors": "The file has no colours",
|
||||
|
||||
+469
-14
File diff suppressed because it is too large.
Load diff
+532
-15
File diff suppressed because it is too large.
Load diff
@@ -566,6 +566,7 @@
|
||||
"Select edges": "Sélectionner des arêtes",
|
||||
"Select points of the sketch being edited": "Sélectionner des points de l'esquisse en cours de modification",
|
||||
"Select the centre the pattern turns around first": "Sélectionner d'abord le centre autour duquel la répétition pivote",
|
||||
"Select the curves to divide first": "Sélectionner d'abord les courbes à diviser",
|
||||
"Select the curves to offset first": "Sélectionner d'abord les courbes à décaler",
|
||||
"Select the mirror line": "Sélectionner la ligne de symétrie",
|
||||
"Select the sketch curves or points to mirror first": "Sélectionner d'abord les courbes ou points d'esquisse à symétriser",
|
||||
@@ -1048,6 +1049,7 @@
|
||||
"cmd.pointcloud_edit": "Modifier le nuage de points",
|
||||
"cmd.pointcloud_insert": "Insérer un nuage de points",
|
||||
"cmd.pointcloud_list": "Nuages de points",
|
||||
"cmd.pointcloud_reload": "Recharger le nuage de points",
|
||||
"cmd.render.compare.divider": "Déplacer le séparateur de comparaison des rendus",
|
||||
"cmd.render.result.discard": "Écarter le résultat de rendu",
|
||||
"cmd.render.result.select": "Sélectionner le résultat de rendu",
|
||||
@@ -1193,6 +1195,7 @@
|
||||
"cmd.sketch_options": "Options de la palette d'esquisse",
|
||||
"cmd.sketch_paste": "Coller les entités d'esquisse",
|
||||
"cmd.sketch_point3d": "Point 3D",
|
||||
"cmd.sketch_point_divide": "Diviser la courbe",
|
||||
"cmd.sketch_polygon_circumscribed": "Polygone circonscrit",
|
||||
"cmd.sketch_polygon_edge": "Polygone par côté",
|
||||
"cmd.sketch_polygon_inscribed": "Polygone inscrit",
|
||||
@@ -1425,6 +1428,7 @@
|
||||
"file_load.reading_percent": "Lecture du fichier... {percent} %",
|
||||
"file_load.rebuilding": "Reconstruction de l’entité {done} sur {total}",
|
||||
"file_load.recovering": "Récupération de la conception",
|
||||
"file_load.reloading_cloud": "Rechargement du nuage de points",
|
||||
"file_load.stopping": "Attente de l’arrêt de l’opération précédente...",
|
||||
"file_load.updating_links": "Mise à jour des liens",
|
||||
"file_load.waiting": "En attente d’une opération sur fichier",
|
||||
@@ -1636,6 +1640,7 @@
|
||||
"help.sketch.pattern.circular": "Copie la géométrie d'esquisse autour d'un centre, sur un cercle complet ou un angle donné. À utiliser pour des cercles de perçages, des rayons et des dents.",
|
||||
"help.sketch.pattern.rectangular": "Copie la géométrie d'esquisse en lignes et colonnes à des espacements donnés. À utiliser pour des grilles de trous, de rainures ou d'aérations.",
|
||||
"help.sketch.point": "Place un point d'esquisse. À utiliser comme référence pour des cotes, des contraintes, des centres de perçage ou des fonctions ultérieures.",
|
||||
"help.sketch.point.divide": "Place des points qui divisent les courbes choisies en longueurs égales. Les points restent sur chaque courbe et gardent leur espacement quand elle change.",
|
||||
"help.sketch.point3d": "Place un point dans l'espace, avec Esquisse 3D activée. À utiliser comme référence pour des courbes et trajectoires 3D.",
|
||||
"help.sketch.polygon.circumscribed": "Dessine un polygone régulier autour d'un cercle, dimensionné du centre au milieu d'un côté. À utiliser lorsque la largeur sur plats est connue, comme pour un écrou hexagonal.",
|
||||
"help.sketch.polygon.edge": "Dessine un polygone régulier à partir des deux extrémités d'un côté. À utiliser lorsque la longueur et la position d'un côté sont connues.",
|
||||
@@ -2201,6 +2206,8 @@
|
||||
"prefs.edges": "Arêtes et ombrage",
|
||||
"prefs.extend": "Étendre",
|
||||
"prefs.extra_navigation": "Ctrl+glisser gauche dans le vide fait orbiter ; maintenir Espace pour un panoramique.",
|
||||
"prefs.extrude_arrow_face_stops": "La flèche d'extrusion s'arrête aux faces",
|
||||
"prefs.extrude_arrow_face_stops_note": "En faisant glisser la flèche de distance d'Extrusion, elle s'arrête aux faces planes parallèles au profil, comme l'autre côté d'un bloc qu'on découpe, et souligne la face. Désactivé : la flèche avance seulement par pas ronds.",
|
||||
"prefs.extrude_view_isometric": "Passer la vue en isométrique à l'ouverture de l'extrusion",
|
||||
"prefs.extrude_view_return": "Revenir à la vue précédente à la fermeture de l'extrusion",
|
||||
"prefs.follows_os": "Suit le système",
|
||||
@@ -2780,6 +2787,8 @@
|
||||
"render.cpu_lighting": "Préréglage d'éclairage",
|
||||
"render.cpu_lights": "Lumières CPU",
|
||||
"render.cpu_linear_color": "Couleur linéaire (R, V, B)",
|
||||
"render.cpu_maps_saved_help": "Le rendu CPU accepte les cartes opaques enregistrées : choisissez une surface, puis enregistrez ses cartes dans la vue. Avec l’éclairage indirect, un autre corps peut utiliser Verre ; le corps avec les cartes ne le peut pas. Désactivez les réflexions sélectionnées, l’anisotropie et les effets procéduraux. Les fichiers temporaires de cartes utilisent le GPU.",
|
||||
"render.cpu_material_certification": "La vérification CPU valide la géométrie de verre prise en charge avant le rendu. Le verre fermé utilise la distance géométrique.",
|
||||
"render.cpu_neutral": "Neutre",
|
||||
"render.cpu_opaque_required": "Le lancer de rayons CPU nécessite un arrière-plan opaque. Décochez Arrière-plan transparent pour continuer.",
|
||||
"render.cpu_options_pending": "Ce panneau CPU ne peut pas encore modifier l'émission, les effets de surface, le verre ni l'anisotropie. Effacez ces options d'API avant de l'utiliser.",
|
||||
@@ -3905,6 +3914,7 @@
|
||||
"sketch.dimension_applied": "Cote appliquée",
|
||||
"sketch.dimension_applied_defined": "Cote appliquée ; paramètre `{name}` défini",
|
||||
"sketch.dimension_applied_renamed": "Cote appliquée ; paramètre nommé `{name}`",
|
||||
"sketch.divide_hint": "Les points divisent chaque courbe en longueurs égales et les gardent quand elle change.",
|
||||
"sketch.dof_left": "{count} degrés de liberté restants",
|
||||
"sketch.dof_left_one": "{count} degré de liberté restant",
|
||||
"sketch.draw_curves": "Dessiner en {linetype}",
|
||||
@@ -4694,6 +4704,7 @@
|
||||
"ui.heading_create_sketch": "CRÉER UNE ESQUISSE",
|
||||
"ui.heading_cylinder": "CYLINDRE",
|
||||
"ui.heading_design": "DESIGN",
|
||||
"ui.heading_divide_curve": "DIVISER LA COURBE",
|
||||
"ui.heading_draft": "DÉPOUILLE",
|
||||
"ui.heading_edit": "ÉDITION",
|
||||
"ui.heading_equation_curve": "COURBE PAR ÉQUATION",
|
||||
@@ -4940,6 +4951,7 @@
|
||||
"ui.point_cloud_no_file_colors": "Le fichier n'a pas de couleurs",
|
||||
"ui.point_cloud_pause": "Pause",
|
||||
"ui.point_cloud_play": "Lire",
|
||||
"ui.point_cloud_reload": "Recharger le fichier",
|
||||
"ui.point_cloud_single_color": "Couleur unique",
|
||||
"ui.point_cloud_size": "Taille des points",
|
||||
"ui.point_cloud_units": "Unités du fichier",
|
||||
@@ -5032,6 +5044,7 @@
|
||||
"ui.second_rail": "Second rail",
|
||||
"ui.section_analysis": "Analyse de coupe",
|
||||
"ui.section_size": "Taille de la section",
|
||||
"ui.segments": "Segments",
|
||||
"ui.select": "Sélectionner",
|
||||
"ui.selectOther": "Sélectionner un autre…",
|
||||
"ui.selectTangentChain": "Sélectionner la chaîne tangente",
|
||||
|
||||
+468
-13
File diff suppressed because it is too large.
Load diff
@@ -567,6 +567,7 @@
|
||||
"Select edges": "Seleziona spigoli",
|
||||
"Select points of the sketch being edited": "Seleziona punti dello schizzo in modifica",
|
||||
"Select the centre the pattern turns around first": "Seleziona prima il centro attorno a cui ruota la serie",
|
||||
"Select the curves to divide first": "Selezionare prima le curve da dividere",
|
||||
"Select the curves to offset first": "Seleziona prima le curve per l'offset",
|
||||
"Select the mirror line": "Seleziona la linea di simmetria",
|
||||
"Select the sketch curves or points to mirror first": "Seleziona prima le curve o i punti dello schizzo da specchiare",
|
||||
@@ -1194,6 +1195,7 @@
|
||||
"cmd.sketch_options": "Opzioni della tavolozza schizzo",
|
||||
"cmd.sketch_paste": "Incolla entità dello schizzo",
|
||||
"cmd.sketch_point3d": "Punto 3D",
|
||||
"cmd.sketch_point_divide": "Dividi curva",
|
||||
"cmd.sketch_polygon_circumscribed": "Poligono circoscritto",
|
||||
"cmd.sketch_polygon_edge": "Poligono per lato",
|
||||
"cmd.sketch_polygon_inscribed": "Poligono inscritto",
|
||||
@@ -1637,6 +1639,7 @@
|
||||
"help.sketch.pattern.circular": "Copia la geometria dello schizzo attorno a un punto centrale, su un cerchio completo o su un angolo stabilito. Usalo per cerchi di bulloni, raggi e denti.",
|
||||
"help.sketch.pattern.rectangular": "Copia la geometria dello schizzo in righe e colonne con spaziature stabilite. Usalo per griglie di fori, asole o prese d'aria.",
|
||||
"help.sketch.point": "Colloca un punto dello schizzo. Usalo come riferimento per quote, vincoli, centri di fori o lavorazioni successive.",
|
||||
"help.sketch.point.divide": "Posiziona punti che dividono le curve scelte in lunghezze uguali. I punti restano su ogni curva e ne mantengono la spaziatura quando cambia.",
|
||||
"help.sketch.point3d": "Colloca un punto nello spazio, con Schizzo 3D attivo. Usalo come riferimento per curve e percorsi 3D.",
|
||||
"help.sketch.polygon.circumscribed": "Disegna un poligono regolare attorno a un cerchio, dimensionato dal centro al punto medio di un lato. Usalo quando è nota l'apertura chiave, come per un dado esagonale.",
|
||||
"help.sketch.polygon.edge": "Disegna un poligono regolare a partire dai due estremi di un lato. Usalo quando sono note la lunghezza e la posizione di un lato.",
|
||||
@@ -3902,6 +3905,7 @@
|
||||
"sketch.dimension_applied": "Quota applicata",
|
||||
"sketch.dimension_applied_defined": "Quota applicata; parametro `{name}` definito",
|
||||
"sketch.dimension_applied_renamed": "Quota applicata; parametro denominato `{name}`",
|
||||
"sketch.divide_hint": "I punti dividono ogni curva in lunghezze uguali e le mantengono quando cambia.",
|
||||
"sketch.dof_left": "{count} gradi di libertà rimanenti",
|
||||
"sketch.dof_left_one": "{count} grado di libertà rimanente",
|
||||
"sketch.draw_curves": "Disegna come {linetype}",
|
||||
@@ -4691,6 +4695,7 @@
|
||||
"ui.heading_create_sketch": "CREA SCHIZZO",
|
||||
"ui.heading_cylinder": "CILINDRO",
|
||||
"ui.heading_design": "PROGETTAZIONE",
|
||||
"ui.heading_divide_curve": "DIVIDI CURVA",
|
||||
"ui.heading_draft": "SFORMO",
|
||||
"ui.heading_edit": "MODIFICA",
|
||||
"ui.heading_equation_curve": "CURVA DA EQUAZIONE",
|
||||
@@ -5029,6 +5034,7 @@
|
||||
"ui.second_rail": "Seconda guida",
|
||||
"ui.section_analysis": "Analisi in sezione",
|
||||
"ui.section_size": "Dimensione della sezione",
|
||||
"ui.segments": "Segmenti",
|
||||
"ui.select": "Seleziona",
|
||||
"ui.selectOther": "Seleziona altro…",
|
||||
"ui.selectTangentChain": "Seleziona catena tangente",
|
||||
|
||||
+468
-13
File diff suppressed because it is too large.
Load diff
+258
-10
@@ -547,6 +547,7 @@
|
||||
"Select edges": "모서리 선택",
|
||||
"Select points of the sketch being edited": "편집 중인 스케치의 점을 선택하세요",
|
||||
"Select the centre the pattern turns around first": "패턴이 회전할 중심을 먼저 선택하세요",
|
||||
"Select the curves to divide first": "먼저 분할할 곡선을 선택하세요",
|
||||
"Select the curves to offset first": "오프셋할 곡선을 먼저 선택하세요",
|
||||
"Select the mirror line": "대칭선을 선택하세요",
|
||||
"Select the sketch curves or points to mirror first": "대칭 복사할 스케치 곡선 또는 점을 먼저 선택하세요",
|
||||
@@ -664,6 +665,7 @@
|
||||
"Unsuppress": "비활성화 해제",
|
||||
"Updating the preview": "미리보기 업데이트 중",
|
||||
"Use active author placement": "활성 작성자 배치 사용",
|
||||
"Use axis direction only": "축 방향만 사용",
|
||||
"Use fixed plane": "고정 평면 사용",
|
||||
"Use saved fixed plane": "저장된 고정 평면 사용",
|
||||
"Use selected face as fixed plane": "선택한 면을 고정 평면으로 사용",
|
||||
@@ -982,6 +984,7 @@
|
||||
"cmd.occurrence_ground": "고정",
|
||||
"cmd.occurrence_move": "인스턴스 이동",
|
||||
"cmd.occurrence_properties": "인스턴스 물리 속성",
|
||||
"cmd.panel.action": "패널 동작 실행",
|
||||
"cmd.panel.activate": "패널 탭 활성화",
|
||||
"cmd.panel.close": "패널 닫기",
|
||||
"cmd.panel.collapse": "패널 구역 접기",
|
||||
@@ -1025,6 +1028,9 @@
|
||||
"cmd.pointcloud_edit": "포인트 클라우드 편집",
|
||||
"cmd.pointcloud_insert": "포인트 클라우드 삽입",
|
||||
"cmd.pointcloud_list": "포인트 클라우드",
|
||||
"cmd.pointcloud_reload": "포인트 클라우드 다시 불러오기",
|
||||
"cmd.render.coat.bind": "클리어 코트 저장",
|
||||
"cmd.render.coat.unbind": "클리어 코트 제거",
|
||||
"cmd.render.compare.divider": "렌더 비교 구분선 이동",
|
||||
"cmd.render.result.discard": "렌더 결과 버리기",
|
||||
"cmd.render.result.select": "렌더 결과 선택",
|
||||
@@ -1164,6 +1170,7 @@
|
||||
"cmd.sketch_options": "스케치 팔레트 옵션",
|
||||
"cmd.sketch_paste": "스케치 요소 붙여넣기",
|
||||
"cmd.sketch_point3d": "3D 점",
|
||||
"cmd.sketch_point_divide": "곡선 분할",
|
||||
"cmd.sketch_polygon_circumscribed": "외접 다각형",
|
||||
"cmd.sketch_polygon_edge": "변 다각형",
|
||||
"cmd.sketch_polygon_inscribed": "내접 다각형",
|
||||
@@ -1238,6 +1245,7 @@
|
||||
"cmd.view.render_browser": "렌더 브라우저",
|
||||
"cmd.view.render_dock": "렌더 도크 이동",
|
||||
"cmd.view.render_focus": "렌더 집중 보기",
|
||||
"cmd.view.render_live": "실시간 렌더링 일시 중지 또는 재개",
|
||||
"cmd.view.status_details": "뷰포트 상태 상세 정보",
|
||||
"cmd.view.status_items": "뷰포트 상태 항목",
|
||||
"cmd.view_ambient_occlusion": "앰비언트 오클루전",
|
||||
@@ -1258,6 +1266,7 @@
|
||||
"cmd.view_right": "우측면 뷰",
|
||||
"cmd.view_save": "새 이름 있는 보기",
|
||||
"cmd.view_shots_strip": "샷 스트립",
|
||||
"cmd.view_tool_zoom": "드래그로 확대/축소",
|
||||
"cmd.view_top": "윗면 뷰",
|
||||
"color.blue": "파랑",
|
||||
"color.copy": "클릭하여 색상 값 복사",
|
||||
@@ -1383,6 +1392,7 @@
|
||||
"file_load.reading_percent": "파일 읽는 중... {percent}%",
|
||||
"file_load.rebuilding": "피처 다시 빌드 중 {done}/{total}",
|
||||
"file_load.recovering": "디자인 복구 중",
|
||||
"file_load.reloading_cloud": "포인트 클라우드 다시 불러오는 중",
|
||||
"file_load.step_build": "모델 만드는 중",
|
||||
"file_load.step_feature": "피처 {done}/{total}",
|
||||
"file_load.step_part": "부품 {done}/{total}",
|
||||
@@ -1441,6 +1451,7 @@
|
||||
"help.sketch.construction_line.tangent_two": "두 원 또는 원호를 선택한 뒤 미리보기에서 공통 접선을 선택합니다. 접점은 그려진 곡선 위에 있어야 합니다.",
|
||||
"help.sketch.construction_line.vertical": "한 점을 지나는 무한 수직 보조 직선을 만듭니다. 나중에 편집해도 수직 구속이 유지됩니다.",
|
||||
"help.sketch.equation_curve": "범위에 걸쳐 수식으로 곡선을 그립니다: x(t)와 y(t), 또는 y = f(x). 수식에 매개변수를 쓸 수 있으며 곡선이 그 값을 따라갑니다. 사인파, 나선, 기어 이의 인벌류트에 사용합니다.",
|
||||
"help.sketch.point.divide": "선택한 곡선을 같은 길이로 나누는 점을 배치합니다. 점은 각 곡선 위에 남고 곡선이 바뀌어도 간격을 유지합니다.",
|
||||
"help.solid.chamfer": "선택한 모서리를 지정한 거리만큼 평평하게 깎습니다. 날카로운 모서리를 다듬거나 핀 또는 나사가 쉽게 들어가도록 할 때 사용합니다.",
|
||||
"help.solid.combine": "바디를 결합하거나, 대상 바디에서 잘라내거나, 서로 겹치는 체적만 남기며, 도구 바디를 유지할 수도 있습니다. 부품을 합치거나, 한 형상으로 다른 형상을 잘라내거나, 두 바디가 겹치는 곳을 찾을 때 사용합니다.",
|
||||
"help.solid.extrude": "스케치 프로파일을 지정한 거리만큼 3D로 밀어내 재료를 더하거나 제거합니다. 평면 윤곽을 블록, 보스 또는 포켓으로 만들 때 사용합니다.",
|
||||
@@ -1765,6 +1776,7 @@
|
||||
"navbar.value_tip": "{name} · {value}",
|
||||
"navbar.visual_style": "시각 스타일",
|
||||
"navbar.zoom": "확대/축소",
|
||||
"navbar.zoom_hold_tip": "확대/축소 (단축키 누르고 있기)",
|
||||
"needs two joints": "조인트 두 개가 필요함",
|
||||
"new configuration": "새 구성",
|
||||
"new parameter": "새 매개변수",
|
||||
@@ -1990,6 +2002,10 @@
|
||||
"prefs.hide_constraint_glyphs_zoomed_out": "축소 시 구속 조건 기호 숨기기",
|
||||
"prefs.hide_constraint_glyphs_zoomed_out_note": "스케치를 충분히 축소하면 구속 조건 기호가 가려지지 않도록 숨깁니다. 끄기: 확대/축소와 관계없이 고정된 화면 크기를 유지합니다.",
|
||||
"prefs.history": "이력",
|
||||
"prefs.history_bar_groups": "이력 막대를 그룹으로 접기",
|
||||
"prefs.history_bar_groups_note": "긴 이력에서는 한 컴포넌트의 연속된 특성을 하나의 칩으로 접고, 특성 폴더는 접힌 상태로 시작합니다. 삽입한 STEP 어셈블리는 Group 폴더에 들어갑니다. 끄면 각 특성을 표시하고, 폴더를 펼친 상태로 시작하며, 폴더를 만들지 않습니다.",
|
||||
"prefs.history_group_joints": "이력에서 조인트 묶기",
|
||||
"prefs.history_group_joints_note": "조인트가 두 개 이상이면 개수가 표시된 버튼 하나로 묶고, 클릭하면 각 조인트를 표시합니다. 끄면 각 조인트를 하나씩 표시합니다.",
|
||||
"prefs.history_origin_bodies": "원점과 바디를 맨 위에 표시",
|
||||
"prefs.history_origin_bodies_note": "왼쪽 또는 브라우저 아래의 히스토리가 활성 구성 요소의 바디 폴더와 원점으로 시작하며, 브라우저처럼 표시 아이콘과 메뉴가 있습니다. 아래쪽 히스토리는 바뀌지 않습니다.",
|
||||
"prefs.history_play_button": "기록 컨트롤에 기록 재생 버튼 표시",
|
||||
@@ -2069,6 +2085,7 @@
|
||||
"prefs.origin_plane_names": "원점 평면 이름",
|
||||
"prefs.origin_plane_names_note": "브라우저, 대화 상자, 목록에 표시되는 이름입니다. {top}은 XY, {front}는 XZ, {right}는 YZ이며 Z가 위쪽입니다. 명령, 스크립트, 저장된 디자인은 XY, XZ, YZ를 유지합니다.",
|
||||
"prefs.overall_speed": "전체 속도",
|
||||
"prefs.panel_layout.recovery": "저장된 패널 레이아웃을 복원하지 못했습니다. 저장된 데이터는 유지되며 클래식은 계속 사용할 수 있습니다.",
|
||||
"prefs.parameter_list_rows_tip": "빈 수식 상자에서 아래쪽 화살표로 표시할 매개변수의 최대 개수입니다.",
|
||||
"prefs.persistent_ribbon_pressed": "활성 리본 명령 강조 표시",
|
||||
"prefs.persistent_ribbon_pressed_help": "효과가 켜져 있는 동안 리본 명령을 강조 표시합니다. 끄면 이전의 중립적인 모양과 명령 도움말을 유지합니다.",
|
||||
@@ -2095,6 +2112,8 @@
|
||||
"prefs.quality_smoother": "더 부드럽게",
|
||||
"prefs.remember_dialog_values": "명령 대화 상자 값 기억",
|
||||
"prefs.remember_dialog_values.help": "기본값은 꺼짐입니다. 켜면 명령이 성공한 후 SolidCraft를 닫을 때까지 같은 명령을 다음에 열 때 안전한 값과 옵션을 다시 사용합니다.",
|
||||
"prefs.render_legacy_image_defaults": "이전 렌더 이미지 기본값 사용",
|
||||
"prefs.render_legacy_image_defaults_help": "이전의 수동 이미지 작업 방식을 유지합니다. 새 설정은 CPU 래스터를 사용하고 CPU 광선 추적은 고정 샘플링을 사용하며 결과는 직접 엽니다. 렌더에 들어갈 때 뷰를 다시 맞추고, 샷을 전환해도 저장된 카메라를 복원하지 않으며, 이전의 프레이밍과 탐색 방식을 사용합니다. 자동 실시간 이미지 피드백을 끕니다. 저장된 설정은 변경하지 않습니다.",
|
||||
"prefs.reports_saved": "{n}개 저장됨",
|
||||
"prefs.restore_page_defaults": "페이지 기본값 복원",
|
||||
"prefs.ribbon_click_ends_tool": "실행 중인 도구의 버튼을 클릭하면 도구 종료",
|
||||
@@ -2160,6 +2179,7 @@
|
||||
"prefs.sketch_conflict_colour": "충돌하는 기하를 충돌 색상으로 표시",
|
||||
"prefs.sketch_conflict_colour_note": "스케치의 구속 조건이 충돌하는 동안 실패한 구속 조건의 글리프나 치수뿐 아니라 그 구속 조건이 잡고 있는 곡선과 점도 충돌 색상으로 그립니다. 끄기: 평소 색상을 유지합니다.",
|
||||
"prefs.sketch_construction_lines": "확장 보조 직선 도구",
|
||||
"prefs.sketch_mirror_auto_line": "미리 선택한 보조 직선을 미러 선으로 사용",
|
||||
"prefs.sketch_open_look_at": "스케치를 열 때 정면으로 돌리기",
|
||||
"prefs.sketch_open_look_at_note": "끄기: 스케치를 만들거나 편집해도 뷰가 그대로입니다. 필요할 때 '바라보기'로 스케치를 정면으로 봅니다.",
|
||||
"prefs.sketch_recent_snap": "최근 중심과 중점에 자동 스냅",
|
||||
@@ -2208,6 +2228,8 @@
|
||||
"prefs.structure.work": "작업",
|
||||
"prefs.supersampling_brief": "뷰를 더 크게 그린 뒤 줄여서 필터링합니다. 매우 선명하지만 더 무겁습니다.",
|
||||
"prefs.tab_accent_note": "강조 색상이 활성 탭을 따라갑니다",
|
||||
"prefs.tab_double_click_renames": "디자인 탭을 두 번 클릭하여 이름 바꾸기",
|
||||
"prefs.tab_double_click_renames_note": "새 이름을 입력한 뒤 Enter 키를 누르거나 다른 곳을 클릭하면 적용되고, Esc 키를 누르면 취소됩니다. 끄면: 탭을 두 번 클릭할 때 막대의 빈 부분처럼 창이 최대화됩니다.",
|
||||
"prefs.theme_file": "테마 파일",
|
||||
"prefs.theme_follow": "테마 파일 따르기",
|
||||
"prefs.theme_follow_error": "적용되지 않음: {error}. 마지막으로 적용된 정상 테마를 유지합니다.",
|
||||
@@ -2297,6 +2319,9 @@
|
||||
"refused.join": "{body}에 결합하지 못했습니다.",
|
||||
"refused.repair": "부품 복구",
|
||||
"refused.show_face": "면 보기",
|
||||
"render.adaptive.pilot_progress": "적응형 파일럿 · {current}/{target} 패스",
|
||||
"render.adaptive.preview_help": "파일럿 이미지는 예산 배분에 사용되며 최종 이미지에서 제외됩니다. 본 처리는 픽셀마다 별도의 예산을 사용하므로 반복 횟수는 모든 픽셀의 동일한 샘플 수를 뜻하지 않습니다.",
|
||||
"render.adaptive.production_progress": "적응형 본 처리 · {current}/{target} 회",
|
||||
"render.adaptive_absolute": "절대 RGB 오차 하한",
|
||||
"render.adaptive_coverage": "커버리지 오차 목표",
|
||||
"render.adaptive_enable": "독립 파일럿으로 샘플 할당",
|
||||
@@ -2325,6 +2350,7 @@
|
||||
"render.aging_metallic": "레이어 금속성 비율",
|
||||
"render.aging_origin": "필드 원점 · 월드 mm",
|
||||
"render.aging_patina": "구리 녹청",
|
||||
"render.aging_raytrace_help": "에이징은 CPU 광선 추적과 GPU 경로 추적에 적용됩니다. 래스터는 도식적인 렌더링을 유지합니다.",
|
||||
"render.aging_refresh_targets": "현재 바디 검사",
|
||||
"render.aging_roughness": "레이어 거칠기",
|
||||
"render.aging_rust": "산화철 / 녹",
|
||||
@@ -2345,6 +2371,7 @@
|
||||
"render.appearance_editor.closed": "닫힌 솔리드",
|
||||
"render.appearance_editor.coat": "클리어 코트",
|
||||
"render.appearance_editor.cpu_reason": "CPU 광선 추적이 필요합니다.",
|
||||
"render.appearance_editor.discard_saved_edit": "저장하지 않은 광학 편집 버리기",
|
||||
"render.appearance_editor.glass": "유리와 흡수",
|
||||
"render.appearance_editor.glass_enable": "이 바디에 물리 유리 사용",
|
||||
"render.appearance_editor.glass_note": "닫힌 유리는 형상 거리를 사용합니다. 같은 바디에 클리어 코트나 맵을 함께 사용할 수 없습니다.",
|
||||
@@ -2363,7 +2390,7 @@
|
||||
"render.appearance_editor.replace": "이 바디의 저장된 광학 설정 교체",
|
||||
"render.appearance_editor.revalidate": "이 바디 다시 검증",
|
||||
"render.appearance_editor.save": "이 광학 설정 저장",
|
||||
"render.appearance_editor.save_reason": "저장하려면 현재 GPU 바디에 물리 유리가 필요합니다. 코트와 로컬 이미지 맵은 임시로 유지됩니다.",
|
||||
"render.appearance_editor.save_reason": "유리를 저장하려면 현재 CPU 또는 GPU 바디에서 활성화하세요. 클리어 코트는 샷에 코트 저장을 사용하세요. 로컬 이미지 파일은 임시 설정으로 유지됩니다.",
|
||||
"render.appearance_editor.saved": "이 샷에 저장됨",
|
||||
"render.appearance_editor.saved_state": "이 광학 설정은 이 샷과 함께 저장되어 있습니다.",
|
||||
"render.appearance_editor.scatter_reason": "내부 산란에는 닫힌 솔리드 경계가 필요합니다.",
|
||||
@@ -2409,9 +2436,13 @@
|
||||
"render.base_metallic": "금속성 비율",
|
||||
"render.base_opaque_only": "이 편집기는 불투명 바디의 의미를 유지합니다. 광학 투과에는 명시적인 유리 컨트롤을 사용하세요.",
|
||||
"render.batch_all_shots": "모든 샷 ({count})",
|
||||
"render.batch_current_settings_help": "현재 이미지 설정과 저장된 각 샷의 카메라를 사용해 한 번에 한 샷씩 렌더링합니다.",
|
||||
"render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.",
|
||||
"render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.",
|
||||
"render.batch_owner_limit": "문서 샷 대기열은 최대 32개까지 유지할 수 있습니다. 기존 대기열을 완료하거나 취소하세요.",
|
||||
"render.batch_preparing": "다음 샷 준비 중",
|
||||
"render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중",
|
||||
"render.batch_waiting_worker": "렌더링 준비 대기 중",
|
||||
"render.bloom_enable": "표시 블룸",
|
||||
"render.bloom_help": "양의 선형 하이라이트를 세 번의 정규화 필터로 확산하는 출력 전용 효과입니다. 반경은 출력 픽셀 단위이며 sRGB 전에 더합니다. 렌즈·볼륨·수렴 개선이 아니며 원본 EXR은 변하지 않습니다.",
|
||||
"render.bloom_opaque": "블룸에는 불투명 출력이 필요합니다. 투명 PNG를 몰래 합성하지 않고 거부합니다.",
|
||||
@@ -2441,6 +2472,16 @@
|
||||
"render.category_paint": "페인트",
|
||||
"render.category_plastic": "플라스틱",
|
||||
"render.category_wood": "목재",
|
||||
"render.caustics_depth": "집광 경로 깊이",
|
||||
"render.caustics_enable": "점광원 및 방향광의 유리 집광",
|
||||
"render.caustics_help": "광자 수는 노이즈와 계산량을 조절합니다. 수집 반경은 세밀한 표현과 부드러운 추정 사이를 조절합니다. CPU에는 간접 조명이 필요합니다.",
|
||||
"render.caustics_path_required": "CPU 집광에는 간접 조명이 필요합니다.",
|
||||
"render.caustics_photons": "광자 수",
|
||||
"render.caustics_radius": "수집 반경",
|
||||
"render.check_glass_cpu": "CPU는 검증된 평면 유리판과 축 정렬 상자를 지원합니다. 일반적인 닫힌 메시, 중첩 및 내부 산란에는 간접광이 필요합니다. 닫힌 유리를 통과하는 투과 그림자는 아직 지원하지 않습니다.",
|
||||
"render.check_glass_gpu": "GPU는 검증된 분리 유리 또는 명시적으로 활성화한 검증된 중첩을 지원합니다. 중첩에는 볼록한 바깥 형상, 완전히 내부에 포함된 안쪽 형상 및 서로 닿지 않는 경계가 필요합니다.",
|
||||
"render.check_media_remaining": "밀도 격자, 변위, 전체 스펙트럼 적분 및 편광 상태 전파는 지원되지 않습니다.",
|
||||
"render.check_media_scope": "활성 내부 산란에는 닫힌 유리 매질이 필요하며 직선 그림자 투과와 노이즈 제거를 꺼야 합니다. GPU에는 프레넬 계층도 하나만 필요합니다. 활성 외부 대기는 유리 또는 표면 노이즈 제거와 함께 사용할 수 없습니다.",
|
||||
"render.check_opaque": "투명도: 불투명 표면만 지원하며 배경 알파를 지원합니다.",
|
||||
"render.check_sorted_alpha": "투명도: 정렬된 알파 근사.",
|
||||
"render.check_transmission": "투명도: 물리적 투과.",
|
||||
@@ -2459,7 +2500,7 @@
|
||||
"render.children.copy_request": "요청 JSON 복사",
|
||||
"render.children.coverage_error": "커버리지 오차",
|
||||
"render.children.cpu": "CPU 레이 트레이싱",
|
||||
"render.children.denoise": "완성 이미지의 노이즈 줄이기",
|
||||
"render.children.denoise": "이미지 노이즈 줄이기",
|
||||
"render.children.depth": "경로 깊이",
|
||||
"render.children.distortion": "왜곡",
|
||||
"render.children.edge_samples": "모서리 샘플",
|
||||
@@ -2522,6 +2563,14 @@
|
||||
"render.choose_look": "먼저 외관 라이브러리에서 외관을 선택하세요",
|
||||
"render.chromatic_offset": "색수차 가장자리 오프셋",
|
||||
"render.clear_stage": "저장된 무대 제거",
|
||||
"render.coat_discard": "코트 편집 버리기",
|
||||
"render.coat_pending_edit": "이 코트 편집은 저장되지 않았습니다. 샷에 저장하거나 편집을 버리세요.",
|
||||
"render.coat_remove": "저장된 코트 제거",
|
||||
"render.coat_remove_note": "이 대상의 코트를 샷에서 제거합니다. 형상, 외관 및 물리 재료는 변경되지 않습니다.",
|
||||
"render.coat_remove_title": "저장된 클리어 코트를 제거할까요?",
|
||||
"render.coat_revalidate_saved": "저장된 코트가 변경되었습니다. 이 편집을 버리고 대상을 다시 연 뒤 편집하세요.",
|
||||
"render.coat_save": "샷에 코트 저장",
|
||||
"render.coat_saved_help": "클리어 코트는 불투명 표면에 광택 층을 추가합니다. 샷에 저장하세요. 같은 대상에 유리를 사용할 수 없습니다. CPU 사용자 지정 반사 또는 이방성 재정의도 이 대상을 함께 사용할 수 없습니다.",
|
||||
"render.compare_divider": "비교 구분선",
|
||||
"render.compare_live": "라이브",
|
||||
"render.compare_live_preview": "라이브 미리보기",
|
||||
@@ -2555,10 +2604,18 @@
|
||||
"render.cpu_budget_triangles": "삼각형 수 상한",
|
||||
"render.cpu_budget_workstation": "워크스테이션 (대규모 장면)",
|
||||
"render.cpu_captured_hdr": "이 이미지용으로 캡처된 HDR",
|
||||
"render.cpu_celestial_adopt": "간접 조명을 사용하는 CPU 레이 트레이싱 · 경로 깊이 {depth} · {spp} SPP · 추적 그림자 · 시드 {seed} · 기본 샘플1개",
|
||||
"render.cpu_celestial_adopt_label": "간접 조명을 사용하는 CPU 레이 트레이싱",
|
||||
"render.cpu_celestial_path_required": "유한 태양과 그라데이션 하늘은 CPU 간접 조명을 사용합니다.",
|
||||
"render.cpu_celestial_switch": "이 태양 또는 하늘을 유지하려면 간접 조명을 사용하는 CPU 레이 트레이싱을 선택하세요.",
|
||||
"render.cpu_celestial_unportable": "현재 투과 샘플 설정에는 GPU 경로 추적을 유지하세요.",
|
||||
"render.cpu_check_capture_help": "검사와 시작은 같은 파일 다이제스트를 확인하거나 포함된 HDR을 사용합니다. 각 이미지는 캡처된 소스를 유지합니다.",
|
||||
"render.cpu_check_changed": "이 검사 후 컨트롤이나 모델이 변경되었습니다. 렌더링 전에 다시 검사하세요.",
|
||||
"render.cpu_constant_direct_help": "간접 조명이 꺼져 있으면 이 일정한 광원은 반사나 유리를 통해 보일 수 있지만 불투명한 표면을 밝히지는 않습니다. 장면 조명으로 사용하려면 간접 조명을 켜세요.",
|
||||
"render.cpu_constant_enable_indirect_plan": "경로 깊이 {depth}, 픽셀당 {spp}개 샘플의 점진적 샘플링(시드 {seed}), 샘플당 기본 광선 1개, 추적된 그림자를 사용합니다. 이미지 크기, CPU 예산 및 다른 설정을 유지합니다.",
|
||||
"render.cpu_constant_help": "상수 방사 휘도는 반사되거나 투과된 광선에 보입니다. 직접 확산 조명은 제공하지 않습니다.",
|
||||
"render.cpu_custom_directions": "프리셋을 사용자 지정 방향성 조명으로 교체",
|
||||
"render.cpu_denoise_help": "이미지가 갱신될 때마다 노이즈를 줄입니다. 미세한 디테일과 피사계 심도 경계가 부드러워질 수 있습니다. 원본 EXR은 바뀌지 않습니다. 완성된 이미지를 조정할 때는 해당 원본 이미지를 사용하며 노이즈 감소를 다시 적용하지 않습니다.",
|
||||
"render.cpu_direction": "광원 방향 (X, Y, Z)",
|
||||
"render.cpu_directional": "방향성 조명",
|
||||
"render.cpu_directional_add": "방향성 조명 추가",
|
||||
@@ -2570,8 +2627,11 @@
|
||||
"render.cpu_environment_samples": "HDR 조명 샘플",
|
||||
"render.cpu_exposure_help": "CPU 노출은 −16~16 EV 사이여야 합니다. 이 범위를 벗어난 GPU 노출은 변경하기 전까지 유지됩니다.",
|
||||
"render.cpu_fixed": "단일 이미지",
|
||||
"render.cpu_fixed_retained": "고정 샘플링 유지",
|
||||
"render.cpu_glass_enable_path": "간접 조명 켜기",
|
||||
"render.cpu_hdr_help": "Radiance .hdr, 2:1 파노라마, 최대 2048 × 1024 및 16 MiB. CPU는 파일에 명시적인 sRGB/D65 원색이 필요하며, 원색이 지정되지 않은 파일과 EXR은 거부됩니다.",
|
||||
"render.cpu_hdr_reflection_help": "HDR 거친 반사에는 완전한 금속성 바디와 면 표면이 필요합니다. 검사가 지원되지 않는 조합을 보고합니다.",
|
||||
"render.cpu_indirect_method_required": "이 간접 조명 모드를 켜려면 CPU 레이 트레이싱을 선택하세요.",
|
||||
"render.cpu_key_rim": "키와 림",
|
||||
"render.cpu_last_check": "마지막 CPU 검사",
|
||||
"render.cpu_light_help": "방향성 조명 최대 여덟 개. 사용자 지정 목록이 비어 있으면 조명이 꺼지고, 프리셋을 선택하면 그 조명이 복원됩니다. 색상은 선형 RGB이고 강도는 와트가 아닌 상대값입니다.",
|
||||
@@ -2583,18 +2643,32 @@
|
||||
"render.cpu_lighting": "조명 프리셋",
|
||||
"render.cpu_lights": "CPU 조명",
|
||||
"render.cpu_linear_color": "선형 색상 (R, G, B)",
|
||||
"render.cpu_maps_saved_help": "CPU 렌더링은 저장한 불투명 표면 맵을 사용할 수 있습니다. 표면을 선택하고 샷에 맵을 저장하세요. 간접광을 사용하면 다른 바디에 유리를 사용할 수 있지만, 맵이 있는 바디에는 유리를 사용할 수 없습니다. 선택 반사, 비등방성 및 절차적 효과는 끄세요. 임시 맵 파일 경로는 GPU를 사용합니다.",
|
||||
"render.cpu_material_certification": "CPU 검사는 렌더링 전에 지원되는 유리 형상을 검증합니다. 닫힌 유리는 기하학적 거리를 사용합니다.",
|
||||
"render.cpu_neutral": "중립",
|
||||
"render.cpu_opaque_hint": "CPU 레이 트레이싱은 불투명한 배경을 사용합니다.",
|
||||
"render.cpu_opaque_required": "CPU 레이 트레이싱에는 불투명 배경이 필요합니다. 계속하려면 투명 배경을 해제하세요.",
|
||||
"render.cpu_options_pending": "이 CPU 패널은 아직 발광, 표면 효과, 유리, 이방성을 편집할 수 없습니다. 사용하기 전에 해당 API 옵션을 해제하세요.",
|
||||
"render.cpu_path_depth": "경로 깊이",
|
||||
"render.cpu_path_help": "불투명 표면 사이에서 반사되고 지원되는 유리 형상을 통과하는 빛을 계산합니다. 점진적 렌더링과 레이 추적 그림자가 필요합니다. 경로 깊이는 첫 교점부터 조명이 계산되는 표면, 유리 경계 및 산란 이벤트를 셉니다(1–16). 깊이 1은 불투명 표면의 직접 조명만 계산합니다. 값을 높이면 반사나 유리 통과가 늘어나며 시간이 더 걸릴 수 있습니다. 사용자 반사 설정이나 이방성을 사용하려면 간접 조명을 끄세요.",
|
||||
"render.cpu_path_lighting": "간접 조명",
|
||||
"render.cpu_path_optics_reason": "설정은 유지됩니다. 사용자 반사 설정이나 이방성을 사용하려면 간접 조명을 끄세요.",
|
||||
"render.cpu_point": "점 조명",
|
||||
"render.cpu_point_add": "점 조명 추가",
|
||||
"render.cpu_point_help": "선택한 방향성 조명에 더해지는 점 조명 최대 여덟 개. 거리는 mm 단위이며, 최소 거리는 기준 거리를 넘을 수 없습니다.",
|
||||
"render.cpu_primary_samples": "픽셀당 가장자리 샘플",
|
||||
"render.cpu_progressive": "CPU 프로그레시브",
|
||||
"render.cpu_progressive_adopt": "점진적 샘플링 사용",
|
||||
"render.cpu_progressive_adopt_help": "전환하면 패스마다 카메라 샘플 하나를 사용합니다. 이미지 크기, 조명 및 반사 설정은 유지됩니다.",
|
||||
"render.cpu_progressive_always": "점진적 샘플링은 항상 켜져 있습니다",
|
||||
"render.cpu_progressive_help": "기존 CPU 적분기를 1차 샘플 하나씩 패스로 누적합니다. 선택한 반사에는 샘플 하나가 필요하며, 면 조명, 유전체, 이방성에는 단일 이미지가 필요합니다.",
|
||||
"render.cpu_progressive_limits": "최대 1,048,576픽셀과 16,777,216 픽셀 × 샘플 평가. 샘플을 바꿔도 이미지 크기가 자동으로 조정되지 않습니다.",
|
||||
"render.cpu_progressive_reflection_adopt": "전환하기 전에 선택한 반사의 시도 횟수를 1로 설정하세요.",
|
||||
"render.cpu_progressive_seed": "CPU 샘플링 시드",
|
||||
"render.cpu_progressive_spp": "픽셀당 샘플",
|
||||
"render.cpu_quality_budget_help": "크기, 제작 샘플 상한, 시드와 CPU 리소스 프로필을 변경합니다. 카메라, 렌즈, 조명, GI 깊이와 효과는 유지됩니다.",
|
||||
"render.cpu_quality_progressive_required": "CPU 예산을 선택하기 전에 아래에서 점진적 샘플링을 활성화하세요.",
|
||||
"render.cpu_quality_summary": "{width} × {height} · 샘플 상한 {samples} · 시드 {seed} · {profile}",
|
||||
"render.cpu_reflection_add": "거친 반사 추가",
|
||||
"render.cpu_reflection_depth": "반사 깊이 (1~8)",
|
||||
"render.cpu_reflection_empty": "선택한 바디 없음: 장면 반사가 꺼져 있습니다.",
|
||||
@@ -2608,7 +2682,21 @@
|
||||
"render.cpu_runtime_help": "숫자 조명과 환경 설정은 설정과 함께 저장됩니다. 바디 반사와 HDR 파일은 임시로 유지됩니다. 기존 면 조명과 스폿 원뿔 값은 보존됩니다.",
|
||||
"render.cpu_sampling_mode": "CPU 샘플링 모드",
|
||||
"render.cpu_shadows": "그림자 드리우기",
|
||||
"render.cpu_sky_bounds": "하늘 회전은 ±1,000,000 라디안 이내의 유한 값이어야 하며 강도는 0~100이어야 합니다.",
|
||||
"render.cpu_studio_enable": "이 리그의 간접 조명 켜기",
|
||||
"render.cpu_studio_enable_apply": "간접 조명을 켜고 적용",
|
||||
"render.cpu_studio_indirect_help": "이 태양 리그에는 깊이 8의 간접 조명, 추적된 그림자, 패스당 카메라 샘플 1개가 필요합니다. 점진적 렌더링이 꺼져 있으면 픽셀당 샘플 16개와 시드 0으로 시작합니다. 기존 점진적 설정과 리소스 프로필은 유지됩니다. 호환되지 않는 설정은 변경하지 않고 적용을 중단합니다.",
|
||||
"render.cpu_studio_radiance_limit": "이 리그의 면 광원 방사 휘도 {radiance}은(는) CPU 한도 64를 넘습니다. 작성된 조명은 유지됩니다. 다른 리그나 GPU를 선택하세요.",
|
||||
"render.cpu_subsurface_denoise_reason": "CPU 내부 산란을 사용하려면 노이즈 제거를 끄세요. 설정은 유지됩니다.",
|
||||
"render.cpu_subsurface_help": "산란은 닫힌 유리 내부에서 빛의 방향을 바꿉니다. 양수 비율에는 간접광을 사용하고 노이즈 제거를 끄세요. 비율은 mm당 충돌 횟수이며, 0은 산란을 추가하지 않습니다. 방향 편향이 양수이면 전방, 음수이면 후방을 선호합니다.",
|
||||
"render.cpu_summary": "CPU 레이 트레이싱 · 반사 · HDR · 방향성 및 점 조명",
|
||||
"render.cpu_transparent_help": "투명 PNG는 배경을 제거하고 가장자리 커버리지를 유지합니다. 바디와 면의 불투명도는 100%여야 합니다.",
|
||||
"render.cpu_volume_enable_path": "간접 조명 켜기",
|
||||
"render.cpu_volume_enable_path_plan": "CPU 레이 트레이싱 · 경로 깊이 {depth} · 픽셀당 {spp}샘플 · 시드 {seed} · 레이 트레이싱 그림자. 작성한 대기와 이미지 예산을 유지합니다.",
|
||||
"render.cpu_volume_help": "CPU 대기는 간접 조명을 사용합니다. 소광 계수가 0이면 저장된 상자는 안개 없이 유지됩니다.",
|
||||
"render.cpu_volume_method_adopt": "간접 조명을 사용하는 CPU 레이 트레이싱",
|
||||
"render.cpu_volume_method_incompatible": "이 조명, 샘플링 또는 대기 설정을 이 방식으로 옮길 수 없습니다. 설정은 유지됩니다.",
|
||||
"render.cpu_volume_path_required": "CPU 대기를 사용하려면 간접 조명을 켜세요.",
|
||||
"render.cpu_warm_cool": "따뜻함과 차가움",
|
||||
"render.diag_bodies": "표시된 바디",
|
||||
"render.diag_job_details": "캡처된 작업 세부 정보",
|
||||
@@ -2618,6 +2706,7 @@
|
||||
"render.diag_preflight_details": "사전 점검 세부 정보",
|
||||
"render.diag_request": "정확한 현재 요청",
|
||||
"render.diag_triangles": "삼각형",
|
||||
"render.directional_sun_limit": "GPU는 부드러운 태양 하나를 포함해 방향성 광원을 총 8개까지 지원합니다. 원거리 광원을 추가하려면 선명한 그림자의 방향성 조명을 복제하세요.",
|
||||
"render.discard_continue": "초안을 버리고 계속",
|
||||
"render.draft_confirm_help": "현재 렌더 초안에 적용하지 않은 편집이 있습니다. 전환하기 전에 저장하거나, 명시적으로 버리거나, 계속 편집하세요.",
|
||||
"render.draft_confirm_title": "편집한 렌더 설정 보존",
|
||||
@@ -2767,7 +2856,7 @@
|
||||
"render.export_display": "내보내기: 표시 PNG",
|
||||
"render.export_image_label": "이미지 내보내기",
|
||||
"render.export_linear": "내보내기: 원본 선형 EXR",
|
||||
"render.exr_pending": "GPU는 원본 선형 EXR을 보존할 수 있습니다. 압축, 다중 레이어 이미지 및 보조 렌더 패스는 아직 사용할 수 없습니다.",
|
||||
"render.exr_pending": "CPU 레이 트레이싱과 GPU 패스 트레이싱은 원본 선형 EXR을 보존할 수 있습니다. 압축, 다중 레이어 이미지 및 보조 렌더 패스는 아직 사용할 수 없습니다.",
|
||||
"render.film_grain": "사진 그레인",
|
||||
"render.fit": "제품에 맞추기",
|
||||
"render.fixed_camera": "카메라",
|
||||
@@ -2805,10 +2894,20 @@
|
||||
"render.frame_tall": "9:16 · 세로형",
|
||||
"render.frame_thirds": "삼분할선",
|
||||
"render.frame_wide": "16:9 · 와이드스크린",
|
||||
"render.glass_abbe": "아베 수",
|
||||
"render.glass_dispersion": "색 분산",
|
||||
"render.glass_film": "박막 간섭",
|
||||
"render.glass_film_ior": "박막 굴절률",
|
||||
"render.glass_film_thickness": "박막 두께",
|
||||
"render.glass_model_enable": "고급 유리 모델",
|
||||
"render.glass_model_help": "유리 거칠기는 투과 광선을 산란시킵니다. 분산과 박막 색상은 세 파장 대역을 사용합니다. 거친 얇은 판은 직선 투과 그림자를 꺼야 합니다.",
|
||||
"render.glass_roughness": "유리 거칠기",
|
||||
"render.gpu_depth": "최대 경로 깊이",
|
||||
"render.gpu_job_shader_wait": "셰이더 준비에 몇 분이 걸릴 수 있습니다",
|
||||
"render.gpu_options_help": "샘플, 깊이, 시드, 노출은 이 설정과 함께 저장됩니다. 활성 이미지 방식만 저장됩니다.",
|
||||
"render.gpu_path_failed": "GPU 패스 트레이서를 사용할 수 없음",
|
||||
"render.gpu_path_first_setup": "이 GPU에서 첫 설정은 몇 분이 걸릴 수 있으며, 그동안 SolidCraft는 계속 사용할 수 있습니다. 드라이버가 컴파일된 셰이더를 보관하면 이후 시작에서 재사용합니다.",
|
||||
"render.gpu_path_not_started": "GPU 경로 추적기 설정이 아직 시작되지 않았습니다.",
|
||||
"render.gpu_path_preparing": "GPU 패스 트레이서: 셰이더 컴파일 중…",
|
||||
"render.gpu_seed": "난수 시드",
|
||||
"render.gpu_unavailable": "이 장치에서는 GPU 패스 트레이싱을 사용할 준비가 되지 않았습니다.",
|
||||
@@ -3003,6 +3102,8 @@
|
||||
"render.light_product_centre": "제품 중심",
|
||||
"render.light_size": "크기",
|
||||
"render.light_softness": "부드러움",
|
||||
"render.light_space_world": "월드 좌표의 조명",
|
||||
"render.light_space_world_help": "조명의 위치와 방향은 월드 좌표를 사용합니다. 카메라를 회전해도 조명은 움직이지 않습니다.",
|
||||
"render.light_temperature": "색온도",
|
||||
"render.light_temperature_help": "흑체 색상 근사값이며 선형 RGB로 저장됩니다.",
|
||||
"render.light_type": "유형",
|
||||
@@ -3059,6 +3160,25 @@
|
||||
"render.linear_help": "노이즈 제거, 노출, 톤 매핑, 필터, 배경 전의 32비트 부동 소수점 RGBA 마스터를 보존합니다. 선형 sRGB/D65, 커버리지 프리멀티플라이. 추가 메모리는 명시적으로 허용됩니다. 압축이나 추가 패스는 없습니다.",
|
||||
"render.linear_retain": "원본 선형 EXR 보존",
|
||||
"render.linear_unavailable": "선택한 완료 프레임에는 보존된 EXR이 없습니다. 렌더링 전에 보존을 켜세요. 이전 PNG로는 원본 방사 휘도를 복구할 수 없습니다.",
|
||||
"render.live.adaptive": "라이브 · {width} × {height} · {progress}",
|
||||
"render.live.final_changed": "라이브 렌더링을 중지하는 동안 렌더 요청이 변경되었습니다. 최종 이미지를 다시 시작하세요.",
|
||||
"render.live.final_waiting": "최종 이미지 준비 중 · 라이브 렌더 리소스 해제 중",
|
||||
"render.live.invalid_size": "라이브 렌더링에는 양수의 출력 너비와 높이가 필요합니다.",
|
||||
"render.live.pause": "라이브 일시 중지",
|
||||
"render.live.paused": "라이브 · 일시 중지됨",
|
||||
"render.live.paused_outdated": "라이브 · 일시 중지됨 · 업데이트 필요",
|
||||
"render.live.quality_help": "대화형 품질: 가장 긴 변은 최대 512픽셀입니다. 선택한 렌더러와 지원하는 효과를 사용합니다. 최종 해상도, 설정 및 내보내기는 별도로 유지됩니다.",
|
||||
"render.live.refused": "라이브 사용 불가: {reason}",
|
||||
"render.live.resume": "라이브 재개",
|
||||
"render.live.samples": "라이브 · {width} × {height} · {current}/{target} 샘플",
|
||||
"render.live.source_current": "{method} · 라이브",
|
||||
"render.live.source_outdated": "{method} · 이전 이미지",
|
||||
"render.live.source_outdated_help": "라이브 렌더링이 업데이트 중이거나 사용할 수 없는 동안 마지막으로 캡처한 이미지를 표시합니다. 현재 장면 또는 이미지 설정과 다를 수 있습니다.",
|
||||
"render.live.source_settings_help": "출력을 열어 렌더러와 이미지 설정을 편집합니다.",
|
||||
"render.live.stopped": "라이브 렌더링 중지됨",
|
||||
"render.live.updating": "라이브 · 대화형 품질(최대 512 px) · 업데이트 중",
|
||||
"render.live.waiting_canvas": "렌더 캔버스 대기 중",
|
||||
"render.live.worker_stopped": "라이브 렌더 캡처 작업이 결과를 반환하기 전에 중지되었습니다",
|
||||
"render.look_add": "컬러 룩 추가",
|
||||
"render.look_applied": "{name} 적용됨",
|
||||
"render.look_bleach": "블리치 바이패스 느낌",
|
||||
@@ -3088,6 +3208,9 @@
|
||||
"render.material_coat_help": "기존 불투명 외관 위의 표현용 유전체 코팅입니다. 가중치가 0이면 기본 외관이 그대로 유지됩니다.",
|
||||
"render.material_color_map": "기본 색상 이미지 (sRGB)",
|
||||
"render.material_color_replace": "기본 맵으로 바디 색상 교체",
|
||||
"render.material_cpu_glass_only": "임시 이미지 파일 맵에는 GPU가 필요합니다. CPU는 저장된 내장 표면 맵을 사용할 수 있습니다.",
|
||||
"render.material_cpu_optics_limits": "지원되는 닫힌 유리 형상, 검증된 중첩 및 내부 산란에는 간접 조명을 켜세요. 얇은 시트는 그림자에 빛을 통과시킬 수 있습니다. 그 외에는 평면 시트나 축 정렬 상자를 사용하세요. 서로 닿는 형상과 닫힌 유리를 통과하는 투과 그림자는 아직 지원하지 않습니다. 값은 유지됩니다.",
|
||||
"render.material_cpu_saved_runtime_conflict": "저장된 CPU 광학 설정은 임시 광학 바인딩과 함께 사용할 수 없습니다. 검토한 설정을 저장하거나 충돌하는 임시 바인딩을 제거하세요.",
|
||||
"render.material_custom": "사용자 지정 표현용 광학",
|
||||
"render.material_enable": "이 GPU 재질 재정의 사용",
|
||||
"render.material_filter": "장면 바디 필터…",
|
||||
@@ -3108,6 +3231,7 @@
|
||||
"render.material_normal_map": "노멀 이미지 (OpenGL, +Y)",
|
||||
"render.material_normal_strength": "노멀 강도 (0~1)",
|
||||
"render.material_origin": "매핑 원점 X · Y · Z (mm)",
|
||||
"render.material_raytrace_required": "물리 유리에는 CPU 레이 트레이싱이나 GPU 패스 트레이싱이 필요합니다.",
|
||||
"render.material_refresh": "장면 바디 새로 고침",
|
||||
"render.material_refresh_needed": "장면이 변경되었습니다. 대상을 추가하기 전에 바디 목록을 새로 고치세요.",
|
||||
"render.material_remove": "이 지정 제거",
|
||||
@@ -3117,6 +3241,7 @@
|
||||
"render.material_revalidate_needed": "이 지정은 이전 장면 리비전에 속합니다. 렌더링 전에 정확한 바디 식별을 다시 검증하세요.",
|
||||
"render.material_roughness": "코트 거칠기 (0.045~1)",
|
||||
"render.material_roughness_map": "거칠기 맵 (선형)",
|
||||
"render.material_saved_edit_pending": "광학 편집을 아직 저장하지 않았습니다. 검토한 값을 저장하거나 저장된 할당을 제거하거나 편집을 버리세요. 임시 바인딩과 지원하지 않는 효과는 저장된 대상을 덮어쓸 수 없습니다.",
|
||||
"render.material_shadow": "직선 그림자 광선 투과",
|
||||
"render.material_target_missing": "바디 순번과 이름이 더 이상 일치하지 않습니다. 이 지정을 제거하고 의도한 바디를 명시적으로 다시 선택하세요.",
|
||||
"render.material_thickness": "얇은 판 두께 (mm)",
|
||||
@@ -3128,7 +3253,7 @@
|
||||
"render.method_cpu": "CPU 레이 트레이싱",
|
||||
"render.method_gpu": "GPU 패스 트레이싱",
|
||||
"render.method_limit_raster": "래스터는 고정된 불투명 스튜디오 미리보기를 사용합니다. 지원되는 광학 컨트롤을 쓰려면 명시적인 레이 트레이싱 방식을 선택하세요.",
|
||||
"render.method_raster": "CPU 래스터",
|
||||
"render.method_raster": "CPU 래스터 (도식)",
|
||||
"render.navigation_help": "카메라는 디자인에서와 같이 움직입니다(환경설정 › 탐색). 설정 저장은 현재 카메라를 기록합니다.",
|
||||
"render.nested_enable": "보증된 중첩 유전체",
|
||||
"render.nested_help": "최대 16개의 포함 레이어. 모든 부모는 볼록해야 하고 모든 자식은 부모 안에 완전히 들어가야 합니다. 교차, 맞닿은 표면, 얇은 판, 직선 그림자 투과는 거부됩니다. 카메라 내부 상태는 보증된 계층을 따릅니다. 액체 표면을 만들거나 맞닿은 CAD 경계를 병합하지는 않습니다.",
|
||||
@@ -3156,16 +3281,19 @@
|
||||
"render.output_exr_unavailable": "여기서는 EXR 출력을 설정할 수 없습니다. 선형 EXR 내보내기에는 선형 원본을 보관한 완료된 GPU 이미지가 필요합니다.",
|
||||
"render.output_fit": "맞춤",
|
||||
"render.output_format": "형식",
|
||||
"render.output_format_status": "PNG는 완료된 표시 이미지 그대로입니다. 선택적 GPU EXR은 표시 필터 전 선형 FLOAT32 방사 휘도를 보존합니다. 미리보기 캐시나 다른 작업으로 바꾸어 내보내지 않습니다.",
|
||||
"render.output_format_status": "PNG는 완료된 표시 이미지 그대로입니다. 선택적 CPU/GPU EXR은 표시 필터 전 선형 FLOAT32 방사 휘도를 보존합니다. 미리보기 캐시나 다른 작업으로 바꾸어 내보내지 않습니다.",
|
||||
"render.output_grading": "색 보정",
|
||||
"render.output_image": "이미지",
|
||||
"render.output_largest": "{width} × {height} 최대",
|
||||
"render.output_lock_ratio": "가로세로 비율 고정",
|
||||
"render.output_master_unavailable": "EXR을 내보내려면 원본 EXR 데이터가 있는 완성 이미지를 선택하세요. 새 이미지를 렌더링하기 전에 원본 EXR을 활성화하세요.",
|
||||
"render.output_over_budget": "요청한 이미지가 선택한 리소스 범위를 초과합니다. 호환되는 크기나 프로필을 명시적으로 선택하세요. 자동으로 낮추지 않습니다.",
|
||||
"render.output_presentation_limits": "CPU 이미지 효과와 EXR 출력은 너비와 높이가 각각 최대 8192픽셀이고 총 16,777,216픽셀 이하인 이미지를 지원합니다.",
|
||||
"render.output_presets_help": "형식, 품질 및 검사 목록은 출력 편집기에 있습니다.",
|
||||
"render.output_quality": "품질",
|
||||
"render.output_quality_waiting": "품질 규약 대기 중",
|
||||
"render.output_ratio_refused": "연결된 치수가 이 방식의 크기 제한을 초과합니다. 이전 크기가 유지됩니다. 비율 고정을 풀거나 더 작은 값을 선택하세요.",
|
||||
"render.output_raytrace_only": "이미지 효과에는 CPU 레이 트레이싱 또는 GPU 패스 트레이싱이 필요합니다.",
|
||||
"render.output_ready": "렌더링 준비 완료",
|
||||
"render.output_run_check": "검사 실행",
|
||||
"render.output_size_limit": "{method}: 한 변 최대 {dimension} px, 총 {pixels} 픽셀. 가능한 최대 크기: {width} × {height}.",
|
||||
@@ -3220,6 +3348,12 @@
|
||||
"render.post_saturation": "채도",
|
||||
"render.post_title": "표시 필터",
|
||||
"render.post_vignette": "비네트",
|
||||
"render.preparation_cancelled": "렌더링 준비가 취소되었습니다",
|
||||
"render.preparation_checking": "렌더링 확인 중",
|
||||
"render.preparation_retirement_failed": "렌더링 준비 정리에 실패했습니다. 이 창에서는 다른 이미지를 준비할 수 없습니다.",
|
||||
"render.preparation_retiring": "렌더링 준비 마무리 중",
|
||||
"render.preparation_unavailable": "렌더링 준비를 사용할 수 없음",
|
||||
"render.presentation_banner": "이미지 효과는 CPU 및 GPU 레이 트레이싱에서 사용할 수 있습니다. 이 페이지를 열어도 방식이 바뀌지 않습니다.",
|
||||
"render.preview": "통합 미리보기",
|
||||
"render.preview_help": "래스터 셰이딩과 블렌딩 투명도를 사용합니다. 굴절, HDRI 및 최종 렌더링은 아직 지원하지 않습니다.",
|
||||
"render.preview_image_settings_help": "실시간 미리보기는 고정된 스튜디오 조명을 유지합니다. 노출과 이미지 조명은 검사 또는 시작할 때 이미지 작업에 적용됩니다.",
|
||||
@@ -3238,11 +3372,15 @@
|
||||
"render.quality_ack": "고정 예산 변환과 생략 항목 확인",
|
||||
"render.quality_apply": "이 고정 샘플링 예산 사용",
|
||||
"render.quality_balanced": "균형",
|
||||
"render.quality_budget_help": "크기, 샘플 수, 깊이, 시드 및 노이즈 제거를 설정합니다. 다른 이미지 설정은 유지됩니다.",
|
||||
"render.quality_custom": "사용자 지정",
|
||||
"render.quality_denoise_off": "노이즈 제거: 꺼짐",
|
||||
"render.quality_denoise_on": "노이즈 제거: 켜짐",
|
||||
"render.quality_draft": "초안",
|
||||
"render.quality_high": "높음",
|
||||
"render.quality_projection_help": "Q 프리셋에는 향후 요구 사항이 포함됩니다. 이 동작은 지원되는 고정 샘플 PNG 예산만 변환하며, 적응형 중지, 원본 선형 출력, 독립 투과 제한은 명시적으로 생략합니다.",
|
||||
"render.quality_projection_help": "이 검토에서는 해상도, 샘플 예산, 경로 깊이, 시드 및 노이즈 제거만 변경합니다. 다른 설정은 유지되며 수렴은 보장되지 않습니다.",
|
||||
"render.quality_review": "샘플링 예산 검토",
|
||||
"render.quality_summary": "{width} × {height} · 샘플 {samples}개 · 깊이 {depth} · 시드 {seed} · {denoise}",
|
||||
"render.queue_pending": "이 UI에는 자동 프로덕션 대기열이나 애니메이션 렌더러가 없습니다. 완료된 정지 이미지는 별도로 내보낼 수 있습니다.",
|
||||
"render.radial_assign": "외관 지정",
|
||||
"render.radial_compare": "비교",
|
||||
@@ -3272,7 +3410,7 @@
|
||||
"render.result_navigation": "이동과 확대/축소는 탐색 환경 설정을 따릅니다. Space + 드래그로 이동합니다.",
|
||||
"render.result_open": "완료된 이미지를 메인 캔버스에서 엽니다.",
|
||||
"render.result_preview": "실시간 미리보기",
|
||||
"render.result_provisional": "임시 CPU 이미지",
|
||||
"render.result_provisional": "임시 이미지",
|
||||
"render.result_provisional_help": "이 체크포인트는 내보낼 수 없습니다. 내보내기는 마지막 완료 결과를 유지하며, 취소하면 그 결과로 돌아갑니다.",
|
||||
"render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.",
|
||||
"render.result_retained": "마지막 완료 이미지를 표시하고 있습니다. 더 새로운 렌더링이 이를 대체하지 않았습니다.",
|
||||
@@ -3360,9 +3498,11 @@
|
||||
"render.shot_frame_subject": "피사체 맞추기",
|
||||
"render.shot_invalid_camera": "카메라 값은 범위 내의 유한한 수여야 합니다.",
|
||||
"render.shot_lens": "렌즈",
|
||||
"render.shot_lens_cpu_progressive_reason": "CPU 피사계 심도를 켜기 전에 샘플링에서 점진적 샘플링을 적용하세요.",
|
||||
"render.shot_lens_enable_reason": "조리개와 초점 거리를 편집하려면 피사계 심도를 켜세요.",
|
||||
"render.shot_lens_gpu_reason": "피사계 심도에는 GPU 경로 추적이 필요합니다.",
|
||||
"render.shot_lens_perspective_reason": "피사계 심도에는 원근 투영이 필요합니다.",
|
||||
"render.shot_lens_raytrace_reason": "피사계 심도는 CPU 레이 트레이싱과 GPU 패스 트레이싱에서 사용할 수 있습니다.",
|
||||
"render.shot_look_selection": "선택 항목 바라보기",
|
||||
"render.shot_manager": "저장된 샷",
|
||||
"render.shot_new_name": "새 샷 이름",
|
||||
@@ -3396,7 +3536,12 @@
|
||||
"render.sky_horizon": "지평선 · 선형 RGB",
|
||||
"render.sky_zenith": "천정 · 선형 RGB",
|
||||
"render.soft_focus": "소프트 포커스",
|
||||
"render.spot_axis": "빛의 방출 방향",
|
||||
"render.spot_cone": "스폿 원뿔",
|
||||
"render.spot_gpu_help": "각도는 빛의 방출 방향을 기준으로 측정합니다. 안쪽 각도와 바깥쪽 각도 사이에서 빛이 약해집니다. 감쇠 범위가 매우 좁으면 CPU 렌더링이 필요합니다.",
|
||||
"render.spot_help": "각도는 빛의 방출 방향을 기준으로 측정합니다. 안쪽 각도와 바깥쪽 각도 사이에서 빛이 약해집니다.",
|
||||
"render.spot_inner": "안쪽 반각",
|
||||
"render.spot_outer": "바깥쪽 반각",
|
||||
"render.stage_frame": "구도",
|
||||
"render.stage_layout.appearance_note": "클릭하여 선택 항목에 적용합니다.",
|
||||
"render.stage_layout.studio_note": "클릭하여 적용 전에 검토하세요.",
|
||||
@@ -3436,7 +3581,7 @@
|
||||
"render.stage_panels.prepare_plan": "생성 계획 준비",
|
||||
"render.stage_panels.projects": "투영",
|
||||
"render.stage_panels.quality_ack": "고정 예산과 생략 사항을 확인했습니다",
|
||||
"render.stage_panels.quality_omissions": "적응형 중지 및 오차 목표, 별도 투과 깊이, 러시안 룰렛 규칙, 원시 선형 출력, EXR 마스터 및 수렴 인증.",
|
||||
"render.stage_panels.quality_omissions": "이 예산은 적응형 오차 목표, 독립적인 투과 한도, 러시안 룰렛 규칙 또는 선형 마스터 보존을 설정하지 않으며 수렴을 보장하지 않습니다.",
|
||||
"render.stage_panels.reference": "참조",
|
||||
"render.stage_panels.references": "참조",
|
||||
"render.stage_panels.remove_optics": "광학 설정 제거",
|
||||
@@ -3480,7 +3625,7 @@
|
||||
"render.stage_panels.subtitle_environment": "원본 HDR 환경 · 전체 장면",
|
||||
"render.stage_panels.subtitle_maps": "제작된 공간 맵 · 임시 미리 보기",
|
||||
"render.stage_panels.subtitle_physical": "읽기 전용 계획 · 재질 생성 또는 할당 없음",
|
||||
"render.stage_panels.subtitle_quality": "고정 GPU 예산 · 향후 요구 사항 생략",
|
||||
"render.stage_panels.subtitle_quality": "GPU 샘플링 예산 · 표시된 설정만 변경",
|
||||
"render.stage_panels.subtitle_rig": "제작된 조명 리그 · 광원 및 수동 카드",
|
||||
"render.stage_panels.subtitle_saved_maps": "제작된 맵 · 이 샷에 저장",
|
||||
"render.stage_panels.subtitle_stage": "물리적 바닥 및 스테이지 · 제품에 맞춤",
|
||||
@@ -3505,7 +3650,7 @@
|
||||
"render.studio_area_help": "단면 직사각형 최대 네 개. 직교하는 반변 U와 V가 크기를 정하고, U × V가 비추는 쪽을 향합니다. 좌표는 월드 공간 밀리미터입니다.",
|
||||
"render.studio_center": "중심 X, Y, Z (mm)",
|
||||
"render.studio_denoise": "완성 이미지의 노이즈 줄이기",
|
||||
"render.studio_denoise_help": "최종 가장자리 인식 필터입니다. 미세한 디테일이 부드러워질 수 있습니다. 유리와 날카로운 정반사 표면은 필터를 거치지 않습니다.",
|
||||
"render.studio_denoise_help": "프로그레시브 이미지와 완성 이미지에 경계를 보존하는 필터를 적용합니다. 미세한 디테일이 부드러워질 수 있습니다. 유리와 날카로운 정반사 표면은 필터를 거치지 않습니다.",
|
||||
"render.studio_direction": "태양 방향 (X, Y, Z)",
|
||||
"render.studio_environment": "환경",
|
||||
"render.studio_environment_bounds": "환경 회전은 ±1,000,000라디안 이내의 유한한 값이어야 하고 강도는 0과 100 사이여야 합니다.",
|
||||
@@ -3598,11 +3743,15 @@
|
||||
"render.use_preview": "통합 미리보기 사용",
|
||||
"render.volume_albedo": "산란 알베도 · 선형 RGB",
|
||||
"render.volume_anisotropy": "위상 평균 코사인",
|
||||
"render.volume_denoise_required": "대기를 사용하려면 노이즈 감소를 끄세요.",
|
||||
"render.volume_enable": "참여 매질 사용",
|
||||
"render.volume_extinction": "소광 계수",
|
||||
"render.volume_glass_required": "이 설정에서는 대기와 유리를 함께 사용할 수 없습니다.",
|
||||
"render.volume_help": "유한한 상자 하나 안의 GPU 전송으로, 카메라 및 간접 경로에 비어 감쇠와 HG 산란을 적용합니다. 그림자 감쇠를 포함해 명시적 스튜디오/HDR/하늘 조명을 사용합니다. 양의 위상 코사인은 앞으로 산란합니다. 유리 경계와 표면 노이즈 제거는 명시적으로 꺼야 합니다. 소광이 0이면 전송은 바뀌지 않습니다. 물리적 달 대기, 밀도 그리드, 볼륨 발광, 스펙트럼 전송, 보증된 재질 속성이 아닙니다.",
|
||||
"render.volume_lighting_required": "대기를 렌더링하려면 환경 또는 명시적인 조명 구성을 선택하세요.",
|
||||
"render.volume_max": "최대 범위 · 월드 mm",
|
||||
"render.volume_min": "최소 범위 · 월드 mm",
|
||||
"render.volume_single_stratum_required": "대기를 렌더링하려면 투과 샘플을 1로 설정하세요.",
|
||||
"render.volume_title": "제한된 균질 볼륨",
|
||||
"render.wait_add_light": "아직 지원되지 않음: 이름이 있는 조명 만들기",
|
||||
"render.wait_batch": "아직 지원되지 않음: 저장된 샷 렌더 대기열",
|
||||
@@ -3718,6 +3867,7 @@
|
||||
"sketch.dimension_applied": "치수를 적용했습니다",
|
||||
"sketch.dimension_applied_defined": "치수를 적용했습니다. 매개변수 `{name}`을(를) 정의했습니다",
|
||||
"sketch.dimension_applied_renamed": "치수를 적용했습니다. 매개변수 이름을 `{name}`(으)로 지정했습니다",
|
||||
"sketch.divide_hint": "점은 각 곡선을 같은 길이로 나누고 곡선이 바뀌어도 이를 유지합니다.",
|
||||
"sketch.dof_left": "남은 자유도 {count}개",
|
||||
"sketch.dof_left_one": "남은 자유도 {count}개",
|
||||
"sketch.draw_curves": "{linetype}(으)로 그리기",
|
||||
@@ -4529,6 +4679,7 @@
|
||||
"ui.heading_custom_view_navigator": "사용자 지정 뷰 탐색기",
|
||||
"ui.heading_cylinder": "원통",
|
||||
"ui.heading_design": "디자인",
|
||||
"ui.heading_divide_curve": "곡선 분할",
|
||||
"ui.heading_draft": "구배",
|
||||
"ui.heading_edit": "편집",
|
||||
"ui.heading_equation_curve": "방정식 곡선",
|
||||
@@ -4728,6 +4879,101 @@
|
||||
"ui.palette_sketch_options": "스케치 옵션",
|
||||
"ui.pan": "이동",
|
||||
"ui.pan_zoom_orbit": "이동, 확대/축소, 궤도 회전",
|
||||
"ui.panel_fixture.apply": "적용",
|
||||
"ui.panel_fixture.cancel": "취소",
|
||||
"ui.panel_fixture.caption": "합성 패널 견본",
|
||||
"ui.panel_fixture.draft": "유지된 초안",
|
||||
"ui.panel_fixture.editor": "견본 편집기",
|
||||
"ui.panel_fixture.explanation": "이 합성 콘텐츠는 숨기거나 이동해도 초안을 유지합니다.",
|
||||
"ui.panel_fixture.fill": "높이 채우기 견본",
|
||||
"ui.panel_fixture.finish": "완료",
|
||||
"ui.panel_fixture.finished": "합성 트랜잭션 종료됨",
|
||||
"ui.panel_fixture.footer": "견본 동작은 설계를 변경하지 않습니다.",
|
||||
"ui.panel_fixture.guard": "트랜잭션이 활성 상태일 때 취소 거부",
|
||||
"ui.panel_fixture.inline": "한 줄 견본",
|
||||
"ui.panel_fixture.live": "합성 트랜잭션 활성 상태",
|
||||
"ui.panel_fixture.log": "견본 로그",
|
||||
"ui.panel_fixture.pin": "고정된 견본",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "서비스 업데이트: {count}",
|
||||
"ui.panel_host.attention": "주의 필요",
|
||||
"ui.panel_host.bottom": "아래쪽",
|
||||
"ui.panel_host.close": "패널 닫기",
|
||||
"ui.panel_host.collapse": "패널 접기",
|
||||
"ui.panel_host.expand": "패널 펼치기",
|
||||
"ui.panel_host.floating": "플로팅",
|
||||
"ui.panel_host.focus": "패널에 초점",
|
||||
"ui.panel_host.focus_target": "{title}에 초점",
|
||||
"ui.panel_host.header": "패널 머리글",
|
||||
"ui.panel_host.join": "탭 결합",
|
||||
"ui.panel_host.join_target": "{title}와 탭 결합",
|
||||
"ui.panel_host.left": "왼쪽",
|
||||
"ui.panel_host.menu": "패널 동작",
|
||||
"ui.panel_host.move": "이동 위치",
|
||||
"ui.panel_host.overflow": "더 많은 패널",
|
||||
"ui.panel_host.popout": "창에서 열기",
|
||||
"ui.panel_host.resize": "패널 크기 조정",
|
||||
"ui.panel_host.right": "오른쪽",
|
||||
"ui.panel_host.rule.availability": "이 패널을 사용할 수 없습니다.",
|
||||
"ui.panel_host.rule.bounds": "패널이 크기 제한에 맞지 않습니다.",
|
||||
"ui.panel_host.rule.capability": "이 호스트는 해당 동작을 지원하지 않습니다.",
|
||||
"ui.panel_host.rule.collection_limit": "패널 배치가 한도에 도달했습니다.",
|
||||
"ui.panel_host.rule.duplicate_id": "이 패널 식별자는 이미 사용 중입니다.",
|
||||
"ui.panel_host.rule.exactly_once": "각 패널은 한 번 나타나야 합니다.",
|
||||
"ui.panel_host.rule.feature_disabled": "이 패널에서 해당 동작이 비활성화되어 있습니다.",
|
||||
"ui.panel_host.rule.id": "패널 식별자가 유효하지 않습니다.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "이 패널들은 탭 그룹을 공유할 수 없습니다.",
|
||||
"ui.panel_host.rule.lifecycle": "패널이 이 동작을 완료하지 못했습니다.",
|
||||
"ui.panel_host.rule.missing_target": "이 패널 대상은 더 이상 사용할 수 없습니다.",
|
||||
"ui.panel_host.rule.no_space": "이 패널 배치를 위한 공간이 없습니다.",
|
||||
"ui.panel_host.rule.pin_conflict": "이 가장자리에는 다른 패널이 이미 고정되어 있습니다.",
|
||||
"ui.panel_host.rule.pin_order": "고정된 패널은 가장자리의 첫 위치를 유지해야 합니다.",
|
||||
"ui.panel_host.rule.placement": "이 패널은 해당 위치로 이동할 수 없습니다.",
|
||||
"ui.panel_host.rule.revision": "배치가 변경되었습니다. 동작을 다시 시도하세요.",
|
||||
"ui.panel_host.rule.schema": "패널 요청이 유효하지 않습니다.",
|
||||
"ui.panel_host.rule.version": "이 패널 배치 버전은 지원되지 않습니다.",
|
||||
"ui.panel_host.sash": "인접한 패널 크기 조정",
|
||||
"ui.panel_host.scroll_horizontal": "패널 열 스크롤",
|
||||
"ui.panel_host.scroll_vertical": "패널 스택 스크롤",
|
||||
"ui.panel_host.surface": "패널",
|
||||
"ui.panel_host.tab": "패널 탭",
|
||||
"ui.panel_host.tabs": "모든 탭",
|
||||
"ui.panel_layout.applied": "{name}을(를) {workspace}에 적용했습니다",
|
||||
"ui.panel_layout.cancel": "취소",
|
||||
"ui.panel_layout.confirm_replace": "“{name}”을(를) 덮어쓸까요?",
|
||||
"ui.panel_layout.copy": "복사",
|
||||
"ui.panel_layout.current": "현재 레이아웃",
|
||||
"ui.panel_layout.custom": "사용자 지정",
|
||||
"ui.panel_layout.custom_hint": "{name} 이후 패널이 이동되었습니다.",
|
||||
"ui.panel_layout.details": "자세히",
|
||||
"ui.panel_layout.layout_workspace": "레이아웃 작업 공간",
|
||||
"ui.panel_layout.page_defaults_hint": "이 페이지의 설정을 초기화합니다. 패널 배치와 저장된 레이아웃은 유지됩니다.",
|
||||
"ui.panel_layout.panel_layout": "패널 레이아웃",
|
||||
"ui.panel_layout.panel_style": "패널 스타일",
|
||||
"ui.panel_layout.replace": "레이아웃 덮어쓰기",
|
||||
"ui.panel_layout.replace_current": "현재 배치로 덮어쓰기",
|
||||
"ui.panel_layout.replace_short": "덮어쓰기",
|
||||
"ui.panel_layout.reset": "작업 공간 초기화",
|
||||
"ui.panel_layout.reset_hint": "{workspace}을(를) 기본 배치로 초기화합니다. 저장된 레이아웃은 유지됩니다.",
|
||||
"ui.panel_layout.reset_short": "초기화",
|
||||
"ui.panel_layout.restore_failed": "레이아웃을 복원하지 못했습니다",
|
||||
"ui.panel_layout.save": "레이아웃 저장",
|
||||
"ui.panel_layout.save_as": "다른 이름으로 저장",
|
||||
"ui.panel_layout.save_as_tile": "다른 이름으로 저장…",
|
||||
"ui.panel_layout.selected": "선택됨",
|
||||
"ui.panel_layout.suggested_name": "레이아웃 {n}",
|
||||
"ui.panel_layout.try_again": "다시 시도",
|
||||
"ui.panel_layout.validation.builtin": "기본 제공 레이아웃은 변경할 수 없습니다",
|
||||
"ui.panel_layout.validation.duplicate": "이미 사용 중인 이름입니다",
|
||||
"ui.panel_layout.validation.empty": "이름을 입력하세요",
|
||||
"ui.panel_layout.validation.full": "64개 중 64개가 저장되었습니다. 덮어쓸 레이아웃을 선택하세요.",
|
||||
"ui.panel_layout.validation.invalid": "제어 문자 없이 1–64자를 사용하세요",
|
||||
"ui.panel_layout.workspace.classic": "클래식",
|
||||
"ui.panel_layout.workspace.modelling": "모델링",
|
||||
"ui.panel_layout.workspace.render": "렌더링",
|
||||
"ui.panel_layout.workspace.review": "검토",
|
||||
"ui.panel_layout.workspace.sketch": "스케치",
|
||||
"ui.panel_layout.your_layout": "내 레이아웃",
|
||||
"ui.parallel": "평행",
|
||||
"ui.parameters": "매개변수",
|
||||
"ui.part_size_needs_a_part": "크기를 바꿀 삽입된 표준 부품(나사, 너트, 와셔 또는 핀)을 선택하십시오. 바디를 키우거나 줄이려면 축척을 사용하십시오.",
|
||||
@@ -4767,6 +5013,7 @@
|
||||
"ui.point_cloud_height_high": "최고 높이",
|
||||
"ui.point_cloud_height_low": "최저 높이",
|
||||
"ui.point_cloud_no_file_colors": "파일에 색상 정보가 없습니다",
|
||||
"ui.point_cloud_reload": "파일에서 다시 불러오기",
|
||||
"ui.point_cloud_single_color": "단색",
|
||||
"ui.point_cloud_size": "점 크기",
|
||||
"ui.point_cloud_units": "파일 단위",
|
||||
@@ -4857,6 +5104,7 @@
|
||||
"ui.second_rail": "두 번째 레일",
|
||||
"ui.section_analysis": "단면 분석",
|
||||
"ui.section_size": "단면 크기",
|
||||
"ui.segments": "세그먼트 수",
|
||||
"ui.select": "선택",
|
||||
"ui.selectOther": "기타 선택…",
|
||||
"ui.selectTangentChain": "접선 체인 선택",
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"en": { "browser.canvas_locked": "The canvas is locked. Unlock it first." },
|
||||
"ar": { "browser.canvas_locked": "اللوحة مقفلة. ألغِ قفلها أولاً." },
|
||||
"de": { "browser.canvas_locked": "Die Leinwand ist gesperrt. Entsperren Sie sie zuerst." },
|
||||
"he": { "browser.canvas_locked": "הקנבס נעול. בטל את הנעילה תחילה." },
|
||||
"ja": { "browser.canvas_locked": "キャンバスはロックされています。先にロックを解除してください。" },
|
||||
"ko": { "browser.canvas_locked": "캔버스가 잠겨 있습니다. 먼저 잠금을 해제하세요." },
|
||||
"vi": { "browser.canvas_locked": "Canvas đang bị khóa. Hãy mở khóa trước." },
|
||||
"zh": { "browser.canvas_locked": "画布已锁定。请先解锁。" }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"en": {
|
||||
"prefs.sketch.escape_twice_finishes": "Double Esc finishes the sketch",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Two quick presses of Esc end the sketch. Off: Esc only cancels the tool or the selection, and Finish Sketch ends the sketch."
|
||||
},
|
||||
"ar": {
|
||||
"prefs.sketch.escape_twice_finishes": "الضغط المزدوج على Esc ينهي الرسم التخطيطي",
|
||||
"prefs.sketch.escape_twice_finishes_note": "ضغطتان سريعتان على Esc تنهيان الرسم التخطيطي. عند الإيقاف: يلغي Esc الأداة أو التحديد فقط، وينهي أمر «إنهاء الرسم» الرسم التخطيطي."
|
||||
},
|
||||
"de": {
|
||||
"prefs.sketch.escape_twice_finishes": "Doppeltes Esc beendet die Skizze",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Zweimal schnell Esc drücken beendet die Skizze. Aus: Esc bricht nur das Werkzeug oder die Auswahl ab, und Skizze beenden schließt die Skizze."
|
||||
},
|
||||
"fr": {
|
||||
"prefs.sketch.escape_twice_finishes": "Un double Échap termine l'esquisse",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Deux pressions rapides sur Échap terminent l'esquisse. Désactivé : Échap annule seulement l'outil ou la sélection, et Terminer l'esquisse ferme l'esquisse."
|
||||
},
|
||||
"he": {
|
||||
"prefs.sketch.escape_twice_finishes": "לחיצה כפולה על Esc מסיימת את הסקיצה",
|
||||
"prefs.sketch.escape_twice_finishes_note": "שתי לחיצות מהירות על Esc מסיימות את הסקיצה. כבוי: Esc רק מבטל את הכלי או את הבחירה, ו'סיום סקיצה' מסיים את הסקיצה."
|
||||
},
|
||||
"ja": {
|
||||
"prefs.sketch.escape_twice_finishes": "Esc を 2 回押してスケッチを終了",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Esc をすばやく 2 回押すとスケッチを終了します。オフ: Esc はツールや選択の取り消しだけを行い、スケッチは「スケッチを終了」で終了します。"
|
||||
},
|
||||
"ko": {
|
||||
"prefs.sketch.escape_twice_finishes": "Esc를 두 번 누르면 스케치 종료",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Esc를 빠르게 두 번 누르면 스케치를 끝냅니다. 끄면: Esc는 도구나 선택만 취소하고, 스케치는 스케치 종료로 끝냅니다."
|
||||
},
|
||||
"vi": {
|
||||
"prefs.sketch.escape_twice_finishes": "Nhấn Esc hai lần để kết thúc bản phác thảo",
|
||||
"prefs.sketch.escape_twice_finishes_note": "Nhấn nhanh Esc hai lần sẽ kết thúc bản phác thảo. Tắt: Esc chỉ hủy công cụ hoặc vùng chọn, và Hoàn tất phác thảo sẽ kết thúc bản phác thảo."
|
||||
},
|
||||
"zh": {
|
||||
"prefs.sketch.escape_twice_finishes": "连按两次 Esc 结束草图",
|
||||
"prefs.sketch.escape_twice_finishes_note": "快速按两次 Esc 会结束草图。关闭时:Esc 只取消工具或选择,用“完成草图”结束草图。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"en": {
|
||||
"ui.mesh_import_origin": "Move to origin",
|
||||
"ui.mesh_import_origin_tip": "Center the mesh on X and Y with its base on Z = 0. When off, the mesh keeps the coordinates stored in the file."
|
||||
},
|
||||
"en-GB": {
|
||||
"ui.mesh_import_origin_tip": "Centre the mesh on X and Y with its base on Z = 0. When off, the mesh keeps the coordinates stored in the file."
|
||||
},
|
||||
"ar": {
|
||||
"ui.mesh_import_origin": "النقل إلى نقطة الأصل",
|
||||
"ui.mesh_import_origin_tip": "توسيط الشبكة على المحورين X وY ووضع قاعدتها على Z = 0. عند إيقافه تحتفظ الشبكة بالإحداثيات المخزنة في الملف."
|
||||
},
|
||||
"de": {
|
||||
"ui.mesh_import_origin": "In den Ursprung verschieben",
|
||||
"ui.mesh_import_origin_tip": "Das Netz in X und Y zentrieren und seine Unterseite auf Z = 0 legen. Wenn aus, behält das Netz die Koordinaten aus der Datei."
|
||||
},
|
||||
"es": {
|
||||
"ui.mesh_import_origin": "Mover al origen",
|
||||
"ui.mesh_import_origin_tip": "Centra la malla en X e Y con su base en Z = 0. Si está desactivado, la malla conserva las coordenadas guardadas en el archivo."
|
||||
},
|
||||
"fr": {
|
||||
"ui.mesh_import_origin": "Déplacer à l'origine",
|
||||
"ui.mesh_import_origin_tip": "Centre le maillage en X et Y et pose sa base sur Z = 0. Désactivé, le maillage garde les coordonnées enregistrées dans le fichier."
|
||||
},
|
||||
"he": {
|
||||
"ui.mesh_import_origin": "הזזה לראשית",
|
||||
"ui.mesh_import_origin_tip": "מרכוז הרשת ב-X וב-Y והנחת הבסיס שלה על Z = 0. כשהאפשרות כבויה, הרשת שומרת על הקואורדינטות שבקובץ."
|
||||
},
|
||||
"it": {
|
||||
"ui.mesh_import_origin": "Sposta all'origine",
|
||||
"ui.mesh_import_origin_tip": "Centra la mesh in X e Y con la base su Z = 0. Se disattivato, la mesh mantiene le coordinate salvate nel file."
|
||||
},
|
||||
"ja": {
|
||||
"ui.mesh_import_origin": "原点へ移動",
|
||||
"ui.mesh_import_origin_tip": "メッシュを X と Y の中心に置き、底面を Z = 0 に合わせます。オフの場合、ファイルに保存された座標のままになります。"
|
||||
},
|
||||
"ko": {
|
||||
"ui.mesh_import_origin": "원점으로 이동",
|
||||
"ui.mesh_import_origin_tip": "메시를 X와 Y의 중앙에 놓고 바닥을 Z = 0에 맞춥니다. 끄면 파일에 저장된 좌표를 그대로 유지합니다."
|
||||
},
|
||||
"pt-BR": {
|
||||
"ui.mesh_import_origin": "Mover para a origem",
|
||||
"ui.mesh_import_origin_tip": "Centraliza a malha em X e Y com a base em Z = 0. Desligado, a malha mantém as coordenadas salvas no arquivo."
|
||||
},
|
||||
"vi": {
|
||||
"ui.mesh_import_origin": "Di chuyển về gốc tọa độ",
|
||||
"ui.mesh_import_origin_tip": "Căn giữa lưới theo X và Y, đặt đáy của nó tại Z = 0. Khi tắt, lưới giữ nguyên tọa độ lưu trong tệp."
|
||||
},
|
||||
"zh": {
|
||||
"ui.mesh_import_origin": "移动到原点",
|
||||
"ui.mesh_import_origin_tip": "将网格在 X 和 Y 方向居中,并将底面置于 Z = 0。关闭时,网格保留文件中存储的坐标。"
|
||||
}
|
||||
}
|
||||
@@ -433,6 +433,7 @@
|
||||
"Select bodies (a face picks its body)": "Selecione corpos (uma face seleciona seu corpo)",
|
||||
"Select bodies or faces instead": "Selecionar corpos ou faces em vez disso",
|
||||
"Select edges": "Selecione arestas",
|
||||
"Select the curves to divide first": "Selecione primeiro as curvas a dividir",
|
||||
"Selection filter": "Filtro de seleção",
|
||||
"Semantic faces share their appearance across instances.": "Faces semânticas compartilham a aparência entre instâncias.",
|
||||
"Send your report on GitHub": "Envie seu relatório no GitHub",
|
||||
@@ -878,6 +879,7 @@
|
||||
"cmd.sketch_options": "Opções da paleta de esboço",
|
||||
"cmd.sketch_paste": "Colar entidades do esboço",
|
||||
"cmd.sketch_point3d": "Ponto 3D",
|
||||
"cmd.sketch_point_divide": "Dividir curva",
|
||||
"cmd.sketch_polygon_circumscribed": "Polígono circunscrito",
|
||||
"cmd.sketch_polygon_edge": "Polígono por aresta",
|
||||
"cmd.sketch_polygon_inscribed": "Polígono inscrito",
|
||||
@@ -1055,6 +1057,7 @@
|
||||
"help.licences": "Licenças",
|
||||
"help.mit": "Licença MIT",
|
||||
"help.notice": "NOTICE",
|
||||
"help.sketch.point.divide": "Coloca pontos que dividem as curvas escolhidas em comprimentos iguais. Os pontos ficam em cada curva e mantêm o espaçamento quando ela muda.",
|
||||
"help.solid.chamfer": "Corta as arestas selecionadas com um bisel plano na distância que você definir. Use para quebrar arestas vivas ou facilitar a entrada de um pino ou parafuso.",
|
||||
"help.solid.extrude": "Empurra um perfil de esboço para o 3D ao longo de uma distância, adicionando ou removendo material. Use para transformar um contorno plano em um bloco, um ressalto ou um rebaixo.",
|
||||
"help.solid.fillet": "Arredonda as arestas selecionadas com uma concordância circular suave do raio que você definir. Use para suavizar arestas vivas, por resistência, conforto ou aparência.",
|
||||
@@ -1441,6 +1444,7 @@
|
||||
"shortcut.pin": "Fixar no topo da caixa S",
|
||||
"shortcut.unpin": "Desafixar",
|
||||
"sketch.degrees_of_freedom": "{count} graus de liberdade",
|
||||
"sketch.divide_hint": "Os pontos dividem cada curva em comprimentos iguais e os mantêm quando ela muda.",
|
||||
"sketch.dof_left": "{count} graus de liberdade restantes",
|
||||
"sketch.dof_left_one": "{count} grau de liberdade restante",
|
||||
"sketch.draw_curves": "Desenhar como {linetype}",
|
||||
@@ -2017,6 +2021,7 @@
|
||||
"ui.heading_create_sketch": "CRIAR ESBOÇO",
|
||||
"ui.heading_cylinder": "CILINDRO",
|
||||
"ui.heading_design": "PROJETO",
|
||||
"ui.heading_divide_curve": "DIVIDIR CURVA",
|
||||
"ui.heading_draft": "ÂNGULO DE SAÍDA",
|
||||
"ui.heading_edit": "EDITAR",
|
||||
"ui.heading_extrude": "EXTRUDAR",
|
||||
@@ -2274,6 +2279,7 @@
|
||||
"ui.scale": "Escala",
|
||||
"ui.second_rail": "Segundo trilho",
|
||||
"ui.section_analysis": "Análise de seção",
|
||||
"ui.segments": "Segmentos",
|
||||
"ui.select": "Selecionar",
|
||||
"ui.selectOther": "Selecionar outro…",
|
||||
"ui.selectTangentChain": "Selecionar cadeia tangente",
|
||||
|
||||
@@ -567,6 +567,7 @@
|
||||
"Select edges": "Выберите рёбра",
|
||||
"Select points of the sketch being edited": "Выберите точки редактируемого эскиза",
|
||||
"Select the centre the pattern turns around first": "Сначала выберите центр, вокруг которого поворачивается массив",
|
||||
"Select the curves to divide first": "Сначала выберите кривые для деления",
|
||||
"Select the curves to offset first": "Сначала выберите кривые для смещения",
|
||||
"Select the mirror line": "Выберите линию зеркала",
|
||||
"Select the sketch curves or points to mirror first": "Сначала выберите кривые или точки эскиза для зеркального отражения",
|
||||
@@ -1185,6 +1186,7 @@
|
||||
"cmd.sketch_options": "Параметры палитры эскиза",
|
||||
"cmd.sketch_paste": "Вставить элементы эскиза",
|
||||
"cmd.sketch_point3d": "3D-точка",
|
||||
"cmd.sketch_point_divide": "Разделить кривую",
|
||||
"cmd.sketch_polygon_circumscribed": "Описанный многоугольник",
|
||||
"cmd.sketch_polygon_edge": "Многоугольник по ребру",
|
||||
"cmd.sketch_polygon_inscribed": "Вписанный многоугольник",
|
||||
@@ -1623,6 +1625,7 @@
|
||||
"help.sketch.pattern.circular": "Копирует геометрию эскиза вокруг центральной точки на полный круг или заданный угол. Используйте для окружностей болтов, спиц и зубьев.",
|
||||
"help.sketch.pattern.rectangular": "Копирует геометрию эскиза рядами и столбцами с заданным шагом. Используйте для сеток отверстий, пазов или вентиляционных прорезей.",
|
||||
"help.sketch.point": "Ставит точку эскиза. Используйте как ориентир для размеров, ограничений, центров отверстий или последующих операций.",
|
||||
"help.sketch.point.divide": "Ставит точки, делящие выбранные кривые на равные по длине части. Точки остаются на каждой кривой и сохраняют шаг при её изменении.",
|
||||
"help.sketch.point3d": "Ставит точку в пространстве при включённом 3D-эскизе. Используйте как ориентир для 3D-кривых и траекторий.",
|
||||
"help.sketch.polygon.circumscribed": "Рисует правильный многоугольник вокруг окружности; размер задаётся от центра до середины стороны. Используйте, когда известен размер под ключ, например у шестигранной гайки.",
|
||||
"help.sketch.polygon.edge": "Рисует правильный многоугольник по двум концам одной стороны. Используйте, когда известны длина и положение стороны.",
|
||||
@@ -3840,6 +3843,7 @@
|
||||
"sketch.dimension_applied": "Размер применён",
|
||||
"sketch.dimension_applied_defined": "Размер применён; параметр `{name}` определён",
|
||||
"sketch.dimension_applied_renamed": "Размер применён; параметру присвоено имя `{name}`",
|
||||
"sketch.divide_hint": "Точки делят каждую кривую на равные по длине части и сохраняют их при её изменении.",
|
||||
"sketch.dof_left": "Осталось степеней свободы: {count}",
|
||||
"sketch.dof_left_one": "Осталась {count} степень свободы",
|
||||
"sketch.draw_curves": "Рисовать как {linetype}",
|
||||
@@ -4629,6 +4633,7 @@
|
||||
"ui.heading_create_sketch": "СОЗДАТЬ ЭСКИЗ",
|
||||
"ui.heading_cylinder": "ЦИЛИНДР",
|
||||
"ui.heading_design": "ДИЗАЙН",
|
||||
"ui.heading_divide_curve": "РАЗДЕЛИТЬ КРИВУЮ",
|
||||
"ui.heading_draft": "УКЛОН",
|
||||
"ui.heading_edit": "ИЗМЕНИТЬ",
|
||||
"ui.heading_equation_curve": "КРИВАЯ ПО УРАВНЕНИЮ",
|
||||
@@ -4956,6 +4961,7 @@
|
||||
"ui.second_rail": "Вторая направляющая",
|
||||
"ui.section_analysis": "Анализ сечения",
|
||||
"ui.section_size": "Размер сечения",
|
||||
"ui.segments": "Сегменты",
|
||||
"ui.select": "Выбрать",
|
||||
"ui.selectOther": "Выбрать другое…",
|
||||
"ui.selectTangentChain": "Выбрать касательную цепочку",
|
||||
|
||||
+468
-13
File diff suppressed because it is too large.
Load diff
+2920
-2914
File diff suppressed because it is too large.
Load diff
+468
-13
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"order": 155,
|
||||
"provenance": "Original SolidCraft mapping of Solarized (MIT palette)",
|
||||
"base": "dark",
|
||||
"borders": {},
|
||||
"colors": {
|
||||
"accent": "#268bd2",
|
||||
"accent_soft": "#073642",
|
||||
"agent_busy": "#268bd2",
|
||||
"agent_ok": "#859900",
|
||||
"app_bar": "#002b36",
|
||||
"app_bar_hover": "#073642",
|
||||
"app_bar_hover_button": "#073642",
|
||||
"app_bar_hover_strong": "#586e75",
|
||||
"app_bar_hover_subtle": "#073642",
|
||||
"app_bar_separator": "#586e75",
|
||||
"app_bar_tab_active": "#073642",
|
||||
"app_bar_text": "#93a1a1",
|
||||
"axis_x": "#dc322f",
|
||||
"axis_y": "#859900",
|
||||
"axis_z": "#346e88",
|
||||
"bend_down": "#b58900",
|
||||
"bend_up": "#859900",
|
||||
"body": "#586e75",
|
||||
"body_edge": "#346e88",
|
||||
"body_selected": "#073642",
|
||||
"border": "#586e75",
|
||||
"box_crossing": "#859900",
|
||||
"box_window": "#268bd2",
|
||||
"chip": "#268bd2",
|
||||
"construction_geom": "#cb4b16",
|
||||
"construction_plane": "#b4870022",
|
||||
"continuity": [
|
||||
"#859900",
|
||||
"#346e88",
|
||||
"#b58900",
|
||||
"#6c71c4"
|
||||
],
|
||||
"control_border": "#586e75",
|
||||
"control_fill": "#073642",
|
||||
"cube_border": "#586e75",
|
||||
"cube_face": "#073642",
|
||||
"cube_hover": "#586e75",
|
||||
"cube_text": "#93a1a1",
|
||||
"dialog_bg": "#073642",
|
||||
"dialog_body": "#073642",
|
||||
"dialog_border": "#586e75",
|
||||
"dialog_footer": "#073642",
|
||||
"dialog_label": "#93a1a1",
|
||||
"dialog_rule": "#586e75",
|
||||
"dimension": "#2aa198",
|
||||
"dimension_driven": "#1f7f78",
|
||||
"error": "#dc322f",
|
||||
"field": "#002b36",
|
||||
"file_background": "#073642",
|
||||
"file_border": "#586e75",
|
||||
"file_dim": "#93a1a1",
|
||||
"file_image_tint": "#002b36",
|
||||
"file_primary": "#586e75",
|
||||
"file_primary_border": "#268bd2",
|
||||
"file_primary_ink": "#ffffff",
|
||||
"file_rail": "#1b6397",
|
||||
"file_rail_hover": "#2670a6",
|
||||
"file_rail_ink": "#ffffff",
|
||||
"file_recovery": "#073642",
|
||||
"file_recovery_border": "#b58900",
|
||||
"file_recovery_ink": "#93a1a1",
|
||||
"file_recovery_well": "#002b36",
|
||||
"file_surface": "#073642",
|
||||
"form_accent": "#6b70c3",
|
||||
"form_dim": "#839496",
|
||||
"form_error": "#dc322f",
|
||||
"form_error_fill": "#586e75",
|
||||
"form_fill": "#a2a9f8",
|
||||
"form_ink": "#93a1a1",
|
||||
"form_primary": "#268bd2",
|
||||
"form_soft": "#073642",
|
||||
"form_success": "#859900",
|
||||
"form_success_fill": "#586e75",
|
||||
"form_tab_ink": "#565a9d",
|
||||
"glyph_bg": "#073642",
|
||||
"glyph_edge": "#da2f2d",
|
||||
"glyph_text": "#da2f2d",
|
||||
"grid": "#073642",
|
||||
"grid_major": "#586e75",
|
||||
"hover": "#586e75",
|
||||
"hover_edge": "#346e88",
|
||||
"hover_edge_halo": "#002b36",
|
||||
"hover_profile": "#268cd228",
|
||||
"hover_profile_edge": "#346e88",
|
||||
"icon": "#93a1a1",
|
||||
"icons.agent": "#6c71c4",
|
||||
"icons.highlight": "#93a1a1",
|
||||
"icons.marker_halo": "#002b36cc",
|
||||
"interference": "#dc322f",
|
||||
"logo": [
|
||||
"#268bd2",
|
||||
"#346e88",
|
||||
"#586e75"
|
||||
],
|
||||
"manipulator": "#268bd2",
|
||||
"mesh_accent": "#97751d",
|
||||
"mesh_fill": "#d7aa3c",
|
||||
"mesh_ink": "#7b5d00",
|
||||
"mesh_soft": "#073642",
|
||||
"on_accent": "#ffffff",
|
||||
"origin_plane": "#b3860028",
|
||||
"origin_plane_edge": "#b6890088",
|
||||
"origin_plane_hover": "#288bd340",
|
||||
"origin_point": "#839496",
|
||||
"overlay": "#073642",
|
||||
"panel": "#073642",
|
||||
"panel_header": "#002b36",
|
||||
"preview_add": "#346e88",
|
||||
"preview_cut": "#dc323066",
|
||||
"preview_new": "#b58900",
|
||||
"preview_sketch": "#859900",
|
||||
"profile_fill": "#35718722",
|
||||
"render_accent": "#cf317e",
|
||||
"render_fill": "#f986b4",
|
||||
"render_ink": "#ad2c6b",
|
||||
"render_soft": "#073642",
|
||||
"rubber_band": "#268bd2",
|
||||
"section_cap": "#b58900",
|
||||
"sel_edge": "#346e88",
|
||||
"sel_edge_rim": "#346e88",
|
||||
"sel_face": "#073642",
|
||||
"sel_profile": "#073642",
|
||||
"sel_profile_edge": "#346e88",
|
||||
"sel_vertex": "#346e88",
|
||||
"selected_bg": "#0a3e50",
|
||||
"selected_ink": "#93a1a1",
|
||||
"sheet_fill": "#58c6bc",
|
||||
"sheet_ink": "#1d6d67",
|
||||
"sheet_soft": "#073642",
|
||||
"sketch": "#346e88",
|
||||
"sketch_accent": "#738400",
|
||||
"sketch_centerline": "#b58900",
|
||||
"sketch_construction": "#b58900",
|
||||
"sketch_fixed": "#93a1a1",
|
||||
"sketch_halo": "#002b36",
|
||||
"sketch_ink": "#5a6800",
|
||||
"sketch_locked": "#859900",
|
||||
"sketch_lost": "#dc322f",
|
||||
"sketch_point": "#93a1a1",
|
||||
"sketch_point_free": "#346e88",
|
||||
"sketch_projected": "#6c71c4",
|
||||
"sketch_soft": "#073642",
|
||||
"surface_accent": "#cb4b16",
|
||||
"surface_fill": "#fb906b",
|
||||
"surface_ink": "#a83e12",
|
||||
"surface_soft": "#073642",
|
||||
"tab_on_fill_dark": "#002b36",
|
||||
"text": "#93a1a1",
|
||||
"text_dim": "#839496",
|
||||
"timeline": "#073642",
|
||||
"timeline_item": "#073642",
|
||||
"timeline_item_error": "#eabcad",
|
||||
"timeline_marker": "#839496",
|
||||
"toolbar": "#073642",
|
||||
"viewport_bottom": "#002b36",
|
||||
"viewport_top": "#002b36",
|
||||
"warning": "#b58900"
|
||||
},
|
||||
"format": "solidcraft-theme/1",
|
||||
"icon_palette": {
|
||||
"constraint": [
|
||||
"#fee0dc",
|
||||
"#fb8d81",
|
||||
"#da2f2d"
|
||||
],
|
||||
"construction": [
|
||||
"#fee1d7",
|
||||
"#fb906b",
|
||||
"#cb4b16"
|
||||
],
|
||||
"form": [
|
||||
"#e3e6fe",
|
||||
"#a2a9f8",
|
||||
"#6b70c3"
|
||||
],
|
||||
"guide": "#839496",
|
||||
"ink": "#fdf6e3",
|
||||
"line": "#93a1a1",
|
||||
"mesh": [
|
||||
"#fde5b2",
|
||||
"#d7aa3c",
|
||||
"#97751d"
|
||||
],
|
||||
"passive-1": "#586e75",
|
||||
"passive-2": "#073642",
|
||||
"passive-3": "#002b36",
|
||||
"sketch": [
|
||||
"#def67b",
|
||||
"#a8be40",
|
||||
"#738400"
|
||||
],
|
||||
"solid": [
|
||||
"#d5ebff",
|
||||
"#67b9fb",
|
||||
"#1480c6"
|
||||
],
|
||||
"surface": [
|
||||
"#fee1d7",
|
||||
"#fb906b",
|
||||
"#cb4b16"
|
||||
]
|
||||
},
|
||||
"name": "Solarized Dark",
|
||||
"radii": {
|
||||
"control_radius": 6,
|
||||
"radius_lg": 8,
|
||||
"radius_md": 6,
|
||||
"radius_sm": 4,
|
||||
"radius_xl": 10,
|
||||
"sketch_mode_radius": 7
|
||||
}
|
||||
}
|
||||
@@ -210,13 +210,16 @@ fn map_plane_ref(m: &Mat, p: &mut PlaneRef) {
|
||||
map_plane_ref(m, base);
|
||||
map_geo_ref(m, point);
|
||||
}
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, line, .. } => {
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, line, pivot, .. } => {
|
||||
map_plane_ref(m, base);
|
||||
*axis_origin = apply_point(m, *axis_origin);
|
||||
*axis_dir = apply_vector(m, *axis_dir);
|
||||
if let Some(g) = line {
|
||||
map_geo_ref(m, g);
|
||||
}
|
||||
if let Some(g) = pivot {
|
||||
map_geo_ref(m, g);
|
||||
}
|
||||
}
|
||||
// Named origin planes and construction planes are the component's own.
|
||||
PlaneRef::Origin { .. } | PlaneRef::Construction { .. } => {}
|
||||
@@ -353,25 +356,7 @@ impl Document {
|
||||
/// Every placement of each component: (component, occurrence path ids, world transform).
|
||||
/// A branch stops past [`MAX_PLACEMENT_DEPTH`] levels, the walk past [`MAX_PLACEMENTS`] placements.
|
||||
pub fn placements(&self) -> Vec<(u64, Vec<u64>, Mat)> {
|
||||
let mut out = vec![(0, Vec::new(), IDENTITY)];
|
||||
let mut stack: Vec<(u64, Vec<u64>, Mat)> = vec![(0, Vec::new(), IDENTITY)];
|
||||
while let Some((comp, path, m)) = stack.pop() {
|
||||
if out.len() > MAX_PLACEMENTS {
|
||||
break;
|
||||
}
|
||||
// Only this branch stops past the depth limit; the others are still walked.
|
||||
if path.len() > MAX_PLACEMENT_DEPTH {
|
||||
continue;
|
||||
}
|
||||
for o in self.occurrences.iter().filter(|o| o.parent == comp) {
|
||||
let mut p = path.clone();
|
||||
p.push(o.id);
|
||||
let w = mat_mul(&m, &o.transform);
|
||||
out.push((o.component, p.clone(), w));
|
||||
stack.push((o.component, p, w));
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::occurrence_tree::OccurrenceTree::new(self).placements_with(|o| o.transform)
|
||||
}
|
||||
|
||||
/// Every body as the world shows it: its world name ("Body1", or "Body1 (Occ:2)" for a
|
||||
@@ -461,13 +446,14 @@ impl Document {
|
||||
if self.component_within(parent, component) {
|
||||
return true;
|
||||
}
|
||||
let tree = crate::occurrence_tree::OccurrenceTree::new(self);
|
||||
let mut stack = vec![component];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
while let Some(c) = stack.pop() {
|
||||
if !seen.insert(c) || seen.len() > MAX_PLACEMENTS {
|
||||
continue;
|
||||
}
|
||||
for o in self.occurrences.iter().filter(|o| o.parent == c) {
|
||||
for o in tree.children(c) {
|
||||
if o.component == parent {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ pub struct Canvas {
|
||||
pub flip: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
/// Locked (#12310): its place, size, angle and flip stay as they are, and it is not deleted,
|
||||
/// until it is unlocked. Its opacity, visibility and name can still change.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub locked: bool,
|
||||
/// The component it belongs to (its plane is in that component's frame, so it moves with
|
||||
/// the component's occurrence); 0 = the root.
|
||||
#[serde(default, skip_serializing_if = "is_root")]
|
||||
|
||||
@@ -119,11 +119,14 @@ fn remap_plane(p: &mut PlaneRef, ids: &BTreeMap<u64, u64>, bodies: &BTreeMap<Str
|
||||
remap_plane(base, ids, bodies, depth + 1)?;
|
||||
remap_geo(point, ids, bodies, depth + 1)?;
|
||||
}
|
||||
PlaneRef::AtAngle { base, line, .. } => {
|
||||
PlaneRef::AtAngle { base, line, pivot, .. } => {
|
||||
remap_plane(base, ids, bodies, depth + 1)?;
|
||||
if let Some(g) = line {
|
||||
remap_geo(g, ids, bodies, depth + 1)?;
|
||||
}
|
||||
if let Some(g) = pivot {
|
||||
remap_geo(g, ids, bodies, depth + 1)?;
|
||||
}
|
||||
}
|
||||
PlaneRef::Face { name, anchor, .. } => {
|
||||
if let Some(name) = name {
|
||||
@@ -323,11 +326,14 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> {
|
||||
}
|
||||
match p {
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => checked_plane(base, depth + 1)?,
|
||||
PlaneRef::AtAngle { base, line, .. } => {
|
||||
PlaneRef::AtAngle { base, line, pivot, .. } => {
|
||||
checked_plane(base, depth + 1)?;
|
||||
if let Some(g) = line {
|
||||
checked_geo(g, depth + 1)?;
|
||||
}
|
||||
if let Some(g) = pivot {
|
||||
checked_geo(g, depth + 1)?;
|
||||
}
|
||||
}
|
||||
PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } | PlaneRef::AxisPoint { axis: a, point: b } => {
|
||||
checked_geo(a, depth + 1)?;
|
||||
|
||||
@@ -923,9 +923,10 @@ impl PlaneRef {
|
||||
refs.push(point.as_mut());
|
||||
refs
|
||||
}
|
||||
PlaneRef::AtAngle { base, line, .. } => {
|
||||
PlaneRef::AtAngle { base, line, pivot, .. } => {
|
||||
let mut v = base.refs_mut();
|
||||
v.extend(line.as_deref_mut());
|
||||
v.extend(pivot.as_deref_mut());
|
||||
v
|
||||
}
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => base.refs_mut(),
|
||||
|
||||
@@ -61,6 +61,9 @@ pub enum PlaneRef {
|
||||
/// Another plane rotated about a line (in world coordinates) by an angle expression. With
|
||||
/// `line`, an edge or round face of the model ([`crate::construct::model_axis`]), the line is
|
||||
/// found there on each evaluation and `axis_origin`/`axis_dir` are where it was when picked.
|
||||
/// With `direction_only`, only the axis direction is used: it is projected onto the base
|
||||
/// (nothing of that projection is kept as geometry) and the plane turns about the line
|
||||
/// through `pivot`, or through the base origin when `pivot` is absent.
|
||||
AtAngle {
|
||||
base: Box<PlaneRef>,
|
||||
axis_origin: Vec3,
|
||||
@@ -68,6 +71,12 @@ pub enum PlaneRef {
|
||||
angle: Expr,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
line: Option<Box<GeoRef>>,
|
||||
/// Use only the axis direction (projected onto the base), not the axis as a full line.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
direction_only: bool,
|
||||
/// Pivot for `direction_only`; absent means the base plane's origin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pivot: Option<Box<GeoRef>>,
|
||||
},
|
||||
/// A construction plane feature (by id).
|
||||
Construction { feature: FeatureId },
|
||||
@@ -321,6 +330,12 @@ pub struct Extent {
|
||||
/// Through all bodies in the direction(s) instead of `distance`.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub through_all: bool,
|
||||
/// Two Sides as older builds read it: `distance2` goes the other way from wherever the
|
||||
/// first side went, so a negative entered distance sends it back along the normal. Saved
|
||||
/// designs from before entered distances kept their sides carry it, so they rebuild as
|
||||
/// they did whatever their expressions evaluate to; new and edited extrudes leave it off.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub second_follows_first: bool,
|
||||
/// Taper angle (expression; positive grows the profile).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[walk(angle = "Taper angle")]
|
||||
@@ -4428,7 +4443,7 @@ impl Document {
|
||||
let b = self.resolve_plane_in(vals, base, depth + 1, st)?;
|
||||
Ok(b.offset(Self::eval_in(vals, distance, Kind::Length)?))
|
||||
}
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line } => {
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line, direction_only, pivot } => {
|
||||
let b = self.resolve_plane_in(vals, base, depth + 1, st)?;
|
||||
let a = Self::eval_in(vals, angle, Kind::Angle)?;
|
||||
let (axis_origin, axis_dir) = match line {
|
||||
@@ -4438,7 +4453,26 @@ impl Document {
|
||||
}
|
||||
None => (*axis_origin, *axis_dir),
|
||||
};
|
||||
let d = axis_dir.normalized().ok_or_else(|| DocError::Invalid("rotation axis".into()))?;
|
||||
let (axis_origin, d) = if *direction_only {
|
||||
let n = b.normal();
|
||||
let in_plane = axis_dir - n * n.dot(axis_dir);
|
||||
let d = in_plane
|
||||
.normalized()
|
||||
.ok_or_else(|| DocError::Invalid("the axis is square to the plane, so it has no direction in the plane".into()))?;
|
||||
let pivot = match pivot {
|
||||
Some(g) => {
|
||||
let st = st.ok_or_else(|| DocError::Invalid("this plane is built from the model: evaluate first".into()))?;
|
||||
crate::construct::point(&crate::construct::Ctx { doc: self, vals, st, depth }, g)?
|
||||
}
|
||||
None => b.origin,
|
||||
};
|
||||
// Keep the pivot in the base so a slightly off pick still turns about an in-plane line.
|
||||
let pivot = pivot - n * n.dot(pivot - b.origin);
|
||||
(pivot, d)
|
||||
} else {
|
||||
let d = axis_dir.normalized().ok_or_else(|| DocError::Invalid("rotation axis".into()))?;
|
||||
(axis_origin, d)
|
||||
};
|
||||
let rot = |v: Vec3| v * a.cos() + d.cross(v) * a.sin() + d * (d.dot(v) * (1.0 - a.cos()));
|
||||
let o = axis_origin + rot(b.origin - axis_origin);
|
||||
Plane::new(o, rot(b.x), rot(b.y)).ok_or_else(|| DocError::Invalid("degenerate plane".into()))
|
||||
|
||||
@@ -90,7 +90,7 @@ pub struct Drawing {
|
||||
}
|
||||
|
||||
/// The fields a drawing's record has: anything else in a file is a newer build's.
|
||||
const RECORD_FIELDS: [&str; 7] = ["format", "name", "sources", "properties", "units", "language", "sheets"];
|
||||
const RECORD_FIELDS: [&str; 8] = ["format", "format_pending", "name", "sources", "properties", "units", "language", "sheets"];
|
||||
|
||||
/// Move the elements of the list `key` that don't read as `T` out of a newer build's drawing.
|
||||
fn take_unread<T: serde::de::DeserializeOwned>(top: &mut serde_json::Map<String, Value>, key: &str, one: &str, file: &mut NewerDrawing) {
|
||||
|
||||
+145
-62
@@ -467,6 +467,21 @@ fn removed_note(gone: &[Vec3]) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Current feature evaluation validation mode (`EachStep`, `EachFeature`, or `Off`).
|
||||
static EVAL_VALIDATION: std::cell::Cell<kernel::Validation> = const { std::cell::Cell::new(kernel::Validation::EachFeature) };
|
||||
}
|
||||
|
||||
/// Restores `EVAL_VALIDATION` to its previous value when dropped.
|
||||
struct EvalValidationGuard(kernel::Validation);
|
||||
|
||||
impl Drop for EvalValidationGuard {
|
||||
/// Restores the saved validation mode on scope exit.
|
||||
fn drop(&mut self) {
|
||||
EVAL_VALIDATION.set(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A blend's refusal as too large (`why`) with the largest `size` (radius, distance) that fits,
|
||||
/// as `search` finds it by building candidates ([`kernel::fillet_max`]): the refusal as it is
|
||||
/// when none fits or the search itself fails (a candidate failing for another reason says
|
||||
@@ -476,6 +491,9 @@ fn with_largest_fit(
|
||||
size: &str,
|
||||
search: impl FnOnce() -> std::result::Result<Option<(f64, kernel::Body)>, kernel::KernelError>,
|
||||
) -> kernel::KernelError {
|
||||
if EVAL_VALIDATION.get() == kernel::Validation::Off {
|
||||
return kernel::KernelError::TooLarge(why);
|
||||
}
|
||||
// On solidcore the refusal names a size already, less a margin (34.99 where 35 builds), and
|
||||
// its edge: the edge stays, the size is the largest the search builds, solidcore's where the
|
||||
// search finds none.
|
||||
@@ -2350,6 +2368,7 @@ impl Model {
|
||||
let r = match frame_error.or(bad_param) {
|
||||
Some(e) => Err(kernel::KernelError::Failed(e)),
|
||||
None => kernel::guard(&f.name, || {
|
||||
let _val_guard = EvalValidationGuard(EVAL_VALIDATION.replace(validation));
|
||||
let (r, deferred) =
|
||||
kernel::validating(validation, || eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair));
|
||||
r.map_err(|e| match e {
|
||||
@@ -3684,6 +3703,27 @@ fn body_at(st: &ModelState, body: &Option<crate::BodyName>, points: &[Vec3]) ->
|
||||
.ok_or_else(|| DocError::Invalid("there is no body".into()))
|
||||
}
|
||||
|
||||
/// Whether the whole line through `p` along `dir` (both ways) meets the box (slab test). A zero
|
||||
/// component of `dir` keeps the line in its slab only when `p` is already within it.
|
||||
fn line_meets_box(p: Vec3, dir: Vec3, b: &solidcraft_geom::Aabb3) -> bool {
|
||||
if b.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (o, d, min, max) in [(p.x, dir.x, b.min.x, b.max.x), (p.y, dir.y, b.min.y, b.max.y), (p.z, dir.z, b.min.z, b.max.z)] {
|
||||
if d == 0.0 || !d.is_finite() {
|
||||
if !(min..=max).contains(&o) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (t0, t1) = ((min - o) / d, (max - o) / d);
|
||||
lo = lo.max(t0.min(t1));
|
||||
hi = hi.min(t0.max(t1));
|
||||
}
|
||||
lo <= hi
|
||||
}
|
||||
|
||||
/// A hole stays on its face when the model changes: a position now inside a body moves back
|
||||
/// against the drilling direction to the surface, one now above it moves down onto it. Only the
|
||||
/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). Edit Hole seeds from
|
||||
@@ -3694,6 +3734,12 @@ pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) ->
|
||||
let mut best: Option<Vec3> = None;
|
||||
for b in st.bodies.iter().filter(|b| in_hole_scope(scope, b)) {
|
||||
let m = b.mesh();
|
||||
// Every test below casts along the line through `p`: a mesh whose box that line misses
|
||||
// has no triangle to hit, so skip it before scanning its triangles (in an assembly of
|
||||
// hundreds of parts, these scans were most of a hole's time).
|
||||
if !line_meets_box(p, dir, &m.bounds().inflated(eps * 8.0)) {
|
||||
continue;
|
||||
}
|
||||
// Already on the surface: the drill enters right here.
|
||||
if let Some((t, _)) = m.raycast(p - dir * eps, dir)
|
||||
&& t < eps * 4.0
|
||||
@@ -3710,15 +3756,18 @@ pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) ->
|
||||
best.unwrap_or(p)
|
||||
}
|
||||
|
||||
/// The faces of the model near `p`: for each, how far `p` is from it, the outward normal there
|
||||
/// (the surface's own normal for planes, cylinders and spheres, turned the way the face looks out
|
||||
/// of its body; the nearest mesh facet's otherwise) and, for a plane, how far `p` is from the
|
||||
/// plane itself. Only faces within `reach` of `p`, nearest first, of the bodies in `scope`
|
||||
/// (every body when it is empty).
|
||||
fn faces_through(st: &ModelState, p: Vec3, reach: f64, scope: &[String]) -> Vec<(f64, Vec3, Option<f64>)> {
|
||||
let mut out: Vec<(f64, Vec3, Option<f64>)> = Vec::new();
|
||||
for b in st.bodies.iter().filter(|b| !b.body.is_mesh() && in_hole_scope(scope, b)) {
|
||||
/// The faces of the model near `p`, nearest first, before their surfaces are looked at: for
|
||||
/// each, how far `p` is from it, its body, its index and the outward normal of its nearest mesh
|
||||
/// facet. Only faces within `reach` of `p`, of the bodies in `scope` (every body when it is
|
||||
/// empty). Ties keep body order, then face order.
|
||||
fn faces_near(st: &ModelState, p: Vec3, reach: f64, scope: &[String]) -> Vec<NearFace> {
|
||||
let mut out: Vec<NearFace> = Vec::new();
|
||||
for (i, b) in st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && in_hole_scope(scope, b)) {
|
||||
let m = b.mesh();
|
||||
// No facet is nearer `p` than the mesh's box: one beyond `reach` has none to give.
|
||||
if !m.bounds().inflated(reach).contains(p) {
|
||||
continue;
|
||||
}
|
||||
// The nearest facet of each face of this body.
|
||||
let mut near: BTreeMap<u32, (f64, Vec3)> = BTreeMap::new();
|
||||
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
|
||||
@@ -3729,53 +3778,67 @@ fn faces_through(st: &ModelState, p: Vec3, reach: f64, scope: &[String]) -> Vec<
|
||||
near.insert(*f, (d, n));
|
||||
}
|
||||
}
|
||||
for (f, (d, facet)) in near {
|
||||
let (exact, off) = match kernel::face_surface(&b.body, f as usize) {
|
||||
Some(kernel::FaceSurface::Plane { normal, point }) => (Some(*normal), Some((p - point).dot(normal).abs())),
|
||||
Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => {
|
||||
let v = p - origin;
|
||||
((v - axis * v.dot(axis)).normalized(), None)
|
||||
}
|
||||
Some(kernel::FaceSurface::Sphere { center, .. }) => ((p - center).normalized(), None),
|
||||
// Square to the line through the apex, not the nearest facet's normal (#10698).
|
||||
Some(kernel::FaceSurface::Cone { apex, axis, half_angle }) => {
|
||||
let v = p - apex;
|
||||
let out = (v - axis * v.dot(axis)).normalized();
|
||||
(out.and_then(|u| (u * half_angle.cos() - axis * half_angle.sin()).normalized()), None)
|
||||
}
|
||||
// Away from the nearest point of the ring the tube goes round.
|
||||
Some(kernel::FaceSurface::Torus { center, axis, major, .. }) => {
|
||||
let v = p - center;
|
||||
let ring = (v - axis * v.dot(axis)).normalized().map(|u| center + u * major);
|
||||
(ring.and_then(|q| (p - q).normalized()), None)
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
let n = match exact {
|
||||
Some(n) if n.dot(facet) < 0.0 => -n,
|
||||
Some(n) => n,
|
||||
None => facet,
|
||||
};
|
||||
out.push((d, n, off));
|
||||
}
|
||||
out.extend(near.into_iter().map(|(f, (d, n))| (d, i, f, n)));
|
||||
}
|
||||
out.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
out
|
||||
}
|
||||
|
||||
/// The faces near `p` a hole placed there goes by (as [`faces_through`]): those of the bodies in
|
||||
/// A face of [`faces_near`]: its distance from the point, its body, its index and the outward
|
||||
/// normal of its nearest mesh facet.
|
||||
type NearFace = (f64, usize, u32, Vec3);
|
||||
|
||||
/// One face of [`faces_near`] as [`faces_through`] gives it: the distance, the outward normal
|
||||
/// (the surface's own normal for planes, cylinders, spheres, cones and tori, turned the way the
|
||||
/// face looks out of its body; the nearest mesh facet's otherwise) and, for a plane, how far `p`
|
||||
/// is from the plane itself. Classifying the surface is the costly part, so callers that stop at
|
||||
/// the first face that answers them ask for no more than that.
|
||||
fn face_through(st: &ModelState, p: Vec3, (d, body, f, facet): NearFace) -> (f64, Vec3, Option<f64>) {
|
||||
#[cfg(test)]
|
||||
cost_tests::count(|c| c.surfaces += 1);
|
||||
let exact = st.bodies.get(body).and_then(|b| kernel::face_surface(&b.body, f as usize));
|
||||
let (exact, off) = match exact {
|
||||
Some(kernel::FaceSurface::Plane { normal, point }) => (Some(*normal), Some((p - point).dot(normal).abs())),
|
||||
Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => {
|
||||
let v = p - origin;
|
||||
((v - axis * v.dot(axis)).normalized(), None)
|
||||
}
|
||||
Some(kernel::FaceSurface::Sphere { center, .. }) => ((p - center).normalized(), None),
|
||||
// Square to the line through the apex, not the nearest facet's normal (#10698).
|
||||
Some(kernel::FaceSurface::Cone { apex, axis, half_angle }) => {
|
||||
let v = p - apex;
|
||||
let out = (v - axis * v.dot(axis)).normalized();
|
||||
(out.and_then(|u| (u * half_angle.cos() - axis * half_angle.sin()).normalized()), None)
|
||||
}
|
||||
// Away from the nearest point of the ring the tube goes round.
|
||||
Some(kernel::FaceSurface::Torus { center, axis, major, .. }) => {
|
||||
let v = p - center;
|
||||
let ring = (v - axis * v.dot(axis)).normalized().map(|u| center + u * major);
|
||||
(ring.and_then(|q| (p - q).normalized()), None)
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
let n = match exact {
|
||||
Some(n) if n.dot(facet) < 0.0 => -n,
|
||||
Some(n) => n,
|
||||
None => facet,
|
||||
};
|
||||
(d, n, off)
|
||||
}
|
||||
|
||||
/// The faces near `p` a hole placed there goes by (as [`faces_near`]): those of the bodies in
|
||||
/// `scope`, the hole's own, when one of them passes within `on` of `p`, else those of every body.
|
||||
/// Where a plate's face touches another body both faces pass through `p`, and a hole that drills
|
||||
/// the plate goes by the plate's face, never the other body's (#12066). A hole placed on another
|
||||
/// body's face, to drill through it into its own body behind, still goes by that face.
|
||||
fn hole_faces_through(st: &ModelState, p: Vec3, reach: f64, on: f64, scope: &[String]) -> Vec<(f64, Vec3, Option<f64>)> {
|
||||
fn hole_faces_near(st: &ModelState, p: Vec3, reach: f64, on: f64, scope: &[String]) -> Vec<NearFace> {
|
||||
if !scope.is_empty() {
|
||||
let own = faces_through(st, p, reach, scope);
|
||||
if own.first().is_some_and(|(d, _, _)| *d <= on) {
|
||||
let own = faces_near(st, p, reach, scope);
|
||||
if own.first().is_some_and(|c| c.0 <= on) {
|
||||
return own;
|
||||
}
|
||||
}
|
||||
faces_through(st, p, reach, &[])
|
||||
faces_near(st, p, reach, &[])
|
||||
}
|
||||
|
||||
/// The way a hole placed at `p` drills: into the material, against the outward normal of the
|
||||
@@ -3785,17 +3848,22 @@ fn hole_faces_through(st: &ModelState, p: Vec3, reach: f64, on: f64, scope: &[St
|
||||
/// of the bodies in `scope` (the bodies the hole drills; empty for every body) decide.
|
||||
pub fn hole_direction_at(st: &ModelState, p: Vec3, scope: &[String]) -> Option<Vec3> {
|
||||
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
|
||||
let faces = hole_faces_through(st, p, f64::INFINITY, size * 1e-4, scope);
|
||||
if let Some((d, n, _)) = faces.first()
|
||||
&& *d <= size * 1e-4
|
||||
// Every face of the model, nearest first; each surface is classified only when the rules
|
||||
// below reach it. Classifying all of them first took most of a hole's time in an assembly
|
||||
// of hundreds of parts, where the nearest face nearly always answers.
|
||||
let near = hole_faces_near(st, p, f64::INFINITY, size * 1e-4, scope);
|
||||
let mut faces = near.iter().map(|c| face_through(st, p, *c));
|
||||
let first = faces.next();
|
||||
if let Some((d, n, _)) = first
|
||||
&& d <= size * 1e-4
|
||||
{
|
||||
return Some(-*n);
|
||||
return Some(-n);
|
||||
}
|
||||
if let Some((_, n, _)) = faces.iter().find(|(_, _, off)| off.is_some_and(|o| o <= size * 1e-4)) {
|
||||
return Some(-*n);
|
||||
if let Some((_, n, _)) = first.into_iter().chain(faces).find(|(_, _, off)| off.is_some_and(|o| o <= size * 1e-4)) {
|
||||
return Some(-n);
|
||||
}
|
||||
let reach = st.bodies.iter().map(crate::appearance::pick_tolerance).fold(0.0, f64::max);
|
||||
faces.first().filter(|(d, _, _)| *d <= reach).map(|(_, n, _)| -*n)
|
||||
first.filter(|(d, _, _)| *d <= reach).map(|(_, n, _)| -n)
|
||||
}
|
||||
|
||||
/// A hole placed on a face drills into the material: when its direction leaves every face it
|
||||
@@ -3808,7 +3876,7 @@ pub fn hole_direction_at(st: &ModelState, p: Vec3, scope: &[String]) -> Option<V
|
||||
/// the plate there, drills the plate (#12066).
|
||||
fn hole_dir_into_face(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 {
|
||||
let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);
|
||||
let faces = hole_faces_through(st, p, size * 1e-5, size * 1e-5, scope);
|
||||
let faces: Vec<_> = hole_faces_near(st, p, size * 1e-5, size * 1e-5, scope).into_iter().map(|c| face_through(st, p, c)).collect();
|
||||
if faces.is_empty() || faces.iter().any(|(_, n, _)| n.dot(dir) < -1e-9) {
|
||||
return dir;
|
||||
}
|
||||
@@ -5745,13 +5813,13 @@ fn feature_tools_with_constructor(
|
||||
FeatureKind::Torus { center, major, minor, .. } => {
|
||||
Ok(unnamed(vec![kernel::torus(point(vals, center)?, val(vals, major, Kind::Length)?, val(vals, minor, Kind::Length)?)?]))
|
||||
}
|
||||
FeatureKind::Cone { base, axis, radius, top_radius, height, .. } => Ok(unnamed(vec![more::cone(
|
||||
FeatureKind::Cone { base, axis, radius, top_radius, height, .. } => Ok(vec![more::cone(
|
||||
point(vals, base)?,
|
||||
axis.0,
|
||||
val(vals, radius, Kind::Length)?,
|
||||
val(vals, top_radius, Kind::Length)?,
|
||||
val(vals, height, Kind::Length)?,
|
||||
)?])),
|
||||
)?]),
|
||||
FeatureKind::Hole { .. } => Ok(hole_feature_tools(vals, st, f)?.into_iter().map(|(tool, _)| tool).collect()),
|
||||
_ => Err(DocError::Invalid(format!("{} cannot be patterned or mirrored yet", f.name))),
|
||||
}
|
||||
@@ -6083,15 +6151,28 @@ fn from_profile_on_closed_path(segs: Vec<solidcore_record::Seg2>, path: &Plane,
|
||||
/// Where an extrude of distance `d` starts and ends along the sketch normal, before any start
|
||||
/// offset: one side, the other, both (symmetric), or a second distance on the other side.
|
||||
///
|
||||
/// A second distance (`distance2`) goes the other way from the first side, wherever that went:
|
||||
/// against the normal for `direction: negative` (#2700), and back along it when a negative
|
||||
/// distance or a To Object below the sketch sends the first side down.
|
||||
/// A second distance (`distance2`) goes the other way from the first side: against the normal,
|
||||
/// or along it for `direction: negative` (#2700). Entered distances keep those sides whatever
|
||||
/// their signs; a To Object below the sketch or a Through All that reaches down sends the first
|
||||
/// side down and the second back along the normal.
|
||||
pub(crate) fn extent_sides(vals: &BTreeMap<String, Value>, extent: &crate::Extent, d: f64, direction: crate::Direction) -> Result<(f64, f64)> {
|
||||
Ok(match (&extent.distance2, direction) {
|
||||
(Some(d2), _) => {
|
||||
let first = if direction == crate::Direction::Negative { -d } else { d };
|
||||
let negative = direction == crate::Direction::Negative;
|
||||
let first = if negative { -d } else { d };
|
||||
let d2 = val(vals, d2, Kind::Length)?;
|
||||
(if first < 0.0 { d2 } else { -d2 }, first)
|
||||
// An entered distance keeps its side whatever its sign: Direction fixes the sides,
|
||||
// and a sign only turns its own side over. A reach computed from the model (To
|
||||
// Object, Through All) has the sign of where the object is, so the other side
|
||||
// follows it.
|
||||
let second = if extent.second_follows_first || extent.to.is_some() || extent.through_all {
|
||||
if first < 0.0 { d2 } else { -d2 }
|
||||
} else if negative {
|
||||
d2
|
||||
} else {
|
||||
-d2
|
||||
};
|
||||
(second, first)
|
||||
}
|
||||
(None, crate::Direction::Positive) => (0.0, d),
|
||||
(None, crate::Direction::Negative) => (-d, 0.0),
|
||||
@@ -7151,12 +7232,14 @@ pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u
|
||||
PlaneRef::Offset { base, distance } => {
|
||||
PlaneRef::Offset { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), distance: distance.clone() }
|
||||
}
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line } => PlaneRef::AtAngle {
|
||||
PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line, direction_only, pivot } => PlaneRef::AtAngle {
|
||||
base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?),
|
||||
axis_origin: *axis_origin,
|
||||
axis_dir: *axis_dir,
|
||||
angle: angle.clone(),
|
||||
line: line.clone(),
|
||||
direction_only: *direction_only,
|
||||
pivot: pivot.clone(),
|
||||
},
|
||||
PlaneRef::Flipped { base, about_y } => {
|
||||
PlaneRef::Flipped { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), about_y: *about_y }
|
||||
@@ -7956,8 +8039,8 @@ fn eval_feature(
|
||||
FeatureKind::Cone { base, axis, radius, top_radius, height, operation } => {
|
||||
let (radius, top_radius, height) =
|
||||
(val(vals, radius, Kind::Length)?, val(vals, top_radius, Kind::Length)?, val(vals, height, Kind::Length)?);
|
||||
let b = more::cone(point(vals, base)?, axis.0, radius, top_radius, height)?;
|
||||
apply_op(doc, st, f, vec![b], *operation, &[])
|
||||
let tool = more::cone(point(vals, base)?, axis.0, radius, top_radius, height)?;
|
||||
apply_traced(doc, st, f, vec![tool], *operation, &[])
|
||||
}
|
||||
FeatureKind::Combine { target, tools, operation, keep_tools } => {
|
||||
if tools.iter().any(|t| t == target) {
|
||||
@@ -8306,7 +8389,7 @@ fn move_constructions_with(doc: &Document, st: &mut ModelState, moved: &[crate::
|
||||
fn plane_is_fixed(plane: &PlaneRef) -> bool {
|
||||
match plane {
|
||||
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => true,
|
||||
PlaneRef::AtAngle { line: Some(_), .. } => false,
|
||||
PlaneRef::AtAngle { line: Some(_), .. } | PlaneRef::AtAngle { pivot: Some(_), .. } => false,
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_is_fixed(base),
|
||||
_ => false,
|
||||
}
|
||||
@@ -8317,7 +8400,7 @@ fn plane_is_fixed(plane: &PlaneRef) -> bool {
|
||||
fn plane_reads_geometry(plane: &PlaneRef) -> bool {
|
||||
match plane {
|
||||
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } | PlaneRef::Construction { .. } => false,
|
||||
PlaneRef::AtAngle { line: Some(_), .. } => true,
|
||||
PlaneRef::AtAngle { line: Some(_), .. } | PlaneRef::AtAngle { pivot: Some(_), .. } => true,
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_reads_geometry(base),
|
||||
PlaneRef::ThroughPoint { .. }
|
||||
| PlaneRef::Midplane { .. }
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::*;
|
||||
/// intersect) ran its booleans on, bodies searched for the cylinder a tap marking lies on,
|
||||
/// bodies whose faces a tapped hole read for its wall, intersects run to find a pattern's copies
|
||||
/// that cut nothing, and the tools a cut of many tools is made with (one when they are cut in one
|
||||
/// go).
|
||||
/// go), and face surfaces classified for a hole's direction.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(super) struct Counts {
|
||||
pub moved: usize,
|
||||
@@ -36,6 +36,7 @@ pub(super) struct Counts {
|
||||
pub tapped_wall: usize,
|
||||
pub miss_intersects: usize,
|
||||
pub cut_tools: usize,
|
||||
pub surfaces: usize,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -53,6 +54,7 @@ thread_local! {
|
||||
tapped_wall: 0,
|
||||
miss_intersects: 0,
|
||||
cut_tools: 0,
|
||||
surfaces: 0,
|
||||
})
|
||||
};
|
||||
}
|
||||
@@ -1786,3 +1788,51 @@ fn an_added_and_deleted_sketch_entity_keeps_its_fingerprint() {
|
||||
assert_eq!(model.state().sketch_keys.get(&id).copied(), key);
|
||||
assert_eq!((model.last_recomputed, model.last_restored), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hole_skips_the_parts_its_line_cannot_reach() {
|
||||
use solidcraft_geom::Aabb3;
|
||||
let unit = Aabb3 { min: Vec3::ZERO, max: Vec3::new(1.0, 1.0, 1.0) };
|
||||
// Down through the box, from above and from below (the line runs both ways).
|
||||
assert!(super::line_meets_box(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0), &unit));
|
||||
assert!(super::line_meets_box(Vec3::new(0.5, 0.5, -5.0), Vec3::new(0.0, 0.0, -1.0), &unit));
|
||||
// Beside it, parallel to a side: a zero direction component keeps the line out of the slab.
|
||||
assert!(!super::line_meets_box(Vec3::new(2.0, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0), &unit));
|
||||
// Slanted past a corner, and slanted through it.
|
||||
assert!(!super::line_meets_box(Vec3::new(3.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), &unit));
|
||||
assert!(super::line_meets_box(Vec3::new(-1.0, -1.0, 0.5), Vec3::new(1.0, 1.0, 0.0), &unit));
|
||||
// Touching a face counts; an empty box never meets.
|
||||
assert!(super::line_meets_box(Vec3::new(1.0, 0.5, 9.0), Vec3::new(0.0, 0.0, 1.0), &unit));
|
||||
assert!(!super::line_meets_box(Vec3::new(0.5, 0.5, 0.5), Vec3::new(0.0, 0.0, 1.0), &Aabb3::EMPTY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hole_classifies_the_faces_it_reads_not_every_face_of_the_design() {
|
||||
// Forty separate cylinders, three faces each. A hole placed on the top of one drills down,
|
||||
// and finding that out reads the nearest face only: it used to classify every face of every
|
||||
// body first, which in an assembly of hundreds of imported parts took seconds per hole.
|
||||
let mut doc = Document::new("hole direction work");
|
||||
for k in 0..40 {
|
||||
let kind = FeatureKind::Cylinder {
|
||||
base: point_expr(Vec3::new(10.0 * f64::from(k), 0.0, 0.0)),
|
||||
axis: Dir(Vec3::Z),
|
||||
radius: "2".into(),
|
||||
height: "10".into(),
|
||||
operation: Operation::NewBody,
|
||||
references: Vec::new(),
|
||||
};
|
||||
doc.add_feature(kind, None).unwrap();
|
||||
}
|
||||
let mut model = Model::new();
|
||||
model.evaluate(&doc);
|
||||
let st = model.state();
|
||||
assert_eq!(st.bodies.len(), 40);
|
||||
let mut dir = None;
|
||||
let work = counted(|| dir = super::hole_direction_at(&st, Vec3::new(250.5, 0.5, 10.0), &[]));
|
||||
let dir = dir.unwrap();
|
||||
assert!((dir - Vec3::new(0.0, 0.0, -1.0)).len() < 1e-9, "drills down into the top: {dir:?}");
|
||||
assert!(work.surfaces <= 2, "classified {} face surfaces for one hole", work.surfaces);
|
||||
// A point on a side wall drills into that wall.
|
||||
let side = super::hole_direction_at(&st, Vec3::new(252.0, 0.0, 5.0), &[]).unwrap();
|
||||
assert!((side - Vec3::new(-1.0, 0.0, 0.0)).len() < 1e-6, "into the side wall: {side:?}");
|
||||
}
|
||||
@@ -1441,7 +1441,8 @@ const MAX_CONE_SIZE: f64 = 1e7;
|
||||
/// of `top_radius` `height` along `axis` (a negative height goes the other way). A top radius of
|
||||
/// 0 (or below a micrometre) makes a full cone ending in an apex. Built, as the torus is, by
|
||||
/// revolving its half section, a trapezoid (a triangle for a full cone) with an edge on the axis.
|
||||
pub(super) fn cone(base: Vec3, axis: Vec3, radius: f64, top_radius: f64, height: f64) -> Result<Body> {
|
||||
/// Its faces are named `bottom`, `side` and `top` ([`crate::lineage::cone_roles`]).
|
||||
pub(super) fn cone(base: Vec3, axis: Vec3, radius: f64, top_radius: f64, height: f64) -> Result<Traced> {
|
||||
let in_range = |v: f64| v.is_finite() && v.abs() <= MAX_CONE_SIZE;
|
||||
if !(in_range(base.x) && in_range(base.y) && in_range(base.z)) {
|
||||
return Err(DocError::Invalid("the cone's base is out of range".into()));
|
||||
@@ -1475,14 +1476,16 @@ pub(super) fn cone(base: Vec3, axis: Vec3, radius: f64, top_radius: f64, height:
|
||||
(Some(b), true) => b,
|
||||
_ => return Err(DocError::Invalid("the cone could not be built".into())),
|
||||
};
|
||||
// Read off the revolve's own history; moving the body keeps its faces' order.
|
||||
let roles = crate::lineage::cone_roles(&body);
|
||||
if (dir - Vec3::Z).len() < 1e-12 && base.len() == 0.0 {
|
||||
return Ok(body);
|
||||
return Ok(Traced::made(body, roles));
|
||||
}
|
||||
// A rotation taking +Z onto the axis (x and y square to it, right-handed), then the base.
|
||||
let x = Plane::from_normal(base, dir).ok_or_else(|| DocError::Invalid("the cone's axis has no direction".into()))?.x;
|
||||
let y = dir.cross(x);
|
||||
let m = [[x.x, x.y, x.z, 0.0], [y.x, y.y, y.z, 0.0], [dir.x, dir.y, dir.z, 0.0], [base.x, base.y, base.z, 1.0]];
|
||||
Ok(kernel::transform_matrix(&body, m)?)
|
||||
Ok(Traced::made(kernel::transform_matrix(&body, m)?, roles))
|
||||
}
|
||||
|
||||
/// A primitive tool's exact geometry, for [`sheet_primitive_cut`].
|
||||
|
||||
+17
-12
@@ -785,20 +785,24 @@ pub(crate) fn decode(mut v: Value, version: u32, applied: Option<&[String]>) ->
|
||||
return Err(DocError::Invalid("damaged design: timeline folder cannot contain itself".into()));
|
||||
}
|
||||
}
|
||||
// Each folder's chain of parents ends at the top, walked once: a chain stops at a folder
|
||||
// already known to end there. Walking every chain with a search per step took minutes on a
|
||||
// design with 10 000 nested folders.
|
||||
let parents: std::collections::BTreeMap<u64, Option<u64>> = d.timeline_groups.iter().map(|g| (g.id, g.parent)).collect();
|
||||
let mut ends = std::collections::BTreeSet::new();
|
||||
for group in &d.timeline_groups {
|
||||
if let Some(parent) = group.parent {
|
||||
if !group_ids.contains(&parent) {
|
||||
return Err(DocError::Invalid("damaged design: timeline folder has an unknown parent".into()));
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut current = Some(parent);
|
||||
while let Some(id) = current {
|
||||
if !seen.insert(id) {
|
||||
return Err(DocError::Invalid("damaged design: cyclic timeline folders".into()));
|
||||
}
|
||||
current = d.timeline_groups.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent);
|
||||
}
|
||||
if group.parent.is_some_and(|parent| !group_ids.contains(&parent)) {
|
||||
return Err(DocError::Invalid("damaged design: timeline folder has an unknown parent".into()));
|
||||
}
|
||||
let mut chain = std::collections::BTreeSet::new();
|
||||
let mut current = Some(group.id);
|
||||
while let Some(id) = current.filter(|id| !ends.contains(id)) {
|
||||
if !chain.insert(id) {
|
||||
return Err(DocError::Invalid("damaged design: cyclic timeline folders".into()));
|
||||
}
|
||||
current = parents.get(&id).copied().flatten();
|
||||
}
|
||||
ends.extend(chain);
|
||||
}
|
||||
if let Some(id) = crate::non_contiguous_timeline_group(&d.features, &d.timeline_groups) {
|
||||
return Err(DocError::Invalid(format!("damaged design: timeline folder {id} is not contiguous")));
|
||||
@@ -1914,6 +1918,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: Some("0 deg".into()),
|
||||
corner: Default::default(),
|
||||
to: Some(crate::FacePick(solidcore_record::Vec3::new(0.0, 0.0, 10.0))),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! A canvas can be locked (#12310): `locked: true` on the canvas keeps its place, size, angle and
|
||||
//! flip, and keeps it from being deleted, until it is unlocked. Older designs need no
|
||||
//! transformation: without the field a canvas is unlocked, as before. The last release warns about
|
||||
//! the newer format number and opens the design with its canvases unlocked.
|
||||
@@ -0,0 +1,91 @@
|
||||
//! CPU render jobs can save optional `options.output` presentation: tone map, finishing,
|
||||
//! backdrop and raw linear EXR retention. Older designs omit it and retain the exact previous
|
||||
//! f64 PNG output; exposure remains owned by RenderSetup. Readers missing these changes open
|
||||
//! the newer design with a warning and preserve saved values they cannot read.
|
||||
//! CPU jobs also save optional `options.lens` using the shared physical thin-lens
|
||||
//! aperture radius and axial focus distance. Positive aperture requires perspective
|
||||
//! plus explicit progressive camera sampling; absent/zero aperture keeps old pixels.
|
||||
//! CPU raytrace jobs also retain default-false `transparent_background` beside options.
|
||||
//! It exports straight-alpha primary geometry coverage; absent fields keep opaque PNGs.
|
||||
//! CPU jobs also save opt-in `options.denoise`; omission/false preserves the prior
|
||||
//! raw PNG calculation. Every complete published pass is filtered without changing
|
||||
//! raw film or the final unfiltered EXR. Older files need no rewrite for this flag.
|
||||
//! CPU jobs also preserve optional `options.path: {max_depth: 1..16}` for explicit
|
||||
//! progressive diffuse/specular transport and certified Glass boundaries. The depth
|
||||
//! counts shaded surfaces, optical boundaries and active scattering events. Traced shadows are required;
|
||||
//! selected reflection/anisotropy overrides and unsupported closed-Glass
|
||||
//! shadow connections refuse with authored intent retained. Omission keeps the legacy producer.
|
||||
//!
|
||||
//! CPU raytrace jobs save optional `options.aging` using the existing ordered
|
||||
//! SavedAgingStack schema and stable definition/feature/component/occurrence targets.
|
||||
//! Empty/absent stacks preserve prior saved JSON, CPU pixel arithmetic and work.
|
||||
//! Check and Start resolve stable targets against the captured scene; stale/hidden
|
||||
//! targets are refused rather than made global. Captured indices/names remain
|
||||
//! runtime-only. Aging changes the opaque BRDF before lighting and denoising guides;
|
||||
//! it does not change geometry, emission, physical materials or mass. Certified
|
||||
//! glass targets and passive stages remain excluded; independently authored anisotropic axes
|
||||
//! cannot be replaced by scalar aging roughness and are refused explicitly.
|
||||
//!
|
||||
//! Saves up to eight hard GPU directional sources alongside the existing optional
|
||||
//! finite Sun (eight combined). Older designs omit the new list and retain their
|
||||
//! exact implicit studio or finite-Sun lighting. Readers missing the new list warn
|
||||
//! about the newer design and preserve these unread sources.
|
||||
//! Also saves up to eight GPU point/spot sources with exact world-mm positions,
|
||||
//! reference/minimum distances and optional world-axis/radian half cones. Missing
|
||||
//! punctual lists stay empty. CPU cone intent retains its wider f64 domain; GPU
|
||||
//! cone feathers below the documented precision bound refuse without rewriting.
|
||||
//!
|
||||
//! CPU jobs may also consume the existing portable saved `surfaces` bindings for
|
||||
//! opaque built-in base color, roughness, metallic and normal maps. No new map
|
||||
//! schema is added; raster and unsupported CPU optical combinations refuse the
|
||||
//! authored bindings instead of dropping them. Old files without maps keep the
|
||||
//! old CPU allocation/work/pixel path.
|
||||
//! CPU jobs also save optional `options.adaptive` using the existing independent-pilot
|
||||
//! policy. Explicit progressive production sampling is required; the unchanged CPU
|
||||
//! profile budgets pilots plus the production cap. Exact per-pixel counts and pilot
|
||||
//! statistics stay runtime-only; final SamplingReport and PreviewInfo.adaptive reuse
|
||||
//! the existing metadata contract without changing linear-master schema/channels.
|
||||
|
||||
//! CPU `options.path` may consume the existing saved ClosedMesh optical boundary
|
||||
//! after exact f64 edge, vertex-link, embedding/contact, outward and conservative
|
||||
//! nested-parent certification. Runtime-only ClosedMesh and thin-shadow lowering
|
||||
//! preserve stable authored optics. No new saved field or geometry repair is added.
|
||||
//! Absent-path sheet/box transport and default serialized bytes remain unchanged.
|
||||
//! Closed-shadow connections, Glass combined with external volume and selected
|
||||
//! reflection/anisotropy combinations refuse explicitly with authored values retained.
|
||||
//! Perspective CPU Path captures classify each physical eye/pupil cooperatively
|
||||
//! against the certified boundaries and initialize the nested Beer medium stack.
|
||||
//! Exact origin/near-clip boundary contacts refuse without changing saved cameras
|
||||
//! or optics. This runtime-only extension adds no serialized field.
|
||||
//! Existing saved OpticalMaterial.subsurface may also lower to optional captured
|
||||
//! CPU dielectric subsurface parameters with explicit progressive Path. Selected
|
||||
//! certified closed media use scalar free flight, HG directions and separate Beer
|
||||
//! absorption, including physical eye/pupil starts and nested current media. No
|
||||
//! refracting-boundary next-event approximation is added. Active scattering and
|
||||
//! surface denoising refuse together; unsupported thin/legacy routes retain intent.
|
||||
//! Some(rate0) remains serialized but adds no collision work/RNG or pixel change.
|
||||
//! CPU jobs may also preserve optional options.volume using the same bounded
|
||||
//! HomogeneousVolume world-box/extinction/RGB albedo/HG contract as GPU Atmosphere.
|
||||
//! Positive extinction requires explicit progressive Path and disables no existing
|
||||
//! option implicitly: Glass/SSS and surface denoising refuse with intent retained.
|
||||
//! Absent/zero volume keeps the original transport work/RNG/heap owner count/pixels.
|
||||
//! Inline intent's actual fixed retained-request size is prepaid even when absent;
|
||||
//! regrade owns its separate header reservation until its last status handle drops.
|
||||
//! Physical eye/pupil prefixes and the orthographic signed line/box union do not
|
||||
//! alter saved camera/framing/model bounds or its model near interval. Existing
|
||||
//! ray-distance/profile/task/frame/codec/host caps remain unchanged.
|
||||
|
||||
//! CPU jobs also retain optional `sun` and `sky` intent. `sun` reuses the shared
|
||||
//! finite-cap direction/angular-radius/radiance domain; `sky` reuses the portable
|
||||
//! gradient/rotation/intensity schema. Both require explicit CPU Path transport.
|
||||
//! Omitted fields preserve old designs and the absent producer allocation/work/RNG
|
||||
//! path. Constant, Sky and HDR sources are exclusive; finite Sun is additive.
|
||||
//! No generated sky image or runtime resource is serialized.
|
||||
//!
|
||||
//! CPU and GPU jobs also save `coats`, up to the existing 64 runtime coat target
|
||||
//! bound, with stable definition/feature/component/occurrence identities and exact
|
||||
//! weight, roughness and dielectric IOR. Empty/absent lists keep prior JSON and
|
||||
//! capture behavior. Coats require opaque targets; even a zero-weight authored coat
|
||||
//! cannot share a target with Glass. Capture resolves targets without changing
|
||||
//! appearances, engineering materials or geometry. Unsupported CPU selected
|
||||
//! reflection/anisotropy overrides refuse instead of dropping the coat.
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Glass assignments can save optional `model` roughness, Abbe dispersion and a
|
||||
//! coherent dielectric film (IOR and thickness in nanometres). Omission retains
|
||||
//! the preceding smooth, nondispersive interface and incoherent sheet response.
|
||||
//! CPU and GPU jobs can save optional `caustics` photon count, gather radius in
|
||||
//! millimetres, light-path depth and seed. Omission creates no photon map and
|
||||
//! retains preceding sampling. Older releases ask for an update rather than
|
||||
//! discard these authored material and light-transport choices. No migration of
|
||||
//! existing designs, geometry, engineering material or saved camera is required.
|
||||
@@ -0,0 +1,5 @@
|
||||
//! An at-angle construction plane may save `direction_only` and an optional `pivot` point: the
|
||||
//! plane turns about the line through the pivot (or the base origin) using only the axis
|
||||
//! direction projected onto the base. An older design has neither and keeps turning about the
|
||||
//! axis as a full line. The last release refuses a design that has this change (the newer
|
||||
//! format number) instead of opening it without the option.
|
||||
@@ -0,0 +1,4 @@
|
||||
//! A point cloud remembers the file it was read from (#8818): `source`, its path, which
|
||||
//! `pointcloud.reload` reads again, and `max_points`, the limit it reads it under. Older designs
|
||||
//! need no transformation: their clouds have no source and cannot be reloaded, only inserted again. The last release refuses a design saved
|
||||
//! with this (the newer format number) instead of opening its clouds without their source.
|
||||
@@ -0,0 +1,5 @@
|
||||
//! A sketch constraint can hold a point at a share of a curve's length (`"type": "point_along"`,
|
||||
//! with the point `p`, the curve `c` and the share `at` from 0 to 1), as Divide Curve places its
|
||||
//! points (#8969). Older designs need no transformation: they have no such constraint. The last
|
||||
//! release refuses a design that has one and asks for an update, instead of failing to read its
|
||||
//! sketch.
|
||||
@@ -0,0 +1,61 @@
|
||||
//! In a two-sided extrude (`distance2`) with entered distances, Direction fixes the sides and the
|
||||
//! sign of a distance only turns its own side over; `distance2` no longer follows the first
|
||||
//! side across the sketch plane. Older builds sent `distance2` to the other side of a negative
|
||||
//! first distance, so this step marks every saved two-sided extrude with entered distances
|
||||
//! `second_follows_first`, which keeps that reading. The distances themselves are left as they
|
||||
//! were, so an expression keeps the old sides whatever it evaluates to and a feature's named
|
||||
//! inputs keep their values for the expressions that use them. An extent that reaches to an
|
||||
//! object or through all already lets the second side follow the first, and a symmetric one has
|
||||
//! no second side. The last release asks for an update instead of opening a design that carries
|
||||
//! this change.
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn step(v: &mut Value) -> crate::Result<()> {
|
||||
let Some(Value::Array(features)) = v.get_mut("features") else {
|
||||
return Ok(());
|
||||
};
|
||||
for feature in features {
|
||||
if !matches!(feature.get("type").and_then(Value::as_str), Some("extrude" | "surface_extrude")) {
|
||||
continue;
|
||||
}
|
||||
let Some(extent) = feature.get_mut("extent").and_then(Value::as_object_mut) else { continue };
|
||||
let plain = extent.get("distance2").is_some_and(|d| !d.is_null())
|
||||
&& extent.get("to").is_none_or(Value::is_null)
|
||||
&& !extent.get("through_all").and_then(Value::as_bool).unwrap_or(false)
|
||||
&& extent.get("direction").and_then(Value::as_str) != Some("symmetric");
|
||||
if plain {
|
||||
extent.insert("second_follows_first".into(), Value::Bool(true));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn saved_two_sided_extrudes_keep_their_sides_and_distances() {
|
||||
let mut v = json!({"features": [
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "direction": "negative", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-0 mm", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-width", "distance2": "10 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "through_all": true, "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "to": [0.0, 0.0, 1.0], "distance2": "5 mm"}},
|
||||
{"type": "sketch"}
|
||||
]});
|
||||
let before = v.clone();
|
||||
super::step(&mut v).unwrap();
|
||||
let features = v["features"].as_array().unwrap();
|
||||
let marked: Vec<bool> = features.iter().map(|f| f["extent"]["second_follows_first"] == json!(true)).collect();
|
||||
assert_eq!(marked, [true, true, true, true, false, false, false, false]);
|
||||
for (f, b) in features.iter().zip(before["features"].as_array().unwrap()) {
|
||||
assert_eq!((&f["extent"]["distance"], &f["extent"]["direction"]), (&b["extent"]["distance"], &b["extent"]["direction"]));
|
||||
}
|
||||
let mut empty = json!({"name": "Untitled"});
|
||||
super::step(&mut empty).unwrap();
|
||||
assert_eq!(empty, json!({"name": "Untitled"}));
|
||||
}
|
||||
}
|
||||
@@ -463,6 +463,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -95,9 +95,17 @@ fn with_unit(rhs: &str, units: &str) -> String {
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// `name = expression` typed again exactly as an existing user parameter was defined (each
|
||||
/// of several holes made one at a time, or one command per hole, given `ScrewDepth = 5`):
|
||||
/// the same value in the same unit, so it uses that parameter instead of being refused.
|
||||
fn defines_again(&self, d: &Pending) -> bool {
|
||||
self.param(&d.name).is_some_and(|p| !p.model && p.expr.trim() == d.expression.trim() && d.unit.as_ref().is_none_or(|u| *u == p.unit))
|
||||
}
|
||||
|
||||
/// Store every value typed as `name = expression`: the user parameter `name` with that
|
||||
/// expression (a bare number read as the value would read it, in that unit), and `name`
|
||||
/// where the text was. A name that is taken or reserved is refused, as is a definition where
|
||||
/// where the text was. A name that is taken or reserved is refused (unless it is a user
|
||||
/// parameter defined exactly so, which the text then names), as is a definition where
|
||||
/// none can be made: in a parameter's own expression or a configuration cell. All or nothing:
|
||||
/// on an error the design is unchanged.
|
||||
pub fn define_inline(&mut self) -> Result<Vec<Defined>> {
|
||||
@@ -182,7 +190,7 @@ impl Document {
|
||||
if let Some(problem) = Self::param_name_problem(&d.name) {
|
||||
return Err(DocError::Invalid(problem));
|
||||
}
|
||||
if self.name_taken(&d.name) {
|
||||
if self.name_taken(&d.name) && !self.defines_again(d) {
|
||||
return Err(DocError::Invalid(format!(
|
||||
"there is already a parameter `{}`: type `{}` to use it, or change it in Parameters",
|
||||
d.name, d.name
|
||||
@@ -191,6 +199,10 @@ impl Document {
|
||||
}
|
||||
let mut out = Vec::with_capacity(found.defs.len());
|
||||
for d in found.defs {
|
||||
// Typed again as it was defined, the text just names the parameter already there.
|
||||
if self.defines_again(&d) {
|
||||
continue;
|
||||
}
|
||||
// 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.
|
||||
|
||||
@@ -49,6 +49,7 @@ pub mod motion;
|
||||
mod name_lookup;
|
||||
mod names;
|
||||
pub mod naming;
|
||||
mod occurrence_tree;
|
||||
mod params;
|
||||
pub mod persistent_name;
|
||||
pub mod physical_material;
|
||||
@@ -73,6 +74,7 @@ pub use print_face::PrintFace;
|
||||
pub mod project;
|
||||
mod project3d;
|
||||
pub mod render_aging;
|
||||
pub mod render_coat;
|
||||
pub mod render_job;
|
||||
pub mod render_optics;
|
||||
pub mod render_resources;
|
||||
@@ -100,7 +102,7 @@ pub use eval::{
|
||||
pub use eval::{EvalCache, KeptResults};
|
||||
pub use expr::Expr;
|
||||
pub use names::{BodyName, FeatureId, FeatureName, SketchId, copy_name};
|
||||
pub use params::{ParamRow, ParamUser, cycles};
|
||||
pub use params::{ParamRow, ParamUser, cycles, name_words_match};
|
||||
pub use points::{Dir, FacePick, Position, plain};
|
||||
pub use solidcraft_kernel as kernel;
|
||||
pub use solidcraft_sketch as sketch;
|
||||
|
||||
@@ -429,6 +429,24 @@ pub(crate) fn cylinder_tool(body: Body) -> Traced {
|
||||
Traced::made(body, roles)
|
||||
}
|
||||
|
||||
/// The roles of a cone primitive's faces, from the body revolved from its half section (base
|
||||
/// side first, then the sloped side, then the top side of a cut-off cone; the side on the axis
|
||||
/// makes no face): `bottom`, `side` and `top`, as a cylinder's are (#7476). `None` when the body
|
||||
/// has no history of its own.
|
||||
pub(crate) fn cone_roles(body: &Body) -> Option<Vec<Vec<String>>> {
|
||||
body.history().filter(|h| h.operands == 0).map(|h| {
|
||||
h.faces
|
||||
.iter()
|
||||
.map(|f| match f.origins.as_slice() {
|
||||
[FaceOrigin::Profile { segment: 0 }] => vec!["bottom".to_string()],
|
||||
[FaceOrigin::Profile { segment: 1 }] => vec!["side".to_string()],
|
||||
[FaceOrigin::Profile { segment: 2 }] => vec!["top".to_string()],
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// A tool a feature builds without a sketch (a boss's post, a rib, a lip's band), its faces named
|
||||
/// by the part it makes: `<part>:top` (its end cap), `<part>:base` (its start cap) and
|
||||
/// `<part>:side:<k>` (swept from segment `k` of its profile), as its construction records them.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! The occurrence tree of a document: each component's child occurrences, gathered in one pass,
|
||||
//! and the walk of every placement from the root over them. Walking it costs the placements,
|
||||
//! where scanning every occurrence for each component visited cost placements times occurrences.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{Document, IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, mat_mul};
|
||||
|
||||
/// Each component's child occurrences, in document order, as a document held them when made.
|
||||
pub(crate) struct OccurrenceTree<'a> {
|
||||
children: HashMap<u64, Vec<&'a Occurrence>>,
|
||||
}
|
||||
|
||||
impl<'a> OccurrenceTree<'a> {
|
||||
pub(crate) fn new(doc: &'a Document) -> Self {
|
||||
let mut children: HashMap<u64, Vec<&Occurrence>> = HashMap::new();
|
||||
for o in &doc.occurrences {
|
||||
children.entry(o.parent).or_default().push(o);
|
||||
}
|
||||
OccurrenceTree { children }
|
||||
}
|
||||
|
||||
/// The occurrences placed in `component`, in document order.
|
||||
pub(crate) fn children(&self, component: u64) -> &[&'a Occurrence] {
|
||||
self.children.get(&component).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Every placement from the root: (component, occurrence path ids, world transform), with
|
||||
/// each occurrence placed in its parent by `transform`. Depth first, children in document
|
||||
/// order. A branch stops past [`MAX_PLACEMENT_DEPTH`] levels, the walk past [`MAX_PLACEMENTS`]
|
||||
/// placements.
|
||||
pub(crate) fn placements_with(&self, transform: impl Fn(&Occurrence) -> Mat) -> Vec<(u64, Vec<u64>, Mat)> {
|
||||
let mut out = vec![(0, Vec::new(), IDENTITY)];
|
||||
let mut stack: Vec<(u64, Vec<u64>, Mat)> = vec![(0, Vec::new(), IDENTITY)];
|
||||
while let Some((comp, path, m)) = stack.pop() {
|
||||
if out.len() > MAX_PLACEMENTS {
|
||||
break;
|
||||
}
|
||||
// Only this branch stops past the depth limit; the others are still walked.
|
||||
if path.len() > MAX_PLACEMENT_DEPTH {
|
||||
continue;
|
||||
}
|
||||
for o in self.children(comp) {
|
||||
let mut p = path.clone();
|
||||
p.push(o.id);
|
||||
let w = mat_mul(&m, &transform(o));
|
||||
out.push((o.component, p.clone(), w));
|
||||
stack.push((o.component, p, w));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "occurrence_tree_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,253 @@
|
||||
use solidcore_record::Vec3;
|
||||
|
||||
use super::OccurrenceTree;
|
||||
use crate::*;
|
||||
|
||||
/// `placements` as it walked before the tree: a scan of every occurrence for each component
|
||||
/// visited. The tree must give exactly this, in this order, for every document.
|
||||
fn scanning_placements(doc: &Document) -> Vec<(u64, Vec<u64>, Mat)> {
|
||||
let mut out = vec![(0, Vec::new(), IDENTITY)];
|
||||
let mut stack: Vec<(u64, Vec<u64>, Mat)> = vec![(0, Vec::new(), IDENTITY)];
|
||||
while let Some((comp, path, m)) = stack.pop() {
|
||||
if out.len() > MAX_PLACEMENTS {
|
||||
break;
|
||||
}
|
||||
if path.len() > MAX_PLACEMENT_DEPTH {
|
||||
continue;
|
||||
}
|
||||
for o in doc.occurrences.iter().filter(|o| o.parent == comp) {
|
||||
let mut p = path.clone();
|
||||
p.push(o.id);
|
||||
let w = mat_mul(&m, &o.transform);
|
||||
out.push((o.component, p.clone(), w));
|
||||
stack.push((o.component, p, w));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `inside_component`'s walk as it was before the tree: is `parent` placed anywhere below `component`?
|
||||
fn scanning_inside(doc: &Document, parent: u64, component: u64) -> bool {
|
||||
if doc.component_within(parent, component) {
|
||||
return true;
|
||||
}
|
||||
let mut stack = vec![component];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
while let Some(c) = stack.pop() {
|
||||
if !seen.insert(c) || seen.len() > MAX_PLACEMENTS {
|
||||
continue;
|
||||
}
|
||||
for o in doc.occurrences.iter().filter(|o| o.parent == c) {
|
||||
if o.component == parent {
|
||||
return true;
|
||||
}
|
||||
stack.push(o.component);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Every (parent, component) pair over the ids a document names, and one id it doesn't.
|
||||
fn same_inside(doc: &Document) -> std::result::Result<(), String> {
|
||||
let mut ids: Vec<u64> = doc.occurrences.iter().flat_map(|o| [o.parent, o.component]).chain([0, 999]).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
for &parent in &ids {
|
||||
for &component in &ids {
|
||||
if doc.inside_component(parent, component) != scanning_inside(doc, parent, component) {
|
||||
return Err(format!("inside_component({parent}, {component})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An occurrence of `component` in `parent`, moved by its id so every path's transform differs.
|
||||
fn occurrence(id: u64, component: u64, parent: u64) -> Occurrence {
|
||||
let t = Vec3::new(id as f64, (id % 7) as f64, 0.5 * (id % 3) as f64);
|
||||
Occurrence {
|
||||
id,
|
||||
component,
|
||||
parent,
|
||||
name: format!("C{component}:{id}"),
|
||||
transform: rigid(t, Vec3::ZERO, Vec3::Z, 0.01 * id as f64),
|
||||
grounded: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn with(occurrences: Vec<Occurrence>) -> Document {
|
||||
let mut doc = Document::new("tree");
|
||||
doc.occurrences = occurrences;
|
||||
doc
|
||||
}
|
||||
|
||||
/// Component `k` placed once in component `k - 1`, `depth` levels below the root.
|
||||
fn chain(depth: u64) -> Document {
|
||||
with((1..=depth).map(|k| occurrence(k, k, k - 1)).collect())
|
||||
}
|
||||
|
||||
/// The documents whose walks must not move: the walk's boundaries and the hostile shapes a file
|
||||
/// can hold.
|
||||
fn shapes() -> Vec<(&'static str, Document)> {
|
||||
// 2 under the root, each holding 400 of component 3, each holding 150 of component 4: past
|
||||
// MAX_PLACEMENTS, so the walk stops part way.
|
||||
let mut wide = vec![occurrence(1, 1, 0), occurrence(2, 1, 0)];
|
||||
wide.extend((0..400).map(|i| occurrence(10 + i, 3, 1)));
|
||||
wide.extend((0..150).map(|i| occurrence(1000 + i, 4, 3)));
|
||||
vec![
|
||||
("empty", with(Vec::new())),
|
||||
("one level", with(vec![occurrence(1, 1, 0), occurrence(2, 2, 0), occurrence(3, 1, 0)])),
|
||||
("depth 63", chain(63)),
|
||||
("depth 64", chain(64)),
|
||||
("depth 65", chain(65)),
|
||||
("depth 66", chain(66)),
|
||||
("a component twice under one parent", with(vec![occurrence(1, 1, 0), occurrence(2, 2, 1), occurrence(3, 2, 1), occurrence(4, 3, 2)])),
|
||||
("an occurrence whose parent is missing", with(vec![occurrence(1, 1, 0), occurrence(2, 2, 99), occurrence(3, 3, 2)])),
|
||||
("a cycle", with(vec![occurrence(1, 1, 0), occurrence(2, 2, 1), occurrence(3, 1, 2)])),
|
||||
("a component inside itself", with(vec![occurrence(1, 1, 0), occurrence(2, 1, 1)])),
|
||||
("duplicated occurrence ids", with(vec![occurrence(1, 1, 0), occurrence(1, 2, 0), occurrence(2, 3, 1), occurrence(2, 3, 2)])),
|
||||
("children listed out of order", with(vec![occurrence(5, 2, 1), occurrence(1, 1, 0), occurrence(4, 3, 2), occurrence(2, 2, 1)])),
|
||||
("past MAX_PLACEMENTS", with(wide)),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_is_the_scanning_walk_for_every_shape() {
|
||||
for (name, doc) in shapes() {
|
||||
let walked = doc.placements();
|
||||
assert_eq!(walked, scanning_placements(&doc), "{name}");
|
||||
assert_eq!(OccurrenceTree::new(&doc).placements_with(|o| o.transform), walked, "{name}");
|
||||
if doc.occurrences.len() < 100 {
|
||||
assert_eq!(same_inside(&doc), Ok(()), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_stops_at_its_caps_as_before() {
|
||||
let deepest = |doc: &Document| doc.placements().iter().map(|(_, path, _)| path.len()).max();
|
||||
// A branch is walked to MAX_PLACEMENT_DEPTH levels and one past it (today's 65-id path), no further.
|
||||
assert_eq!(deepest(&chain(64)), Some(64));
|
||||
assert_eq!(deepest(&chain(66)), Some(MAX_PLACEMENT_DEPTH + 1));
|
||||
let (_, wide) = shapes().pop().unwrap();
|
||||
let n = wide.placements().len();
|
||||
assert!(n > MAX_PLACEMENTS && n <= MAX_PLACEMENTS + 400, "stops once past the cap: {n}");
|
||||
// A cycle ends at the depth cap, not in a loop.
|
||||
let (_, cycle) = shapes().into_iter().find(|(name, _)| *name == "a cycle").unwrap();
|
||||
assert_eq!(deepest(&cycle), Some(MAX_PLACEMENT_DEPTH + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn children_are_listed_in_document_order() {
|
||||
let doc = with(vec![occurrence(5, 2, 1), occurrence(1, 1, 0), occurrence(4, 3, 1), occurrence(2, 2, 1), occurrence(3, 9, 7)]);
|
||||
let tree = OccurrenceTree::new(&doc);
|
||||
let ids = |c: u64| tree.children(c).iter().map(|o| o.id).collect::<Vec<_>>();
|
||||
assert_eq!(ids(1), [5, 4, 2]);
|
||||
assert_eq!(ids(0), [1]);
|
||||
assert_eq!(ids(7), [3], "an occurrence under a missing parent is still its child");
|
||||
assert!(ids(2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_uses_the_transform_it_is_given() {
|
||||
let doc = with(vec![occurrence(1, 1, 0), occurrence(2, 2, 1)]);
|
||||
let moved = rigid(Vec3::new(0.0, 0.0, 9.0), Vec3::ZERO, Vec3::Z, 0.0);
|
||||
let walked = OccurrenceTree::new(&doc).placements_with(|o| if o.id == 1 { moved } else { o.transform });
|
||||
let child = &doc.occurrences[1].transform;
|
||||
assert_eq!(walked[1], (1, vec![1], moved));
|
||||
assert_eq!(walked[2], (2, vec![1, 2], mat_mul(&moved, child)));
|
||||
}
|
||||
|
||||
/// splitmix64, so each run makes the same documents.
|
||||
fn next(state: &mut u64) -> u64 {
|
||||
*state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut z = *state;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_documents_walk_as_before() {
|
||||
// Few component ids and parents drawn from them, so repeats, missing parents, cycles and
|
||||
// duplicated ids all come up.
|
||||
let mut state = 4032;
|
||||
for round in 0..300 {
|
||||
let n = next(&mut state) % 40;
|
||||
let components = 1 + next(&mut state) % 12;
|
||||
let occurrences = (0..n)
|
||||
.map(|i| {
|
||||
let id = if next(&mut state).is_multiple_of(9) { i / 2 } else { i + 1 };
|
||||
let component = 1 + next(&mut state) % components;
|
||||
let parent = next(&mut state) % (components + 2);
|
||||
occurrence(id, component, parent)
|
||||
})
|
||||
.collect();
|
||||
let doc = with(occurrences);
|
||||
assert_eq!(doc.placements(), scanning_placements(&doc), "round {round}");
|
||||
assert_eq!(same_inside(&doc), Ok(()), "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A generated assembly of `top` modules, each holding `parts` parts, each part holding `pins`
|
||||
/// pins: the shape of a large imported board.
|
||||
fn assembly(top: u64, parts: u64, pins: u64) -> Document {
|
||||
let mut occurrences = Vec::new();
|
||||
let mut id = 0;
|
||||
let mut add = |component: u64, parent: u64, n: u64| {
|
||||
for _ in 0..n {
|
||||
id += 1;
|
||||
occurrences.push(occurrence(id, component, parent));
|
||||
}
|
||||
};
|
||||
add(1, 0, top);
|
||||
for part in 0..parts {
|
||||
add(10 + part, 1, 1);
|
||||
add(5, 10 + part, pins);
|
||||
}
|
||||
with(occurrences)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual optimized walk microbenchmark; no timing assertion"]
|
||||
fn benchmark_placements_walk() {
|
||||
// About 10,000 and 97,500 placements, under MAX_PLACEMENTS.
|
||||
for (top, parts, pins) in [(10, 100, 9), (39, 250, 9)] {
|
||||
let doc = assembly(top, parts, pins);
|
||||
let time = |walk: &dyn Fn() -> Vec<(u64, Vec<u64>, Mat)>| {
|
||||
let start = std::time::Instant::now();
|
||||
let walked = walk();
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1000.;
|
||||
std::hint::black_box(walked);
|
||||
elapsed
|
||||
};
|
||||
let median = |mut ms: Vec<f64>| {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
};
|
||||
let walked = doc.placements();
|
||||
assert_eq!(walked, scanning_placements(&doc));
|
||||
let (scan, tree) = (|| scanning_placements(&doc), || doc.placements());
|
||||
// Each order in turn, so neither walk always runs on a cache the other warmed.
|
||||
for scanning_first in [true, false] {
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
for _ in 0..9 {
|
||||
if scanning_first {
|
||||
old.push(time(&scan));
|
||||
new.push(time(&tree));
|
||||
} else {
|
||||
new.push(time(&tree));
|
||||
old.push(time(&scan));
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"{} occurrences, {} placements, {} first: scanning={:.3}ms tree={:.3}ms (median of 9, tree includes building it)",
|
||||
doc.occurrences.len(),
|
||||
walked.len(),
|
||||
if scanning_first { "scanning" } else { "tree" },
|
||||
median(old),
|
||||
median(new)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+144
-11
@@ -371,6 +371,14 @@ impl Document {
|
||||
users.entry(x.as_str()).or_default().push(k.clone());
|
||||
}
|
||||
}
|
||||
// A feature that reads a parameter itself (a sketch point at `a`) is one of its users
|
||||
// too, named as `parameters.graph` names it (#12293).
|
||||
let reads: Vec<(String, BTreeSet<String>)> = self.features.iter().map(|f| (format!("Feature:{}", f.name), self.feature_reads(f))).collect();
|
||||
for (feature, names) in &reads {
|
||||
for n in names {
|
||||
users.entry(n.as_str()).or_default().push(feature.clone());
|
||||
}
|
||||
}
|
||||
let used_by = |n: &str| -> Vec<String> { users.get(n).cloned().unwrap_or_default() };
|
||||
let value = |n: &str, k: Kind| {
|
||||
vals.get(n).and_then(|v| v.to_kind(k).ok()).map(|x| if k == Kind::Angle { x.to_degrees() } else { x }).map(expr::round_reported)
|
||||
@@ -1036,23 +1044,34 @@ impl Document {
|
||||
let mut names: BTreeSet<String> = f.param_names.iter().filter(|n| !n.is_empty()).cloned().collect();
|
||||
if let FeatureKind::Sketch { sketch, .. } = &f.kind {
|
||||
names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));
|
||||
names.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values()).flat_map(|e| expr::references(e)));
|
||||
names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));
|
||||
names.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref()).flat_map(expr::references));
|
||||
names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e)));
|
||||
}
|
||||
// Sheet metal and plastic features rebuild when their rules' parameters change (#4420).
|
||||
if f.kind.is_sheet() {
|
||||
names.extend(self.sheet.rules.iter().flat_map(|r| r.fields()).flat_map(|(f, e, _)| rule_references(f, e)));
|
||||
}
|
||||
if f.kind.is_plastic() {
|
||||
names.extend(self.plastic.rules.iter().flat_map(|r| r.fields()).flat_map(|(f, e, _)| rule_references(f, e)));
|
||||
}
|
||||
names.extend(self.feature_reads(f));
|
||||
out.extend(names.into_iter().map(|n| (format!("Feature:{}", f.name), n)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The parameters a feature reads through expressions it holds itself, not through a named
|
||||
/// input or dimension of its own: a sketch's point coordinates, texts, equations and pattern
|
||||
/// expressions, and the rules a sheet metal or plastic feature is built with.
|
||||
fn feature_reads(&self, f: &crate::Feature) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
if let FeatureKind::Sketch { sketch, .. } = &f.kind {
|
||||
names.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values()).flat_map(|e| expr::references(e)));
|
||||
names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));
|
||||
names.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref()).flat_map(expr::references));
|
||||
names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e)));
|
||||
}
|
||||
// Sheet metal and plastic features rebuild when their rules' parameters change (#4420).
|
||||
if f.kind.is_sheet() {
|
||||
names.extend(self.sheet.rules.iter().flat_map(|r| r.fields()).flat_map(|(f, e, _)| rule_references(f, e)));
|
||||
}
|
||||
if f.kind.is_plastic() {
|
||||
names.extend(self.plastic.rules.iter().flat_map(|r| r.fields()).flat_map(|(f, e, _)| rule_references(f, e)));
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Features whose result depends on a parameter (directly or through other parameters).
|
||||
pub fn features_using_param(&self, name: &str) -> Vec<u64> {
|
||||
let defs = self.param_defs();
|
||||
@@ -1131,6 +1150,76 @@ fn csv_fields(record: &str) -> Result<Vec<String>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `query` spells the starts of some words of `name`, in order, ignoring case: for
|
||||
/// `tooth_outward_flange_diameter`, `toodia`, `toofla`, `outdia` and `toofladia` all match
|
||||
/// (#11978). Words may be skipped but not reordered. Underscores, hyphens, spaces and other
|
||||
/// separators split `name` into words, and so do camelCase and letter-digit boundaries.
|
||||
/// Underscores, hyphens and spaces in `query` are ignored. A query with any other symbol (an
|
||||
/// expression such as `width *`) or with no letters or digits never matches here. This only adds
|
||||
/// to a plain substring search: callers keep that one too.
|
||||
pub fn name_words_match(name: &str, query: &str) -> bool {
|
||||
if query.chars().any(|c| !(c.is_alphanumeric() || matches!(c, '_' | '-' | ' '))) {
|
||||
return false;
|
||||
}
|
||||
let query: Vec<char> = query.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect();
|
||||
let words = name_words(name);
|
||||
// Every query character must come from some word, so a longer query can never match;
|
||||
// this also bounds the work below by the name's length.
|
||||
if query.is_empty() || query.len() > words.iter().map(Vec::len).sum::<usize>() {
|
||||
return false;
|
||||
}
|
||||
// `reached[i]`: the first `i` query characters are spelled by word starts seen so far.
|
||||
let mut reached = vec![false; query.len() + 1];
|
||||
if let Some(first) = reached.first_mut() {
|
||||
*first = true;
|
||||
}
|
||||
for word in &words {
|
||||
// From the highest start down, so each word extends a match at most once.
|
||||
for start in (0..query.len()).rev() {
|
||||
if !reached.get(start).copied().unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
let rest = query.get(start..).unwrap_or_default();
|
||||
for (k, _) in word.iter().zip(rest).take_while(|(a, b)| a == b).enumerate() {
|
||||
if let Some(r) = reached.get_mut(start + k + 1) {
|
||||
*r = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if reached.last().copied().unwrap_or(false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The words of a parameter name, in lower case: see [`name_words_match`].
|
||||
fn name_words(name: &str) -> Vec<Vec<char>> {
|
||||
let mut words = Vec::new();
|
||||
let mut word: Vec<char> = Vec::new();
|
||||
let mut previous: Option<char> = None;
|
||||
for c in name.chars() {
|
||||
let split = match previous {
|
||||
_ if !c.is_alphanumeric() => true,
|
||||
Some(p) => (p.is_lowercase() && c.is_uppercase()) || p.is_numeric() != c.is_numeric(),
|
||||
None => false,
|
||||
};
|
||||
if split && !word.is_empty() {
|
||||
words.push(std::mem::take(&mut word));
|
||||
}
|
||||
if c.is_alphanumeric() {
|
||||
word.extend(c.to_lowercase());
|
||||
previous = Some(c);
|
||||
} else {
|
||||
previous = None;
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
words.push(word);
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// Parameters whose definitions depend on each other in a loop.
|
||||
pub fn cycles(list: &[(String, String, Kind)]) -> BTreeSet<String> {
|
||||
let refs: BTreeMap<&str, Vec<String>> = list.iter().map(|(n, e, _)| (n.as_str(), expr::references(e))).collect();
|
||||
@@ -1217,3 +1306,47 @@ mod design_length_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod name_words_tests {
|
||||
use super::name_words_match;
|
||||
|
||||
#[test]
|
||||
fn the_starts_of_words_in_order_find_a_long_name() {
|
||||
let name = "tooth_outward_flange_diameter";
|
||||
for query in ["too", "dia", "toodia", "toofla", "outdia", "toofladia", "TooDia", "too_dia", "tooth outward", "toothoutwardflangediameter"] {
|
||||
assert!(name_words_match(name, query), "{query}");
|
||||
}
|
||||
// Out of order, from inside a word, more than the words hold, or not a name at all.
|
||||
for query in ["diatoo", "ooth", "toodiax", "toox", "", "_", "- ", "tooth *", "too.dia"] {
|
||||
assert!(!name_words_match(name, query), "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camel_case_hyphens_and_digits_split_words() {
|
||||
assert!(name_words_match("boltHoleDepth", "bhd"));
|
||||
assert!(name_words_match("boltHoleDepth", "holedep"));
|
||||
assert!(name_words_match("rib-count-max", "rcm"));
|
||||
assert!(name_words_match("hole2_depth", "h2d"));
|
||||
assert!(name_words_match("Länge_Außen", "läau"));
|
||||
assert!(!name_words_match("boltholedepth", "bhd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_word_can_take_over_part_of_a_match() {
|
||||
// `ab` must not be taken whole from `abc` when the match needs `a` and then `bd...`.
|
||||
assert!(name_words_match("abc_bd", "abd"));
|
||||
assert!(name_words_match("aa_ab", "aab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_queries_never_panic() {
|
||||
let long = "a_".repeat(5_000);
|
||||
assert!(name_words_match(&long, &"a".repeat(5_000)));
|
||||
assert!(!name_words_match(&long, &"a".repeat(5_001)));
|
||||
for (name, query) in [("", "a"), ("\u{0}", "\u{0}"), ("İ", "i"), ("ß", "ss"), ("🙂_x", "x"), ("x", "🙂")] {
|
||||
let _ = name_words_match(name, query);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ fn local_plane(plane: &PlaneRef, depth: usize) -> bool {
|
||||
PlaneRef::Origin { name: _ } | PlaneRef::Custom { plane: _ } | PlaneRef::Placed { origin: _, x_dir: _, y_dir: _ } => true,
|
||||
PlaneRef::Offset { base, distance: _ }
|
||||
| PlaneRef::Flipped { base, about_y: _ }
|
||||
| PlaneRef::AtAngle { base, axis_origin: _, axis_dir: _, angle: _, line: None } => local_plane(base, depth + 1),
|
||||
| PlaneRef::AtAngle { base, axis_origin: _, axis_dir: _, angle: _, line: None, pivot: None, .. } => local_plane(base, depth + 1),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,7 @@ pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap
|
||||
distance2: _,
|
||||
start_offset: _,
|
||||
through_all,
|
||||
second_follows_first: _,
|
||||
taper: _,
|
||||
to,
|
||||
to_offset: _,
|
||||
|
||||
@@ -80,6 +80,13 @@ pub struct PointCloud {
|
||||
/// Only the elements within every filter's range are shown.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub filters: Vec<Filter>,
|
||||
/// The file the cloud was read from, to read again (`pointcloud.reload`).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub source: String,
|
||||
/// The most points the file was read under, which a reload reads it under again; `None`: the
|
||||
/// reader's default.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_points: Option<u64>,
|
||||
}
|
||||
|
||||
/// Where a property's values come from on one kind of element.
|
||||
@@ -556,6 +563,8 @@ mod tests {
|
||||
complex: Complex::default(),
|
||||
color_property: None,
|
||||
filters: Vec::new(),
|
||||
source: String::new(),
|
||||
max_points: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ fn cloud(points: &[[f32; 3]], segments: &[u32], triangles: &[u32], columns: Vec<
|
||||
complex: Complex { segments: Indices(segments.to_vec().into()), triangles: Indices(triangles.to_vec().into()), columns, names: Vec::new() },
|
||||
color_property: None,
|
||||
filters: Vec::new(),
|
||||
source: String::new(),
|
||||
max_points: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -453,6 +453,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -637,6 +638,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Portable opaque clear-coat assignments. Targets are stable definition/feature/
|
||||
//! component/occurrence identities; captured mesh ordinals never enter a design.
|
||||
use crate::{
|
||||
DocError, Result,
|
||||
render_surface::{RenderBodyTarget, bounded_sequence},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solidcraft_render::clear_coat::ClearCoat;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Matches the existing runtime clear-coat override bound for either executor.
|
||||
pub const MAX_COAT_BINDINGS: usize = 64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct CoatMaterial {
|
||||
pub weight: f64,
|
||||
pub roughness: f64,
|
||||
pub ior: f64,
|
||||
}
|
||||
impl PartialEq for CoatMaterial {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.weight.to_bits() == other.weight.to_bits()
|
||||
&& self.roughness.to_bits() == other.roughness.to_bits()
|
||||
&& self.ior.to_bits() == other.ior.to_bits()
|
||||
}
|
||||
}
|
||||
impl Default for CoatMaterial {
|
||||
fn default() -> Self {
|
||||
Self { weight: 1.0, roughness: 0.12, ior: 1.5 }
|
||||
}
|
||||
}
|
||||
impl CoatMaterial {
|
||||
pub fn validate(self) -> Result<()> {
|
||||
self.to_runtime().map(|_| ())
|
||||
}
|
||||
pub fn to_runtime(self) -> Result<ClearCoat> {
|
||||
ClearCoat::new(self.weight, self.roughness, self.ior).map_err(|e| DocError::Invalid(e.to_string()))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SavedCoat {
|
||||
pub target: RenderBodyTarget,
|
||||
pub coat: CoatMaterial,
|
||||
}
|
||||
impl SavedCoat {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.target.validate()?;
|
||||
self.coat.validate()
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct CoatBindings(Vec<SavedCoat>);
|
||||
impl CoatBindings {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
pub fn iter(&self) -> impl Iterator<Item = &SavedCoat> {
|
||||
self.0.iter()
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.len() > MAX_COAT_BINDINGS || self.0.capacity() > MAX_COAT_BINDINGS {
|
||||
return Err(DocError::Invalid("at most 64 saved clear-coat targets".into()));
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for binding in self.iter() {
|
||||
binding.validate()?;
|
||||
if !seen.insert(&binding.target) {
|
||||
return Err(DocError::Invalid("duplicate saved clear-coat target".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Validate before mutation; replacement is explicit and stays on the same target.
|
||||
pub fn set(&mut self, binding: SavedCoat, replace: bool) -> Result<()> {
|
||||
binding.validate()?;
|
||||
if let Some(old) = self.0.iter_mut().find(|old| old.target == binding.target) {
|
||||
if old == &binding {
|
||||
return Ok(());
|
||||
}
|
||||
if !replace {
|
||||
return Err(DocError::Invalid("clear-coat target already has a binding; explicit replacement required".into()));
|
||||
}
|
||||
*old = binding;
|
||||
} else {
|
||||
if self.len() >= MAX_COAT_BINDINGS {
|
||||
return Err(DocError::Invalid("at most 64 saved clear-coat targets".into()));
|
||||
}
|
||||
self.0.try_reserve_exact(1).map_err(|_| DocError::Invalid("could not reserve saved clear-coat binding".into()))?;
|
||||
if self.0.capacity() > MAX_COAT_BINDINGS {
|
||||
return Err(DocError::Invalid("saved clear-coat capacity exceeds admission".into()));
|
||||
}
|
||||
self.0.push(binding);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn remove(&mut self, target: &RenderBodyTarget) -> bool {
|
||||
let before = self.len();
|
||||
self.0.retain(|binding| &binding.target != target);
|
||||
self.len() != before
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for CoatBindings {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
|
||||
let result = Self(bounded_sequence::<D, SavedCoat, MAX_COAT_BINDINGS>(d)?);
|
||||
result.validate().map_err(serde::de::Error::custom)?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use solidcraft_render::{
|
||||
Camera,
|
||||
job::{
|
||||
CpuBudget, CpuProgressiveOptions, DirectionalLightOptions, JobOptions, LightingPreset, PunctualLightOptions, RaytraceEnvironmentOptions,
|
||||
RaytraceOptions, RectangleLightOptions, StudioLighting, ThinLens, ToneMap,
|
||||
RaytraceOptions, RectangleLightOptions, StudioLighting, Sun, ThinLens, ToneMap,
|
||||
},
|
||||
lighting::environment::SkyGradient,
|
||||
};
|
||||
@@ -28,12 +28,15 @@ pub enum RenderJob {
|
||||
},
|
||||
CpuRaytrace {
|
||||
#[serde(default)]
|
||||
options: CpuJob,
|
||||
transparent_background: bool,
|
||||
// Keep numerical CPU intent out of every raster/GPU enum value too.
|
||||
#[serde(default)]
|
||||
options: Box<CpuJob>,
|
||||
},
|
||||
GpuPath {
|
||||
#[serde(default)]
|
||||
transparent_background: bool,
|
||||
// StudioLighting is a bounded four-light value; boxing keeps the other variants small.
|
||||
// StudioLighting contains bounded inline area/directional sources; boxing keeps the other variants small.
|
||||
#[serde(default)]
|
||||
options: Box<GpuJob>,
|
||||
},
|
||||
@@ -44,7 +47,19 @@ impl RenderJob {
|
||||
match self {
|
||||
Self::Raster { .. } if exposure_ev != 0.0 => Err(DocError::Invalid("saved raster rendering requires exposure_ev: 0".into())),
|
||||
Self::Raster { .. } => Ok(()),
|
||||
Self::CpuRaytrace { options } => options.to_runtime(exposure_ev).map(|_| ()),
|
||||
Self::CpuRaytrace { options, transparent_background } => {
|
||||
options.validate(exposure_ev)?;
|
||||
if let Some(output) = &options.output {
|
||||
output
|
||||
.presentation(exposure_ev, [0; 3], *transparent_background)
|
||||
.validate()
|
||||
.map_err(|error| DocError::Invalid(error.to_string()))?;
|
||||
}
|
||||
if let Some(lens) = options.lens {
|
||||
lens.validate_camera(camera).map_err(|error| DocError::Invalid(error.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::GpuPath { options, transparent_background } => {
|
||||
if *transparent_background && options.backdrop.is_some() {
|
||||
return Err(DocError::Invalid("choose a camera backdrop or transparent PNG, not both".into()));
|
||||
@@ -67,6 +82,26 @@ impl RenderJob {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct CpuJob {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub caustics: Option<solidcraft_render::job::CausticOptions>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub volume: Option<solidcraft_render::job::volume::HomogeneousVolume>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sun: Option<Sun>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sky: Option<SkyEnvironment>,
|
||||
#[serde(skip_serializing_if = "crate::render_aging::SavedAgingStack::is_empty")]
|
||||
pub aging: crate::render_aging::SavedAgingStack,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub adaptive: Option<solidcraft_render::job::adaptive::AdaptiveSampling>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<solidcraft_render::job::CpuPathOptions>,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub denoise: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub lens: Option<ThinLens>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output: Option<Box<solidcraft_render::job::OutputOptions>>,
|
||||
#[serde(skip_serializing_if = "CpuBudget::is_compact")]
|
||||
pub budget: CpuBudget,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -94,6 +129,16 @@ pub struct CpuJob {
|
||||
impl Default for CpuJob {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
caustics: None,
|
||||
volume: None,
|
||||
sun: None,
|
||||
sky: None,
|
||||
aging: Default::default(),
|
||||
adaptive: None,
|
||||
denoise: false,
|
||||
path: None,
|
||||
lens: None,
|
||||
output: None,
|
||||
budget: CpuBudget::Compact,
|
||||
progressive: None,
|
||||
primary_samples: 1,
|
||||
@@ -111,12 +156,28 @@ impl Default for CpuJob {
|
||||
}
|
||||
|
||||
impl CpuJob {
|
||||
/// Validate saved parameters without inventing captured targets.
|
||||
pub fn validate(&self, exposure_ev: f64) -> Result<()> {
|
||||
self.validated_parameters(exposure_ev).map(|_| ())
|
||||
}
|
||||
/// Validate portable map compatibility without claiming that stable aging
|
||||
/// identities have been resolved into captured runtime body indices.
|
||||
pub fn validate_surface_maps(&self, exposure_ev: f64) -> Result<()> {
|
||||
let options = self.validated_parameters(exposure_ev)?;
|
||||
solidcraft_render::job::textures::validate_cpu_options(&options).map_err(|e| DocError::Invalid(e.to_string()))
|
||||
}
|
||||
/// Pure lowering, valid on hosts without a CPU raytracer. Checks bounds before cloning lists.
|
||||
pub fn to_runtime(&self, exposure_ev: f64) -> Result<RaytraceOptions> {
|
||||
if self.aging.iter().any(|layer| layer.target.is_some()) {
|
||||
return Err(DocError::Invalid("targeted CPU aging requires stable occurrence resolution against the current scene".into()));
|
||||
}
|
||||
self.validated_parameters(exposure_ev)
|
||||
}
|
||||
fn validated_parameters(&self, exposure_ev: f64) -> Result<RaytraceOptions> {
|
||||
if let Some(hdr) = self.hdr {
|
||||
hdr.validate()?;
|
||||
if self.environment.is_some() {
|
||||
return Err(DocError::Invalid("choose either saved CPU HDR or constant environment".into()));
|
||||
if self.environment.is_some() || self.sky.is_some() {
|
||||
return Err(DocError::Invalid("choose either saved CPU HDR, gradient Sky or constant environment".into()));
|
||||
}
|
||||
}
|
||||
bounded(&self.lights, 8, "directional lights")?;
|
||||
@@ -128,7 +189,27 @@ impl CpuJob {
|
||||
// Preserve hidden editable intent in CpuJob, but do not submit tuning for
|
||||
// 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 aging = self.aging.parameters_only()?;
|
||||
let sky = self
|
||||
.sky
|
||||
.as_ref()
|
||||
.map(|sky| -> Result<_> {
|
||||
sky.validate()?;
|
||||
let SkyEnvironment::Sky { gradient, rotation_rad, intensity } = *sky;
|
||||
Ok(Box::new(solidcraft_render::job::CpuSky { gradient, rotation_rad, intensity }))
|
||||
})
|
||||
.transpose()?;
|
||||
let options = RaytraceOptions {
|
||||
caustics: self.caustics,
|
||||
volume: self.volume,
|
||||
sun: self.sun.map(Box::new),
|
||||
sky,
|
||||
aging: (!aging.is_empty()).then(|| Box::new(aging)),
|
||||
adaptive: self.adaptive.map(Box::new),
|
||||
denoise: self.denoise,
|
||||
path: self.path,
|
||||
lens: self.lens,
|
||||
output: self.output.clone(),
|
||||
budget: self.budget,
|
||||
progressive: self.progressive,
|
||||
primary_samples: self.primary_samples,
|
||||
@@ -152,6 +233,8 @@ impl CpuJob {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct GpuJob {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub caustics: Option<solidcraft_render::job::CausticOptions>,
|
||||
#[serde(skip_serializing_if = "crate::render_aging::SavedAgingStack::is_empty")]
|
||||
pub aging: crate::render_aging::SavedAgingStack,
|
||||
pub nested_media: bool,
|
||||
@@ -186,6 +269,7 @@ impl Default for GpuJob {
|
||||
fn default() -> Self {
|
||||
let options = JobOptions::default();
|
||||
Self {
|
||||
caustics: None,
|
||||
aging: Default::default(),
|
||||
nested_media: options.nested_media,
|
||||
volume: options.volume,
|
||||
@@ -233,6 +317,7 @@ impl GpuJob {
|
||||
environment.validate()?;
|
||||
}
|
||||
let options = JobOptions {
|
||||
caustics: self.caustics,
|
||||
aging: self.aging.parameters_only()?,
|
||||
nested_media: self.nested_media,
|
||||
volume: self.volume,
|
||||
@@ -346,3 +431,50 @@ 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)]
|
||||
mod cpu_volume_portable_tests {
|
||||
use super::*;
|
||||
use solidcraft_render::job::{CpuPathOptions, CpuProgressiveOptions, volume::HomogeneousVolume};
|
||||
#[test]
|
||||
fn cpu_volume_saved_parameters_roundtrip_lower_without_default_adoption_or_hidden_repairs() {
|
||||
let v = HomogeneousVolume {
|
||||
min_mm: [-2.0, -3.0, -4.0],
|
||||
max_mm: [5.0, 6.0, 7.0],
|
||||
extinction_per_mm: 0.3,
|
||||
scattering_albedo: [0.2, 0.4, 0.6],
|
||||
anisotropy: -0.37,
|
||||
};
|
||||
let old = serde_json::to_value(CpuJob::default()).unwrap();
|
||||
assert!(old.get("volume").is_none());
|
||||
let mut job = CpuJob {
|
||||
volume: Some(v),
|
||||
path: Some(CpuPathOptions { max_depth: 8 }),
|
||||
progressive: Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }),
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_value(&job).unwrap();
|
||||
let reopened: CpuJob = serde_json::from_value(json.clone()).unwrap();
|
||||
assert_eq!(reopened, job);
|
||||
assert_eq!(reopened.to_runtime(0.0).unwrap().volume, Some(v));
|
||||
job.denoise = true;
|
||||
let before = job.clone();
|
||||
assert!(job.validate(0.0).is_err());
|
||||
assert_eq!(job, before);
|
||||
job.denoise = false;
|
||||
job.path = None;
|
||||
let before = job.clone();
|
||||
assert!(job.validate(0.0).is_err());
|
||||
assert_eq!(job, before);
|
||||
job.volume.as_mut().unwrap().extinction_per_mm = 0.0;
|
||||
job.denoise = true;
|
||||
job.validate(0.0).unwrap();
|
||||
let inactive = serde_json::to_value(&job).unwrap();
|
||||
assert_eq!(inactive["volume"]["anisotropy"], -0.37);
|
||||
assert_eq!(serde_json::from_value::<CpuJob>(inactive).unwrap(), job);
|
||||
job.volume = None;
|
||||
job.denoise = false;
|
||||
job.progressive = None;
|
||||
assert_eq!(serde_json::to_value(job).unwrap(), old);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ pub enum OpticalBoundary {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct OpticalMaterial {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<solidcraft_render::glass_model::GlassModel>,
|
||||
pub ior: f64,
|
||||
pub absorption_per_mm: [f64; 3],
|
||||
pub boundary: OpticalBoundary,
|
||||
@@ -32,12 +34,79 @@ pub struct OpticalMaterial {
|
||||
}
|
||||
impl Default for OpticalMaterial {
|
||||
fn default() -> Self {
|
||||
Self { ior: 1.5, absorption_per_mm: [0.0; 3], boundary: Default::default(), thickness_mm: 0.0, shadow_transmission: false, subsurface: None }
|
||||
Self {
|
||||
model: None,
|
||||
ior: 1.5,
|
||||
absorption_per_mm: [0.0; 3],
|
||||
boundary: Default::default(),
|
||||
thickness_mm: 0.0,
|
||||
shadow_transmission: false,
|
||||
subsurface: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl OpticalMaterial {
|
||||
/// The CPU consumer is a certified subset of the existing saved optical contract.
|
||||
/// Keep authored unsupported values intact and refuse them, never drop effects.
|
||||
pub fn validate_for_cpu(self) -> Result<()> {
|
||||
self.validate_for_cpu_path(false)
|
||||
}
|
||||
/// General closed boundaries require the explicit finite progressive path.
|
||||
pub fn validate_for_cpu_path(self, path: bool) -> Result<()> {
|
||||
self.validate()?;
|
||||
if self.model.is_some() && !path {
|
||||
return Err(DocError::Invalid("advanced Glass models require CPU Indirect lighting".into()));
|
||||
}
|
||||
if self.shadow_transmission && (!path || self.boundary != OpticalBoundary::ThinSheet) {
|
||||
return Err(DocError::Invalid(
|
||||
"CPU transmissive shadows require Indirect lighting and a thin sheet; closed refractive light connections remain unsupported".into(),
|
||||
));
|
||||
}
|
||||
if self.subsurface.is_some() && !path {
|
||||
return Err(DocError::Invalid("CPU subsurface scattering requires Indirect lighting and a certified closed medium".into()));
|
||||
}
|
||||
if self.absorption_per_mm.into_iter().any(|v| !(0.0..=100.0).contains(&v)) || !(0.0..=10000.0).contains(&self.thickness_mm) {
|
||||
return Err(DocError::Invalid("CPU glass absorption must be 0..100 per mm and virtual sheet thickness 0..10000 mm".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A closed optical boundary is accepted only if the CPU producer subsequently
|
||||
/// certifies the captured mesh as its exact axis-aligned-box subset. The saved
|
||||
/// boundary is not rewritten and no arbitrary closed-mesh support is implied.
|
||||
pub fn to_cpu(self, body_index: usize, body_name: &str) -> Result<solidcraft_render::job::DielectricOptions> {
|
||||
self.to_cpu_for_path(body_index, body_name, false)
|
||||
}
|
||||
pub fn to_cpu_for_path(self, body_index: usize, body_name: &str, path: bool) -> Result<solidcraft_render::job::DielectricOptions> {
|
||||
self.validate_for_cpu_path(path)?;
|
||||
if body_name.is_empty() || body_name.len() > 1024 || body_name.chars().any(char::is_control) {
|
||||
return Err(DocError::Invalid("CPU optical target requires a bounded captured body name".into()));
|
||||
}
|
||||
Ok(solidcraft_render::job::DielectricOptions {
|
||||
model: self.model,
|
||||
subsurface: self.subsurface,
|
||||
shadow_transmission: self.shadow_transmission,
|
||||
body_index,
|
||||
body_name: body_name.into(),
|
||||
boundary: match self.boundary {
|
||||
OpticalBoundary::ThinSheet => solidcraft_render::job::DielectricBoundary::ThinSheet,
|
||||
OpticalBoundary::ClosedMesh if path => solidcraft_render::job::DielectricBoundary::ClosedMesh,
|
||||
OpticalBoundary::ClosedBox | OpticalBoundary::ClosedMesh => solidcraft_render::job::DielectricBoundary::ClosedBox,
|
||||
},
|
||||
ior: self.ior,
|
||||
absorption_per_mm: self.absorption_per_mm,
|
||||
thickness_mm: self.thickness_mm,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate(self) -> Result<()> {
|
||||
let error = |message: String| DocError::Invalid(message);
|
||||
if let Some(model) = self.model {
|
||||
model.validate(self.ior).map_err(|e| error(e.to_string()))?;
|
||||
if self.boundary == OpticalBoundary::ThinSheet && self.shadow_transmission && model.roughness > 0.0 {
|
||||
return Err(error("rough thin-sheet Glass requires disabled straight transmitted shadows".into()));
|
||||
}
|
||||
}
|
||||
OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, self.ior).map_err(|e| error(e.to_string()))?;
|
||||
if self.boundary != OpticalBoundary::ThinSheet && self.thickness_mm != 0.0 {
|
||||
return Err(error("closed optical thickness comes from geometry; thickness_mm must be zero".into()));
|
||||
@@ -90,6 +159,19 @@ impl OpticalBindings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_for_cpu(&self) -> Result<()> {
|
||||
self.validate_for_cpu_path(false)
|
||||
}
|
||||
pub fn validate_for_cpu_path(&self, path: bool) -> Result<()> {
|
||||
self.validate()?;
|
||||
if self.len() > 8 {
|
||||
return Err(DocError::Invalid("CPU supports at most eight certified optical targets".into()));
|
||||
}
|
||||
for binding in self.iter() {
|
||||
binding.optics.validate_for_cpu_path(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn set(&mut self, binding: SavedOptics, replace: bool) -> Result<()> {
|
||||
binding.validate()?;
|
||||
if let Some(old) = self.0.iter_mut().find(|old| old.target == binding.target) {
|
||||
@@ -125,6 +207,48 @@ impl<'de> Deserialize<'de> for OpticalBindings {
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod advanced_model_contract_tests {
|
||||
use super::*;
|
||||
use solidcraft_render::glass_model::{Dispersion, GlassModel, ThinFilm};
|
||||
#[test]
|
||||
fn advanced_optics_keep_every_authored_number_through_saved_and_cpu_lowering() {
|
||||
let model = GlassModel {
|
||||
roughness: 0.27,
|
||||
dispersion: Some(Dispersion { abbe_number: 45.0 }),
|
||||
thin_film: Some(ThinFilm { ior: 1.36, thickness_nm: 420.0 }),
|
||||
};
|
||||
let optics = OpticalMaterial { model: Some(model), ..Default::default() };
|
||||
let wire = serde_json::to_value(optics).unwrap();
|
||||
assert_eq!(serde_json::from_value::<OpticalMaterial>(wire.clone()).unwrap(), optics);
|
||||
assert_eq!(optics.to_cpu_for_path(2, "Original Glass", true).unwrap().model, Some(model));
|
||||
assert!(optics.to_cpu(2, "Original Glass").is_err());
|
||||
assert_eq!(serde_json::to_value(optics).unwrap(), wire);
|
||||
assert!(serde_json::to_value(OpticalMaterial::default()).unwrap().get("model").is_none());
|
||||
let sheet = OpticalMaterial {
|
||||
model: Some(GlassModel { roughness: 0.0, ..model }),
|
||||
boundary: OpticalBoundary::ThinSheet,
|
||||
shadow_transmission: true,
|
||||
..optics
|
||||
};
|
||||
sheet.validate_for_cpu_path(true).unwrap();
|
||||
assert!(OpticalMaterial { model: Some(model), ..sheet }.validate().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn caustic_quality_is_portable_between_both_saved_jobs_and_runtime_requests() {
|
||||
use crate::render_job::{CpuJob, GpuJob};
|
||||
let caustics = Some(solidcraft_render::job::CausticOptions { photons: 8192, radius_mm: 0.4, max_depth: 12, seed: 381 });
|
||||
let cpu = CpuJob { caustics, path: Some(Default::default()), progressive: Some(Default::default()), ..Default::default() };
|
||||
let gpu = GpuJob { caustics, ..Default::default() };
|
||||
assert_eq!(cpu.to_runtime(0.0).unwrap().caustics, caustics);
|
||||
assert_eq!(gpu.to_runtime(0.0).unwrap().caustics, caustics);
|
||||
assert_eq!(serde_json::from_value::<CpuJob>(serde_json::to_value(&cpu).unwrap()).unwrap(), cpu);
|
||||
assert_eq!(serde_json::from_value::<GpuJob>(serde_json::to_value(&gpu).unwrap()).unwrap(), gpu);
|
||||
assert!(serde_json::to_value(CpuJob::default()).unwrap().get("caustics").is_none());
|
||||
assert!(serde_json::to_value(GpuJob::default()).unwrap().get("caustics").is_none());
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -166,4 +290,86 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_optical_consumer_preserves_saved_boundary_and_refuses_unrepresented_effects() {
|
||||
let closed = OpticalMaterial { ior: 1.51, absorption_per_mm: [0.1, 0.02, 0.0], ..Default::default() };
|
||||
let original = serde_json::to_value(closed).unwrap();
|
||||
let cpu = closed.to_cpu(3, "Glass@part-2").unwrap();
|
||||
assert_eq!(cpu.boundary, solidcraft_render::job::DielectricBoundary::ClosedBox);
|
||||
assert_eq!((cpu.body_index, cpu.body_name.as_str()), (3, "Glass@part-2"));
|
||||
assert_eq!((cpu.ior, cpu.absorption_per_mm), (1.51, [0.1, 0.02, 0.0]));
|
||||
assert_eq!(serde_json::to_value(closed).unwrap(), original, "CPU specialization never rewrites the authored closed boundary");
|
||||
let thin = OpticalMaterial { boundary: OpticalBoundary::ThinSheet, thickness_mm: 2.0, ..closed };
|
||||
assert_eq!(thin.to_cpu(0, "Sheet").unwrap().boundary, solidcraft_render::job::DielectricBoundary::ThinSheet);
|
||||
for (value, reason) in [
|
||||
(OpticalMaterial { shadow_transmission: true, ..thin }, "transmissive shadows"),
|
||||
(OpticalMaterial { subsurface: Some(Subsurface { scattering_per_mm: 0.0, anisotropy: 0.0 }), ..closed }, "subsurface"),
|
||||
(OpticalMaterial { absorption_per_mm: [101.0, 0.0, 0.0], ..closed }, "absorption"),
|
||||
(OpticalMaterial { thickness_mm: 10001.0, ..thin }, "thickness"),
|
||||
] {
|
||||
let before = serde_json::to_value(value).unwrap();
|
||||
assert!(value.to_cpu(0, "Target").unwrap_err().to_string().contains(reason));
|
||||
assert_eq!(serde_json::to_value(value).unwrap(), before);
|
||||
}
|
||||
let mut optics = OpticalBindings::default();
|
||||
for feature in 1..=9 {
|
||||
optics
|
||||
.set(
|
||||
SavedOptics {
|
||||
target: RenderBodyTarget { definition: format!("Glass{feature}"), feature, component: 0, occurrence_path: vec![] },
|
||||
optics: closed,
|
||||
},
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
optics.validate().unwrap();
|
||||
assert!(optics.validate_for_cpu().is_err());
|
||||
let target = RenderBodyTarget { definition: "Glass".into(), feature: 1, component: 0, occurrence_path: vec![] };
|
||||
let mut setup = crate::render_settings::RenderSetup {
|
||||
job: Some(crate::render_job::RenderJob::CpuRaytrace { transparent_background: false, options: Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
setup.optics.set(SavedOptics { target, optics: closed }, false).unwrap();
|
||||
setup.validate().unwrap();
|
||||
let wire = serde_json::to_value(&setup).unwrap();
|
||||
assert_eq!(serde_json::from_value::<crate::render_settings::RenderSetup>(wire).unwrap(), setup);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cpu_general_glass_contract_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn saved_general_glass_requires_explicit_path_and_preserves_unsupported_choices_and_old_wire() {
|
||||
let optics = OpticalMaterial { ior: 1.51, absorption_per_mm: [0.1, 0.2, 0.3], boundary: OpticalBoundary::ClosedMesh, ..Default::default() };
|
||||
assert_eq!(optics.to_cpu(0, "Glass").unwrap().boundary, solidcraft_render::job::DielectricBoundary::ClosedBox);
|
||||
let general = optics.to_cpu_for_path(0, "Glass", true).unwrap();
|
||||
assert_eq!(general.boundary, solidcraft_render::job::DielectricBoundary::ClosedMesh);
|
||||
assert_eq!((general.ior, general.absorption_per_mm), (optics.ior, optics.absorption_per_mm));
|
||||
let scattering = OpticalMaterial { subsurface: Some(Subsurface { scattering_per_mm: 0.1, anisotropy: 0.3 }), ..optics };
|
||||
let before = serde_json::to_value(scattering).unwrap();
|
||||
assert!(scattering.to_cpu(0, "Glass").is_err(), "the legacy consumer remains explicit");
|
||||
assert_eq!(scattering.to_cpu_for_path(0, "Glass", true).unwrap().subsurface, scattering.subsurface);
|
||||
assert_eq!(serde_json::to_value(scattering).unwrap(), before);
|
||||
let encoded = serde_json::to_value(&general).unwrap();
|
||||
assert!(encoded.get("shadow_transmission").is_none());
|
||||
assert_eq!(serde_json::from_value::<solidcraft_render::job::DielectricOptions>(encoded).unwrap(), general);
|
||||
let thin = OpticalMaterial { boundary: OpticalBoundary::ThinSheet, shadow_transmission: true, ..optics };
|
||||
assert!(thin.to_cpu(0, "Glass").is_err());
|
||||
assert!(thin.to_cpu_for_path(0, "Glass", true).unwrap().shadow_transmission);
|
||||
for value in [
|
||||
OpticalMaterial { shadow_transmission: true, ..optics },
|
||||
OpticalMaterial {
|
||||
boundary: OpticalBoundary::ThinSheet,
|
||||
subsurface: Some(Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }),
|
||||
..optics
|
||||
},
|
||||
] {
|
||||
let before = value;
|
||||
assert!(value.to_cpu_for_path(0, "Glass", true).is_err());
|
||||
assert_eq!(value, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ pub struct RenderSetup {
|
||||
pub surfaces: crate::render_surface::SurfaceBindings,
|
||||
#[serde(skip_serializing_if = "crate::render_optics::OpticalBindings::is_empty")]
|
||||
pub optics: crate::render_optics::OpticalBindings,
|
||||
#[serde(skip_serializing_if = "crate::render_coat::CoatBindings::is_empty")]
|
||||
pub coats: crate::render_coat::CoatBindings,
|
||||
#[serde(skip_serializing_if = "solidcraft_render::stage::Stage::is_empty")]
|
||||
pub stage: solidcraft_render::stage::Stage,
|
||||
}
|
||||
@@ -78,6 +80,7 @@ impl Default for RenderSetup {
|
||||
background: [236, 240, 245],
|
||||
job: None,
|
||||
optics: Default::default(),
|
||||
coats: Default::default(),
|
||||
surfaces: Default::default(),
|
||||
stage: Default::default(),
|
||||
}
|
||||
@@ -87,9 +90,13 @@ impl Default for RenderSetup {
|
||||
impl RenderSetup {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let (limits, cpu) = match &self.job {
|
||||
Some(RenderJob::CpuRaytrace { options }) => {
|
||||
(options.budget.image_limits(options.progressive.is_some()), Some(CpuSize { progressive: options.progressive }))
|
||||
}
|
||||
Some(RenderJob::CpuRaytrace { options, .. }) => (
|
||||
options.budget.image_limits(options.progressive.is_some()),
|
||||
Some(CpuSize {
|
||||
progressive: solidcraft_render::job::cpu_camera_sampling(options.progressive, options.adaptive, options.budget)
|
||||
.map_err(|e| DocError::Invalid(e.to_string()))?,
|
||||
}),
|
||||
),
|
||||
Some(RenderJob::GpuPath { .. }) => (solidcraft_render::job::GPU_PATH_LIMITS, None),
|
||||
_ => (RenderLimits::default(), None),
|
||||
};
|
||||
@@ -111,8 +118,30 @@ impl RenderSetup {
|
||||
fn validate_with_limits(&self, limits: RenderLimits, cpu: Option<CpuSize>) -> Result<()> {
|
||||
self.surfaces.validate()?;
|
||||
self.optics.validate()?;
|
||||
if !self.optics.is_empty() && !matches!(self.job, Some(RenderJob::GpuPath { .. })) {
|
||||
return Err(DocError::Invalid("saved optics require an explicit GPU job".into()));
|
||||
self.coats.validate()?;
|
||||
if !self.coats.is_empty() && !matches!(self.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) {
|
||||
return Err(DocError::Invalid("saved clear coats require an explicit CPU or GPU raytrace job".into()));
|
||||
}
|
||||
if self.coats.iter().any(|coat| self.optics.iter().any(|optics| coat.target == optics.target)) {
|
||||
return Err(DocError::Invalid("clear coat and Glass cannot share a target, including zero-weight authored coats".into()));
|
||||
}
|
||||
match &self.job {
|
||||
Some(RenderJob::CpuRaytrace { options, .. }) => {
|
||||
self.optics.validate_for_cpu_path(options.path.is_some())?;
|
||||
if options.volume.is_some_and(|v| v.active()) && !self.optics.is_empty() {
|
||||
return Err(DocError::Invalid(
|
||||
"CPU Atmosphere cannot combine with saved Glass or subsurface scattering; settings are kept".into(),
|
||||
));
|
||||
}
|
||||
if options.denoise && self.optics.iter().any(|binding| binding.optics.subsurface.is_some_and(|s| s.active())) {
|
||||
return Err(DocError::Invalid(
|
||||
"CPU subsurface random walks have no surface-denoiser guides; disable denoising explicitly".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Some(RenderJob::GpuPath { .. }) => {}
|
||||
_ if !self.optics.is_empty() => return Err(DocError::Invalid("saved optics require an explicit CPU or GPU raytrace job".into())),
|
||||
_ => {}
|
||||
}
|
||||
if self.optics.iter().any(|o| self.surfaces.iter().any(|s| s.target == o.target)) {
|
||||
return Err(DocError::Invalid("saved opaque surface maps and optical boundaries cannot share a target".into()));
|
||||
@@ -121,10 +150,23 @@ impl RenderSetup {
|
||||
if !self.stage.is_empty() && matches!(self.job, Some(RenderJob::Raster { .. })) {
|
||||
return Err(DocError::Invalid("passive stage geometry requires raytracing; raster cannot silently discard it".into()));
|
||||
}
|
||||
if !self.surfaces.is_empty() && !matches!(self.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) {
|
||||
return Err(DocError::Invalid(
|
||||
"saved surfaces require an explicit CPU raytrace or GPU path job; unsupported methods cannot discard bindings".into(),
|
||||
));
|
||||
if !self.surfaces.is_empty() {
|
||||
match &self.job {
|
||||
Some(RenderJob::GpuPath { .. }) => {}
|
||||
Some(RenderJob::CpuRaytrace { options, .. }) => {
|
||||
if !self.optics.is_empty() && options.path.is_none() {
|
||||
return Err(DocError::Invalid(
|
||||
"CPU surface maps cannot combine with saved Glass; preserve the bindings and select a compatible method".into(),
|
||||
));
|
||||
}
|
||||
options.validate_surface_maps(self.exposure_ev)?;
|
||||
}
|
||||
_ => {
|
||||
return Err(DocError::Invalid(
|
||||
"saved surfaces require an explicit CPU raytrace or GPU path job; unsupported methods cannot discard bindings".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (width, height) = (u64::from(self.width), u64::from(self.height));
|
||||
if width == 0 || height == 0 {
|
||||
@@ -170,10 +212,22 @@ impl RenderSetup {
|
||||
));
|
||||
}
|
||||
job.validate(&self.camera, self.exposure_ev)?;
|
||||
if let RenderJob::CpuRaytrace { options } = job
|
||||
&& let Some(progressive) = options.progressive
|
||||
{
|
||||
progressive.validate_image_with_budget(self.width, self.height, options.budget).map_err(|e| DocError::Invalid(e.to_string()))?;
|
||||
if let RenderJob::CpuRaytrace { options, .. } = job {
|
||||
if options.denoise {
|
||||
solidcraft_render::job::validate_cpu_denoise_image(self.width, self.height).map_err(|e| DocError::Invalid(e.to_string()))?;
|
||||
}
|
||||
options
|
||||
.budget
|
||||
.validate_image(
|
||||
self.width,
|
||||
self.height,
|
||||
solidcraft_render::job::cpu_camera_sampling(options.progressive, options.adaptive, options.budget)
|
||||
.map_err(|e| DocError::Invalid(e.to_string()))?,
|
||||
)
|
||||
.map_err(|e| DocError::Invalid(e.to_string()))?;
|
||||
if let Some(output) = &options.output {
|
||||
output.validate_image(self.width, self.height).map_err(|e| DocError::Invalid(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Desired mode/format/backend may be unavailable on this host. Saving intent is not preflight.
|
||||
@@ -245,7 +299,7 @@ impl RenderSettings {
|
||||
}
|
||||
}
|
||||
match &setup.job {
|
||||
Some(RenderJob::CpuRaytrace { options }) => {
|
||||
Some(RenderJob::CpuRaytrace { options, .. }) => {
|
||||
if let Some(hdr) = options.hdr {
|
||||
hdr.validate_resource(&self.resources)?;
|
||||
}
|
||||
@@ -328,11 +382,12 @@ mod tests {
|
||||
RenderSetup {
|
||||
exposure_ev: 1.25,
|
||||
job: Some(RenderJob::CpuRaytrace {
|
||||
options: CpuJob {
|
||||
transparent_background: false,
|
||||
options: Box::new(CpuJob {
|
||||
lights: Some(Vec::new()),
|
||||
hdr: Some(CpuHdrEnvironment { resource: id, rotation_rad: 0.75, intensity: 2.0, samples: 64 }),
|
||||
..Default::default()
|
||||
},
|
||||
}),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -580,7 +635,7 @@ mod tests {
|
||||
let cpu = |budget, width, height| RenderSetup {
|
||||
width,
|
||||
height,
|
||||
job: Some(RenderJob::CpuRaytrace { options: CpuJob { budget, ..Default::default() } }),
|
||||
job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(CpuJob { budget, ..Default::default() }) }),
|
||||
..Default::default()
|
||||
};
|
||||
let compact = cpu(CpuBudget::Compact, 3840, 2160);
|
||||
@@ -588,7 +643,7 @@ mod tests {
|
||||
assert!(message.contains("3840 × 2160 exceeds the image limits (4096 pixels per side, 4194304 pixels in all)"), "{message}");
|
||||
assert!(message.contains("the largest image at this aspect is 2730 × 1536"), "{message}");
|
||||
assert!(message.contains("choose the Studio CPU resource profile, or a smaller size"), "{message}");
|
||||
assert!(matches!(&compact.job, Some(RenderJob::CpuRaytrace { options }) if options.budget == CpuBudget::Compact));
|
||||
assert!(matches!(&compact.job, Some(RenderJob::CpuRaytrace { options, .. }) if options.budget == CpuBudget::Compact));
|
||||
let message = compact.validate_for_cpu(CpuBudget::Compact).unwrap_err().to_string();
|
||||
assert!(message.contains("choose the Studio CPU resource profile"), "{message}");
|
||||
|
||||
@@ -647,7 +702,7 @@ mod tests {
|
||||
let saved = serde_json::to_value(&reopened.render).unwrap();
|
||||
assert!(saved["setups"]["Legacy"].get("job").is_none());
|
||||
assert_eq!(saved["setups"]["Legacy"]["environment_rotation"], 0.75);
|
||||
let RenderJob::CpuRaytrace { options } = settings.setups["CPU"].job.as_ref().unwrap() else { panic!("CPU intent changed") };
|
||||
let RenderJob::CpuRaytrace { options, .. } = settings.setups["CPU"].job.as_ref().unwrap() else { panic!("CPU intent changed") };
|
||||
let runtime = options.to_runtime(settings.setups["CPU"].exposure_ev).unwrap();
|
||||
assert_eq!(runtime.exposure_ev, 1.25);
|
||||
assert_eq!(runtime.area_samples, Some(64));
|
||||
@@ -671,11 +726,11 @@ mod tests {
|
||||
for options in [json!({}), json!({"lights":null,"punctual_lights":null,"area_lights":null,"environment":null})] {
|
||||
let setup: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace","options":options}})).unwrap();
|
||||
setup.validate().unwrap();
|
||||
assert_eq!(setup.job, Some(RenderJob::CpuRaytrace { options: CpuJob::default() }));
|
||||
assert_eq!(setup.job, Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::default() }));
|
||||
}
|
||||
let empty: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace","options":{"lights":[]}}})).unwrap();
|
||||
empty.validate().unwrap();
|
||||
assert_ne!(empty.job, Some(RenderJob::CpuRaytrace { options: CpuJob::default() }));
|
||||
assert_ne!(empty.job, Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::default() }));
|
||||
for (lighting, explicit) in [(serde_json::Value::Null, false), (json!({"environment":[0,0,0],"area_lights":[]}), true)] {
|
||||
let setup: RenderSetup = serde_json::from_value(json!({"job":{"method":"gpu_path","options":{"lighting":lighting}}})).unwrap();
|
||||
setup.validate().unwrap();
|
||||
@@ -697,7 +752,7 @@ mod tests {
|
||||
let document = Document { render: Arc::new(settings), ..Default::default() };
|
||||
let reopened = Document::from_json(&document.to_json()).unwrap();
|
||||
assert_eq!(document, reopened);
|
||||
let RenderJob::CpuRaytrace { options } = reopened.render.setups["Film"].job.as_ref().unwrap() else { panic!("method changed") };
|
||||
let RenderJob::CpuRaytrace { options, .. } = reopened.render.setups["Film"].job.as_ref().unwrap() else { panic!("method changed") };
|
||||
let runtime = options.to_runtime(1.5).unwrap();
|
||||
assert_eq!(runtime.progressive.unwrap().seed, u32::MAX);
|
||||
assert_eq!(runtime.exposure_ev, 1.5);
|
||||
@@ -714,6 +769,104 @@ mod tests {
|
||||
assert!(serde_json::from_value::<RenderSettings>(incompatible).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_transparent_intent_roundtrips_offline_and_keeps_opaque_defaults() {
|
||||
use serde_json::json;
|
||||
let opaque: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace"}})).unwrap();
|
||||
assert!(matches!(opaque.job, Some(RenderJob::CpuRaytrace { transparent_background: false, .. })));
|
||||
let setup: RenderSetup =
|
||||
serde_json::from_value(json!({"width":8,"height":8,"job":{"method":"cpu_raytrace","transparent_background":true,"options":{
|
||||
"primary_samples":4,"output":{"linear_exr":true}}}}))
|
||||
.unwrap();
|
||||
setup.validate().unwrap();
|
||||
let document = Document {
|
||||
render: Arc::new(RenderSettings { setups: std::collections::BTreeMap::from([("Cutout".into(), setup)]), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(document, Document::from_json(&document.to_json()).unwrap());
|
||||
for output in [json!({"backdrop":{}}), json!({"finishing":{"bloom":{"strength":1}}}), json!({"finishing":{"photographic":{"grain":0.03}}})] {
|
||||
let settings = json!({"setups":{"Cutout":{"job":{"method":"cpu_raytrace","transparent_background":true,"options":{"output":output}}}}});
|
||||
let error = serde_json::from_value::<RenderSettings>(settings.clone()).unwrap_err();
|
||||
assert!(error.to_string().contains("opaque"), "valid opaque-only effects remain authored and refused");
|
||||
let mut saved: serde_json::Value = serde_json::from_str(&Document::default().to_json()).unwrap();
|
||||
saved["render"] = settings;
|
||||
let error = Document::from_json(&saved.to_string()).unwrap_err();
|
||||
assert!(error.to_string().contains("opaque"), "the full document loader must enforce the same saved output contract");
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_value::<RenderSetup>(json!({"job":{"method":"cpu_raytrace","options":{"transparent_background":true}}})).is_err(),
|
||||
"one alpha authority beside the numerical job"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_physical_lens_roundtrips_offline_and_keeps_disabled_legacy_intent() {
|
||||
use serde_json::json;
|
||||
let camera = Camera { fov: 0.7, distance: 20.0, ..Default::default() };
|
||||
let saved = json!({"setups":{"Focus":{"width":64,"height":32,"camera":camera,
|
||||
"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":8,"seed":81},
|
||||
"lens":{"aperture_radius_mm":0.5,"focus_distance_mm":20.0}}}}}});
|
||||
let settings: RenderSettings = serde_json::from_value(saved.clone()).unwrap();
|
||||
let document = Document { render: Arc::new(settings), ..Default::default() };
|
||||
assert_eq!(document, Document::from_json(&document.to_json()).unwrap());
|
||||
let RenderJob::CpuRaytrace { options, .. } = document.render.setups["Focus"].job.as_ref().unwrap() else { panic!("CPU method changed") };
|
||||
assert_eq!(options.to_runtime(1.5).unwrap().lens, options.lens);
|
||||
let mut fixed = saved.clone();
|
||||
fixed["setups"]["Focus"]["job"]["options"].as_object_mut().unwrap().remove("progressive");
|
||||
assert!(serde_json::from_value::<RenderSettings>(fixed.clone()).is_err());
|
||||
fixed["setups"]["Focus"]["job"]["options"]["lens"]["aperture_radius_mm"] = json!(0);
|
||||
fixed["setups"]["Focus"]["camera"]["fov"] = json!(0);
|
||||
let zero: RenderSettings = serde_json::from_value(fixed).unwrap();
|
||||
assert_eq!(serde_json::to_value(&zero).unwrap()["setups"]["Focus"]["job"]["options"]["lens"]["aperture_radius_mm"].as_f64(), Some(0.0));
|
||||
for lens in [
|
||||
json!({"aperture_radius_mm":-1,"focus_distance_mm":20}),
|
||||
json!({"aperture_radius_mm":0.5,"focus_distance_mm":0}),
|
||||
json!({"aperture_radius_mm":0.5,"focus_distance_mm":20,"f_stop":2}),
|
||||
] {
|
||||
let mut invalid = saved.clone();
|
||||
invalid["setups"]["Focus"]["job"]["options"]["lens"] = lens;
|
||||
assert!(serde_json::from_value::<RenderSettings>(invalid).is_err());
|
||||
}
|
||||
let mut ortho = saved;
|
||||
ortho["setups"]["Focus"]["camera"]["fov"] = json!(0);
|
||||
assert!(serde_json::from_value::<RenderSettings>(ortho).is_err());
|
||||
assert!(serde_json::to_value(CpuJob::default()).unwrap().get("lens").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_output_presentation_roundtrips_offline_without_another_exposure_authority() {
|
||||
use serde_json::json;
|
||||
assert!(serde_json::to_value(CpuJob::default()).unwrap().get("output").is_none());
|
||||
let saved = json!({"setups":{"CPU output":{"width":64,"height":32,"exposure_ev":1.5,
|
||||
"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":7,"seed":81},
|
||||
"output":{"tone_map":"aces_fitted","finishing":{"rgb_gain":[1.2,0.8,1.1],"photographic":{"grain":0.03,"seed":42},
|
||||
"bloom":{"strength":0.2,"threshold":0.5,"radius":2}},"backdrop":{"mode":"radial"},"linear_exr":true}}}}}});
|
||||
let settings: RenderSettings = serde_json::from_value(saved).unwrap();
|
||||
let setup = &settings.setups["CPU output"];
|
||||
let RenderJob::CpuRaytrace { options, .. } = setup.job.as_ref().unwrap() else { panic!("CPU job expected") };
|
||||
let runtime = options.to_runtime(setup.exposure_ev).unwrap();
|
||||
assert_eq!(runtime.exposure_ev, 1.5);
|
||||
assert_eq!(runtime.output, options.output);
|
||||
let encoded = serde_json::to_value(&settings).unwrap();
|
||||
assert!(encoded["setups"]["CPU output"]["job"]["options"]["output"].get("exposure_ev").is_none());
|
||||
assert_eq!(settings, serde_json::from_value::<RenderSettings>(encoded.clone()).unwrap());
|
||||
for bad in [json!({"exposure_ev":1}), json!({"samples":4}), json!({"linear_exr":"yes"}), json!({"finishing":{"rgb_gain":[-1,1,1]}})] {
|
||||
let mut invalid = encoded.clone();
|
||||
invalid["setups"]["CPU output"]["job"]["options"]["output"] = bad;
|
||||
assert!(serde_json::from_value::<RenderSettings>(invalid).is_err());
|
||||
}
|
||||
let wide = json!({"width":16384,"height":1,"job":{"method":"cpu_raytrace","options":{"budget":"workstation"}}});
|
||||
serde_json::from_value::<RenderSetup>(wide.clone()).unwrap().validate().unwrap();
|
||||
for output in [json!({"tone_map":"aces_fitted"}), json!({"linear_exr":true})] {
|
||||
let mut invalid = wide.clone();
|
||||
invalid["job"]["options"]["output"] = output;
|
||||
assert!(
|
||||
serde_json::from_value::<RenderSetup>(invalid).unwrap().validate().is_err(),
|
||||
"active output must respect its existing shared envelope"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_jobs_reject_unbounded_invalid_and_nonportable_inputs() {
|
||||
use serde_json::json;
|
||||
@@ -817,6 +970,7 @@ mod tests {
|
||||
#[cfg(test)]
|
||||
mod cpu_budget_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions};
|
||||
|
||||
#[test]
|
||||
@@ -837,11 +991,12 @@ mod cpu_budget_tests {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
job: Some(RenderJob::CpuRaytrace {
|
||||
options: CpuJob {
|
||||
transparent_background: false,
|
||||
options: Box::new(CpuJob {
|
||||
budget: CpuBudget::Studio,
|
||||
progressive: Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }),
|
||||
..Default::default()
|
||||
},
|
||||
}),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -849,7 +1004,7 @@ mod cpu_budget_tests {
|
||||
let text = serde_json::to_string(&setup).unwrap();
|
||||
let reopened: RenderSetup = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(setup, reopened);
|
||||
let Some(RenderJob::CpuRaytrace { options }) = &mut setup.job else {
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else {
|
||||
panic!("CPU fixture");
|
||||
};
|
||||
options.budget = CpuBudget::Compact;
|
||||
@@ -861,4 +1016,372 @@ 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_path_is_explicit_bounded_offline_intent_and_roundtrips_without_changing_legacy_jobs() {
|
||||
let old = CpuJob::default();
|
||||
assert!(old.path.is_none());
|
||||
assert!(serde_json::to_value(&old).unwrap().get("path").is_none());
|
||||
for depth in [1, 8, 16] {
|
||||
let setup:RenderSetup=serde_json::from_value(json!({"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"path":{"max_depth":depth},"progressive":{"samples_per_pixel":7,"seed":9}}}})).unwrap();
|
||||
setup.validate().unwrap();
|
||||
let mut document = crate::Document::default();
|
||||
std::sync::Arc::make_mut(&mut document.render).setups.insert("GI".into(), setup);
|
||||
let bytes = serde_json::to_vec(&document).unwrap();
|
||||
let reopened: crate::Document = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(document, reopened);
|
||||
}
|
||||
for raw in [
|
||||
json!({"path":{"max_depth":0},"progressive":{"samples_per_pixel":7,"seed":9}}),
|
||||
json!({"path":{"max_depth":17},"progressive":{"samples_per_pixel":7,"seed":9}}),
|
||||
json!({"path":{"max_depth":8}}),
|
||||
json!({"path":{"max_depth":8},"progressive":{"samples_per_pixel":7,"seed":9},"shadows":false}),
|
||||
] {
|
||||
let options: CpuJob = serde_json::from_value(raw).unwrap();
|
||||
assert!(options.to_runtime(0.0).is_err());
|
||||
}
|
||||
assert!(serde_json::from_value::<CpuJob>(json!({"path":{"max_depth":8,"unknown":true}})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn cpu_denoise_saved_flag_roundtrips_offline_and_keeps_false_omitted() {
|
||||
use solidcraft_render::job::CpuBudget;
|
||||
let mut setup = RenderSetup {
|
||||
width: 16,
|
||||
height: 8,
|
||||
job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(CpuJob { denoise: true, ..Default::default() }) }),
|
||||
..Default::default()
|
||||
};
|
||||
setup.validate().unwrap();
|
||||
let wire = serde_json::to_value(&setup).unwrap();
|
||||
assert_eq!(wire["job"]["options"]["denoise"], true);
|
||||
assert_eq!(serde_json::from_value::<RenderSetup>(wire).unwrap(), setup);
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") };
|
||||
assert!(options.to_runtime(1.5).unwrap().denoise);
|
||||
options.denoise = false;
|
||||
assert!(serde_json::to_value(&setup).unwrap()["job"]["options"].get("denoise").is_none());
|
||||
let default: CpuJob = serde_json::from_value(serde_json::json!({})).unwrap();
|
||||
let explicit: CpuJob = serde_json::from_value(serde_json::json!({"denoise":false})).unwrap();
|
||||
assert_eq!(default, explicit);
|
||||
assert!(!default.to_runtime(0.0).unwrap().denoise);
|
||||
assert!(serde_json::from_value::<CpuJob>(serde_json::json!({"denoise":"true"})).is_err());
|
||||
setup.width = 8193;
|
||||
setup.height = 1;
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") };
|
||||
options.budget = CpuBudget::Workstation;
|
||||
setup.validate().unwrap();
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") };
|
||||
options.denoise = true;
|
||||
assert!(setup.validate().unwrap_err().to_string().contains("CPU denoising"));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn composed_cpu_path_preserves_saved_optics_alpha_filter_lens_and_master_intent() {
|
||||
use crate::render_optics::{OpticalMaterial, SavedOptics};
|
||||
use crate::render_surface::RenderBodyTarget;
|
||||
use solidcraft_render::job::{CpuPathOptions, CpuProgressiveOptions, OutputOptions, ThinLens};
|
||||
let mut setup = RenderSetup {
|
||||
camera: Camera { fov: 0.6, distance: 123.0, ..Default::default() },
|
||||
width: 8,
|
||||
height: 8,
|
||||
job: Some(RenderJob::CpuRaytrace {
|
||||
transparent_background: true,
|
||||
options: Box::new(CpuJob {
|
||||
denoise: true,
|
||||
path: Some(CpuPathOptions { max_depth: 3 }),
|
||||
progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }),
|
||||
lens: Some(ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 123.0 }),
|
||||
output: Some(Box::new(OutputOptions { linear_exr: true, ..Default::default() })),
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
setup.validate().unwrap();
|
||||
setup
|
||||
.optics
|
||||
.set(
|
||||
SavedOptics {
|
||||
target: RenderBodyTarget { definition: "Glass".into(), feature: 1, component: 0, occurrence_path: Vec::new() },
|
||||
optics: OpticalMaterial::default(),
|
||||
},
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let before = setup.clone();
|
||||
setup.validate().unwrap();
|
||||
assert_eq!(setup, before, "validation must not lower or rewrite authored optics");
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU fixture") };
|
||||
options.path = None;
|
||||
setup.validate().unwrap();
|
||||
assert!(matches!(&setup.job, Some(RenderJob::CpuRaytrace { transparent_background:true, options })
|
||||
if options.denoise && options.output.as_ref().unwrap().linear_exr && options.lens.is_some()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn gpu_hard_directional_intent_roundtrips_and_hostile_lists_refuse_at_document_load() {
|
||||
use serde_json::json;
|
||||
let light = json!({"direction":[0.0,0.0,2.0],"color":[0.25,0.5,1.0],"intensity":0.0});
|
||||
let settings = json!({"setups":{"Lights":{"job":{"method":"gpu_path","options":{"lighting":{"directional_lights":vec![light.clone();8]}}}}}});
|
||||
let saved: RenderSettings = serde_json::from_value(settings.clone()).unwrap();
|
||||
let doc = crate::Document { render: std::sync::Arc::new(saved.clone()), ..Default::default() };
|
||||
assert_eq!(crate::Document::from_json(&doc.to_json()).unwrap(), doc);
|
||||
let encoded = serde_json::to_value(&saved).unwrap();
|
||||
assert_eq!(encoded["setups"]["Lights"]["job"]["options"]["lighting"]["directional_lights"], json!(vec![light.clone(); 8]));
|
||||
for list in [
|
||||
json!(vec![light.clone(); 9]),
|
||||
json!([{"direction":[0,0,0],"color":[1,1,1],"intensity":1}]),
|
||||
json!([{"direction":[0,0,1],"color":[1,1,1],"intensity":65}]),
|
||||
] {
|
||||
let mut bad = settings.clone();
|
||||
bad["setups"]["Lights"]["job"]["options"]["lighting"]["directional_lights"] = list;
|
||||
assert!(serde_json::from_value::<RenderSettings>(bad).is_err());
|
||||
}
|
||||
let mut over_combined = settings;
|
||||
over_combined["setups"]["Lights"]["job"]["options"]["lighting"]["sun"] =
|
||||
json!({"direction":[0,0,1],"angular_radius_rad":0.02,"radiance":[1,1,1]});
|
||||
assert!(serde_json::from_value::<RenderSettings>(over_combined.clone()).is_err());
|
||||
let mut document = serde_json::to_value(crate::Document::default()).unwrap();
|
||||
document["render"] = over_combined;
|
||||
assert!(crate::Document::from_json(&serde_json::to_string(&document).unwrap()).is_err());
|
||||
let old: RenderSettings = serde_json::from_value(json!({"setups":{"Old":{"job":{"method":"gpu_path","options":{}}}}})).unwrap();
|
||||
let Some(RenderJob::GpuPath { options, .. }) = &old.setups["Old"].job else { panic!("gpu job") };
|
||||
assert!(options.lighting.is_none());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn saved_cpu_aging_is_optional_bounded_and_preserves_stable_targets_without_runtime_ordinals() {
|
||||
use crate::render_aging::SavedAgingStack;
|
||||
use crate::render_surface::RenderBodyTarget;
|
||||
use solidcraft_render::job::aging::{AgingKind, AgingLayer};
|
||||
let old = CpuJob::default();
|
||||
assert!(serde_json::to_value(&old).unwrap().get("aging").is_none());
|
||||
let mut layers = SavedAgingStack::default();
|
||||
layers.push(AgingLayer::preset(AgingKind::Dust)).unwrap();
|
||||
let target = RenderBodyTarget { definition: "Aged panel".into(), feature: 19, component: 0, occurrence_path: Vec::new() };
|
||||
layers.get_mut(0).unwrap().target = Some(target.clone());
|
||||
let job = CpuJob { aging: layers.clone(), progressive: Some(Default::default()), denoise: true, ..Default::default() };
|
||||
job.validate(0.5).unwrap();
|
||||
assert!(job.to_runtime(0.5).unwrap_err().to_string().contains("stable occurrence"));
|
||||
let setup = RenderSetup {
|
||||
width: 8,
|
||||
height: 8,
|
||||
exposure_ev: 0.5,
|
||||
job: Some(RenderJob::CpuRaytrace { transparent_background: true, options: Box::new(job) }),
|
||||
..Default::default()
|
||||
};
|
||||
setup.validate().unwrap();
|
||||
let wire = serde_json::to_value(&setup).unwrap();
|
||||
assert_eq!(wire["job"]["options"]["aging"][0]["target"]["definition"], "Aged panel");
|
||||
assert!(wire["job"]["options"]["aging"][0]["target"].get("body_index").is_none());
|
||||
assert_eq!(serde_json::from_value::<RenderSetup>(wire.clone()).unwrap(), setup);
|
||||
let mut legacy = wire.clone();
|
||||
legacy["job"]["options"]["aging"][0]["target"] = serde_json::json!({"body_index":0,"body_name":"Aged panel"});
|
||||
assert!(serde_json::from_value::<RenderSetup>(legacy).unwrap_err().to_string().contains("explicit rebinding"));
|
||||
let mut nine = wire;
|
||||
nine["job"]["options"]["aging"] = serde_json::json!(vec![serde_json::json!({}); 9]);
|
||||
assert!(serde_json::from_value::<RenderSetup>(nine).is_err());
|
||||
layers.get_mut(0).unwrap().target = None;
|
||||
let runtime = CpuJob { aging: layers, ..Default::default() }.to_runtime(0.5).unwrap();
|
||||
assert!(runtime.aging.unwrap().active());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cpu_adaptive_saved_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions};
|
||||
#[test]
|
||||
fn saved_cpu_adaptive_intent_roundtrips_offline_and_pays_pilots_inside_the_existing_profile() {
|
||||
let setup: RenderSetup = serde_json::from_value(json!({"width":128,"height":64,
|
||||
"job":{"method":"cpu_raytrace","transparent_background":true,"options":{
|
||||
"progressive":{"samples_per_pixel":48,"seed":81},"adaptive":{"pilot_samples":16,"min_samples":16},
|
||||
"denoise":true,"path":{"max_depth":3},"output":{"linear_exr":true}}}}))
|
||||
.unwrap();
|
||||
setup.validate().unwrap();
|
||||
let value = serde_json::to_value(&setup).unwrap();
|
||||
assert_eq!(serde_json::from_value::<RenderSetup>(value.clone()).unwrap(), setup);
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = setup.job.as_ref() else { panic!("CPU job expected") };
|
||||
let runtime = options.to_runtime(0.0).unwrap();
|
||||
assert_eq!(runtime.adaptive.as_deref().copied(), options.adaptive);
|
||||
assert_eq!(runtime.preview_target().unwrap(), 64);
|
||||
assert_eq!(runtime.camera_sampling().unwrap(), Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 81 }));
|
||||
let mut too_large = setup.clone();
|
||||
too_large.width = 1024;
|
||||
too_large.height = 1024;
|
||||
assert!(too_large.validate().is_err(), "64 total passes exceed Compact's existing camera-sample bound");
|
||||
let mut cap = value.clone();
|
||||
cap["job"]["options"]["progressive"]["samples_per_pixel"] = json!(64);
|
||||
assert!(
|
||||
serde_json::from_value::<RenderSetup>(cap).unwrap().validate().is_err(),
|
||||
"16 pilots cannot be hidden outside Compact's 64-sample cap"
|
||||
);
|
||||
for (budget, maximum) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 4096)] {
|
||||
let mut runtime = runtime.clone();
|
||||
runtime.budget = budget;
|
||||
runtime.progressive = Some(CpuProgressiveOptions { samples_per_pixel: maximum - 16, seed: 81 });
|
||||
assert_eq!(runtime.preview_target().unwrap(), maximum);
|
||||
runtime.progressive.as_mut().unwrap().samples_per_pixel += 1;
|
||||
assert!(runtime.validate().is_err(), "{budget:?} must include the pilot stage in its unchanged cap");
|
||||
}
|
||||
let mut fixed = value.clone();
|
||||
fixed["job"]["options"].as_object_mut().unwrap().remove("progressive");
|
||||
assert!(serde_json::from_value::<RenderSetup>(fixed).unwrap().validate().is_err());
|
||||
let mut hostile = value;
|
||||
hostile["job"]["options"]["adaptive"]["certified_convergence"] = json!(true);
|
||||
assert!(serde_json::from_value::<RenderSetup>(hostile).is_err());
|
||||
let old = serde_json::to_value(CpuJob::default()).unwrap();
|
||||
assert!(old.get("adaptive").is_none(), "default-absent saved jobs keep their prior schema bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod saved_coat_tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
Document,
|
||||
render_coat::{CoatMaterial, SavedCoat},
|
||||
render_surface::RenderBodyTarget,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn target(feature: u64) -> RenderBodyTarget {
|
||||
RenderBodyTarget { definition: format!("Coated{feature}"), feature, component: 0, occurrence_path: vec![] }
|
||||
}
|
||||
fn document(gpu: bool) -> Document {
|
||||
let mut doc = Document::default();
|
||||
let job = if gpu {
|
||||
RenderJob::GpuPath { transparent_background: false, options: Default::default() }
|
||||
} else {
|
||||
RenderJob::CpuRaytrace { transparent_background: false, options: Default::default() }
|
||||
};
|
||||
Arc::make_mut(&mut doc.render).setups.insert("Coated".into(), RenderSetup { width: 8, height: 8, job: Some(job), ..Default::default() });
|
||||
doc
|
||||
}
|
||||
#[test]
|
||||
fn saved_coat_document_roundtrip_preserves_every_number_and_old_omission_for_both_methods() {
|
||||
for gpu in [false, true] {
|
||||
let mut doc = document(gpu);
|
||||
let old = doc.to_json();
|
||||
let old_value: Value = serde_json::from_str(&old).unwrap();
|
||||
assert!(old_value["render"]["setups"]["Coated"].get("coats").is_none());
|
||||
assert_eq!(Document::from_json(&old).unwrap().to_json(), old);
|
||||
let coat = CoatMaterial { weight: -0.0, roughness: 0.22, ior: 1.74 };
|
||||
Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap().coats.set(SavedCoat { target: target(1), coat }, false).unwrap();
|
||||
let encoded = doc.to_json();
|
||||
let loaded = Document::from_json(&encoded).unwrap();
|
||||
assert_eq!(loaded.render, doc.render);
|
||||
let saved = loaded.render.setups["Coated"].coats.iter().next().unwrap();
|
||||
assert_eq!(saved.coat, coat);
|
||||
assert_eq!(saved.coat.weight.to_bits(), (-0.0_f64).to_bits());
|
||||
let wire = serde_json::to_value(saved).unwrap();
|
||||
assert!(wire.get("body_index").is_none() && wire.get("body_name").is_none());
|
||||
assert!(wire["target"].get("feature").is_some());
|
||||
let setup = Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap();
|
||||
let changed = SavedCoat { target: target(1), coat: CoatMaterial { weight: 0.0, ..coat } };
|
||||
assert!(setup.coats.set(changed.clone(), false).is_err(), "authored signed zero is not silently replaced");
|
||||
setup.coats.set(changed, true).unwrap();
|
||||
assert_eq!(setup.coats.iter().next().unwrap().coat.weight.to_bits(), 0.0_f64.to_bits());
|
||||
assert!(setup.coats.remove(&target(1)));
|
||||
assert_eq!(doc.to_json(), old, "removing the only coat restores exact legacy document bytes");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn malformed_saved_coats_refuse_through_the_full_document_loader() {
|
||||
let mut doc = document(false);
|
||||
Arc::make_mut(&mut doc.render)
|
||||
.setups
|
||||
.get_mut("Coated")
|
||||
.unwrap()
|
||||
.coats
|
||||
.set(SavedCoat { target: target(1), coat: Default::default() }, false)
|
||||
.unwrap();
|
||||
let base: Value = serde_json::from_str(&doc.to_json()).unwrap();
|
||||
for (key, value) in
|
||||
[("weight", json!(-0.01)), ("weight", json!(1.01)), ("roughness", json!(0.02)), ("ior", json!(3.01)), ("unknown", json!(true))]
|
||||
{
|
||||
let mut bad = base.clone();
|
||||
bad["render"]["setups"]["Coated"]["coats"][0]["coat"][key] = value;
|
||||
assert!(Document::from_json(&bad.to_string()).is_err(), "invalid coat {key}");
|
||||
}
|
||||
let mut duplicate = base.clone();
|
||||
let row = duplicate["render"]["setups"]["Coated"]["coats"][0].clone();
|
||||
duplicate["render"]["setups"]["Coated"]["coats"] = json!([row, row]);
|
||||
assert!(Document::from_json(&duplicate.to_string()).is_err());
|
||||
for key in ["body_index", "runtime_path"] {
|
||||
let mut bad = base.clone();
|
||||
bad["render"]["setups"]["Coated"]["coats"][0][key] = json!(0);
|
||||
assert!(Document::from_json(&bad.to_string()).is_err());
|
||||
}
|
||||
let mut too_many = base;
|
||||
too_many["render"]["setups"]["Coated"]["coats"] =
|
||||
json!((1..=65).map(|feature| SavedCoat { target: target(feature), coat: Default::default() }).collect::<Vec<_>>());
|
||||
assert!(Document::from_json(&too_many.to_string()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn saved_coat_uses_existing_sixty_four_target_bound_and_rejects_glass_even_at_zero_weight() {
|
||||
use crate::render_optics::{OpticalMaterial, SavedOptics};
|
||||
for gpu in [false, true] {
|
||||
let mut doc = document(gpu);
|
||||
let setup = Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap();
|
||||
for feature in 1..=64 {
|
||||
setup.coats.set(SavedCoat { target: target(feature), coat: CoatMaterial { weight: 0.0, ..Default::default() } }, false).unwrap();
|
||||
}
|
||||
setup.validate().unwrap();
|
||||
assert_eq!(setup.coats.len(), 64);
|
||||
let before = setup.coats.clone();
|
||||
assert!(setup.coats.set(SavedCoat { target: target(65), coat: Default::default() }, false).is_err());
|
||||
assert_eq!(setup.coats, before);
|
||||
setup.optics.set(SavedOptics { target: target(1), optics: OpticalMaterial::default() }, false).unwrap();
|
||||
assert!(setup.validate().unwrap_err().to_string().contains("cannot share"));
|
||||
setup.optics.remove(&target(1));
|
||||
setup.job = Some(RenderJob::Raster { transparent_background: false });
|
||||
assert!(setup.validate().unwrap_err().to_string().contains("raytrace"));
|
||||
assert_eq!(setup.coats, before, "unsupported method retains all authored rows");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cpu_celestial_saved_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
#[test]
|
||||
fn saved_cpu_finite_sun_and_sky_roundtrip_exactly_and_require_explicit_path() {
|
||||
let value = json!({"width":16,"height":12,"job":{"method":"cpu_raytrace","transparent_background":true,"options":{
|
||||
"path":{"max_depth":4},"progressive":{"samples_per_pixel":32,"seed":81},"adaptive":{"pilot_samples":16,"min_samples":16},
|
||||
"sun":{"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.02,"radiance":[301.25,202.5,103.75]},
|
||||
"sky":{"kind":"sky","gradient":{"zenith":[0.25,0.5,1.0],"horizon":[0.75,0.5,0.25],"ground":[0.125,0.25,0.5]},"rotation_rad":0.731,"intensity":75},
|
||||
"denoise":true,"output":{"linear_exr":true},"lights":[]}}});
|
||||
let setup: RenderSetup = serde_json::from_value(value.clone()).unwrap();
|
||||
setup.validate().unwrap();
|
||||
let wire = serde_json::to_value(&setup).unwrap();
|
||||
assert_eq!(serde_json::from_value::<RenderSetup>(wire.clone()).unwrap(), setup);
|
||||
let Some(RenderJob::CpuRaytrace { options, .. }) = &setup.job else { panic!("CPU expected") };
|
||||
let runtime = options.to_runtime(0.0).unwrap();
|
||||
assert_eq!(runtime.sun.as_deref().copied(), options.sun);
|
||||
assert_eq!(runtime.sky.as_deref().unwrap().intensity, 75.0);
|
||||
assert_eq!(runtime.sky.as_deref().unwrap().rotation_rad, 0.731);
|
||||
for (field, replacement) in [
|
||||
("path", serde_json::Value::Null),
|
||||
("sun", json!({"direction":[0,0,1],"angular_radius_rad":0,"radiance":[1,1,1]})),
|
||||
("environment", json!({"color":[1,1,1],"intensity":1})),
|
||||
] {
|
||||
let mut invalid = wire.clone();
|
||||
invalid["job"]["options"][field] = replacement;
|
||||
assert!(serde_json::from_value::<RenderSetup>(invalid).unwrap().validate().is_err(), "{field} must not be silently replaced");
|
||||
}
|
||||
for (field, value) in [("intensity", json!(100.001)), ("rotation_rad", json!(1e6 + 1.0))] {
|
||||
let mut invalid = wire.clone();
|
||||
invalid["job"]["options"]["sky"][field] = value;
|
||||
assert!(serde_json::from_value::<RenderSetup>(invalid).unwrap().validate().is_err());
|
||||
}
|
||||
let defaults = serde_json::to_value(CpuJob::default()).unwrap();
|
||||
assert!(defaults.get("sun").is_none() && defaults.get("sky").is_none());
|
||||
}
|
||||
}
|
||||
@@ -315,4 +315,66 @@ mod tests {
|
||||
target.occurrence_path = vec![2, 2];
|
||||
assert!(target.validate().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn saved_cpu_surface_maps_roundtrip_for_opaque_direct_and_path_and_preserve_unsupported_intent() {
|
||||
use crate::render_settings::{CpuJob, RenderJob, RenderSetup};
|
||||
let mut options = CpuJob::default();
|
||||
let mut setup = RenderSetup {
|
||||
job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) }),
|
||||
..Default::default()
|
||||
};
|
||||
setup.surfaces.set(fixture(), false).unwrap();
|
||||
setup.validate().unwrap();
|
||||
let mut direct_document = crate::Document::default();
|
||||
std::sync::Arc::make_mut(&mut direct_document.render).setups.insert("Maps".into(), setup.clone());
|
||||
assert_eq!(crate::Document::from_json(&direct_document.to_json()).unwrap(), direct_document);
|
||||
options.progressive = Some(solidcraft_render::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 9 });
|
||||
options.shadows = true;
|
||||
options.path = Some(solidcraft_render::job::CpuPathOptions { max_depth: 3 });
|
||||
setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) });
|
||||
setup.validate().unwrap();
|
||||
let mut document = crate::Document::default();
|
||||
std::sync::Arc::make_mut(&mut document.render).setups.insert("Maps".into(), setup.clone());
|
||||
assert_eq!(crate::Document::from_json(&document.to_json()).unwrap(), document);
|
||||
options.path = None;
|
||||
let saved_options_wire = serde_json::to_value(&options).unwrap();
|
||||
let mut runtime = options.to_runtime(0.0).unwrap();
|
||||
runtime.reflections = Some(solidcraft_render::job::ReflectionOptions {
|
||||
bodies: vec![solidcraft_render::job::ReflectionBody { body: "Panel".into(), mode: solidcraft_render::job::ReflectionMode::Mirror }],
|
||||
samples: 1,
|
||||
max_bounces: 2,
|
||||
});
|
||||
runtime.validate().unwrap();
|
||||
let runtime_wire = serde_json::to_value(&runtime).unwrap();
|
||||
let error = solidcraft_render::job::textures::validate_cpu_options(&runtime).unwrap_err();
|
||||
assert!(error.message.contains("selected reflections"));
|
||||
assert_eq!(serde_json::to_value(&runtime).unwrap(), runtime_wire, "map refusal preserves the exact runtime selected override");
|
||||
assert_eq!(serde_json::to_value(&options).unwrap(), saved_options_wire, "runtime overrides do not rewrite saved CPU fields");
|
||||
setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) });
|
||||
setup.validate().unwrap();
|
||||
let mut unknown = serde_json::to_value(&setup).unwrap();
|
||||
unknown["job"]["options"]["reflections"] = serde_json::to_value(&runtime.reflections).unwrap();
|
||||
let error = serde_json::from_value::<RenderSetup>(unknown).unwrap_err();
|
||||
assert!(error.to_string().contains("reflections"), "saved CPU intent must not silently discard runtime-only selected overrides");
|
||||
// Prove the saved field is supported in fixed mode before checking
|
||||
// its incompatibility with still-authored progressive sampling.
|
||||
let mut fixed = options.clone();
|
||||
fixed.progressive = None;
|
||||
fixed.primary_samples = 4;
|
||||
fixed.validate_surface_maps(0.0).unwrap();
|
||||
let surfaces = setup.surfaces.clone();
|
||||
options.primary_samples = 4;
|
||||
setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options) });
|
||||
let wire = serde_json::to_value(&setup).unwrap();
|
||||
assert!(setup.validate().unwrap_err().to_string().contains("CPU progressive requires"));
|
||||
assert_eq!(serde_json::to_value(&setup).unwrap(), wire);
|
||||
assert_eq!(setup.surfaces, surfaces);
|
||||
assert_eq!(setup.surfaces.len(), 1);
|
||||
for job in [None, Some(RenderJob::Raster { transparent_background: false })] {
|
||||
setup.job = job;
|
||||
assert!(setup.validate().is_err());
|
||||
assert_eq!(setup.surfaces, surfaces);
|
||||
assert_eq!(setup.surfaces.len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+374
-9
@@ -123,7 +123,212 @@ fn planar_region(region: &Region2) -> Result<Region2> {
|
||||
region_complexity(std::slice::from_ref(region))?;
|
||||
// Free-form loops stay exact: the planar booleans follow them with arcs and hand a loop
|
||||
// they leave whole its exact segments back.
|
||||
Ok(Region2 { outer: region.outer.ccw(), holes: region.holes.iter().map(|h| h.ccw().reversed()).collect() })
|
||||
Ok(Region2 { outer: without_hairs(region.outer.ccw()), holes: region.holes.iter().map(|h| without_hairs(h.ccw().reversed())).collect() })
|
||||
}
|
||||
|
||||
/// Edges shorter than this (mm) are no edges to the planar booleans: SMLib refuses a face whose
|
||||
/// loop has one ("status 1001", measured up to 1e-5 mm; 4e-5 mm passes). They come from an
|
||||
/// outline with a corner a hair beside a bend zone's edge, split there. Below 0.1 µm: a ledge
|
||||
/// 0.1 µm tall beside a flange's setback stays a sliver of the base.
|
||||
const HAIR: f64 = 5e-5;
|
||||
|
||||
/// `region` with each corner that lies within [`HAIR`] of a bend zone's straight edge
|
||||
/// (`seams`: a point and a unit direction each), but not on it, moved onto it: the straight edges
|
||||
/// meeting there move that end, an arc meeting there moves whole with its centre (and the edge
|
||||
/// beyond it then moves that end too). A cut-out whose edge stops a hair short of a bend line, or
|
||||
/// a hair past it, or whose rounded corner ends there, otherwise leaves a sliver of a face that
|
||||
/// thin along the line, whose edges the sew cannot tell apart ("ambiguous edge contact"); the
|
||||
/// cut moves by under 0.05 µm.
|
||||
fn onto_seams(region: Region2, seams: &[(Vec2, Vec2)]) -> Region2 {
|
||||
if seams.is_empty() {
|
||||
return region;
|
||||
}
|
||||
let off = |p: Vec2, (o, d): (Vec2, Vec2)| (p - o).cross(d);
|
||||
let snap_loop = |mut lp: Loop2| -> Loop2 {
|
||||
let n = lp.segs.len();
|
||||
if n < 2 {
|
||||
return lp;
|
||||
}
|
||||
for j in 0..n {
|
||||
let prev = (j + n - 1) % n;
|
||||
let (Some(p), Some(q)) = (lp.segs.get(j).and_then(seg_start), lp.segs.get(prev).and_then(seg_end)) else { continue };
|
||||
if p.dist(q) > LINEAR_TOL {
|
||||
continue;
|
||||
}
|
||||
let Some(&(o, d)) = seams.iter().find(|&&s| off(p, s) != 0.0 && off(p, s).abs() < HAIR) else { continue };
|
||||
let delta = o + d * (p - o).dot(d) - p;
|
||||
if let Some(segs) = shifted(&lp.segs, j, delta) {
|
||||
lp.segs = segs;
|
||||
}
|
||||
}
|
||||
lp
|
||||
};
|
||||
Region2 { outer: snap_loop(region.outer), holes: region.holes.into_iter().map(snap_loop).collect() }
|
||||
}
|
||||
|
||||
/// `segs` (a closed loop) with the corner where segment `j` starts moved by `delta`: a line
|
||||
/// meeting there moves that end, an arc moves whole and passes the move on to the corner at its
|
||||
/// other end. None when a curve that cannot move so meets the move, or the move goes round the
|
||||
/// whole loop.
|
||||
fn shifted(segs: &[Seg2], j: usize, delta: Vec2) -> Option<Vec<Seg2>> {
|
||||
let n = segs.len();
|
||||
let mut out = segs.to_vec();
|
||||
let mut moved = 0;
|
||||
// forward from j (moving starts), then backward from the segment before j (moving ends)
|
||||
for forward in [true, false] {
|
||||
let mut k = if forward { j } else { (j + n - 1) % n };
|
||||
loop {
|
||||
moved += 1;
|
||||
if moved > n {
|
||||
return None;
|
||||
}
|
||||
match out.get(k).copied()? {
|
||||
Seg2::Line { a, b } => {
|
||||
out[k] = if forward { Seg2::Line { a: a + delta, b } } else { Seg2::Line { a, b: b + delta } };
|
||||
break;
|
||||
}
|
||||
Seg2::Arc { center, radius, start, sweep } => {
|
||||
out[k] = Seg2::Arc { center: center + delta, radius, start, sweep };
|
||||
k = if forward { (k + 1) % n } else { (k + n - 1) % n };
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn seg_start(s: &Seg2) -> Option<Vec2> {
|
||||
match *s {
|
||||
Seg2::Line { a, .. } => Some(a),
|
||||
Seg2::Arc { center, radius, start, .. } => Some(center + Vec2::new(start.cos(), start.sin()) * radius),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn seg_end(s: &Seg2) -> Option<Vec2> {
|
||||
match *s {
|
||||
Seg2::Line { b, .. } => Some(b),
|
||||
Seg2::Arc { center, radius, start, sweep } => Some(center + Vec2::new((start + sweep).cos(), (start + sweep).sin()) * radius),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a cut-out's outline encloses some area: a sliver there and back, or points on a
|
||||
/// line, cuts nothing, and SMLib's face builder refuses it (status 1001).
|
||||
fn encloses_area(r: &Region2) -> bool {
|
||||
r.outer.signed_area().abs() > 1e-9
|
||||
}
|
||||
|
||||
/// [`kernel::extrude_planar_regions`] of `regions` with their loops [`welded`] first.
|
||||
fn extrude_flat(plane: &Plane, regions: &[Region2], z0: f64, z1: f64) -> kernel::Result<Body> {
|
||||
kernel::extrude_planar_regions(plane, welded_regions(regions).as_ref(), z0, z1)
|
||||
}
|
||||
|
||||
/// `regions` with their loops [`welded`], borrowed when every loop is closed already.
|
||||
fn welded_regions(regions: &[Region2]) -> std::borrow::Cow<'_, [Region2]> {
|
||||
let open = |lp: &Loop2| lp.segs.iter().zip(lp.segs.iter().cycle().skip(1)).any(|(p, q)| p.end().dist(q.start()) > NOISE);
|
||||
if !regions.iter().any(|r| open(&r.outer) || r.holes.iter().any(open)) {
|
||||
return std::borrow::Cow::Borrowed(regions);
|
||||
}
|
||||
std::borrow::Cow::Owned(
|
||||
regions.iter().map(|r| Region2 { outer: welded(r.outer.clone()), holes: r.holes.iter().cloned().map(welded).collect() }).collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Gaps up to this (mm) are rounding, not gaps: left as they are, so a loop and its mirror image
|
||||
/// keep their exact mirror coordinates.
|
||||
const NOISE: f64 = 1e-9;
|
||||
|
||||
/// `lp` with each gap between [`NOISE`] and [`HAIR`] between a segment's end and the next one's start closed:
|
||||
/// the next segment starts where the last ends, or the last ends where the next starts when the
|
||||
/// next is an arc (whose ends do not move without its centre). The planar booleans close a loop
|
||||
/// only within 1 nm; a free-form outline the flat pattern was made of (a torn fold's) came out
|
||||
/// of them with its pieces 14 nm apart, which a following boolean refused.
|
||||
fn welded(mut lp: Loop2) -> Loop2 {
|
||||
let n = lp.segs.len();
|
||||
let moved = |s: Seg2, start: bool, to: Vec2| -> Option<Seg2> {
|
||||
Some(match s {
|
||||
Seg2::Line { a, b } => {
|
||||
if start {
|
||||
Seg2::Line { a: to, b }
|
||||
} else {
|
||||
Seg2::Line { a, b: to }
|
||||
}
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
if start {
|
||||
Seg2::Cubic { p0: to, p1, p2, p3 }
|
||||
} else {
|
||||
Seg2::Cubic { p0, p1, p2, p3: to }
|
||||
}
|
||||
}
|
||||
Seg2::Conic { a, apex, b, w } => {
|
||||
if start {
|
||||
Seg2::Conic { a: to, apex, b, w }
|
||||
} else {
|
||||
Seg2::Conic { a, apex, b: to, w }
|
||||
}
|
||||
}
|
||||
Seg2::Bezier { n: deg, mut p } => {
|
||||
let k = if start { 0 } else { usize::from(deg) };
|
||||
*p.get_mut(k)? = to;
|
||||
Seg2::Bezier { n: deg, p }
|
||||
}
|
||||
Seg2::Arc { .. } => return None,
|
||||
})
|
||||
};
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
let (Some(&p), Some(&q)) = (lp.segs.get(i), lp.segs.get(j)) else { continue };
|
||||
let gap = p.end().dist(q.start());
|
||||
if gap <= NOISE || gap >= HAIR {
|
||||
continue;
|
||||
}
|
||||
if let Some(q2) = moved(q, true, p.end()).filter(|s| s.length() >= HAIR) {
|
||||
lp.segs[j] = q2;
|
||||
} else if let Some(p2) = moved(p, false, q.start()).filter(|s| s.length() >= HAIR) {
|
||||
lp.segs[i] = p2;
|
||||
}
|
||||
}
|
||||
lp
|
||||
}
|
||||
|
||||
/// `lp` without its hair edges (shorter than [`HAIR`]): the line the hair runs on from takes it,
|
||||
/// so the corners at the hair's other end stay where they are (an outline split at a bend zone's
|
||||
/// edge keeps its corner on that edge, which the zone shares). A hair at a corner goes to the
|
||||
/// line after it. A hair between two curves stays.
|
||||
fn without_hairs(lp: Loop2) -> Loop2 {
|
||||
let n = lp.segs.len();
|
||||
if n <= 3 || !lp.segs.iter().any(|s| s.length() < HAIR) {
|
||||
return lp;
|
||||
}
|
||||
let along = |line: &Seg2, hair: &Seg2| match (line, (hair.end() - hair.start()).normalized()) {
|
||||
(Seg2::Line { a, b }, Some(d)) => (*b - *a).normalized().is_some_and(|u| u.cross(d).abs() < 1e-3 && u.dot(d) > 0.0),
|
||||
_ => false,
|
||||
};
|
||||
let mut segs = lp.segs;
|
||||
let mut i = 0;
|
||||
while i < segs.len() && segs.len() > 3 {
|
||||
let Some(hair) = segs.get(i).copied().filter(|s| s.length() < HAIR) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
let m = segs.len();
|
||||
let (prev, next) = ((i + m - 1) % m, (i + 1) % m);
|
||||
let prev_takes = segs.get(prev).is_some_and(|p| along(p, &hair)) && !segs.get(next).is_some_and(|q| along(q, &hair));
|
||||
match (prev_takes, segs.get(prev).copied(), segs.get(next).copied()) {
|
||||
(true, Some(Seg2::Line { a, .. }), _) => segs[prev] = Seg2::Line { a, b: hair.end() },
|
||||
(_, _, Some(Seg2::Line { b, .. })) => segs[next] = Seg2::Line { a: hair.start(), b },
|
||||
(_, Some(Seg2::Line { a, .. }), _) => segs[prev] = Seg2::Line { a, b: hair.end() },
|
||||
_ => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
segs.remove(i);
|
||||
}
|
||||
Loop2 { segs }
|
||||
}
|
||||
|
||||
fn region_complexity(regions: &[Region2]) -> Result<(usize, usize)> {
|
||||
@@ -198,7 +403,8 @@ pub(crate) fn material_boolean(a: &[Region2], b: &[Region2], op: kernel::BoolOp,
|
||||
let (be, bp) = region_complexity(b)?;
|
||||
let edges = ae.saturating_add(be);
|
||||
work.charge(edges.saturating_mul(edges).saturating_add(edges.saturating_mul(ap.saturating_add(bp))).saturating_mul(8))?;
|
||||
let regions = kernel::planar_regions_boolean(a, b, op, 1e-7)?;
|
||||
let (a, b) = (welded_regions(a), welded_regions(b));
|
||||
let regions = kernel::planar_regions_boolean(a.as_ref(), b.as_ref(), op, 1e-7)?;
|
||||
region_complexity(®ions)?;
|
||||
Ok(regions)
|
||||
}
|
||||
@@ -1411,6 +1617,23 @@ impl SheetBody {
|
||||
(-f.ext.0 - f.slope.0 * f.leg, f.len + f.ext.1 + f.slope.1 * f.leg)
|
||||
}
|
||||
|
||||
/// The straight edges of the bend zones that run along their bends, as a point and a unit
|
||||
/// direction each: the lines where the folded solid's faces change from a panel to a bend.
|
||||
fn seams(&self) -> Vec<(Vec2, Vec2)> {
|
||||
let mut out = Vec::new();
|
||||
for f in &self.flanges {
|
||||
let Some(d) = f.d.normalized() else { continue };
|
||||
for e in &self.zone(f).outer.segs {
|
||||
if let Seg2::Line { a, b } = *e
|
||||
&& (b - a).normalized().is_some_and(|u| u.cross(d).abs() < 1e-9)
|
||||
{
|
||||
out.push((a, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Flat region of a flange's bend zone: square across the bend at both ends, but at a torn
|
||||
/// end its far edge ends where the panel's does.
|
||||
pub fn zone(&self, f: &SheetFlange) -> Region2 {
|
||||
@@ -1720,8 +1943,9 @@ impl SheetBody {
|
||||
// their fitted arcs there (the flat pattern keeps them exact).
|
||||
let mut cuts = Vec::new();
|
||||
let mut cut_points = 0usize;
|
||||
for hole in &self.holes {
|
||||
let region = fitted_region(&planar_region(hole)?)?;
|
||||
let seams = self.seams();
|
||||
for hole in self.holes.iter().filter(|h| encloses_area(h)) {
|
||||
let region = fitted_region(&onto_seams(planar_region(hole)?, &seams))?;
|
||||
cut_points = cut_points.saturating_add(region_complexity(std::slice::from_ref(®ion))?.1);
|
||||
if cut_points > MAX_FLAT_POINTS {
|
||||
return Err(flat_budget_error());
|
||||
@@ -1969,7 +2193,7 @@ impl SheetBody {
|
||||
let mut local = self.clone();
|
||||
local.frame = Plane::XY;
|
||||
local.flat = true;
|
||||
let body = kernel::extrude_planar_regions(&Plane::XY, ®ions, 0.0, self.t)?;
|
||||
let body = extrude_flat(&Plane::XY, ®ions, 0.0, self.t)?;
|
||||
let mut work = FlatWork::new();
|
||||
let body = local.machine_pockets(body, &mut work)?;
|
||||
let body = local.machine_bores(body, &mut work)?;
|
||||
@@ -2059,7 +2283,7 @@ impl SheetBody {
|
||||
work.charge(100_000)?;
|
||||
// The bore's own panel, flat: the bore never reaches a bend or another panel, in
|
||||
// the folded part or in its flat pattern.
|
||||
let slab = kernel::extrude_planar_regions(&Plane::XY, &cells, 0.0, self.t)?;
|
||||
let slab = extrude_flat(&Plane::XY, &cells, 0.0, self.t)?;
|
||||
let drill = kernel::cylinder(bore.base, bore.axis, bore.radius, bore.height)?;
|
||||
let Some(inside) = kernel::boolean(&drill, &slab, kernel::BoolOp::Intersect)? else { continue };
|
||||
// Cut with the drill clipped to the panel, its ends flush with the panel's rims.
|
||||
@@ -2093,7 +2317,7 @@ impl SheetBody {
|
||||
outer: Loop2 { segs: cell.outer.clone() },
|
||||
holes: cell.holes.iter().map(|h| Loop2 { segs: h.clone() }).collect(),
|
||||
})?;
|
||||
kernel::extrude_planar_regions(&self.frame, &[region], 0.0, self.t)?
|
||||
extrude_flat(&self.frame, &[region], 0.0, self.t)?
|
||||
} else {
|
||||
kernel::sew_touching(&self.faces(std::slice::from_ref(&cell), 0.0, self.t, &mut work)?)?
|
||||
};
|
||||
@@ -2195,7 +2419,7 @@ impl SheetBody {
|
||||
let plane = plane_of(&w, Vec3::ZERO, Vec3::X, Vec3::Y)?;
|
||||
// BRep replay is costlier than planar clipping; share the command budget.
|
||||
work.charge(100_000)?;
|
||||
let tool = kernel::extrude_planar_regions(&plane, &clipped, pocket.z0, pocket.z1)?;
|
||||
let tool = extrude_flat(&plane, &clipped, pocket.z0, pocket.z1)?;
|
||||
body = kernel::boolean(&body, &tool, kernel::BoolOp::Cut)?
|
||||
.ok_or_else(|| DocError::Invalid("sheet pocket removes all sheet material".into()))?;
|
||||
}
|
||||
@@ -2388,7 +2612,7 @@ impl SheetBody {
|
||||
let regions = material_union(regions, &mut work)?;
|
||||
let mut cuts = Vec::new();
|
||||
let mut cut_points = 0usize;
|
||||
for hole in &self.holes {
|
||||
for hole in self.holes.iter().filter(|h| encloses_area(h)) {
|
||||
let region = planar_region(hole)?;
|
||||
cut_points = cut_points.saturating_add(region_complexity(std::slice::from_ref(®ion))?.1);
|
||||
if cut_points > MAX_FLAT_POINTS {
|
||||
@@ -6770,6 +6994,147 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A notch cut from the flat whose edge along the bend lies a hair (0.01 µm to 10 µm) before
|
||||
/// or past a bend zone's edge, on either side of the zone: it refolds into one valid solid,
|
||||
/// as on the line and clearly away from it. The sliver it left between the cut and the
|
||||
/// zone failed to sew ("ambiguous edge contact").
|
||||
#[test]
|
||||
fn a_notch_edge_a_hair_beside_a_bend_zone_edge_refolds() {
|
||||
let rule = RuleValues { bend_radius: 2.0, ..alu() };
|
||||
let outline = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 40.0), Vec2::new(0.0, 40.0)];
|
||||
let mut s = base_flange("Body1", "AL2", &rule, Plane::XY, Region2 { outer: Loop2::polygon(&outline).ccw(), holes: vec![] });
|
||||
s.add_flange(Vec3::new(50.0, 40.0, 2.0), 30.0, std::f64::consts::FRAC_PI_2, 2.0, "inside", false).unwrap();
|
||||
let f = s.flanges[0].clone();
|
||||
let ba = s.allowance(&f);
|
||||
let v0 = vol(&s.solid().unwrap());
|
||||
for (side, line) in [("panel", 0.0), ("flange", ba)] {
|
||||
for off in [0.0, 1e-8, -1e-8, 1.6e-7, -1.6e-7, 1e-5, -1e-5, 0.01, -0.01] {
|
||||
let what = format!("notch on the {side} side, {off} mm beside the zone edge");
|
||||
// The notch runs 20 along the bend from its start, from the zone edge outwards.
|
||||
let edge = line + off;
|
||||
let out = if side == "panel" { -10.0 } else { ba + 40.0 };
|
||||
let (a, b) = (f.p - f.d * 5.0, f.p + f.d * 20.0);
|
||||
let notch = Loop2::polygon(&[a + f.n * edge, b + f.n * edge, b + f.n * out, a + f.n * out]).ccw();
|
||||
let mut cut = s.clone();
|
||||
cut.holes.push(Region2 { outer: notch, holes: vec![] });
|
||||
let body = cut.solid().unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert!(body.validity().is_empty(), "{what}: {:?}", body.validity());
|
||||
assert!(vol(&body) < v0 - 1.0, "{what}: {} vs {v0}", vol(&body));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A loop whose pieces are 14 nm apart (as the planar booleans hand back a torn fold's
|
||||
/// free-form outline) is closed before it is extruded: each segment starts where the one
|
||||
/// before ends, and the plate comes out with the loop's area.
|
||||
#[test]
|
||||
fn a_loop_with_gaps_under_a_hair_is_welded_before_it_is_extruded() {
|
||||
let g = 1.4e-5;
|
||||
let lp = Loop2 {
|
||||
segs: vec![
|
||||
Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) },
|
||||
Seg2::Line { a: Vec2::new(10.0 + g, g), b: Vec2::new(10.0, 10.0) },
|
||||
Seg2::Arc { center: Vec2::new(5.0, 10.0), radius: 5.0, start: 0.0, sweep: std::f64::consts::PI },
|
||||
Seg2::Line { a: Vec2::new(-g, 10.0), b: Vec2::new(0.0, g) },
|
||||
],
|
||||
};
|
||||
let closed = welded(lp.clone());
|
||||
for (p, q) in closed.segs.iter().zip(closed.segs.iter().cycle().skip(1)) {
|
||||
assert_eq!(p.end().dist(q.start()), 0.0, "{p:?} then {q:?}");
|
||||
}
|
||||
let body = extrude_flat(&Plane::XY, &[Region2 { outer: lp, holes: Vec::new() }], 0.0, 2.0).unwrap_or_else(|e| panic!("{e}"));
|
||||
let area = 100.0 + std::f64::consts::PI * 12.5;
|
||||
let volume = body.volume_at(1e-6).unwrap_or(f64::NAN);
|
||||
assert!((volume - 2.0 * area).abs() < 1e-3, "{volume} vs {}", 2.0 * area);
|
||||
}
|
||||
|
||||
/// A rectangle whose outline has an extra vertex on its edge a hair (to 0.01 µm) from where a
|
||||
/// fold's bend zone ends, folded 90° along a line: the flat pattern and the folded solid build,
|
||||
/// as without the vertex. Split there, the panel's loop kept an edge of the hair's length,
|
||||
/// which SMLib's face builder refuses ("SMLib failed (status 1001)").
|
||||
#[test]
|
||||
fn an_outline_vertex_a_hair_from_a_bend_zone_edge_unfolds() {
|
||||
let rule = RuleValues { thickness: 1.5, k_factor: 0.5, bend_radius: 2.0, ..alu() };
|
||||
let line = 30.0;
|
||||
let ba = std::f64::consts::FRAC_PI_2 * (rule.bend_radius + rule.k_factor * rule.thickness);
|
||||
for off in [0.0, 1e-8, 1e-6, -1e-6, 1e-5, -1e-5] {
|
||||
let what = format!("vertex {off} mm from the zone edge");
|
||||
let x = line + ba / 2.0 + off;
|
||||
let outline = [Vec2::new(x, 0.0), Vec2::new(80.0, 0.0), Vec2::new(80.0, 120.0), Vec2::new(0.0, 120.0), Vec2::new(0.0, 0.0)];
|
||||
let mut s = base_flange("Body1", "R", &rule, Plane::XY, Region2 { outer: Loop2::polygon(&outline).ccw(), holes: Vec::new() });
|
||||
let (a, b) = (Vec3::new(line, -200.0, s.t), Vec3::new(line, 200.0, s.t));
|
||||
let mut warning = None;
|
||||
s.add_fold(a, b, std::f64::consts::FRAC_PI_2, rule.bend_radius, "centerline", false, None, &mut warning)
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let flat = s.flat_regions().unwrap_or_else(|e| panic!("{what}: flat: {e}"));
|
||||
assert_eq!(flat.len(), 1, "{what}");
|
||||
let body = s.solid().unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert!(body.validity().is_empty(), "{what}: {:?}", body.validity());
|
||||
}
|
||||
}
|
||||
|
||||
/// As above, with arcs at the zone edge: a notch whose far corner along the edge is rounded,
|
||||
/// and a straight notch with a rounded relief over its edge whose arc ends on the zone edge,
|
||||
/// tangent to it (a corner relief drawn to end on the bend line, which ends 0.03 µm beside it).
|
||||
#[test]
|
||||
fn rounded_cut_corners_a_hair_beside_a_bend_zone_edge_refold() {
|
||||
let rule = RuleValues { bend_radius: 2.0, ..alu() };
|
||||
let outline = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 40.0), Vec2::new(0.0, 40.0)];
|
||||
let mut s = base_flange("Body1", "AL2", &rule, Plane::XY, Region2 { outer: Loop2::polygon(&outline).ccw(), holes: vec![] });
|
||||
s.add_flange(Vec3::new(50.0, 40.0, 2.0), 30.0, std::f64::consts::FRAC_PI_2, 2.0, "inside", false).unwrap();
|
||||
let f = s.flanges[0].clone();
|
||||
let ba = s.allowance(&f);
|
||||
let v0 = vol(&s.solid().unwrap());
|
||||
let line = |a: Vec2, b: Vec2| Seg2::Line { a, b };
|
||||
let arc = |c: Vec2, a: Vec2, b: Vec2| {
|
||||
let (sa, sb) = ((a - c).y.atan2((a - c).x), (b - c).y.atan2((b - c).x));
|
||||
let mut sweep = sb - sa;
|
||||
while sweep > std::f64::consts::PI {
|
||||
sweep -= std::f64::consts::TAU;
|
||||
}
|
||||
while sweep < -std::f64::consts::PI {
|
||||
sweep += std::f64::consts::TAU;
|
||||
}
|
||||
Seg2::Arc { center: c, radius: a.dist(c), start: sa, sweep }
|
||||
};
|
||||
for (side, zone) in [("panel", 0.0), ("flange", ba)] {
|
||||
for off in [3e-5, -3e-5, 1e-6, -1e-6, 0.0] {
|
||||
let edge = zone + off;
|
||||
let out = if side == "panel" { -10.0 } else { ba + 40.0 };
|
||||
let sg = (out - edge).signum();
|
||||
let p = |t: f64, n: f64| f.p + f.d * t + f.n * n;
|
||||
let r = 3.0;
|
||||
let rounded = Loop2 {
|
||||
segs: vec![
|
||||
line(p(-5.0, out), p(-5.0, edge)),
|
||||
line(p(-5.0, edge), p(20.0 - r, edge)),
|
||||
arc(p(20.0 - r, edge + sg * r), p(20.0 - r, edge), p(20.0, edge + sg * r)),
|
||||
line(p(20.0, edge + sg * r), p(20.0, out)),
|
||||
line(p(20.0, out), p(-5.0, out)),
|
||||
],
|
||||
};
|
||||
let notch = Loop2::polygon(&[p(-5.0, edge), p(20.0, edge), p(20.0, out), p(-5.0, out)]);
|
||||
let relief = Loop2 {
|
||||
segs: vec![
|
||||
line(p(0.0, edge), p(0.0, edge + sg * 3.0)),
|
||||
line(p(0.0, edge + sg * 3.0), p(-5.0, edge + sg * 3.0)),
|
||||
line(p(-5.0, edge + sg * 3.0), p(-5.0, edge - sg * 2.0)),
|
||||
line(p(-5.0, edge - sg * 2.0), p(-2.0, edge - sg * 2.0)),
|
||||
arc(p(0.0, edge - sg * 2.0), p(-2.0, edge - sg * 2.0), p(0.0, edge)),
|
||||
],
|
||||
};
|
||||
for (shape, holes) in [("rounded notch", vec![rounded]), ("notch and relief", vec![notch, relief])] {
|
||||
let what = format!("{shape} on the {side} side, {off} mm beside the zone edge");
|
||||
let mut cut = s.clone();
|
||||
cut.holes.extend(holes.into_iter().map(|h| Region2 { outer: h.ccw(), holes: vec![] }));
|
||||
let body = cut.solid().unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert!(body.validity().is_empty(), "{what}: {:?}", body.validity());
|
||||
assert!(vol(&body) < v0 - 1.0, "{what}: {} vs {v0}", vol(&body));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Distance between two parallel 3D lines through a0→a1 and b0→b1 (None if not parallel).
|
||||
fn parallel_gap(a0: Vec3, a1: Vec3, b0: Vec3, b1: Vec3) -> Option<f64> {
|
||||
let (u, v) = ((a1 - a0).normalized()?, (b1 - b0).normalized()?);
|
||||
|
||||
@@ -39,6 +39,7 @@ fn plate_doc() -> (Document, u64) {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -345,6 +346,7 @@ fn box_fillet_cut_timeline() {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -662,6 +664,26 @@ fn a_folder_naming_missing_or_repeated_features_still_opens() {
|
||||
assert_eq!(opened.timeline_groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Repeats", "Stale"], "both folders are kept");
|
||||
}
|
||||
|
||||
/// Timeline folders nested 10 000 deep open at once: each folder's chain of parents is walked
|
||||
/// once, not again for every folder inside it (a 588 KB design took over three minutes). A
|
||||
/// cycle is still refused.
|
||||
#[test]
|
||||
fn deeply_nested_timeline_folders_open_and_a_cycle_does_not() {
|
||||
let mut doc = Document::new("nested folders");
|
||||
let n = 10_000u64;
|
||||
doc.timeline_groups = (0..n)
|
||||
.map(|i| TimelineGroup { id: 100 + i, name: "f".into(), parent: (i + 1 < n).then_some(101 + i), features: vec![], joints: vec![] })
|
||||
.collect();
|
||||
let started = std::time::Instant::now();
|
||||
let opened = Document::from_json(&doc.to_json()).expect("the design opens");
|
||||
assert_eq!(opened.timeline_groups.len(), n as usize);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
|
||||
doc.timeline_groups =
|
||||
(0..3).map(|i| TimelineGroup { id: 100 + i, name: "f".into(), parent: Some(100 + (i + 1) % 3), features: vec![], joints: vec![] }).collect();
|
||||
let refused = Document::from_json(&doc.to_json()).unwrap_err().to_string();
|
||||
assert!(refused.contains("cyclic timeline folders"), "{refused}");
|
||||
}
|
||||
|
||||
/// A marker after the last feature leaves every feature active, as no marker does, so a feature
|
||||
/// added then is active too, not added rolled back (#7741: editing the last feature from the
|
||||
/// History runs its command with the marker there).
|
||||
@@ -1130,6 +1152,7 @@ fn an_extruded_ellipse_or_spline_is_one_wall_named_by_its_curve() {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -411,11 +411,14 @@ impl PlaneRef {
|
||||
base.walk_feature_refs(f, depth + 1);
|
||||
point.walk_feature_refs(f, depth + 1);
|
||||
}
|
||||
Self::AtAngle { base, line, .. } => {
|
||||
Self::AtAngle { base, line, pivot, .. } => {
|
||||
base.walk_feature_refs(f, depth + 1);
|
||||
if let Some(g) = line {
|
||||
g.walk_feature_refs(f, depth + 1);
|
||||
}
|
||||
if let Some(g) = pivot {
|
||||
g.walk_feature_refs(f, depth + 1);
|
||||
}
|
||||
}
|
||||
Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::AxisPoint { axis: a, point: b } | Self::Perpendicular { plane: a, line: b } => {
|
||||
a.walk_feature_refs(f, depth + 1);
|
||||
@@ -448,11 +451,14 @@ impl PlaneRef {
|
||||
base.walk_feature_refs_mut(f, depth + 1);
|
||||
point.walk_feature_refs_mut(f, depth + 1);
|
||||
}
|
||||
Self::AtAngle { base, line, .. } => {
|
||||
Self::AtAngle { base, line, pivot, .. } => {
|
||||
base.walk_feature_refs_mut(f, depth + 1);
|
||||
if let Some(g) = line {
|
||||
g.walk_feature_refs_mut(f, depth + 1);
|
||||
}
|
||||
if let Some(g) = pivot {
|
||||
g.walk_feature_refs_mut(f, depth + 1);
|
||||
}
|
||||
}
|
||||
Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::AxisPoint { axis: a, point: b } | Self::Perpendicular { plane: a, line: b } => {
|
||||
a.walk_feature_refs_mut(f, depth + 1);
|
||||
|
||||
@@ -16,15 +16,38 @@ use solidcraft_doc::{BrowserEntry, FeatureKind, MAX_GROUP_NESTING};
|
||||
use super::CommandSpec;
|
||||
use super::features::{add_feature, check_expr};
|
||||
use crate::params::{bad, bool_, expr, str_};
|
||||
use crate::schema::browser::{DocumentUnitsParams, DocumentUnitsResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn};
|
||||
use crate::schema::browser::{
|
||||
BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,
|
||||
BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,
|
||||
BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, Isolated, RepairDone, RepairFace, RepairHole,
|
||||
RepairParams, RepairResult, RepairSewn, VisibilityState,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const REPAIR_CONTRACT: TypedContract<RepairParams> = TypedContract::new();
|
||||
const UNITS_CONTRACT: TypedContract<DocumentUnitsParams> = TypedContract::new();
|
||||
const RENAME_BODY_CONTRACT: TypedContract<BodyRenameParams> = TypedContract::new();
|
||||
const GROUP_CONTRACT: TypedContract<BrowserGroupParams> = TypedContract::new();
|
||||
const UNGROUP_CONTRACT: TypedContract<BrowserUngroupParams> = TypedContract::new();
|
||||
const RENAME_GROUP_CONTRACT: TypedContract<BrowserRenameGroupParams> = TypedContract::new();
|
||||
const MOVE_CONTRACT: TypedContract<BrowserMoveParams> = TypedContract::new();
|
||||
const ORDER_CONTRACT: TypedContract<BrowserOrderParams> = TypedContract::new();
|
||||
const VISIBILITY_CONTRACT: TypedContract<BrowserVisibilityParams> = TypedContract::new();
|
||||
const FOLD_CONTRACT: TypedContract<BrowserFoldParams> = TypedContract::new();
|
||||
|
||||
/// A reply as JSON: the commands here build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("body.rename", "Rename Body", rename_body).icon("rename").params("body: its name, name: the new name (features that use the body follow)"),
|
||||
CommandSpec::new("body.rename", "Rename Body", crate::checked!("body.rename", rename_body))
|
||||
.icon("rename")
|
||||
.contract(&RENAME_BODY_CONTRACT)
|
||||
.output(output_schema_for::<BodyRenamed>)
|
||||
.params("body: its name, name: the new name (features that use the body follow)"),
|
||||
// The import and failed operations offer it for a part the modelling kernel refuses.
|
||||
CommandSpec::new("body.repair", "Repair Part", crate::checked!("body.repair", repair_body))
|
||||
.icon("body")
|
||||
@@ -36,12 +59,25 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch)
|
||||
.icon("plane")
|
||||
.params("sketch: id or name; plane: as sketch.create; frame?: as sketch.create; author_path?: exact owner occurrence ids; explicitly rebinds or freezes the plane while preserving geometry and dimension names"),
|
||||
CommandSpec::new("browser.group", "New Group", group)
|
||||
CommandSpec::new("browser.group", "New Group", crate::checked!("browser.group", group))
|
||||
.icon("folder")
|
||||
.contract(&GROUP_CONTRACT)
|
||||
.output(output_schema_for::<BrowserGroupMade>)
|
||||
.params("folder?: bodies|sketches|construction; component?: id (default 0); parent?: group id (the new group nests in it, taking its component and folder; at most 8 levels); name?; items?: [keys] (they leave other groups)"),
|
||||
CommandSpec::new("browser.ungroup", "Ungroup", ungroup).icon("folder").params("group: id (its items and child groups go up to the group that holds it, or the folder)"),
|
||||
CommandSpec::new("browser.rename_group", "Rename Group", rename_group).icon("rename").params("group: id, name"),
|
||||
CommandSpec::new("browser.move", "Move Browser Items", move_items).icon("reorder")
|
||||
CommandSpec::new("browser.ungroup", "Ungroup", crate::checked!("browser.ungroup", ungroup))
|
||||
.icon("folder")
|
||||
.contract(&UNGROUP_CONTRACT)
|
||||
.output(output_schema_for::<BrowserUngrouped>)
|
||||
.params("group: id (its items and child groups go up to the group that holds it, or the folder)"),
|
||||
CommandSpec::new("browser.rename_group", "Rename Group", crate::checked!("browser.rename_group", rename_group))
|
||||
.icon("rename")
|
||||
.contract(&RENAME_GROUP_CONTRACT)
|
||||
.output(output_schema_for::<BrowserGroupRenamed>)
|
||||
.params("group: id, name"),
|
||||
CommandSpec::new("browser.move", "Move Browser Items", crate::checked!("browser.move", move_items))
|
||||
.icon("reorder")
|
||||
.contract(&MOVE_CONTRACT)
|
||||
.output(output_schema_for::<BrowserMoved>)
|
||||
.params("folder, component?, items: [keys (strings) and group ids (numbers)]; group?: id (into it; omit for the folder's top level); before?: key or group id (position in it; default the end). A group cannot go into itself or past 8 levels"),
|
||||
CommandSpec::new("document.units", "Change Design Units", crate::checked!("document.units", document_units))
|
||||
.icon("settings")
|
||||
@@ -57,8 +93,16 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().params(
|
||||
"view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?, roll?} (radians, mm, about the up axis; yaw: heading of the line of sight, 0 along +Y (Front), π/2 along +X (Left), π (Back), −π/2 (Right); pitch: the eye's elevation, within ±π/2, π/2 = Top; roll defaults to 0, turns the picture clockwise, must be finite and is clamped to ±π; the View angles readout shows these in degrees; up is refused: the up axis comes from the design settings) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step",
|
||||
),
|
||||
CommandSpec::new("browser.order", "Order Browser Items", order).icon("reorder").params("folder: bodies|sketches|construction|components, component?, order: [keys (strings) and top-level group ids (numbers)] (display order; for `components`, the ids of the components placed in it)"),
|
||||
CommandSpec::new("browser.visibility", "Show/Hide", visibility).icon("eye").params(
|
||||
CommandSpec::new("browser.order", "Order Browser Items", crate::checked!("browser.order", order))
|
||||
.icon("reorder")
|
||||
.contract(&ORDER_CONTRACT)
|
||||
.output(output_schema_for::<BrowserOrdered>)
|
||||
.params("folder: bodies|sketches|construction|components, component?, order: [keys (strings) and top-level group ids (numbers)] (display order; for `components`, the ids of the components placed in it)"),
|
||||
CommandSpec::new("browser.visibility", "Show/Hide", crate::checked!("browser.visibility", visibility))
|
||||
.icon("eye")
|
||||
.contract(&VISIBILITY_CONTRACT)
|
||||
.output(output_schema_for::<BrowserVisibilityResult>)
|
||||
.params(
|
||||
"visible: bool; items?: [sketch id or name | body name | construction name | joint name | O|X|Y|Z|XY|XZ|YZ]; \
|
||||
or joints?: [joint id or name] (their glyphs; they still constrain and move parts); \
|
||||
or features?: [feature id or name] (the bodies they made; path?: [occurrence ids] for only that placement's); \
|
||||
@@ -66,12 +110,22 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
or tree_folders?: [browser folder or group key: c0/bodies, o:4/sketches, c0/g7, c0/joints, c0/canvases, c0/point_clouds] (the folder or group itself: its items keep their own state); \
|
||||
or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (with paths or items of bodies, and visible:true: everything else is hidden, other placements as placements). Saved with the design and undone like any other change (the camera is not)",
|
||||
),
|
||||
CommandSpec::new("browser.expand_all", "Expand All", expand_all).icon("folder").noundo().params(
|
||||
CommandSpec::new("browser.expand_all", "Expand All", crate::checked!("browser.expand_all", expand_all))
|
||||
.icon("folder")
|
||||
.noundo()
|
||||
.contract(&FOLD_CONTRACT)
|
||||
.output(output_schema_for::<BrowserFoldResult>)
|
||||
.params(
|
||||
"path?: [occurrence ids] (that placement and its descendants); component?: id (that component's own folders); \
|
||||
omit both for the whole tree, including folders that start closed (Origin, Named Views, Features). \
|
||||
Display only: open/closed rows are not saved in the design and are not an undo step → open, open_by_default, closed_by_default",
|
||||
),
|
||||
CommandSpec::new("browser.collapse_all", "Collapse All", collapse_all).icon("folder").noundo().params(
|
||||
CommandSpec::new("browser.collapse_all", "Collapse All", crate::checked!("browser.collapse_all", collapse_all))
|
||||
.icon("folder")
|
||||
.noundo()
|
||||
.contract(&FOLD_CONTRACT)
|
||||
.output(output_schema_for::<BrowserFoldResult>)
|
||||
.params(
|
||||
"path?: [occurrence ids]; component?: id; omit both for the whole tree. The row it starts from (the design row for the whole tree) stays open, so its first level remains visible. \
|
||||
Display only; not an undo step → open, open_by_default, closed_by_default",
|
||||
),
|
||||
@@ -221,7 +275,7 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
take_out(d, component, &folder, &gone);
|
||||
let items = gone;
|
||||
d.browser_groups.push(solidcraft_doc::BrowserGroup { id, name: name.clone(), component, folder, parent, items });
|
||||
Ok(json!({ "group": id, "name": name, "parent": parent }))
|
||||
reply(cmd, BrowserGroupMade { group: id, name, parent, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A group's contents go up to the group that holds it (the folder's top level for a top-level
|
||||
@@ -229,7 +283,7 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = group_id(s, p, "browser.ungroup")?;
|
||||
let d = s.doc_mut();
|
||||
let Some(g) = d.browser_group(id).cloned() else { return Ok(json!({ "group": id })) };
|
||||
let Some(g) = d.browser_group(id).cloned() else { return reply("browser.ungroup", BrowserUngrouped { group: id, param_warnings: Vec::new() }) };
|
||||
settle(d, g.component, &g.folder, Some(id));
|
||||
settle(d, g.component, &g.folder, g.parent);
|
||||
let inside = d.browser_group(id).map(|g| g.items.clone()).unwrap_or_default();
|
||||
@@ -243,7 +297,7 @@ fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
take_out(d, g.component, &g.folder, &[BrowserEntry::Group(id)]);
|
||||
d.browser_groups.retain(|x| x.id != id);
|
||||
Ok(json!({ "group": id }))
|
||||
reply("browser.ungroup", BrowserUngrouped { group: id, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -254,7 +308,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(g) = s.doc_mut().browser_groups.iter_mut().find(|g| g.id == id) {
|
||||
g.name = name.to_string();
|
||||
}
|
||||
Ok(json!({ "group": id, "name": name }))
|
||||
reply(cmd, BrowserGroupRenamed { group: id, name: name.to_string(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn move_items(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -312,7 +366,7 @@ fn move_items(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = before.as_ref().and_then(|b| list.iter().position(|e| e == b)).unwrap_or(list.len());
|
||||
list.splice(at..at, items.iter().cloned());
|
||||
}
|
||||
Ok(json!({ "items": items, "group": to }))
|
||||
reply(cmd, BrowserMoved { items, group: to, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn order(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -348,7 +402,7 @@ fn order(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An item that sits in a group belongs to the group's list only.
|
||||
d.browser_order.insert(key, order);
|
||||
}
|
||||
Ok(json!({}))
|
||||
reply(cmd, BrowserOrdered { param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
const ORIGIN: [&str; 7] = ["O", "X", "Y", "Z", "XY", "XZ", "YZ"];
|
||||
@@ -426,7 +480,7 @@ fn shown_feature(world: &solidcraft_doc::ModelState, f: &solidcraft_doc::Feature
|
||||
|
||||
/// A browser folder or group key (`Visibility::hidden_folders`): `c0` or `o:<ids>`, then
|
||||
/// `/bodies`, `/sketches`, `/construction`, `/joints`, `/canvases` or `/g<group id>`.
|
||||
fn tree_folder_key(k: &str) -> bool {
|
||||
pub(crate) fn tree_folder_key(k: &str) -> bool {
|
||||
let Some((scope, last)) = k.rsplit_once('/') else { return false };
|
||||
let scope_ok =
|
||||
scope == "c0" || scope.strip_prefix("o:").is_some_and(|ids| ids.split('/').count() <= 64 && ids.split('/').all(|i| i.parse::<u64>().is_ok()));
|
||||
@@ -486,7 +540,11 @@ fn isolate_bodies(s: &mut Session, p: &Value, visible: bool) -> Result<Value> {
|
||||
s.visibility.hidden_occurrences = hidden;
|
||||
s.visibility.hidden_bodies = hidden_bodies;
|
||||
s.refresh_display();
|
||||
Ok(json!({"visible":true,"isolated":keep,"visibility":s.visibility}))
|
||||
let visibility = VisibilityState::from(&s.visibility);
|
||||
reply(
|
||||
cmd,
|
||||
BrowserVisibilityResult { visible: true, changed: None, isolated: Some(Isolated::Bodies(keep)), visibility, param_warnings: Vec::new() },
|
||||
)
|
||||
}
|
||||
|
||||
/// The tree keys of the Bodies folders and groups (with the groups they are in) that hold the
|
||||
@@ -546,7 +604,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.refresh_display();
|
||||
return Ok(json!({"visible":visible,"changed":keys.len(),"visibility":s.visibility}));
|
||||
let visibility = VisibilityState::from(&s.visibility);
|
||||
return reply(cmd, BrowserVisibilityResult { visible, changed: Some(keys.len()), isolated: None, visibility, param_warnings: Vec::new() });
|
||||
}
|
||||
if let Some(value) = p.get("paths") {
|
||||
if p.get("items").is_some() || p.get("folder").is_some() {
|
||||
@@ -597,7 +656,17 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.visibility.hidden_occurrences = hidden;
|
||||
s.visibility.hidden_bodies = root_bodies;
|
||||
s.refresh_display();
|
||||
return Ok(json!({"visible":true,"isolated":paths,"visibility":s.visibility}));
|
||||
let visibility = VisibilityState::from(&s.visibility);
|
||||
return reply(
|
||||
cmd,
|
||||
BrowserVisibilityResult {
|
||||
visible: true,
|
||||
changed: None,
|
||||
isolated: Some(Isolated::Paths(paths)),
|
||||
visibility,
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
for path in &paths {
|
||||
s.visibility.hidden_occurrences.retain(|p| p != path);
|
||||
@@ -606,7 +675,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.refresh_display();
|
||||
return Ok(json!({"visible":visible,"changed":paths.len(),"visibility":s.visibility}));
|
||||
let visibility = VisibilityState::from(&s.visibility);
|
||||
return reply(cmd, BrowserVisibilityResult { visible, changed: Some(paths.len()), isolated: None, visibility, param_warnings: Vec::new() });
|
||||
}
|
||||
if bool_(p, "isolate").unwrap_or(false) {
|
||||
return isolate_bodies(s, p, visible);
|
||||
@@ -726,7 +796,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.refresh_display();
|
||||
Ok(json!({ "visible": visible, "changed": items.len(), "visibility": s.visibility }))
|
||||
let visibility = VisibilityState::from(&s.visibility);
|
||||
reply(cmd, BrowserVisibilityResult { visible, changed: Some(items.len()), isolated: None, visibility, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// Browser rows that start open (`c0`, Bodies, placements) vs closed (Origin, Features).
|
||||
@@ -873,11 +944,8 @@ fn fold_tree(s: &mut Session, p: &Value, open: bool, cmd: &str) -> Result<Value>
|
||||
if keys.open.len().saturating_add(keys.closed.len()) > MAX_FOLD_KEYS {
|
||||
return Err(bad(cmd, "expand/collapse exceeds 10000 browser rows"));
|
||||
}
|
||||
Ok(json!({
|
||||
"open": open,
|
||||
"open_by_default": keys.open.into_iter().collect::<Vec<_>>(),
|
||||
"closed_by_default": keys.closed.into_iter().collect::<Vec<_>>(),
|
||||
}))
|
||||
let (open_by_default, closed_by_default) = (keys.open.into_iter().collect(), keys.closed.into_iter().collect());
|
||||
reply(cmd, BrowserFoldResult { open, open_by_default, closed_by_default, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn expand_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1198,7 +1266,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name =
|
||||
str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?;
|
||||
if name == old {
|
||||
return Ok(json!({"body": old, "name": name}));
|
||||
return reply(cmd, BodyRenamed { body: old, name: name.to_string(), param_warnings: Vec::new() });
|
||||
}
|
||||
let previous = s.doc.clone();
|
||||
let st = s.model.state();
|
||||
@@ -1323,7 +1391,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A sketch projecting the body in another placement of its component keeps it.
|
||||
super::sketch_project::follow_placed_renames(d, &st, &placed, Some((&old, name)));
|
||||
s.remember_body_rename(&previous, &old, name);
|
||||
Ok(json!({"body": old, "name": name}))
|
||||
reply(cmd, BodyRenamed { body: old, name: name.to_string(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn redefine_sketch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -18,7 +18,7 @@ fn independent_plane(plane: &PlaneRef, depth: usize) -> Result<()> {
|
||||
}
|
||||
match plane {
|
||||
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => Ok(()),
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, line: None, .. } => {
|
||||
PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, line: None, pivot: None, .. } => {
|
||||
independent_plane(base, depth + 1)
|
||||
}
|
||||
_ => Err(bad(CMD, "the copied sketch's plane depends on model geometry; convert it to a fixed plane before pasting into another design")),
|
||||
|
||||
@@ -7,8 +7,10 @@
|
||||
//! come along, all keeping their ids and names, with the parameters they use. It is evaluated on
|
||||
//! its own and has to build the bodies the component has here. Then the component's history is
|
||||
//! replaced by an Import feature of those bodies, linked to the file, and this design has to look
|
||||
//! as it did before. Anything that crosses the component's boundary (a feature outside that uses
|
||||
//! its sketches, bodies moved in or out, a joint to one of its subcomponents) is refused.
|
||||
//! as it did before. A body of the component that a feature outside it built (a mirror or
|
||||
//! pattern into it, a body moved in) takes that history along when nothing else outside depends
|
||||
//! on it. Anything else that crosses the component's boundary (a feature outside that uses its
|
||||
//! sketches, bodies moved out, a joint to one of its subcomponents) is refused.
|
||||
|
||||
use solidcraft_geom::prelude::*;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -18,8 +20,9 @@ use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_doc::{DesignLink, Document, FeatureKind, ModelBody, ModelState};
|
||||
|
||||
use super::{absolute, component_key, file_sha256, inherit_properties, resolve, session_bodies, stored};
|
||||
use super::{absolute, component_key, file_sha256, inherit_properties, reply, resolve, session_bodies, stored};
|
||||
use crate::params::{bad, str_};
|
||||
use crate::schema::component_link::{CopiesResult, CopyInfo, ExtractResult, ReplaceWithLinkResult};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const CMD: &str = "component.extract";
|
||||
@@ -205,8 +208,13 @@ struct Scope {
|
||||
own: BTreeSet<u64>,
|
||||
/// The placements of its subcomponents.
|
||||
inner: BTreeSet<u64>,
|
||||
/// Its features and its subcomponents'.
|
||||
/// Its features and its subcomponents', and the features outside that built its bodies: they
|
||||
/// all leave this design.
|
||||
inside: BTreeSet<u64>,
|
||||
/// Sketches outside that those features use: copied to the new design, kept here.
|
||||
carried: BTreeSet<u64>,
|
||||
/// The features outside that built its bodies.
|
||||
pulled: BTreeSet<u64>,
|
||||
/// Its bodies and its subcomponents'.
|
||||
bodies: BTreeSet<String>,
|
||||
/// The component of every body of the design.
|
||||
@@ -216,6 +224,74 @@ struct Scope {
|
||||
occurrences: BTreeMap<u64, u64>,
|
||||
}
|
||||
|
||||
/// The bodies `after` has that `before` did not have the same, and those it lost: what a feature
|
||||
/// built, changed, moved to another component or used up.
|
||||
fn touched(doc: &Document, before: &ModelState, after: &ModelState) -> BTreeSet<String> {
|
||||
let mut out: BTreeSet<String> = before.bodies.iter().filter(|b| after.body(&b.name).is_none()).map(|b| b.name.clone()).collect();
|
||||
for b in &after.bodies {
|
||||
let same = before.body(&b.name).is_some_and(|old| old.body.same(&b.body) && doc.model_body_component(old) == doc.model_body_component(b));
|
||||
if !same {
|
||||
out.insert(b.name.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The features outside a component (`inside` are its own) that built, changed or moved in
|
||||
/// `wanted`, its bodies built outside it, back to where they started; or the feature that also
|
||||
/// builds or changes a body that stays outside, which keeps the history from going along.
|
||||
fn history_from_outside(
|
||||
s: &Session,
|
||||
inside: &BTreeSet<u64>,
|
||||
mut wanted: BTreeSet<String>,
|
||||
owned: &dyn Fn(&str) -> bool,
|
||||
name: &str,
|
||||
cmd: &str,
|
||||
) -> Result<BTreeSet<u64>> {
|
||||
let empty = ModelState::default();
|
||||
let mut steps: Vec<(&solidcraft_doc::Feature, BTreeSet<String>)> = Vec::new();
|
||||
let mut before: &ModelState = ∅
|
||||
for f in &s.doc.features {
|
||||
let Some(r) = s.model.result(f.id) else { continue };
|
||||
steps.push((f, touched(&s.doc, before, &r.state)));
|
||||
before = &r.state;
|
||||
}
|
||||
let state = s.model.state();
|
||||
let mut pulled = BTreeSet::new();
|
||||
for (f, t) in steps.iter().rev() {
|
||||
if !t.iter().any(|b| wanted.contains(b)) {
|
||||
continue;
|
||||
}
|
||||
if inside.contains(&f.id) {
|
||||
// Already going; a body it used up from outside is checked where that was built
|
||||
wanted.extend(t.iter().filter(|b| state.body(b).is_none()).cloned());
|
||||
continue;
|
||||
}
|
||||
if let Some(other) = t.iter().find(|b| state.body(b).is_some() && !owned(b)) {
|
||||
let mine = t.iter().find(|b| wanted.contains(*b)).cloned().unwrap_or_default();
|
||||
return Err(bad(cmd, format!("{} builds body {mine} of {name} and also body {other} outside it, so it can't go with {name}", f.name)));
|
||||
}
|
||||
pulled.insert(f.id);
|
||||
wanted.extend(t.iter().cloned());
|
||||
}
|
||||
Ok(pulled)
|
||||
}
|
||||
|
||||
/// The last feature that put body `body` in another component.
|
||||
fn mover(s: &Session, body: &str) -> Option<String> {
|
||||
let mut found = None;
|
||||
let mut was = None;
|
||||
for f in &s.doc.features {
|
||||
let Some(r) = s.model.result(f.id) else { continue };
|
||||
let now = r.state.body(body).map(|b| s.doc.model_body_component(b));
|
||||
if was.is_some() && now.is_some() && now != was {
|
||||
found = Some(f.name.clone());
|
||||
}
|
||||
was = now.or(was);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// What goes with component `comp`, or why it can't go on its own.
|
||||
fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
let source = &s.doc;
|
||||
@@ -239,7 +315,21 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
if let Some(o) = source.occurrences.iter().find(|o| children.contains(&o.component) && !subtree.contains(&o.parent)) {
|
||||
return Err(bad(cmd, format!("{} is placed outside {name} too", o.name)));
|
||||
}
|
||||
let inside: BTreeSet<u64> = source.features.iter().filter(|f| subtree.contains(&f.component)).map(|f| f.id).collect();
|
||||
let mut inside: BTreeSet<u64> = source.features.iter().filter(|f| subtree.contains(&f.component)).map(|f| f.id).collect();
|
||||
let state = s.model.state();
|
||||
let owners: BTreeMap<String, u64> = state.bodies.iter().map(|b| (b.name.clone(), source.model_body_component(b))).collect();
|
||||
let owned = |b: &str| owners.get(b).is_some_and(|c| subtree.contains(c));
|
||||
let built_outside: BTreeSet<String> =
|
||||
state.bodies.iter().filter(|b| owned(&b.name) && !inside.contains(&b.feature)).map(|b| b.name.clone()).collect();
|
||||
let pulled = if built_outside.is_empty() { BTreeSet::new() } else { history_from_outside(s, &inside, built_outside, &owned, &name, cmd)? };
|
||||
inside.extend(pulled.iter().copied());
|
||||
let mut carried = BTreeSet::new();
|
||||
let mut todo: Vec<u64> = pulled.iter().flat_map(|id| source.feature(*id).map(|f| f.kind.input_sketches()).unwrap_or_default()).collect();
|
||||
while let Some(id) = todo.pop() {
|
||||
if !inside.contains(&id) && carried.insert(id) {
|
||||
todo.extend(source.feature(id).map(|f| f.kind.input_sketches()).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
if let Some(f) = source.features.iter().find(|f| inside.contains(&f.id) && s.model.result(f.id).is_some_and(|r| r.error.is_some())) {
|
||||
return Err(bad(cmd, format!("{} fails; fix it first", f.name)));
|
||||
}
|
||||
@@ -249,9 +339,10 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
if let Some(f) = source
|
||||
.features
|
||||
.iter()
|
||||
.find(|f| matches!(&f.kind, FeatureKind::BodyTransfer { from, to, .. } if subtree.contains(from) != subtree.contains(to)))
|
||||
// Bodies moved in are checked below: they go when what built them goes too
|
||||
.find(|f| matches!(&f.kind, FeatureKind::BodyTransfer { from, to, .. } if subtree.contains(from) && !subtree.contains(to)))
|
||||
{
|
||||
return Err(bad(cmd, format!("{} moves bodies into or out of {name}", f.name)));
|
||||
return Err(bad(cmd, format!("{} moves bodies out of {name}", f.name)));
|
||||
}
|
||||
let mut occurrences: BTreeMap<u64, u64> = inner.iter().map(|o| (*o, *o)).collect();
|
||||
if let [single] = own.iter().copied().collect::<Vec<_>>().as_slice() {
|
||||
@@ -263,13 +354,17 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
}) {
|
||||
return Err(bad(cmd, format!("joint {} connects a part of {name} to the rest of the design", j.name)));
|
||||
}
|
||||
let state = s.model.state();
|
||||
let owners: BTreeMap<String, u64> = state.bodies.iter().map(|b| (b.name.clone(), source.model_body_component(b))).collect();
|
||||
let mut bodies = BTreeSet::new();
|
||||
for b in &state.bodies {
|
||||
let owned = owners.get(&b.name).is_some_and(|c| subtree.contains(c));
|
||||
let owned = owned(&b.name);
|
||||
if owned != inside.contains(&b.feature) {
|
||||
return Err(bad(cmd, format!("body {} was moved into or out of {name}", b.name)));
|
||||
return Err(bad(
|
||||
cmd,
|
||||
match mover(s, &b.name) {
|
||||
Some(f) => format!("{f} moves body {} out of {name}", b.name),
|
||||
None => format!("body {} was moved into or out of {name}", b.name),
|
||||
},
|
||||
));
|
||||
}
|
||||
if owned && b.body.is_mesh() {
|
||||
return Err(bad(cmd, format!("mesh body {} can't be linked", b.name)));
|
||||
@@ -278,7 +373,7 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
bodies.insert(b.name.clone());
|
||||
}
|
||||
}
|
||||
Ok(Scope { comp, name, subtree, children, own, inner, inside, bodies, owners, occurrences })
|
||||
Ok(Scope { comp, name, subtree, children, own, inner, inside, carried, pulled, bodies, owners, occurrences })
|
||||
}
|
||||
|
||||
/// The design `sc` makes on its own, called `stem`, evaluated and checked to build the bodies it
|
||||
@@ -286,11 +381,12 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
|
||||
fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Session, Vec<String>)> {
|
||||
let source = &s.doc;
|
||||
let (comp, name, bodies) = (sc.comp, &sc.name, &sc.bodies);
|
||||
let to_root = |c: u64| if c == comp { 0 } else { c };
|
||||
// Features from outside that built its bodies come along at the new design's root
|
||||
let to_root = |c: u64| if c == comp || !sc.subtree.contains(&c) { 0 } else { c };
|
||||
let mut part = (**source).clone();
|
||||
part.name = stem.to_string();
|
||||
part.marker = None;
|
||||
part.features.retain(|f| sc.inside.contains(&f.id));
|
||||
part.features.retain(|f| sc.inside.contains(&f.id) || sc.carried.contains(&f.id));
|
||||
for f in &mut part.features {
|
||||
f.component = to_root(f.component);
|
||||
// Bodies numbered or suffixed after the other bodies here (Body2, `X (2)`) keep those
|
||||
@@ -306,6 +402,11 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
|
||||
*from = to_root(*from);
|
||||
*to = to_root(*to);
|
||||
}
|
||||
FeatureKind::Mirror { placements, .. } => {
|
||||
for path in placements {
|
||||
local_path(path, &sc.own);
|
||||
}
|
||||
}
|
||||
FeatureKind::Emboss { face: Some(face), .. } => {
|
||||
local_path(&mut face.path, &sc.own);
|
||||
local_path(&mut face.author_path, &sc.own);
|
||||
@@ -320,6 +421,8 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// A body moved in from outside is already at the root
|
||||
part.features.retain(|f| !matches!(f.kind, FeatureKind::BodyTransfer { from: 0, to: 0, .. }));
|
||||
part.components.retain(|c| sc.children.contains(&c.id));
|
||||
for c in &mut part.components {
|
||||
c.parent = to_root(c.parent);
|
||||
@@ -361,7 +464,7 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
|
||||
part.named_views.clear();
|
||||
part.configs = Default::default();
|
||||
part.assembly = Default::default();
|
||||
let features: BTreeMap<u64, u64> = sc.inside.iter().map(|f| (*f, *f)).collect();
|
||||
let features: BTreeMap<u64, u64> = sc.inside.iter().chain(&sc.carried).map(|f| (*f, *f)).collect();
|
||||
let body_map: BTreeMap<String, String> = bodies.iter().map(|b| (b.clone(), b.clone())).collect();
|
||||
// Joints from the component to the rest of the design stay here, so they are not copied
|
||||
let mut scope = Document { assembly: source.assembly.clone(), ..Document::default() };
|
||||
@@ -397,6 +500,9 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
|
||||
return Err(bad(cmd, format!("{name} does not build body {b} on its own")));
|
||||
};
|
||||
if !same_shape(was, source.model_body_offset(was).unwrap_or(&identity), now, part.doc.model_body_offset(now).unwrap_or(&identity))? {
|
||||
if let Some(f) = source.feature(was.feature).filter(|f| sc.pulled.contains(&f.id)) {
|
||||
return Err(bad(cmd, format!("body {b} comes out differently on its own: {} builds it from outside {name}", f.name)));
|
||||
}
|
||||
return Err(bad(cmd, format!("body {b} comes out differently on its own: something outside {name} changes it")));
|
||||
}
|
||||
}
|
||||
@@ -544,8 +650,8 @@ fn copies_of(s: &Session, linked: u64) -> Result<Vec<u64>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn named(s: &Session, ids: &[u64]) -> Vec<Value> {
|
||||
ids.iter().map(|id| json!({"component": id, "name": s.doc.components.iter().find(|c| c.id == *id).map(|c| c.name.clone())})).collect()
|
||||
fn named(s: &Session, ids: &[u64]) -> Vec<CopyInfo> {
|
||||
ids.iter().map(|id| CopyInfo { component: *id, name: s.doc.components.iter().find(|c| c.id == *id).map(|c| c.name.clone()) }).collect()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -618,8 +724,21 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
link.file_sha256 = Some(read);
|
||||
}
|
||||
Ok(json!({"component": comp, "feature": id, "path": path, "file": shown, "bodies": sc.bodies, "notices": notices, "warnings": warnings,
|
||||
"copies": named(s, &copies)}))
|
||||
let copies = named(s, &copies);
|
||||
reply(
|
||||
CMD,
|
||||
ExtractResult {
|
||||
component: comp,
|
||||
feature: id,
|
||||
path,
|
||||
file: shown,
|
||||
bodies: sc.bodies.iter().cloned().collect(),
|
||||
notices,
|
||||
warnings,
|
||||
copies,
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn copies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -629,7 +748,7 @@ pub(super) fn copies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "that component is not linked to a design"));
|
||||
}
|
||||
let found = copies_of(s, linked)?;
|
||||
Ok(json!({"copies": named(s, &found)}))
|
||||
reply(cmd, CopiesResult { copies: named(s, &found), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
pub(super) fn replace_with_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -711,7 +830,7 @@ pub(super) fn replace_with_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc_mut().occurrences.retain(|x| x.id != o);
|
||||
s.refresh();
|
||||
}
|
||||
Ok(json!({"component": linked, "name": lname, "replaced": replaced, "warnings": warnings}))
|
||||
reply(cmd, ReplaceWithLinkResult { component: linked, name: lname, replaced, warnings, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -979,6 +1098,54 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_built_outside_and_moved_in_goes_with_its_history() {
|
||||
// #12142: a part modelled in context, then moved into its component
|
||||
let dir = folder("moved-in");
|
||||
let mut s = Session::default();
|
||||
let plate = run(&mut s, "component.create", json!({"name": "Plate"}))["component"].as_u64().unwrap();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Own"}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 8, "height": 4, "corner": [30, 0, 0], "body_name": "Block"}));
|
||||
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [-30, 0, 0], "body_name": "Stays"}));
|
||||
run(&mut s, "component.move_bodies", json!({"bodies": ["Block"], "component": plate}));
|
||||
let vol = volumes(&s);
|
||||
let file = dir.join("plate.solidcraft");
|
||||
let out = run(&mut s, "component.extract", json!({"component": "Plate", "path": file}));
|
||||
assert_eq!(out["bodies"], json!(["Block", "Own"]), "{out}");
|
||||
assert_eq!(volumes(&s), vol);
|
||||
assert!(s.model.results.iter().all(|r| r.error.is_none()));
|
||||
let mut part = Session::default();
|
||||
run(&mut part, "doc.open", json!({"path": file}));
|
||||
assert!(part.model.results.iter().all(|r| r.error.is_none()));
|
||||
assert_eq!(volumes(&part).keys().collect::<Vec<_>>(), ["Block", "Own"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_built_with_one_that_stays_outside_names_the_feature() {
|
||||
let dir = folder("built-with");
|
||||
let mut s = Session::default();
|
||||
let plate = run(&mut s, "component.create", json!({"name": "Plate"}))["component"].as_u64().unwrap();
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 20], "body_name": "B"}));
|
||||
// One cut changes both bodies, and only B goes into Plate
|
||||
run(
|
||||
&mut s,
|
||||
"solid.cylinder",
|
||||
json!({"radius": 2, "height": 50, "base": [5, 5, -5], "operation": "cut", "targets": ["A", "B"], "name": "BothCut"}),
|
||||
);
|
||||
run(&mut s, "component.move_bodies", json!({"bodies": ["B"], "component": plate}));
|
||||
let before = serde_json::to_value(&*s.doc).unwrap();
|
||||
let file = dir.join("plate.solidcraft");
|
||||
let err = s.execute("component.extract", &json!({"component": "Plate", "path": file})).unwrap_err().to_string();
|
||||
assert!(err.contains("BothCut"), "{err}");
|
||||
assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before);
|
||||
assert!(!file.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_copies_are_found_and_become_placements_of_the_link() {
|
||||
let dir = folder("copies");
|
||||
|
||||
@@ -19,6 +19,12 @@ use solidcraft_doc::{DesignLink, Document, FeatureKind, LinkedBodyProperties, Us
|
||||
use super::CommandSpec;
|
||||
use super::design_link::{absolute, resolve, stored};
|
||||
use crate::params::{bad, str_, vec3};
|
||||
use crate::schema::component_link::{
|
||||
BreakLinkParams, BreakLinkResult, CopiesParams, CopiesResult, DesignInserted, ExtractParams, ExtractResult, InsertDesignParams,
|
||||
InsertDesignResult, JointDiagnostic, LinkFailure, LinkInfo, LinksParams, LinksResult, RelinkParams, RelinkResult, ReplaceWithLinkParams,
|
||||
ReplaceWithLinkResult, UpdateLinksParams, UpdateLinksResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[path = "component_extract.rs"]
|
||||
@@ -29,39 +35,81 @@ mod extract;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod relink_tests;
|
||||
|
||||
const INSERT_DESIGN_CONTRACT: TypedContract<InsertDesignParams> = TypedContract::new();
|
||||
const UPDATE_LINKS_CONTRACT: TypedContract<UpdateLinksParams> = TypedContract::new();
|
||||
const RELINK_CONTRACT: TypedContract<RelinkParams> = TypedContract::new();
|
||||
const BREAK_LINK_CONTRACT: TypedContract<BreakLinkParams> = TypedContract::new();
|
||||
const EXTRACT_CONTRACT: TypedContract<ExtractParams> = TypedContract::new();
|
||||
const COPIES_CONTRACT: TypedContract<CopiesParams> = TypedContract::new();
|
||||
const REPLACE_WITH_LINK_CONTRACT: TypedContract<ReplaceWithLinkParams> = TypedContract::new();
|
||||
const LINKS_CONTRACT: TypedContract<LinksParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params(
|
||||
CommandSpec::new("component.insert_design", "Insert Design", crate::checked!("component.insert_design", insert_design))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("component")
|
||||
.contract(&INSERT_DESIGN_CONTRACT)
|
||||
.output(output_schema_for::<InsertDesignResult>)
|
||||
.params(
|
||||
"path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \
|
||||
name? (default: the design's name); parent?: component id or name (default: the active one); \
|
||||
translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \
|
||||
reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available",
|
||||
),
|
||||
CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params(
|
||||
CommandSpec::new("component.update_links", "Update Links", crate::checked!("component.update_links", update_links))
|
||||
.icon("update")
|
||||
.contract(&UPDATE_LINKS_CONTRACT)
|
||||
.output(output_schema_for::<UpdateLinksResult>)
|
||||
.params(
|
||||
"component?: id or name (default: every linked component); components?: a list of ids or names, which goes on past a design it \
|
||||
cannot read (that one keeps its bodies, is named in failed and gets a warning) — reads the linked designs again and replaces \
|
||||
their bodies where they changed, as one undo step; → updated, unchanged, failed ([{component, name, error}]), warnings (also \
|
||||
joints whose faces are gone or that no longer solve)",
|
||||
),
|
||||
CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params(
|
||||
CommandSpec::new("component.relink", "Relink Source", crate::checked!("component.relink", relink))
|
||||
.icon("update")
|
||||
.contract(&RELINK_CONTRACT)
|
||||
.output(output_schema_for::<RelinkResult>)
|
||||
.params(
|
||||
"component: id or name of a linked component; path: a saved design (.sc or .json) — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts",
|
||||
),
|
||||
CommandSpec::new("component.break_link", "Break Link", break_link)
|
||||
CommandSpec::new("component.break_link", "Break Link", crate::checked!("component.break_link", break_link))
|
||||
.icon("break")
|
||||
.contract(&BREAK_LINK_CONTRACT)
|
||||
.output(output_schema_for::<BreakLinkResult>)
|
||||
.params("component: id or name of a linked component — keeps its bodies as they are and forgets the design file"),
|
||||
CommandSpec::new("component.extract", "Extract to File", extract::extract).icon("export").params(
|
||||
CommandSpec::new("component.extract", "Extract to File", crate::checked!("component.extract", extract::extract))
|
||||
.icon("export")
|
||||
.contract(&EXTRACT_CONTRACT)
|
||||
.output(output_schema_for::<ExtractResult>)
|
||||
.params(
|
||||
"component: id or name of a component that is not linked; path: the .sc design to write → its history, subcomponents and their joints \
|
||||
move to that design, and the component becomes linked to it (as component.insert_design makes it); returns path, file, feature, bodies, \
|
||||
notices (what stays behind), warnings and copies (components that build the same bodies: see component.replace_with_link)",
|
||||
),
|
||||
CommandSpec::new("component.copies", "Find Identical Copies", extract::copies).icon("inspect").noundo().params(
|
||||
CommandSpec::new("component.copies", "Find Identical Copies", crate::checked!("component.copies", extract::copies))
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
.contract(&COPIES_CONTRACT)
|
||||
.output(output_schema_for::<CopiesResult>)
|
||||
.params(
|
||||
"component: id or name of a linked component → copies: [{component, name}], the components not linked whose own history builds the same bodies",
|
||||
),
|
||||
CommandSpec::new("component.replace_with_link", "Replace with Link", extract::replace_with_link).icon("chain").params(
|
||||
CommandSpec::new("component.replace_with_link", "Replace with Link", crate::checked!("component.replace_with_link", extract::replace_with_link))
|
||||
.icon("chain")
|
||||
.contract(&REPLACE_WITH_LINK_CONTRACT)
|
||||
.output(output_schema_for::<ReplaceWithLinkResult>)
|
||||
.params(
|
||||
"component or components: [ids or names] of components that are not linked; with: a linked component, or path: a .sc design \
|
||||
(its link here, else a new linked component) → each component's history goes and its placements become placements of the linked \
|
||||
component; refused when its bodies are not the same as the link's; returns component, name, replaced and warnings",
|
||||
),
|
||||
CommandSpec::new("component.links", "List Links", list_links).icon("chain").noundo().params(
|
||||
CommandSpec::new("component.links", "List Links", crate::checked!("component.links", list_links))
|
||||
.icon("chain")
|
||||
.noundo()
|
||||
.contract(&LINKS_CONTRACT)
|
||||
.output(output_schema_for::<LinksResult>)
|
||||
.params(
|
||||
"→ linked components: component, name, path, file (resolved), found (null when the file is on a network location not allowed, \
|
||||
or names a device: it is not looked for), changed (whether the file is no longer what this design last read: Update Links \
|
||||
reads it again; null when not found or the link is older than this record), and then host (the network location) and reason",
|
||||
@@ -493,6 +541,12 @@ fn component_key(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<u64> {
|
||||
s.doc.find_component(&k).ok_or_else(|| bad(cmd, format!("no component `{k}`")))
|
||||
}
|
||||
|
||||
/// A command's reply as JSON: they build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "component.insert_design";
|
||||
let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?;
|
||||
@@ -515,7 +569,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut transform = solidcraft_doc::IDENTITY;
|
||||
transform[3] = [translate.x, translate.y, translate.z, 1.0];
|
||||
let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?;
|
||||
return Ok(json!({"occurrence": occurrence, "component": component}));
|
||||
return reply(cmd, InsertDesignResult { inserted: DesignInserted::Reused { occurrence, component }, param_warnings: Vec::new() });
|
||||
}
|
||||
}
|
||||
let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation())?;
|
||||
@@ -555,10 +609,18 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
inherit_properties(s, comp, &properties)?;
|
||||
s.refresh();
|
||||
let st = s.model.state();
|
||||
let bodies: Vec<&str> = st.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.as_str()).collect();
|
||||
Ok(
|
||||
json!({"component": comp, "occurrence": occ, "name": name, "feature": id, "path": path, "bodies": bodies, "created_bodies": bodies, "warnings": sf.warnings}),
|
||||
)
|
||||
let bodies: Vec<String> = st.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect();
|
||||
let inserted = DesignInserted::New {
|
||||
component: comp,
|
||||
occurrence: occ,
|
||||
name,
|
||||
feature: id,
|
||||
path,
|
||||
created_bodies: bodies.clone(),
|
||||
bodies,
|
||||
warnings: sf.warnings,
|
||||
};
|
||||
reply(cmd, InsertDesignResult { inserted, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -581,7 +643,8 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let go_on = p.get("components").is_some();
|
||||
let links: Vec<(u64, DesignLink)> =
|
||||
s.doc.links.iter().filter(|(c, _)| only.as_ref().is_none_or(|o| o.contains(c))).map(|(c, l)| (*c, l.clone())).collect();
|
||||
let (mut updated, mut unchanged, mut warnings, mut failed) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut updated, mut unchanged, mut warnings): (Vec<String>, Vec<String>, Vec<String>) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut failed: Vec<LinkFailure> = Vec::new();
|
||||
let count = links.len();
|
||||
for (index, (comp, link)) in links.into_iter().enumerate() {
|
||||
let cname = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone());
|
||||
@@ -595,7 +658,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (old, file, bytes) = match read_linked(s, comp, &link) {
|
||||
Ok(read) => read,
|
||||
Err(e) if go_on => {
|
||||
failed.push(json!({"component": comp, "name": cname, "error": e}));
|
||||
failed.push(LinkFailure { component: comp, name: cname.clone(), error: e.clone() });
|
||||
warnings.push(format!("{cname} keeps its bodies: {e}"));
|
||||
continue;
|
||||
}
|
||||
@@ -634,7 +697,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(kept) = s.doc_mut().links.get_mut(&comp) {
|
||||
kept.file_sha256.clone_from(&link.file_sha256);
|
||||
}
|
||||
failed.push(json!({"component": comp, "name": cname, "error": e.to_string()}));
|
||||
failed.push(LinkFailure { component: comp, name: cname.clone(), error: e.to_string() });
|
||||
warnings.push(format!("{cname} keeps its bodies: {e}"));
|
||||
continue;
|
||||
}
|
||||
@@ -679,8 +742,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
solidcraft_doc::progress::item(None);
|
||||
// None could be read: nothing to take back either.
|
||||
if updated.is_empty() && unchanged.is_empty() && !failed.is_empty() {
|
||||
let (name, why) = (failed[0]["name"].as_str().unwrap_or_default(), failed[0]["error"].as_str().unwrap_or_default());
|
||||
return Err(bad(cmd, format!("{name}: {why}")));
|
||||
return Err(bad(cmd, format!("{}: {}", failed[0].name, failed[0].error)));
|
||||
}
|
||||
s.refresh();
|
||||
if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) {
|
||||
@@ -691,7 +753,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
|
||||
warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}")));
|
||||
}
|
||||
Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings, "failed": failed}))
|
||||
reply(cmd, UpdateLinksResult { updated, unchanged, warnings, failed, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// `comp`'s linked design as it was last read (its bodies) and as its file is now, read before
|
||||
@@ -777,25 +839,39 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Report the solver's diagnostics. A resolved joint can still describe the wrong
|
||||
// connection after a source edit; the reminder above does not depend on solve errors.
|
||||
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
|
||||
let diagnostics =
|
||||
|rows: &[(u64, String, String)]| rows.iter().map(|(id, name, why)| json!({"joint": id, "name": name, "why": why})).collect::<Vec<_>>();
|
||||
let diagnostics = |rows: &[(u64, String, String)]| {
|
||||
rows.iter().map(|(joint, name, why)| JointDiagnostic { joint: *joint, name: name.clone(), why: why.clone() }).collect::<Vec<_>>()
|
||||
};
|
||||
for (_, name, why) in sol.errors.iter().chain(&sol.conflicts) {
|
||||
warnings.push(format!("joint {name}: {why}"));
|
||||
}
|
||||
let previous_path = stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path));
|
||||
Ok(json!({"component": comp, "feature": link.feature, "path": path, "previous_path": previous_path, "geometry_changed": geometry_changed,
|
||||
"warnings": warnings, "joint_errors": diagnostics(&sol.errors), "joint_conflicts": diagnostics(&sol.conflicts)}))
|
||||
reply(
|
||||
cmd,
|
||||
RelinkResult {
|
||||
component: comp,
|
||||
feature: link.feature,
|
||||
path,
|
||||
previous_path,
|
||||
geometry_changed,
|
||||
warnings,
|
||||
joint_errors: diagnostics(&sol.errors),
|
||||
joint_conflicts: diagnostics(&sol.conflicts),
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "component.break_link";
|
||||
let comp = component_key(s, p, "component", cmd)?;
|
||||
let link = s.doc_mut().links.remove(&comp).ok_or_else(|| bad(cmd, "that component is not linked to a design"))?;
|
||||
Ok(json!({"component": comp, "path": stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path))}))
|
||||
let path = stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path));
|
||||
reply(cmd, BreakLinkResult { component: comp, path, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let links: Vec<Value> = s
|
||||
let links: Vec<LinkInfo> = s
|
||||
.doc
|
||||
.links
|
||||
.iter()
|
||||
@@ -816,16 +892,24 @@ fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
.as_ref()
|
||||
.filter(|_| found == Some(true))
|
||||
.and_then(|kept| file_sha256(Path::new(file.as_ref()), s.path.as_deref()).map(|now| now != *kept));
|
||||
json!({"component": c, "name": name, "path": path, "file": file, "found": found, "changed": changed})
|
||||
LinkInfo::Looked { component: *c, name, path, file: file.into_owned(), found, changed }
|
||||
}
|
||||
Some(solidcraft_io::vfs::Remote::Network(host)) => LinkInfo::Network {
|
||||
component: *c,
|
||||
name,
|
||||
path,
|
||||
file: file.into_owned(),
|
||||
found: None,
|
||||
reason: format!("on the network location \\\\{host}, which is not allowed"),
|
||||
host,
|
||||
},
|
||||
Some(solidcraft_io::vfs::Remote::Device) => {
|
||||
LinkInfo::Device { component: *c, name, path, file: file.into_owned(), found: None, reason: "names a device, not a file".into() }
|
||||
}
|
||||
Some(solidcraft_io::vfs::Remote::Network(host)) => json!({"component": c, "name": name, "path": path, "file": file,
|
||||
"found": null, "host": host, "reason": format!("on the network location \\\\{host}, which is not allowed")}),
|
||||
Some(solidcraft_io::vfs::Remote::Device) => json!({"component": c, "name": name, "path": path, "file": file,
|
||||
"found": null, "reason": "names a device, not a file"}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"links": links}))
|
||||
reply("component.links", LinksResult { links, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -211,6 +211,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
for k in keys(p, "canvases") {
|
||||
// A locked canvas stays (#12310), as a locked body does.
|
||||
if let Some(c) = s.doc.canvases.iter().find(|c| c.id.to_string() == k || c.name == k).filter(|c| c.locked) {
|
||||
skip(super::sketch_canvas::locked_reason(c));
|
||||
continue;
|
||||
}
|
||||
sub(s, "canvas.delete", json!({ "canvas": k }))?;
|
||||
done = true;
|
||||
}
|
||||
|
||||
+118
-25
@@ -87,7 +87,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("timeline.roll_to", "Roll History Marker", roll_to).icon("rollback")
|
||||
.params("position: number of features to keep active, or \"end\" (omit = end) | feature: id|name (the marker goes right after it)"),
|
||||
CommandSpec::new("timeline.reorder", "Reorder Feature", reorder).icon("reorder")
|
||||
.params("feature: id|name, position: its new index, active?: bool (true = it ends up before the history marker, false = behind it; other features keep their state); 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"),
|
||||
.params("feature: id|name, position: its new index, active?: bool (true = it ends up before the history marker, false = behind it; other features keep their state); 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 → feature, position: its index now, from: its index before, moved: bool, note?: why nothing moved, or that a position past the end meant the last slot"),
|
||||
CommandSpec::new("timeline.reorder_many", "Reorder Features", reorder_many).icon("reorder").params(
|
||||
"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",
|
||||
),
|
||||
@@ -449,22 +449,96 @@ fn group_tree(doc: &solidcraft_doc::Document, roots: &[u64]) -> (std::collection
|
||||
}
|
||||
|
||||
fn sort_group_features(doc: &mut solidcraft_doc::Document) {
|
||||
let positions: std::collections::BTreeMap<u64, usize> = doc.features.iter().enumerate().map(|(index, feature)| (feature.id, index)).collect();
|
||||
for group in &mut doc.timeline_groups {
|
||||
sort_folder_features(&doc.features, &mut doc.timeline_groups);
|
||||
}
|
||||
|
||||
fn sort_folder_features(features: &[Feature], folders: &mut [solidcraft_doc::TimelineGroup]) {
|
||||
let positions: std::collections::BTreeMap<u64, usize> = features.iter().enumerate().map(|(index, feature)| (feature.id, index)).collect();
|
||||
for group in folders {
|
||||
group.features.sort_by_key(|feature| positions.get(feature).copied().unwrap_or(usize::MAX));
|
||||
}
|
||||
}
|
||||
|
||||
fn require_contiguous_groups(doc: &solidcraft_doc::Document, cmd: &str) -> Result<()> {
|
||||
let Some(id) = solidcraft_doc::non_contiguous_timeline_group(&doc.features, &doc.timeline_groups) else { return Ok(()) };
|
||||
let name = doc.timeline_groups.iter().find(|group| group.id == id).map(|group| group.name.as_str()).unwrap_or("unknown");
|
||||
Err(bad(cmd, format!("timeline folder `{name}` must contain one contiguous run of features")))
|
||||
Err(not_contiguous(&doc.timeline_groups, id, cmd))
|
||||
}
|
||||
|
||||
fn not_contiguous(folders: &[solidcraft_doc::TimelineGroup], id: u64, cmd: &str) -> EngineError {
|
||||
let name = folders.iter().find(|group| group.id == id).map(|group| group.name.as_str()).unwrap_or("unknown");
|
||||
bad(cmd, format!("timeline folder `{name}` must contain one contiguous run of features"))
|
||||
}
|
||||
|
||||
/// The design's folders once `folder` is added, taking its features and joints out of any other
|
||||
/// folder and becoming the parent of the folders `groups` (whose features and joints it then holds
|
||||
/// through them), and the first folder that would no longer be one run of features, if any.
|
||||
fn folders_with(
|
||||
doc: &solidcraft_doc::Document,
|
||||
mut folder: solidcraft_doc::TimelineGroup,
|
||||
groups: &[u64],
|
||||
) -> (Vec<solidcraft_doc::TimelineGroup>, Option<u64>) {
|
||||
let nested = group_feature_ids(doc, groups);
|
||||
folder.features.retain(|feature| !nested.contains(feature));
|
||||
let nested_joints = group_joint_ids(doc, groups);
|
||||
folder.joints.retain(|joint| !nested_joints.contains(joint));
|
||||
let mut next = doc.timeline_groups.clone();
|
||||
for group in &mut next {
|
||||
group.joints.retain(|joint| !folder.joints.contains(joint));
|
||||
group.features.retain(|feature| !folder.features.contains(feature));
|
||||
if groups.contains(&group.id) {
|
||||
group.parent = Some(folder.id);
|
||||
}
|
||||
}
|
||||
next.push(folder);
|
||||
sort_folder_features(&doc.features, &mut next);
|
||||
let broken = solidcraft_doc::non_contiguous_timeline_group(&doc.features, &next);
|
||||
(next, broken)
|
||||
}
|
||||
|
||||
/// A new folder named `name` holding `features` and `joints`, inside the folder `parent` (`None`:
|
||||
/// at the history's root), as `timeline.group` makes it. Returns its id.
|
||||
pub(crate) fn new_folder(s: &mut Session, name: &str, features: Vec<u64>, joints: Vec<u64>, parent: Option<u64>, cmd: &str) -> Result<u64> {
|
||||
// Folder names are 1…128 bytes, as `timeline.rename_group` takes them.
|
||||
let mut name = name.trim().to_string();
|
||||
while name.len() > 128 {
|
||||
name.pop();
|
||||
}
|
||||
let name = if name.is_empty() { format!("Folder{}", s.doc.timeline_groups.len() + 1) } else { name };
|
||||
let id = s.doc_mut().allocate_id()?;
|
||||
let (folders, broken) = folders_with(&s.doc, solidcraft_doc::TimelineGroup { id, name, parent, features, joints }, &[]);
|
||||
if let Some(broken) = broken {
|
||||
return Err(not_contiguous(&folders, broken, cmd));
|
||||
}
|
||||
s.doc_mut().timeline_groups = folders;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The id a folder that is only being tried out goes by.
|
||||
const TRIAL_FOLDER: u64 = u64::MAX;
|
||||
|
||||
impl Session {
|
||||
/// Why `timeline.group` would refuse a new folder holding `features` inside the folder
|
||||
/// `parent` (`None` at the history's root), in words for a menu's tooltip; `None` when it
|
||||
/// would make it.
|
||||
pub fn group_refusal(&self, features: &[u64], parent: Option<u64>) -> Option<String> {
|
||||
if features.is_empty() {
|
||||
return Some("No features are selected".into());
|
||||
}
|
||||
let trial = solidcraft_doc::TimelineGroup { id: TRIAL_FOLDER, name: String::new(), parent, features: features.to_vec(), joints: Vec::new() };
|
||||
let (folders, broken) = folders_with(&self.doc, trial, &[]);
|
||||
let broken = broken?;
|
||||
if broken == TRIAL_FOLDER {
|
||||
return Some("The features aren't next to each other in the history".into());
|
||||
}
|
||||
let name = folders.iter().find(|folder| folder.id == broken).map_or("", |folder| folder.name.as_str());
|
||||
Some(format!("Folder {name} would no longer hold one run of features"))
|
||||
}
|
||||
}
|
||||
|
||||
fn group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "timeline.group";
|
||||
let mut features = group_features(s, p, false, cmd)?;
|
||||
let mut joints = group_joints(s, p, cmd)?;
|
||||
let features = group_features(s, p, false, cmd)?;
|
||||
let joints = group_joints(s, p, cmd)?;
|
||||
let groups = group_ids(s, p, false, cmd)?;
|
||||
let name = match str_(p, "name").map(str::trim).filter(|name| !name.is_empty()) {
|
||||
Some(name) if name.len() <= 128 => name.to_string(),
|
||||
@@ -481,22 +555,12 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(cmd, "a new folder cannot contain an ancestor of its parent"));
|
||||
}
|
||||
let nested = group_feature_ids(&s.doc, &groups);
|
||||
features.retain(|feature| !nested.contains(feature));
|
||||
let nested_joints = group_joint_ids(&s.doc, &groups);
|
||||
joints.retain(|joint| !nested_joints.contains(joint));
|
||||
let mut next = (*s.doc).clone();
|
||||
for group in &mut next.timeline_groups {
|
||||
group.joints.retain(|joint| !joints.contains(joint));
|
||||
group.features.retain(|feature| !features.contains(feature));
|
||||
if groups.contains(&group.id) {
|
||||
group.parent = Some(id);
|
||||
}
|
||||
let folder = solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features, joints };
|
||||
let (folders, broken) = folders_with(&s.doc, folder, &groups);
|
||||
if let Some(broken) = broken {
|
||||
return Err(not_contiguous(&folders, broken, cmd));
|
||||
}
|
||||
next.timeline_groups.push(solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features, joints });
|
||||
sort_group_features(&mut next);
|
||||
require_contiguous_groups(&next, cmd)?;
|
||||
*s.doc_mut() = next;
|
||||
s.doc_mut().timeline_groups = folders;
|
||||
Ok(json!({"group": id, "name": name, "parent": parent, "groups": groups}))
|
||||
}
|
||||
|
||||
@@ -1521,11 +1585,15 @@ fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "timeline.reorder";
|
||||
let id = feature_id(s, p.get("feature"), cmd)?;
|
||||
let n = s.doc.features.len();
|
||||
let to = num(p, "position").map(|x| x.max(0.0) as usize).ok_or_else(|| bad(cmd, "`position` must be a number"))?.min(n.saturating_sub(1));
|
||||
let asked = num(p, "position").map(|x| x.max(0.0) as usize).ok_or_else(|| bad(cmd, "`position` must be a number"))?;
|
||||
// A position past the end means the last slot; the reply says so (#12140).
|
||||
let to = asked.min(n.saturating_sub(1));
|
||||
let capped = (asked != to).then(|| format!("position {asked} is past the end, so the last slot, {to}, was used"));
|
||||
let from = s.doc.feature_index(id).ok_or_else(|| bad(cmd, "feature"))?;
|
||||
let active = active_param(p, cmd)?;
|
||||
if from == to && active.is_none() {
|
||||
return Ok(json!({"feature": id, "position": to}));
|
||||
let why = capped.map_or_else(|| format!("it is already at position {to}"), |c| format!("{c}, where it already is"));
|
||||
return Ok(json!({"feature": id, "position": to, "from": from, "moved": false, "note": format!("nothing moved: {why}")}));
|
||||
}
|
||||
let mut next = (*s.doc).clone();
|
||||
let f = next.features.remove(from);
|
||||
@@ -1540,11 +1608,27 @@ fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `allow_errors`: made anyway, with what it broke said (#5962).
|
||||
let allow = allow_errors(p, cmd)?;
|
||||
if !broken.is_empty() && !allow {
|
||||
// The moved feature itself failing: say why, and only when it moved earlier suggest that
|
||||
// it now comes before something it uses, such as an extrude ahead of its sketch (#12140).
|
||||
// Moved later, it fails for another reason, such as a feature that removed its body.
|
||||
if let Some((_, error)) = broken.iter().find(|(n, _)| *n == name) {
|
||||
let hint = if to < from {
|
||||
"; if it uses a feature that would now come after it, move that feature earlier first"
|
||||
} else {
|
||||
"; a feature it would now come after changes what it works on"
|
||||
};
|
||||
return Err(bad(cmd, format!("moving {name} to position {to} breaks {name} ({error}){hint}")));
|
||||
}
|
||||
let list: Vec<String> = broken.iter().map(|(n, e)| format!("{n} ({e})")).collect();
|
||||
return Err(bad(cmd, format!("moving {name} there breaks {}", list.join("; "))));
|
||||
}
|
||||
let marker = next.marker;
|
||||
place_marker(s, &mut next, &[id], active, cmd)?;
|
||||
// Never report a move that didn't happen (#12140): the reply gives where the feature is now.
|
||||
let now = next.feature_index(id).ok_or_else(|| bad(cmd, "feature"))?;
|
||||
if now != to {
|
||||
return Err(bad(cmd, format!("{name} would stay at position {now}, not {to}")));
|
||||
}
|
||||
if next != *s.doc {
|
||||
// The check evaluated the new order: keep its results, so setting the design doesn't
|
||||
// evaluate the moved part of the timeline a second time (#6186). Placing the marker
|
||||
@@ -1554,7 +1638,16 @@ fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
*s.doc_mut() = next;
|
||||
}
|
||||
let mut out = json!({"feature": id, "position": to});
|
||||
let mut out = json!({"feature": id, "position": now, "from": from, "moved": now != from});
|
||||
// With `active`, a feature left in place may still cross the history marker: say which.
|
||||
let stayed = (now == from).then(|| {
|
||||
let what = if s.doc.marker == marker { "nothing moved" } else { "only the history marker moved" };
|
||||
format!("{what}: {name} is already at position {now}")
|
||||
});
|
||||
let note: Vec<String> = [capped, stayed].into_iter().flatten().collect();
|
||||
if !note.is_empty() {
|
||||
out["note"] = json!(note.join("; "));
|
||||
}
|
||||
if allow {
|
||||
out["broken"] = broken_json(&broken);
|
||||
}
|
||||
|
||||
@@ -1688,3 +1688,46 @@ fn assistant_toggle_is_refused_headlessly_without_changing_the_document() {
|
||||
let spec = crate::find_command("ui.assistant").unwrap();
|
||||
assert_eq!((spec.shortcut, spec.tab, spec.undoable), (Some("Ctrl+Shift+A"), "", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reorder_reports_where_the_feature_is_or_why_it_did_not_move() {
|
||||
// #12140: a reorder never reports success while the feature stays put without saying so.
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [50, 0, 0], "operation": "new_body", "name": "Block"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Profile"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0], [10, 10], [0, 10]], "closed": true}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new_body", "name": "Pad"}));
|
||||
let names = |s: &Session| s.doc.features.iter().map(|f| f.name.clone()).collect::<Vec<_>>();
|
||||
// A position past the end, where the feature already is: nothing moved, and the note says why.
|
||||
let out = run(&mut s, "timeline.reorder", json!({"feature": "Pad", "position": 9}));
|
||||
assert_eq!((out["position"].as_u64(), out["from"].as_u64(), out["moved"].as_bool()), (Some(2), Some(2), Some(false)));
|
||||
assert!(out["note"].as_str().is_some_and(|n| n.contains("nothing moved") && n.contains("past the end")), "{out}");
|
||||
// Ahead of its own sketch: refused, naming the cause.
|
||||
let e = s.execute("timeline.reorder", &json!({"feature": "Pad", "position": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("breaks Pad") && e.contains("move that feature earlier first"), "{e}");
|
||||
assert_eq!(names(&s), ["Block", "Profile", "Pad"], "a refused move leaves the order");
|
||||
// Moving the sketch first lets the extrude follow; the reply gives the real index.
|
||||
let out = run(&mut s, "timeline.reorder", json!({"feature": "Profile", "position": 0}));
|
||||
assert_eq!((out["position"].as_u64(), out["from"].as_u64(), out["moved"].as_bool()), (Some(0), Some(1), Some(true)));
|
||||
let out = run(&mut s, "timeline.reorder", json!({"feature": "Pad", "position": 1}));
|
||||
assert_eq!((out["position"].as_u64(), out["moved"].as_bool()), (Some(1), Some(true)));
|
||||
assert!(out.get("note").is_none(), "{out}");
|
||||
assert_eq!(names(&s), ["Profile", "Pad", "Block"]);
|
||||
// `active` on a feature left in place: the note says only the marker moved.
|
||||
run(&mut s, "timeline.reorder", json!({"feature": "Block", "position": 2, "active": false}));
|
||||
let out = run(&mut s, "timeline.reorder", json!({"feature": "Block", "position": 2, "active": true}));
|
||||
assert_eq!((out["moved"].as_bool(), s.doc.marker), (Some(false), None));
|
||||
assert!(out["note"].as_str().is_some_and(|n| n.contains("only the history marker moved")), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reorder_refusal_after_a_feature_that_removes_its_body_does_not_blame_the_order_of_its_inputs() {
|
||||
// A fillet moved behind a cut that removes its whole body fails though what it uses is earlier.
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "Base"}));
|
||||
run(&mut s, "solid.fillet", json!({"edges": [[10, 5, 10]], "radius": 1, "name": "Round"}));
|
||||
run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 30, "corner": [-10, -10, -10], "operation": "cut", "name": "Clear"}));
|
||||
let e = s.execute("timeline.reorder", &json!({"feature": "Round", "position": 2})).unwrap_err().to_string();
|
||||
assert!(e.contains("breaks Round") && e.contains("changes what it works on") && !e.contains("earlier first"), "{e}");
|
||||
}
|
||||
@@ -200,7 +200,10 @@ fn a_second_distance_goes_the_other_way_from_the_first_side() {
|
||||
for (settings, lo, hi) in [
|
||||
(json!({"direction":"positive","distance":"10 mm","distance2":"4 mm"}), -4.0, 10.0),
|
||||
(json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"}), -10.0, 4.0),
|
||||
(json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, 4.0),
|
||||
// A sign only turns its own side over: Distance 2 stays where Direction puts it, so a
|
||||
// negative Distance 1 leaves the span between the two ends.
|
||||
(json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, -4.0),
|
||||
(json!({"direction":"negative","distance":"-10 mm","distance2":"4 mm"}), 4.0, 10.0),
|
||||
] {
|
||||
let s = fixture(settings.clone());
|
||||
check(&s, lo, hi);
|
||||
@@ -249,3 +252,34 @@ fn an_older_reversed_two_sided_extrude_keeps_its_shape() {
|
||||
let FeatureKind::Extrude { extent, .. } = &s.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") };
|
||||
assert_eq!(extent.direction, solidcraft_doc::Direction::Positive);
|
||||
}
|
||||
|
||||
/// Designs saved before entered distances kept their sides sent Distance 2 to the other side of
|
||||
/// a negative first distance. Opening one keeps that, for an expression too and after its
|
||||
/// parameter changes, and leaves the distance and its named input as they were.
|
||||
#[test]
|
||||
fn an_older_two_sided_extrude_with_a_negative_distance_keeps_its_sides() {
|
||||
let mut base = fixture(json!({"direction":"positive","distance":"10 mm","distance2":"10 mm"}));
|
||||
run(&mut base, "parameters.add", json!({"name":"width","expression":"20 mm"}));
|
||||
let mut saved: Value = serde_json::from_str(&base.doc.to_json()).unwrap();
|
||||
// As the last release saved it: the format before this build's pending changes.
|
||||
let version: u32 = saved["format"].as_str().unwrap().trim_start_matches("solidcraft/").parse().unwrap();
|
||||
saved["format"] = json!(format!("solidcraft/{}", version - 1));
|
||||
saved.as_object_mut().unwrap().remove("format_pending");
|
||||
for (distance, lo, hi) in [("-width", -20.0, 10.0), ("-0 mm", -10.0, 0.0), ("-10 mm", -10.0, 10.0)] {
|
||||
let mut file = saved.clone();
|
||||
for f in file["features"].as_array_mut().unwrap() {
|
||||
if f["type"] == "extrude" {
|
||||
f["extent"]["distance"] = json!(distance);
|
||||
}
|
||||
}
|
||||
let mut opened = Session::new(Document::from_json(&file.to_string()).unwrap());
|
||||
check(&opened, lo, hi);
|
||||
let FeatureKind::Extrude { extent, .. } = &opened.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") };
|
||||
assert_eq!(extent.distance, distance);
|
||||
if distance == "-width" {
|
||||
run(&mut opened, "parameters.change", json!({"name":"width","expression":"15 mm"}));
|
||||
check(&opened, -15.0, 10.0);
|
||||
}
|
||||
check(&Session::new(Document::from_json(&opened.doc.to_json()).unwrap()), if distance == "-width" { -15.0 } else { lo }, hi);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.key("E")
|
||||
.contract(&EXTRUDE_CONTRACT)
|
||||
.output(output_schema_for::<FeatureResult>)
|
||||
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance on the side direction leaves free, the first side may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it; a negative distance only turns its own side over); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
CommandSpec::new("solid.revolve", "Revolve", revolve)
|
||||
.at("SOLID", "CREATE")
|
||||
.icon("revolve")
|
||||
@@ -155,7 +155,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("plane_angle")
|
||||
.contract(&PLANE_AT_ANGLE_CONTRACT)
|
||||
.output(output_schema_for::<FeatureResult>)
|
||||
.params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle: expr; name?"),
|
||||
.params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle: expr; direction_only?: bool (default false: turn about the axis as a line; true: project the axis direction onto base and turn about the line through pivot, or the base origin); pivot?: point ref (only with direction_only; vertex, sketch point, construction point); name?"),
|
||||
CommandSpec::new("solid.split_face", "Split Face", split_face)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("split_face")
|
||||
@@ -1269,6 +1269,7 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result<Extent>
|
||||
distance2,
|
||||
start_offset,
|
||||
through_all,
|
||||
second_follows_first: false,
|
||||
taper,
|
||||
corner,
|
||||
to: p.get("to").and_then(vec3).map(FacePick),
|
||||
@@ -1708,7 +1709,13 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Another curved face moves along its normal.
|
||||
if super::face::face_is_planar(s, fp) == Some(false) {
|
||||
let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?;
|
||||
return (r.run)(s, &json!({"faces": [face], "distance": distance}));
|
||||
let mut q = json!({"faces": [face], "distance": distance});
|
||||
// The face's body, when given, goes along: found by point alone, a face inside another
|
||||
// part's box (a screw bore in a housing) can be looked for on that part instead.
|
||||
if let Some(body) = p.get("body").filter(|b| b.is_string()) {
|
||||
q["body"] = body.clone();
|
||||
}
|
||||
return (r.run)(s, &q);
|
||||
}
|
||||
}
|
||||
// Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps
|
||||
@@ -2526,17 +2533,30 @@ fn plane_angle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let angle = req_expr(cmd, p, "angle")?;
|
||||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||||
let line = line.map(Box::new);
|
||||
let direction_only = crate::params::bool_(p, "direction_only").unwrap_or(false);
|
||||
let pivot = match p.get("pivot").filter(|t| !t.is_null()) {
|
||||
Some(_) if !direction_only => return Err(bad(cmd, "`pivot` needs `direction_only`: true")),
|
||||
Some(t) => Some(Box::new(super::construct::geo(s, Some(t), cmd, "pivot")?)),
|
||||
None => None,
|
||||
};
|
||||
let at_angle = |base: solidcraft_doc::PlaneRef| solidcraft_doc::PlaneRef::AtAngle {
|
||||
base: Box::new(base),
|
||||
axis_origin,
|
||||
axis_dir,
|
||||
angle: angle.clone(),
|
||||
line: line.clone(),
|
||||
direction_only,
|
||||
pivot: pivot.clone(),
|
||||
};
|
||||
// A planar body face: attached exactly, as a sketch on that face is, so the plane follows it.
|
||||
if let Some(face) = p.get("base").filter(|b| b.get("face").is_some()) {
|
||||
let base = super::sketch::face::capture(s, face, cmd)?;
|
||||
super::sketch::face::capture_positions(s, &base)?;
|
||||
let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line };
|
||||
// The capture is already in the authoring frame.
|
||||
return add_feature_in(s, p, FeatureKind::ConstructionPlane { plane }, false);
|
||||
return add_feature_in(s, p, FeatureKind::ConstructionPlane { plane: at_angle(base) }, false);
|
||||
}
|
||||
let base = plane_param(s, p.get("base"), cmd)?;
|
||||
let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line };
|
||||
add_feature(s, p, FeatureKind::ConstructionPlane { plane })
|
||||
add_feature(s, p, FeatureKind::ConstructionPlane { plane: at_angle(base) })
|
||||
}
|
||||
|
||||
fn split_face(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -31,15 +31,15 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("open")
|
||||
.key("Ctrl+O")
|
||||
.noundo()
|
||||
.params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
|
||||
.params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); origin?: bool for a mesh file (see file.insert_mesh); folder?: bool for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
|
||||
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
|
||||
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?, group?: the folder); folder?: bool (default false; true: an import that brings more than one item into the history (its Import feature and the rigid joints holding its parts) goes into a new history folder named `Group #N`); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
|
||||
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
.params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept)"),
|
||||
.params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept); units?: mm|cm|m|in|ft for an STL or OBJ file, or a PLY file with faces (default mm): the unit its coordinates are in, scaled to millimetres as the file is read (a 3MF or glTF file states its own). The design keeps the millimetre mesh and not the unit, so insert the file again to try another; origin?: bool (default false: the mesh keeps its file's coordinates; true: once read, scaled and stood up, the import's occurrence is moved so the box around its bodies is centred on X and Y of the active component with its lowest point on Z = 0 → moved_to_origin: [x, y, z], the shift made)"),
|
||||
CommandSpec::new("file.save", "Save", save)
|
||||
.icon("save")
|
||||
.key("Ctrl+S")
|
||||
@@ -139,6 +139,9 @@ struct StepOptions {
|
||||
/// (Y becomes Z), as the app's "Stand it up" offer does. `z` (the default) keeps the file's axes.
|
||||
y_up: bool,
|
||||
names: solidcraft_io::StepNames,
|
||||
/// `folder: true`: an import that brings more than one item gets a `Group #N` history folder
|
||||
/// (`import_folder`). `false` (the default) makes none, as before the option.
|
||||
folder: bool,
|
||||
}
|
||||
|
||||
fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
|
||||
@@ -157,7 +160,17 @@ fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
|
||||
.and_then(solidcraft_io::StepNames::parse)
|
||||
.ok_or_else(|| bad(cmd, "`names` must be \"auto\", \"solid\", \"product\" or \"instance\""))?,
|
||||
};
|
||||
Ok(StepOptions { y_up, names })
|
||||
let folder = match p.get("folder") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(folder)) => *folder,
|
||||
Some(_) => {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
"`folder` must be true (an import that brings more than one item goes into a `Group #N` history folder) or false (no folder)",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(StepOptions { y_up, names, folder })
|
||||
}
|
||||
|
||||
/// Read a STEP file as an Import feature.
|
||||
@@ -200,6 +213,7 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
|
||||
// assembly's parts and instances turn together.
|
||||
let turned = if options.y_up { turn_up(s, &placed)? } else { None };
|
||||
let created = created_bodies(s, id);
|
||||
let folder = if options.folder { import_folder(s, id, &placed)? } else { None };
|
||||
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": created, "created_bodies": created, "warnings": sf.warnings, "system": sf.import.system});
|
||||
if let Some((up, exporter)) = exporter_up(&sf.import) {
|
||||
@@ -210,6 +224,9 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
|
||||
if let Some(turned) = turned {
|
||||
out["stand_up"] = json!(turned);
|
||||
}
|
||||
if let Some(folder) = folder {
|
||||
out["group"] = json!(folder);
|
||||
}
|
||||
if let Some(mark) = profiled {
|
||||
let report = crate::schema::diagnostics::ProfileReport::new(&mark.report(), 20);
|
||||
out["profile"] = serde_json::to_value(report).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
@@ -217,6 +234,26 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// An import that brings more than one item into the history (its Import feature and the rigid
|
||||
/// joints holding its parts together) goes into a history folder of its own, named `Group #N`,
|
||||
/// holding the feature and those joints, so it stands apart from the features before and after
|
||||
/// it and the History shows it as one chip. The folder sits in the folder the feature was put
|
||||
/// in, if any. Returns the folder.
|
||||
fn import_folder(s: &mut Session, feature: u64, placed: &import::Placed) -> Result<Option<u64>> {
|
||||
if placed.joints.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parent = s.doc.timeline_groups.iter().find(|folder| folder.features.contains(&feature)).map(|folder| folder.id);
|
||||
let name = next_group_name(&s.doc);
|
||||
super::edit::new_folder(s, &name, vec![feature], placed.joints.clone(), parent, "file.insert_step").map(Some)
|
||||
}
|
||||
|
||||
/// The first `Group #N` no history folder is named yet.
|
||||
fn next_group_name(doc: &Document) -> String {
|
||||
let taken = |name: &str| doc.timeline_groups.iter().any(|folder| folder.name == name);
|
||||
(1..=doc.timeline_groups.len() + 1).map(|n| format!("Group #{n}")).find(|name| !taken(name)).unwrap_or_else(|| "Group".into())
|
||||
}
|
||||
|
||||
/// The bodies an import feature built, by name.
|
||||
fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
|
||||
s.model.state().bodies.iter().filter(|b| b.feature == feature).map(|b| b.name.clone()).collect()
|
||||
@@ -225,7 +262,7 @@ fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
|
||||
/// Add a MeshImport feature for a 3MF, STL, OBJ or glTF file, in a new component named after the
|
||||
/// file. A glTF file's nodes become components in it, and its materials the bodies' looks; it is
|
||||
/// in metres with Y up, so unless `y_up` is false its component is turned to Z up (#1505).
|
||||
fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>) -> Result<Value> {
|
||||
fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>, unit: Option<(&'static str, f64)>, origin: bool) -> Result<Value> {
|
||||
let err = |e: solidcraft_io::IoError| EngineError::Other(format!("{path}: {e}"));
|
||||
let bytes = solidcraft_io::vfs::read(path, solidcraft_io::MAX_3MF_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let gltf = solidcraft_io::is_gltf_path(path);
|
||||
@@ -239,7 +276,7 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
|
||||
}
|
||||
(g.feature, Some(g.plan), g.looks)
|
||||
} else {
|
||||
(solidcraft_io::mesh_import_feature(&bytes, path).map_err(err)?, None, Vec::new())
|
||||
(solidcraft_io::mesh_import_feature_in(&bytes, path, unit.map_or(1.0, |(_, mm)| mm)).map_err(err)?, None, Vec::new())
|
||||
};
|
||||
let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&mf.name).to_string();
|
||||
let cname = import::component_name(path, name);
|
||||
@@ -259,9 +296,17 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
|
||||
s.refresh();
|
||||
}
|
||||
let turned = if gltf && y_up.unwrap_or(true) { turn_up(s, &placed)? } else { None };
|
||||
// After the turn, so it is the stood-up mesh that sits on Z = 0.
|
||||
let moved = if origin { import::move_to_origin(s, &placed)? } else { None };
|
||||
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": bodies, "created_bodies": bodies, "warnings": mf.warnings});
|
||||
placed.report(&mut out);
|
||||
if let Some(shift) = moved {
|
||||
out["moved_to_origin"] = json!([shift.x, shift.y, shift.z]);
|
||||
}
|
||||
if let Some((name, _)) = unit {
|
||||
out["units"] = json!(name);
|
||||
}
|
||||
if let Some(turned) = turned {
|
||||
out["stand_up"] = json!(turned);
|
||||
}
|
||||
@@ -291,6 +336,27 @@ fn mesh_up(p: &Value, path: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
Ok(Some(step_options(p, cmd)?.y_up))
|
||||
}
|
||||
|
||||
/// `units` for an STL, OBJ or PLY file: the unit its coordinates are in (one of
|
||||
/// `solidcraft_doc::point_cloud::UNITS`, the same as a point cloud's), which they are scaled from
|
||||
/// to millimetres as the file is read. The design keeps the millimetre mesh and not the unit, so
|
||||
/// importing again is how a different unit is tried. A 3MF or glTF file states its own.
|
||||
fn mesh_units(p: &Value, path: &str, cmd: &str) -> Result<Option<(&'static str, f64)>> {
|
||||
let names = || solidcraft_doc::point_cloud::UNITS.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ");
|
||||
let unit = match p.get("units") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(u)) => solidcraft_doc::point_cloud::UNITS
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(u))
|
||||
.map(|(name, mm)| (*name, *mm))
|
||||
.ok_or_else(|| bad(cmd, format!("`units` must be one of {} (not `{u}`)", names())))?,
|
||||
Some(_) => return Err(bad(cmd, format!("`units` must be one of {}", names()))),
|
||||
};
|
||||
if solidcraft_io::is_gltf_path(path) || path.to_ascii_lowercase().ends_with(".3mf") {
|
||||
return Err(bad(cmd, "`units` applies to STL, OBJ and PLY files only: a 3MF or glTF file states its own"));
|
||||
}
|
||||
Ok(Some(unit))
|
||||
}
|
||||
|
||||
fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.insert_mesh";
|
||||
let path = path_arg(p, cmd)?;
|
||||
@@ -298,7 +364,21 @@ fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "only 3MF, STL, OBJ, PLY and glTF files (.3mf, .stl, .obj, .ply, .glb, .gltf) can be inserted as meshes"));
|
||||
}
|
||||
let up = mesh_up(p, path, cmd)?;
|
||||
add_mesh(s, path, str_(p, "name"), up)
|
||||
let unit = mesh_units(p, path, cmd)?;
|
||||
add_mesh(s, path, str_(p, "name"), up, unit, mesh_origin(p, cmd)?)
|
||||
}
|
||||
|
||||
/// `origin`: whether a mesh import is moved to the origin (#12543). Off unless asked, so a mesh
|
||||
/// keeps the coordinates its file gives it.
|
||||
fn mesh_origin(p: &Value, cmd: &str) -> Result<bool> {
|
||||
match p.get("origin") {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(Value::Bool(origin)) => Ok(*origin),
|
||||
Some(_) => Err(bad(
|
||||
cmd,
|
||||
"`origin` must be true (the mesh is moved so its box is centred on X and Y with its base on Z = 0) or false (the file's coordinates are kept)",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -336,6 +416,9 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !solidcraft_io::is_step_path(path) && !solidcraft_io::is_gltf_path(path) && p.get("up").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad("doc.open", "`up` applies to STEP, IGES and glTF files only"));
|
||||
}
|
||||
if !solidcraft_io::is_mesh_path(path) && p.get("origin").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad("doc.open", "`origin` applies to 3MF, STL, OBJ and glTF files only"));
|
||||
}
|
||||
if let Some(command) = super::drawing_import_command(path) {
|
||||
let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into());
|
||||
let mut fresh = Session::new(Document::new(&stem));
|
||||
@@ -375,7 +458,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = if solidcraft_io::is_step_path(path) {
|
||||
add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)?
|
||||
} else {
|
||||
add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?)?
|
||||
add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?, mesh_units(p, path, "doc.open")?, mesh_origin(p, "doc.open")?)?
|
||||
};
|
||||
// The design is the file: its component is the one being worked in.
|
||||
if let Some(c) = r["component"].as_u64() {
|
||||
@@ -386,7 +469,18 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.replace_design(fresh);
|
||||
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
|
||||
let mut out = json!({"path": path, "features": s.doc.features.len(), "errors": errors, "bodies": r["bodies"], "warnings": r["warnings"]});
|
||||
for k in ["component", "component_name", "occurrence", "subcomponents", "rigid_joints", "stand_up", "system", "exporter", "exporter_up"] {
|
||||
for k in [
|
||||
"component",
|
||||
"component_name",
|
||||
"occurrence",
|
||||
"subcomponents",
|
||||
"rigid_joints",
|
||||
"stand_up",
|
||||
"moved_to_origin",
|
||||
"system",
|
||||
"exporter",
|
||||
"exporter_up",
|
||||
] {
|
||||
if let Some(v) = r.get(k) {
|
||||
out[k] = v.clone();
|
||||
}
|
||||
@@ -671,6 +765,21 @@ impl Session {
|
||||
self.saved_visibility = done.saved_visibility.clone();
|
||||
}
|
||||
|
||||
/// The design's file was renamed (browser OPFS rename, or an equivalent host move): keep the
|
||||
/// open session on the new path, and when the design name was borrowed from the file, follow
|
||||
/// it so the tab title matches the file list (#11375). A name the user chose is kept, as on
|
||||
/// Save As.
|
||||
pub fn follow_file_rename(&mut self, old_path: &str, new_path: &str) {
|
||||
if self.path.as_deref() != Some(old_path) || old_path == new_path {
|
||||
return;
|
||||
}
|
||||
if let Some(stem) = saved_name(&self.doc.name, Some(old_path), new_path, self.user_named) {
|
||||
let from = self.doc.name.clone();
|
||||
rename_design(self, &from, &stem);
|
||||
}
|
||||
self.path = Some(new_path.to_string());
|
||||
}
|
||||
|
||||
/// Another program or computer wrote the design's file since it was opened or last saved:
|
||||
/// saving to it would replace that work (#5467). A file that is gone has not changed.
|
||||
pub fn disk_changed(&self) -> bool {
|
||||
@@ -1176,6 +1285,34 @@ mod tests {
|
||||
assert!(p["by_category"].as_array().is_some_and(|c| !c.is_empty()) && p["wall_ms"].as_f64().is_some_and(|w| w > 0.0), "{p}");
|
||||
}
|
||||
|
||||
/// Renaming the open design's file updates its path and, when the name came from the file,
|
||||
/// the design name the tab shows (#11375).
|
||||
#[test]
|
||||
fn follow_file_rename_updates_path_and_borrowed_design_name() {
|
||||
let mut s = Session::default();
|
||||
s.doc_mut().name = "Plate".into();
|
||||
s.path = Some("opfs://Plate.solidcraft".into());
|
||||
s.user_named = false;
|
||||
s.follow_file_rename("opfs://Plate.solidcraft", "opfs://Bracket.solidcraft");
|
||||
assert_eq!(s.path.as_deref(), Some("opfs://Bracket.solidcraft"));
|
||||
assert_eq!(s.doc.name, "Bracket");
|
||||
|
||||
let mut kept = Session::default();
|
||||
kept.doc_mut().name = "My part".into();
|
||||
kept.path = Some("opfs://Plate.solidcraft".into());
|
||||
kept.user_named = true;
|
||||
kept.follow_file_rename("opfs://Plate.solidcraft", "opfs://Bracket.solidcraft");
|
||||
assert_eq!(kept.path.as_deref(), Some("opfs://Bracket.solidcraft"));
|
||||
assert_eq!(kept.doc.name, "My part");
|
||||
|
||||
let mut other = Session::default();
|
||||
other.doc_mut().name = "Other".into();
|
||||
other.path = Some("opfs://Other.solidcraft".into());
|
||||
other.follow_file_rename("opfs://Plate.solidcraft", "opfs://Bracket.solidcraft");
|
||||
assert_eq!(other.path.as_deref(), Some("opfs://Other.solidcraft"));
|
||||
assert_eq!(other.doc.name, "Other");
|
||||
}
|
||||
|
||||
/// #8139: with `objects: "component"` a 3MF has one object for each placement of a component
|
||||
/// with two or more bodies, its bodies the object's parts; the design's own bodies stay objects
|
||||
/// of their own. The default (and `objects: "body"`) is one object per body, as before. Read
|
||||
|
||||
@@ -17,7 +17,9 @@ pub(super) struct Exported {
|
||||
pub ext: &'static str,
|
||||
/// A 3MF was asked for and couldn't be written, so this is an STL.
|
||||
pub fell_back: bool,
|
||||
/// The bodies that went in: the ones named, else the selected ones.
|
||||
/// The bodies that went in: the ones named, else the selected ones (read by `file.send`, which
|
||||
/// the browser build doesn't have).
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub bodies: Vec<String>,
|
||||
/// The bodies laid on their print face, and the ones that couldn't be.
|
||||
pub laid: super::print_face::Laid,
|
||||
|
||||
@@ -320,6 +320,63 @@ pub(crate) fn add_in_component(
|
||||
Ok((id, Placed { component: top, occurrence: top_occ, name, components: comps.len(), joints: joint_ids }))
|
||||
}
|
||||
|
||||
/// Move an import to the origin of the component it was inserted into (#12543): the box around
|
||||
/// its bodies, where they are placed, comes to sit centred on X and Y with its lowest point on
|
||||
/// Z = 0. The import's occurrence moves; the file's coordinates in the feature are kept, so the
|
||||
/// move is its placement and Move Occurrence takes it on from there. Returns the shift, in that
|
||||
/// component's frame; `None` when the import has no bodies to place.
|
||||
pub(crate) fn move_to_origin(s: &mut Session, placed: &Placed) -> Result<Option<Vec3>> {
|
||||
let occ = placed.occurrence.ok_or_else(|| EngineError::Other("the import has no placement to move".into()))?;
|
||||
// A component activated without a path is shown at its first placement, as elsewhere.
|
||||
let active = s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(s.active_component));
|
||||
// The frame the import was placed in: the origin it goes to.
|
||||
let parent = s.doc.path_transform(s.active_component, &active).unwrap_or(IDENTITY);
|
||||
let to_parent =
|
||||
solidcraft_doc::mat_inverse(&parent).ok_or_else(|| EngineError::Other("the active component's placement can't be inverted".into()))?;
|
||||
// This placement of the import only: the bodies whose path runs through its occurrence
|
||||
// where it sits in the active component.
|
||||
let ours: Vec<String> = s
|
||||
.doc
|
||||
.body_frames(&s.model.state())
|
||||
.into_iter()
|
||||
.filter(|(_, _, path, _)| path.starts_with(&active) && path.get(active.len()) == Some(&occ))
|
||||
.map(|(name, ..)| name)
|
||||
.collect();
|
||||
let world = s.world_state()?;
|
||||
let mut bounds = solidcraft_geom::Aabb3::EMPTY;
|
||||
for body in world.bodies.iter().filter(|b| ours.contains(&b.name)) {
|
||||
// Each body's own box in the active component's frame: a turned component's frame would
|
||||
// only take a larger box around the world box's corners, leaving the mesh off Z = 0.
|
||||
let b = if solidcraft_doc::is_identity(&to_parent) {
|
||||
body.body.exact_bounds()?
|
||||
} else {
|
||||
solidcraft_doc::kernel::place_matrix(&body.body, to_parent)?.exact_bounds()?
|
||||
};
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
bounds = bounds.union(&b);
|
||||
}
|
||||
if bounds.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let shift = Vec3::new(-(bounds.min.x + bounds.max.x) / 2.0, -(bounds.min.y + bounds.max.y) / 2.0, -bounds.min.z);
|
||||
if ![shift.x, shift.y, shift.z].iter().all(|v| v.is_finite()) {
|
||||
return Err(EngineError::Other("the import's bounds can't be placed at the origin".into()));
|
||||
}
|
||||
let mut by = IDENTITY;
|
||||
by[3] = [shift.x, shift.y, shift.z, 1.0];
|
||||
if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) {
|
||||
let moved = solidcraft_doc::mat_mul(&by, &o.transform);
|
||||
if !solidcraft_doc::is_placement(&moved) {
|
||||
return Err(EngineError::Other("moving the import to the origin takes it out of a placement within 1e9 mm".into()));
|
||||
}
|
||||
o.transform = moved;
|
||||
}
|
||||
s.refresh();
|
||||
Ok(Some(shift))
|
||||
}
|
||||
|
||||
/// Record that body `names[b]` lives in component `c`, placed by `offset`.
|
||||
fn put_bodies(s: &mut Session, names: &[Option<String>], moves: &[(usize, u64, Mat)]) {
|
||||
if moves.is_empty() {
|
||||
|
||||
@@ -895,11 +895,27 @@ fn kind_param(p: &Value, cmd: &str) -> Result<JointKind> {
|
||||
.ok_or_else(|| bad(cmd, "`type` must be rigid, revolute, slider, cylindrical, pin_slot, planar, ball, parallel, perpendicular, angle, point_on_plane, point_on_line or line_on_plane"))
|
||||
}
|
||||
|
||||
fn new_joint_name(s: &Session, p: &Value) -> String {
|
||||
str_(p, "name").map(str::to_string).unwrap_or_else(|| {
|
||||
fn new_joint_name(s: &Session, p: &Value, kind: JointKind) -> String {
|
||||
str_(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| {
|
||||
let label = match kind {
|
||||
JointKind::Rigid => "Rigid",
|
||||
JointKind::Revolute => "Revolute",
|
||||
JointKind::Slider => "Slider",
|
||||
JointKind::Cylindrical => "Cylindrical",
|
||||
JointKind::PinSlot => "Pin_slot",
|
||||
JointKind::Planar => "Planar",
|
||||
JointKind::Ball => "Ball",
|
||||
JointKind::Parallel => "Parallel",
|
||||
JointKind::Perpendicular => "Perpendicular",
|
||||
JointKind::Angle => "Angle",
|
||||
JointKind::PointOnPlane => "Point_on_plane",
|
||||
JointKind::PointOnLine => "Point_on_line",
|
||||
JointKind::LineOnPlane => "Line_on_plane",
|
||||
};
|
||||
let prefix = format!("{label} Joint");
|
||||
let names: std::collections::BTreeSet<_> = s.doc.assembly.joints.iter().map(|j| j.name.as_str()).collect();
|
||||
let number = (1..=s.doc.assembly.joints.len().saturating_add(1)).find(|n| !names.contains(format!("Joint{n}").as_str())).unwrap_or(1);
|
||||
format!("Joint{number}")
|
||||
let number = (1..=s.doc.assembly.joints.len().saturating_add(1)).find(|n| !names.contains(format!("{prefix}{n}").as_str())).unwrap_or(1);
|
||||
format!("{prefix}{number}")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -909,7 +925,7 @@ fn joint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = origin_param(s, p.get("a"), cmd)?;
|
||||
let b = origin_param(s, p.get("b"), cmd)?;
|
||||
let id = s.doc_mut().allocate_id()?;
|
||||
let name = new_joint_name(s, p);
|
||||
let name = new_joint_name(s, p, kind);
|
||||
let offset = match p.get("offset") {
|
||||
Some(v) => value(s, v, false, cmd)?,
|
||||
None => 0.0,
|
||||
@@ -961,7 +977,7 @@ fn as_built(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fa = side(oa)?;
|
||||
let fb = side(ob)?;
|
||||
let id = s.doc_mut().allocate_id()?;
|
||||
let name = new_joint_name(s, p);
|
||||
let name = new_joint_name(s, p, kind);
|
||||
let n = kind.dofs().len();
|
||||
let j = Joint {
|
||||
id,
|
||||
|
||||
@@ -2719,3 +2719,46 @@ fn driving_an_angle_reports_the_number_a_person_would_read() {
|
||||
let j = s.doc.assembly.joints.iter().find(|j| j.name == "Turn").unwrap();
|
||||
assert_ne!(j.values[0].to_degrees(), 30.0, "the stored angle keeps its bits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_joints_generate_type_prefixed_names_or_keep_custom_name() {
|
||||
let mut s = two_cubes();
|
||||
let (a, b) = (occ(&s, "A"), occ(&s, "B"));
|
||||
|
||||
// 1. Without name: revolute joint defaults to "Revolute Joint1"
|
||||
let r1 = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({
|
||||
"type": "revolute",
|
||||
"a": {"occurrence": a, "face": [5, 5, 10]},
|
||||
"b": {"occurrence": b, "face": [25, 5, 0]}
|
||||
}),
|
||||
);
|
||||
assert_eq!(r1["name"], "Revolute Joint1");
|
||||
|
||||
// 2. Without name: slider joint defaults to "Slider Joint1"
|
||||
let r2 = run(
|
||||
&mut s,
|
||||
"joint.as_built",
|
||||
json!({
|
||||
"type": "slider",
|
||||
"a": "A",
|
||||
"b": "B"
|
||||
}),
|
||||
);
|
||||
assert_eq!(r2["name"], "Slider Joint1");
|
||||
|
||||
// 3. With custom name: preserves custom name exactly
|
||||
let r3 = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({
|
||||
"type": "rigid",
|
||||
"name": "CustomRigid",
|
||||
"a": {"occurrence": a, "face": [5, 5, 10]},
|
||||
"b": {"occurrence": b, "face": [25, 5, 0]}
|
||||
}),
|
||||
);
|
||||
assert_eq!(r3["name"], "CustomRigid");
|
||||
}
|
||||
@@ -116,6 +116,42 @@ fn a_chamfer_face_takes_a_sketch_that_follows_the_chamfer() {
|
||||
healthy(&reopened(&s), "OnBevel");
|
||||
}
|
||||
|
||||
/// #7476: a cone's base and the flat top of a cut-off cone take a sketch, as a cylinder's caps
|
||||
/// do, on the origin and placed along a slanted axis. The sketch on the top follows the height.
|
||||
#[test]
|
||||
fn the_flat_faces_of_a_cone_take_a_sketch_that_follows_the_cone() {
|
||||
use solidcore_record::Vec3;
|
||||
let slant = Vec3::new(1., 1., 0.).normalized().unwrap();
|
||||
for (base, axis, along) in [(Vec3::ZERO, json!("Z"), Vec3::Z), (Vec3::new(5., -3., 2.), json!([1, 1, 0]), slant)] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "20 mm"}));
|
||||
let at = [base.x, base.y, base.z];
|
||||
run(&mut s, "solid.cone", json!({"radius": 10, "top_radius": 4, "height": "tall", "base": at, "axis": axis, "name": "Cut"}));
|
||||
run(&mut s, "solid.cone", json!({"radius": 3, "height": 5, "base": [40, 0, 0], "name": "Full"}));
|
||||
no_errors(&s);
|
||||
let top = |tall: f64| base + along * tall;
|
||||
sketch_on(&mut s, [top(20.).x, top(20.).y, top(20.).z], "OnTop");
|
||||
sketch_on(&mut s, at, "OnBase");
|
||||
sketch_on(&mut s, [40., 0., 0.], "OnFullBase");
|
||||
let height = |p: &solidcore_record::Plane| (p.origin - base).dot(along);
|
||||
for (name, role) in [("OnTop", ":top"), ("OnBase", ":bottom"), ("OnFullBase", ":bottom")] {
|
||||
let FaceAttachmentStatus::Healthy { plane, target, .. } = status(&s, name) else { panic!("{name}: {:?}", status(&s, name)) };
|
||||
assert_eq!(target.certificate, Some(FaceCertificate::Lineage), "{name}");
|
||||
assert!(target.name.ends_with(role), "{name}: {}", target.name);
|
||||
let axis = if name == "OnFullBase" { Vec3::Z } else { along };
|
||||
assert!(plane.normal().cross(axis).len() < 1e-9, "{name}: {plane:?}");
|
||||
}
|
||||
assert!((height(&healthy(&s, "OnTop").0) - 20.).abs() < 1e-9);
|
||||
assert!(height(&healthy(&s, "OnBase").0).abs() < 1e-9);
|
||||
run(&mut s, "parameters.change", json!({"name": "tall", "expression": "30 mm"}));
|
||||
no_errors(&s);
|
||||
assert!((height(&healthy(&s, "OnTop").0) - 30.).abs() < 1e-9);
|
||||
assert!(height(&healthy(&s, "OnBase").0).abs() < 1e-9);
|
||||
let t = reopened(&s);
|
||||
assert!((height(&healthy(&t, "OnTop").0) - 30.).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
/// A plate with a boss patterned 3 times along x, `pitch` apart.
|
||||
fn patterned_bosses(sketch_on_seed_first: bool) -> Session {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -4,27 +4,59 @@
|
||||
//! configuration material cells. The design keeps them, so they are saved and undone like
|
||||
//! features.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use solidcraft_doc::appearance::{Look, library};
|
||||
use solidcraft_doc::config::Column;
|
||||
use solidcraft_doc::{DEFAULT_MATERIAL, MATERIALS, MAX_USER_MATERIALS, UserMaterial, valid_density};
|
||||
|
||||
use super::CommandSpec;
|
||||
use super::inspect::{color_param, look_json};
|
||||
use super::inspect::color_param;
|
||||
use crate::params::{bad, str_};
|
||||
use crate::schema::TypedContract;
|
||||
use crate::schema::appearance::LookReply;
|
||||
use crate::schema::materials::{
|
||||
DensityComparison, MaterialCreateParams, MaterialDeleteParams, MaterialDeleted, MaterialEditParams, MaterialInspectParams, MaterialInspected,
|
||||
MaterialReply,
|
||||
};
|
||||
use crate::schema::output_schema_for;
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CREATE_CONTRACT: TypedContract<MaterialCreateParams> = TypedContract::new();
|
||||
const EDIT_CONTRACT: TypedContract<MaterialEditParams> = TypedContract::new();
|
||||
const INSPECT_CONTRACT: TypedContract<MaterialInspectParams> = TypedContract::new();
|
||||
const DELETE_CONTRACT: TypedContract<MaterialDeleteParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("material.create", "New Physical Material", create).icon("material").params(
|
||||
CommandSpec::new("material.create", "New Physical Material", crate::checked!("material.create", create))
|
||||
.icon("material")
|
||||
.contract(&CREATE_CONTRACT)
|
||||
.output(output_schema_for::<MaterialReply>)
|
||||
.params(
|
||||
"name (not a built-in material's); density_g_cm3: (0, 1000]; appearance?: library name (appearance.library) | color?: \"#rrggbb\" or [r, g, b] (0–255), opacity? (0–1), pbr?: {metallic:0..1, roughness:0.045..1, dielectric_ior:1..3} (opaque only, needs color/appearance): the default look. A named appearance keeps its preset response when pbr is omitted; pbr: null selects scalar shading. Optical edits do not change density. physical_card?: validated SI candidate record (null/omitted means unknown); card density never changes assigned density. Assign it with material.assign",
|
||||
),
|
||||
CommandSpec::new("material.edit", "Edit Physical Material", edit).icon("material").enabled(has_user_materials).params(
|
||||
CommandSpec::new("material.edit", "Edit Physical Material", crate::checked!("material.edit", edit))
|
||||
.icon("material")
|
||||
.enabled(has_user_materials)
|
||||
.contract(&EDIT_CONTRACT)
|
||||
.output(output_schema_for::<MaterialReply>)
|
||||
.params(
|
||||
"material: a material defined in this design; name? (bodies and configuration cells follow); density_g_cm3?; appearance? | color?, opacity?, pbr? (as material.create; color: null clears the look). physical_card?: validated SI candidate record (omitted retains, null clears). Omitted appearance/color retains the entire current look",
|
||||
),
|
||||
CommandSpec::new("material.inspect", "Inspect Physical Material", inspect).icon("material").noundo().doc_only().params(
|
||||
CommandSpec::new("material.inspect", "Inspect Physical Material", crate::checked!("material.inspect", inspect))
|
||||
.icon("material")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&INSPECT_CONTRACT)
|
||||
.output(output_schema_for::<MaterialInspected>)
|
||||
.params(
|
||||
"material: built-in or design-owned name. Returns assigned density, default appearance, optional physical_card, validation and density comparison. Read-only; missing engineering data remains unknown and card density does not change mass",
|
||||
),
|
||||
CommandSpec::new("material.delete", "Delete Physical Material", delete).icon("delete").enabled(has_user_materials).params(
|
||||
CommandSpec::new("material.delete", "Delete Physical Material", crate::checked!("material.delete", delete))
|
||||
.icon("delete")
|
||||
.enabled(has_user_materials)
|
||||
.contract(&DELETE_CONTRACT)
|
||||
.output(output_schema_for::<MaterialDeleted>)
|
||||
.params(
|
||||
"material: a material defined in this design; replace?: material for the bodies and configuration cells that use it (without it, a material in use is refused)",
|
||||
),
|
||||
];
|
||||
@@ -90,27 +122,52 @@ fn look(cmd: &str, p: &Value, material: &str) -> Result<Option<Option<Look>>> {
|
||||
Ok(Some(Some(l)))
|
||||
}
|
||||
|
||||
pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {
|
||||
let mut out = json!({"name": m.name, "density_g_cm3": m.density, "appearance": m.appearance.as_ref().map(look_json), "user": true});
|
||||
/// A design material as `material.create` and `material.edit` report it: with its card, the
|
||||
/// card's check and how the card's measured density compares, when it has a card.
|
||||
fn material_reply(cmd: &str, m: &UserMaterial) -> Result<MaterialReply> {
|
||||
let mut out = MaterialReply {
|
||||
name: m.name.clone(),
|
||||
density_g_cm3: m.density,
|
||||
appearance: m.appearance.as_ref().map(LookReply::from),
|
||||
user: true,
|
||||
physical_card: None,
|
||||
physical_validation: None,
|
||||
density_comparison: None,
|
||||
bodies: None,
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
if let Some(record) = &m.physical_card {
|
||||
let card = record.card();
|
||||
out["physical_card"] = json!(record);
|
||||
out["physical_validation"] = json!(card.validate()?);
|
||||
out.physical_card = Some(serde_json::to_value(record).map_err(|e| bad(cmd, e.to_string()))?);
|
||||
out.physical_validation = Some(card.validate()?.into());
|
||||
let measured = card.properties.iter().find_map(|p| match p.data {
|
||||
solidcraft_doc::physical_material::PropertyData::Density { kg_m3 } => Some(kg_m3),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(measured) = measured {
|
||||
out.density_comparison = measured.map(|measured| {
|
||||
let assigned = m.density * 1000.0;
|
||||
let relative_difference = (assigned - measured).abs() / assigned.max(measured);
|
||||
out["density_comparison"] = json!({"assigned_density_kg_m3":assigned,"card_density_kg_m3":measured,
|
||||
"relative_difference":relative_difference,"matches_within_relative_tolerance":relative_difference <= 1e-9,
|
||||
"relative_tolerance":1e-9});
|
||||
}
|
||||
DensityComparison {
|
||||
assigned_density_kg_m3: assigned,
|
||||
card_density_kg_m3: measured,
|
||||
relative_difference,
|
||||
matches_within_relative_tolerance: relative_difference <= 1e-9,
|
||||
relative_tolerance: 1e-9,
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`material_reply`] as JSON, for `material.list` (`cmd/inspect.rs`), which isn't converted yet.
|
||||
pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {
|
||||
reply("material.list", material_reply("material.list", m)?)
|
||||
}
|
||||
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn physical_card(cmd: &str, p: &Value) -> Result<Option<Option<solidcraft_doc::physical_material::ValidatedCard>>> {
|
||||
match p.get("physical_card") {
|
||||
None => Ok(None),
|
||||
@@ -125,21 +182,38 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "material.inspect";
|
||||
let name = str_(p, "material").ok_or_else(|| bad(cmd, "`material` must be a material name"))?;
|
||||
let canonical = s.doc.material_name(name).ok_or_else(|| bad(cmd, format!("unknown material `{name}` (see material.list)")))?;
|
||||
let mut out = if let Some(material) = s.doc.user_materials.iter().find(|m| m.name == canonical) {
|
||||
material_json(material)?
|
||||
// The look a material's bodies show: its own, or a built-in material's default.
|
||||
let appearance = s.doc.material_look(&canonical).as_ref().map(LookReply::from);
|
||||
let out = if let Some(material) = s.doc.user_materials.iter().find(|m| m.name == canonical) {
|
||||
let own = material_reply(cmd, material)?;
|
||||
MaterialInspected {
|
||||
name: own.name,
|
||||
density_g_cm3: own.density_g_cm3,
|
||||
appearance,
|
||||
user: true,
|
||||
physical_card: own.physical_card,
|
||||
physical_validation: own.physical_validation,
|
||||
density_comparison: own.density_comparison,
|
||||
param_warnings: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
let density = MATERIALS
|
||||
.iter()
|
||||
.find(|(n, _)| *n == canonical.as_str())
|
||||
.map(|(_, density)| *density)
|
||||
.ok_or_else(|| bad(cmd, "material is unavailable"))?;
|
||||
json!({"name":canonical,"density_g_cm3":density,"user":false})
|
||||
MaterialInspected {
|
||||
name: canonical,
|
||||
density_g_cm3: density,
|
||||
appearance,
|
||||
user: false,
|
||||
physical_card: None,
|
||||
physical_validation: None,
|
||||
density_comparison: None,
|
||||
param_warnings: Vec::new(),
|
||||
}
|
||||
};
|
||||
out["appearance"] = json!(s.doc.material_look(&canonical).as_ref().map(look_json));
|
||||
if out.get("physical_card").is_none() {
|
||||
out["physical_card"] = Value::Null;
|
||||
}
|
||||
Ok(out)
|
||||
reply(cmd, out)
|
||||
}
|
||||
|
||||
/// The index of the design material `material` names.
|
||||
@@ -160,7 +234,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let material =
|
||||
UserMaterial { density: density(cmd, p)?, appearance: look(cmd, p, &name)?.flatten(), name, physical_card: physical_card(cmd, p)?.flatten() };
|
||||
let out = material_json(&material)?;
|
||||
let out = reply(cmd, material_reply(cmd, &material)?)?;
|
||||
s.doc_mut().user_materials.push(material);
|
||||
Ok(out)
|
||||
}
|
||||
@@ -228,15 +302,15 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let physical_card = physical_card(cmd, p)?.unwrap_or(old.physical_card);
|
||||
let material = UserMaterial { name: name.clone(), density, appearance, physical_card };
|
||||
let mut out = material_json(&material)?;
|
||||
let mut out = material_reply(cmd, &material)?;
|
||||
if let Some(m) = s.doc_mut().user_materials.get_mut(i) {
|
||||
*m = material;
|
||||
}
|
||||
if name != old.name {
|
||||
move_uses(s, &old.name, &name);
|
||||
}
|
||||
out["bodies"] = json!(uses(s, &name).0);
|
||||
Ok(out)
|
||||
out.bodies = Some(uses(s, &name).0);
|
||||
reply(cmd, out)
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -268,5 +342,5 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
move_uses(s, &name, r);
|
||||
}
|
||||
s.doc_mut().user_materials.remove(i);
|
||||
Ok(json!({"deleted": name, "replaced_by": replace, "bodies": bodies}))
|
||||
reply(cmd, MaterialDeleted { deleted: name, replaced_by: replace, bodies, param_warnings: Vec::new() })
|
||||
}
|
||||
@@ -21,7 +21,7 @@ macro_rules! planned {
|
||||
}
|
||||
|
||||
mod bom;
|
||||
mod browser;
|
||||
pub(crate) mod browser;
|
||||
pub(crate) mod clearance;
|
||||
mod clipboard;
|
||||
mod clipboard_foreign;
|
||||
@@ -95,6 +95,8 @@ mod parameters;
|
||||
mod plastic;
|
||||
mod print_face;
|
||||
mod render;
|
||||
pub(crate) use render::{PreparedCapture, prepare_capture_with_metadata, render_cancel_params};
|
||||
pub(crate) use render_ui::batch_request;
|
||||
mod render_ui;
|
||||
#[cfg(test)]
|
||||
mod script_tests;
|
||||
@@ -108,6 +110,7 @@ mod sketch;
|
||||
pub(crate) use sketch::author_path_for_rebind;
|
||||
pub(crate) use sketch::collapse_reason;
|
||||
pub(crate) use sketch::created as sketch_created;
|
||||
pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form};
|
||||
mod canvas_sketch;
|
||||
mod sketch_3d;
|
||||
mod sketch_canvas;
|
||||
@@ -115,6 +118,7 @@ pub mod sketch_clipboard;
|
||||
mod sketch_constraints;
|
||||
mod sketch_construction;
|
||||
mod sketch_create;
|
||||
mod sketch_divide;
|
||||
mod sketch_ends;
|
||||
mod sketch_equation;
|
||||
mod sketch_freeform;
|
||||
@@ -312,6 +316,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
|
||||
v.extend(sketch::COMMANDS.iter());
|
||||
v.extend(sketch_create::COMMANDS.iter());
|
||||
v.extend(sketch_construction::COMMANDS.iter());
|
||||
v.extend(sketch_divide::COMMANDS.iter());
|
||||
v.extend(sketch_equation::COMMANDS.iter());
|
||||
v.extend(sketch_constraints::COMMANDS.iter());
|
||||
v.extend(sketch_import::COMMANDS.iter());
|
||||
|
||||
@@ -16,7 +16,8 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, plac
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::schema::motion::{
|
||||
ContactCheck, ContactCollision, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetChange,
|
||||
ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult,
|
||||
ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams,
|
||||
MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, MotionStudyParams, MotionStudySaved,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -46,6 +47,9 @@ const CONTACT_ENABLE_CONTRACT: TypedContract<ContactEnableParams> = TypedContrac
|
||||
const CONTACT_NONE_CONTRACT: TypedContract<ContactNoParams> = TypedContract::new();
|
||||
const CONTACT_CREATE_CONTRACT: TypedContract<ContactCreateParams> = TypedContract::new();
|
||||
const CONTACT_EDIT_CONTRACT: TypedContract<ContactEditParams> = TypedContract::new();
|
||||
const STUDY_CONTRACT: TypedContract<MotionStudyParams> = TypedContract::new();
|
||||
const STUDY_DELETE_CONTRACT: TypedContract<MotionStudyDeleteParams> = TypedContract::new();
|
||||
const STUDY_LIST_CONTRACT: TypedContract<MotionListParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("contact.enable_sets", "Enable Contact Sets", crate::checked!("contact.enable_sets", enable_sets))
|
||||
@@ -92,10 +96,15 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&CONTACT_NONE_CONTRACT)
|
||||
.output(output_schema_for::<ContactCheck>)
|
||||
.params("→ pairs in contact sets that pass through each other now"),
|
||||
CommandSpec::new("motion.study", "Motion Study", study).at("SOLID", "ASSEMBLE").icon("play").params(
|
||||
"name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \
|
||||
CommandSpec::new("motion.study", "Motion Study", crate::checked!("motion.study", study))
|
||||
.at("SOLID", "ASSEMBLE")
|
||||
.icon("play")
|
||||
.contract(&STUDY_CONTRACT)
|
||||
.output(output_schema_for::<MotionStudySaved>)
|
||||
.params(
|
||||
"name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \
|
||||
(values: degrees for angles, mm for distances, or expressions)",
|
||||
),
|
||||
),
|
||||
CommandSpec::new("motion.play", "Play Motion Study", play).icon("play").params(
|
||||
"study: id|name; step (0…steps) — sets the joints to the study's values there (contact sets stop them); quiet?: bool \
|
||||
(positions of only the occurrences that moved) → values: [{joint, values: [{name, value, unit}]}], positions, moved: whether \
|
||||
@@ -145,8 +154,16 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&FIND_LIMITS_CONTRACT)
|
||||
.output(output_schema_for::<FindLimitsResult>)
|
||||
.params(sweep::FIND_LIMITS_DOC),
|
||||
CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(),
|
||||
CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"),
|
||||
CommandSpec::new("motion.list", "List Motion Studies", crate::checked!("motion.list", list_studies))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&STUDY_LIST_CONTRACT)
|
||||
.output(output_schema_for::<MotionStudies>),
|
||||
CommandSpec::new("motion.delete", "Delete Motion Study", crate::checked!("motion.delete", delete_study))
|
||||
.icon("delete")
|
||||
.contract(&STUDY_DELETE_CONTRACT)
|
||||
.output(output_schema_for::<MotionStudyDeleted>)
|
||||
.params("study"),
|
||||
CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params(
|
||||
"name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \
|
||||
moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",
|
||||
@@ -557,30 +574,30 @@ pub fn drive_joint_index(s: &mut Session, id: u64, q: Vec<f64>, index: usize) ->
|
||||
Ok(drive_with_contact(s, &[(id, q)], &[(id, index)].into_iter().collect())?.0)
|
||||
}
|
||||
|
||||
/// A contact command's reply as JSON: they build their replies from the types their output
|
||||
/// schemas describe, so the two can't drift apart.
|
||||
fn contact_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
/// A command's reply as JSON: the contact and motion study commands build their replies from the
|
||||
/// types their output schemas describe, so the two can't drift apart.
|
||||
fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn enable_sets(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let enabled = bool_(p, "enabled").unwrap_or(true);
|
||||
s.doc_mut().assembly.contact_enabled = enabled;
|
||||
contact_reply("contact.enable_sets", ContactSwitch { enabled, all: None, param_warnings: Vec::new() })
|
||||
typed_reply("contact.enable_sets", ContactSwitch { enabled, all: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn enable_all(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_enabled = true;
|
||||
a.contact_all = true;
|
||||
contact_reply("contact.enable_all", ContactSwitch { enabled: true, all: Some(true), param_warnings: Vec::new() })
|
||||
typed_reply("contact.enable_all", ContactSwitch { enabled: true, all: Some(true), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn disable_all(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_enabled = false;
|
||||
a.contact_all = false;
|
||||
contact_reply("contact.disable_all", ContactSwitch { enabled: false, all: None, param_warnings: Vec::new() })
|
||||
typed_reply("contact.disable_all", ContactSwitch { enabled: false, all: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -598,7 +615,7 @@ fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = &mut s.doc_mut().assembly;
|
||||
a.contact_sets.push(ContactSet { id, name: name.clone(), occurrences: occ, suppressed: false });
|
||||
a.contact_enabled = true;
|
||||
contact_reply(cmd, ContactSetCreated { set: id, name, param_warnings: Vec::new() })
|
||||
typed_reply(cmd, ContactSetCreated { set: id, name, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn set_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
@@ -620,7 +637,7 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = set_index(s, p, cmd)?;
|
||||
if bool_(p, "delete").unwrap_or(false) {
|
||||
s.doc_mut().assembly.contact_sets.remove(i);
|
||||
return contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Deleted { deleted: true }, param_warnings: Vec::new() });
|
||||
return typed_reply(cmd, ContactSetEdited { change: ContactSetChange::Deleted { deleted: true }, param_warnings: Vec::new() });
|
||||
}
|
||||
let occ = if p.get("occurrences").is_some() { Some(occurrences(s, p, cmd)?) } else { None };
|
||||
if occ.as_ref().is_some_and(|o| o.len() < 2) {
|
||||
@@ -637,18 +654,18 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
c.suppressed = x;
|
||||
}
|
||||
let set = c.id;
|
||||
contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Changed { set }, param_warnings: Vec::new() })
|
||||
typed_reply(cmd, ContactSetEdited { change: ContactSetChange::Changed { set }, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn list_sets(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let a = &s.doc.assembly;
|
||||
let sets = a.contact_sets.iter().map(ContactSetInfo::from).collect();
|
||||
contact_reply("contact.list", ContactSets { enabled: a.contact_enabled, all: a.contact_all, sets, param_warnings: Vec::new() })
|
||||
typed_reply("contact.list", ContactSets { enabled: a.contact_enabled, all: a.contact_all, sets, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let collisions = collisions(s).into_iter().map(|(a, b, depth_mm)| ContactCollision { a, b, depth_mm }).collect();
|
||||
contact_reply("contact.check", ContactCheck { collisions, param_warnings: Vec::new() })
|
||||
typed_reply("contact.check", ContactCheck { collisions, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
// ---- Motion studies ----
|
||||
@@ -737,7 +754,7 @@ fn study(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
m
|
||||
}
|
||||
};
|
||||
Ok(json!({"study": out.id, "name": out.name, "steps": out.steps, "keys": out.keys.len()}))
|
||||
typed_reply(cmd, MotionStudySaved { study: out.id, name: out.name, steps: out.steps, keys: out.keys.len(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// Joint values of a study at a step: (joint, full value vector).
|
||||
@@ -1079,36 +1096,37 @@ fn keep_sampled_trace(
|
||||
}
|
||||
|
||||
fn list_studies(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let studies: Vec<Value> = s.doc.assembly.studies.iter().map(|m| study_json(s, m)).collect();
|
||||
Ok(json!({"studies": studies, "traces": associative::list(s)}))
|
||||
let studies = s.doc.assembly.studies.iter().map(|m| study_info(s, m)).collect();
|
||||
typed_reply("motion.list", MotionStudies { studies, traces: associative::list(s), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A study as `motion.list` gives it: key values in the units `motion.study` takes — degrees
|
||||
/// for angles, mm for distances, like `joint.list`'s values — each key with its joint's name,
|
||||
/// so a listed study can be fed back to `motion.study` unchanged.
|
||||
fn study_json(s: &Session, m: &MotionStudy) -> Value {
|
||||
let keys: Vec<Value> = m
|
||||
fn study_info(s: &Session, m: &MotionStudy) -> MotionStudyInfo {
|
||||
let keys = m
|
||||
.keys
|
||||
.iter()
|
||||
.map(|k| {
|
||||
let joint = s.doc.assembly.joints.iter().find(|j| j.id == k.joint);
|
||||
let angle = joint.is_some_and(|j| j.kind.is_angle(k.index));
|
||||
json!({
|
||||
"joint": k.joint,
|
||||
"joint_name": joint.map(|j| j.name.clone()).unwrap_or_else(|| k.joint.to_string()),
|
||||
"index": k.index,
|
||||
"unit": if angle { "deg" } else { "mm" },
|
||||
"points": k.points.iter().map(|(step, v)| json!([step, if angle { v.to_degrees() } else { *v }])).collect::<Vec<_>>(),
|
||||
})
|
||||
MotionStudyKeyInfo {
|
||||
joint: k.joint,
|
||||
joint_name: joint.map(|j| j.name.clone()).unwrap_or_else(|| k.joint.to_string()),
|
||||
index: k.index,
|
||||
unit: if angle { "deg" } else { "mm" }.into(),
|
||||
points: k.points.iter().map(|(step, v)| [*step, if angle { v.to_degrees() } else { *v }]).collect(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
json!({"id": m.id, "name": m.name, "steps": m.steps, "keys": keys})
|
||||
MotionStudyInfo { id: m.id, name: m.name.clone(), steps: m.steps, keys }
|
||||
}
|
||||
|
||||
fn delete_study(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = study_index(s, p, "motion.delete")?;
|
||||
let cmd = "motion.delete";
|
||||
let i = study_index(s, p, cmd)?;
|
||||
let m = s.doc_mut().assembly.studies.remove(i);
|
||||
Ok(json!({"deleted": m.name}))
|
||||
typed_reply(cmd, MotionStudyDeleted { deleted: m.name, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
// ---- Exploded views ----
|
||||
|
||||
@@ -16,6 +16,13 @@ fn occ(s: &Session, component: &str) -> u64 {
|
||||
s.doc.occurrence_of(c).map(|o| o.id).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The call that deletes item `id` with `delete`: Edit Contact Set deletes with `delete: true`;
|
||||
/// Delete Motion Study and Delete Exploded View take only the item, and strict refuses any other
|
||||
/// key (#12155).
|
||||
fn deletion(delete: &str, key: &str, id: u64) -> Value {
|
||||
if delete == "contact.edit" { json!({key: id, "delete": true}) } else { json!({key: id}) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_motion_item_ids_are_not_reused_after_reopening() {
|
||||
for (create, delete, key, params) in [
|
||||
@@ -29,13 +36,13 @@ fn deleted_motion_item_ids_are_not_reused_after_reopening() {
|
||||
run(&mut s, "component.create", json!({"name": name}));
|
||||
}
|
||||
let first = run(&mut s, create, params.clone())[key].as_u64().unwrap();
|
||||
let deletion = json!({key: first, "delete": true});
|
||||
run(&mut s, delete, deletion.clone());
|
||||
let deleting = deletion(delete, key, first);
|
||||
run(&mut s, delete, deleting.clone());
|
||||
let doc = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
|
||||
*s.doc_mut() = doc;
|
||||
let second = run(&mut s, create, params)[key].as_u64().unwrap();
|
||||
assert!(second > first, "{create}: deleted item {first} was reused as {second}");
|
||||
assert!(s.execute(delete, &deletion).is_err());
|
||||
assert!(s.execute(delete, &deleting).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +67,7 @@ fn default_names_skip_names_in_use() {
|
||||
let (first, one) = made(&mut s);
|
||||
let (_, two) = made(&mut s);
|
||||
assert_eq!([one, two], [format!("{prefix}1"), format!("{prefix}2")]);
|
||||
run(&mut s, delete, json!({key: first, "delete": true}));
|
||||
run(&mut s, delete, deletion(delete, key, first));
|
||||
assert_eq!(made(&mut s).1, format!("{prefix}1"), "{create}: the free name, not {prefix}2 again");
|
||||
}
|
||||
// Placements: with the first deleted, a copy takes a name none has.
|
||||
|
||||
@@ -377,6 +377,7 @@ pub(crate) fn refresh(s: &mut Session) {
|
||||
}
|
||||
if changed {
|
||||
s.model.evaluate(&s.doc);
|
||||
s.evaluations = s.evaluations.saturating_add(1);
|
||||
s.revision += 1;
|
||||
}
|
||||
for t in &traces {
|
||||
|
||||
@@ -42,7 +42,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"Save Layout",
|
||||
wire::Save,
|
||||
wire::SaveReply,
|
||||
"name, overwrite?: false, expected_revision?: save complete envelope in injected catalogue"
|
||||
"name, replace?: false (overwrite accepted for compatibility), expected_revision?: save complete envelope in injected catalogue"
|
||||
),
|
||||
command!(
|
||||
"layout.workspace.select",
|
||||
@@ -52,6 +52,14 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
wire::WorkspaceReply,
|
||||
"workspace, expected_revision?: atomically remember outgoing and replace with destination"
|
||||
),
|
||||
command!(
|
||||
"panel.action",
|
||||
"activate",
|
||||
"Run Panel Header Action",
|
||||
wire::HeaderAction,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, action, expected_revision?: invoke a registered owning-controller action"
|
||||
),
|
||||
command!(
|
||||
"panel.activate",
|
||||
"activate",
|
||||
@@ -114,7 +122,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"Move Panel",
|
||||
wire::Move,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, destination: new_section or join_tab, expected_revision?"
|
||||
"target or legacy id, destination: new_section, join_tab or relative, activate?: false, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.native_close",
|
||||
@@ -162,7 +170,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"Resize Panel Section",
|
||||
wire::Resize,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, size: {width,height}, expected_revision?"
|
||||
"target or legacy id, size: {width,height}, thickness_only?: false by default; true changes Bottom height or side column width and ignores the other valid size component, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.resize_pair",
|
||||
|
||||
@@ -9,8 +9,20 @@ use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solve
|
||||
|
||||
use super::{CommandSpec, sketch_store};
|
||||
use crate::params::{bad, bool_, str_};
|
||||
use crate::schema::parameters::{
|
||||
AddedValue, ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams,
|
||||
ParamMoved, ParamNameParams, ParamRenameParams, ParamRenamed,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const ADD_CONTRACT: TypedContract<ParamAddParams> = TypedContract::new();
|
||||
const RENAME_CONTRACT: TypedContract<ParamRenameParams> = TypedContract::new();
|
||||
const NAME_CONTRACT: TypedContract<ParamNameParams> = TypedContract::new();
|
||||
const COMMENT_CONTRACT: TypedContract<ParamCommentParams> = TypedContract::new();
|
||||
const FAVORITE_CONTRACT: TypedContract<ParamFavoriteParams> = TypedContract::new();
|
||||
const MOVE_CONTRACT: TypedContract<ParamMoveParams> = TypedContract::new();
|
||||
|
||||
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; \
|
||||
@@ -26,20 +38,36 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value (mm/deg in every \
|
||||
reply), display_value (in its own unit), source, feature/input, comment, favorite, uses, used_by, error) and cycles",
|
||||
),
|
||||
CommandSpec::new("parameters.add", "Add User Parameter", add)
|
||||
CommandSpec::new("parameters.add", "Add User Parameter", crate::checked!("parameters.add", add))
|
||||
.icon("new")
|
||||
.contract(&ADD_CONTRACT)
|
||||
.output(output_schema_for::<ParamAdded>)
|
||||
.params("name, expression, unit?: as parameters.change (text: a text parameter, its expression the text), comment?, favorite?: bool"),
|
||||
CommandSpec::new("parameters.rename", "Rename Parameter", rename)
|
||||
CommandSpec::new("parameters.rename", "Rename Parameter", crate::checked!("parameters.rename", rename))
|
||||
.icon("rename")
|
||||
.contract(&RENAME_CONTRACT)
|
||||
.output(output_schema_for::<ParamRenamed>)
|
||||
.params("name, new_name (expressions, feature inputs and dimensions that use it follow)"),
|
||||
CommandSpec::new("parameters.delete", "Delete Parameter", delete)
|
||||
CommandSpec::new("parameters.delete", "Delete Parameter", crate::checked!("parameters.delete", delete))
|
||||
.icon("delete")
|
||||
.contract(&NAME_CONTRACT)
|
||||
.output(output_schema_for::<ParamDeleted>)
|
||||
.params("name (refused while something uses it; the error lists the users)"),
|
||||
CommandSpec::new("parameters.favorite", "Favorite Parameter", favorite).icon("star").params("name, favorite?: bool (default true)"),
|
||||
CommandSpec::new("parameters.move", "Move Parameter", move_param)
|
||||
CommandSpec::new("parameters.favorite", "Favorite Parameter", crate::checked!("parameters.favorite", favorite))
|
||||
.icon("star")
|
||||
.contract(&FAVORITE_CONTRACT)
|
||||
.output(output_schema_for::<ParamFavorited>)
|
||||
.params("name, favorite?: bool (default true)"),
|
||||
CommandSpec::new("parameters.move", "Move Parameter", crate::checked!("parameters.move", move_param))
|
||||
.icon("reorder")
|
||||
.contract(&MOVE_CONTRACT)
|
||||
.output(output_schema_for::<ParamMoved>)
|
||||
.params("name, before | after: another user parameter; the user parameter is listed just before or after it"),
|
||||
CommandSpec::new("parameters.comment", "Comment Parameter", comment).icon("text").params("name, comment"),
|
||||
CommandSpec::new("parameters.comment", "Comment Parameter", crate::checked!("parameters.comment", comment))
|
||||
.icon("text")
|
||||
.contract(&COMMENT_CONTRACT)
|
||||
.output(output_schema_for::<ParamCommented>)
|
||||
.params("name, comment"),
|
||||
CommandSpec::new("parameters.users", "Parameter Users", users)
|
||||
.icon("graph")
|
||||
.noundo()
|
||||
@@ -340,35 +368,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc_mut().set_favorite(&name, f)?;
|
||||
}
|
||||
let (vals, _) = s.doc.param_values();
|
||||
if let Some(t) = s.doc.text_param(&name) {
|
||||
return Ok(json!({"name": name, "unit": solidcraft_doc::text_params::TEXT_UNIT, "text": t.text, "value": null}));
|
||||
}
|
||||
Ok(
|
||||
json!({"name": name, "unit": s.doc.param(&name).map(|x| x.unit.clone()), "value": vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))), "display_value": s.doc.param_display_value(&vals, &name).map(expr::round_reported)}),
|
||||
)
|
||||
let value = match s.doc.text_param(&name) {
|
||||
Some(t) => AddedValue::Text { unit: solidcraft_doc::text_params::TEXT_UNIT.into(), text: t.text.clone(), value: None },
|
||||
None => AddedValue::Number {
|
||||
unit: s.doc.param(&name).map(|x| x.unit.clone()),
|
||||
value: vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))),
|
||||
display_value: s.doc.param_display_value(&vals, &name).map(expr::round_reported),
|
||||
},
|
||||
};
|
||||
reply(cmd, ParamAdded { name, value, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A reply as JSON: these commands build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "parameters.rename";
|
||||
let name = param_name(cmd, p)?.to_string();
|
||||
let new = str_(p, "new_name").ok_or_else(|| bad(cmd, "`new_name` is required"))?;
|
||||
let n = s.doc_mut().rename_param(&name, new)?;
|
||||
Ok(json!({"from": name, "to": new.trim(), "references_updated": n}))
|
||||
let references_updated = s.doc_mut().rename_param(&name, new)?;
|
||||
reply(cmd, ParamRenamed { from: name, to: new.trim().to_string(), references_updated, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = param_name("parameters.delete", p)?.to_string();
|
||||
let cmd = "parameters.delete";
|
||||
let name = param_name(cmd, p)?.to_string();
|
||||
let solved = s.solved_sketches();
|
||||
s.doc_mut().remove_param(&name)?;
|
||||
s.settle_value_edit(&solved)?;
|
||||
Ok(json!({"deleted": name}))
|
||||
reply(cmd, ParamDeleted { deleted: name, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn favorite(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = param_name("parameters.favorite", p)?.to_string();
|
||||
let on = bool_(p, "favorite").unwrap_or(true);
|
||||
s.doc_mut().set_favorite(&name, on)?;
|
||||
Ok(json!({"name": name, "favorite": on}))
|
||||
let cmd = "parameters.favorite";
|
||||
let name = param_name(cmd, p)?.to_string();
|
||||
let favorite = bool_(p, "favorite").unwrap_or(true);
|
||||
s.doc_mut().set_favorite(&name, favorite)?;
|
||||
reply(cmd, ParamFavorited { name, favorite, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn move_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -380,8 +419,8 @@ fn move_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, "give one of `before` or `after`: another user parameter")),
|
||||
};
|
||||
s.doc_mut().move_user_param(&name, &target, after)?;
|
||||
let order: Vec<&str> = s.doc.params.iter().filter(|q| !q.model).map(|q| q.name.as_str()).collect();
|
||||
Ok(json!({"name": name, "order": order}))
|
||||
let order = s.doc.params.iter().filter(|q| !q.model).map(|q| q.name.clone()).collect();
|
||||
reply(cmd, ParamMoved { name, order, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn comment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -389,7 +428,7 @@ fn comment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = param_name(cmd, p)?.to_string();
|
||||
let c = str_(p, "comment").ok_or_else(|| bad(cmd, "`comment` must be text"))?;
|
||||
s.doc_mut().set_param_comment(&name, c)?;
|
||||
Ok(json!({"name": name, "comment": c}))
|
||||
reply(cmd, ParamCommented { name, comment: c.to_string(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn users(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -521,13 +560,16 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let lower = word.to_ascii_lowercase();
|
||||
let starts = |n: &str| word.is_empty() || n.to_ascii_lowercase().starts_with(&lower);
|
||||
// A parameter matches wherever the word appears in its name (`side` finds
|
||||
// `cab_side_thickness`, #2757); functions, constants and units match from the start.
|
||||
let within = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);
|
||||
// `cab_side_thickness`, #2757) or by the starts of its words in order (`toodia` finds
|
||||
// `tooth_outward_flange_diameter`, #11978); functions, constants and units match from the
|
||||
// start.
|
||||
let contains = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);
|
||||
let within = |n: &str| contains(n) || solidcraft_doc::name_words_match(n, &word);
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut rows: Vec<solidcraft_doc::ParamRow> = s.doc.param_rows().into_iter().filter(|r| within(&r.name)).collect();
|
||||
// Names that start with the word, then the rest; within each, favourites, then user
|
||||
// parameters, then the others.
|
||||
rows.sort_by_key(|r| (!starts(&r.name), !r.favorite, r.source != "user"));
|
||||
// Names that start with the word, then names that contain it, then names matched only by
|
||||
// the starts of their words; within each, favourites, then user parameters, then the others.
|
||||
rows.sort_by_key(|r| (!starts(&r.name), !contains(&r.name), !r.favorite, r.source != "user"));
|
||||
for r in rows.into_iter().take(200) {
|
||||
// The completion shows the parameter's own unit, so it reads `display_value`.
|
||||
let v = r.display_value.or(r.value).map(|v| format!("{v:.4} {}", r.unit).trim().to_string()).unwrap_or_else(|| "error".into());
|
||||
|
||||
@@ -198,6 +198,31 @@ fn deleting_a_used_parameter_lists_its_users() {
|
||||
assert!(g["edges"].as_array().unwrap().iter().any(|e| e[0] == "Feature:Base" && e[1] == dim.as_str()), "{g}");
|
||||
}
|
||||
|
||||
/// #12293: a parameter that only a sketch point's coordinate reads lists that sketch in the
|
||||
/// parameter list's `used_by`, as `parameters.graph` and `parameters.users` already show it.
|
||||
#[test]
|
||||
fn a_parameter_read_by_a_sketch_point_lists_the_sketch_as_its_user() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "a", "expression": "20 mm"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "h", "expression": "5 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], ["a", 0], ["a", 10], [0, 10]], "closed": true}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": "h", "name": "E"}));
|
||||
let g = run(&mut s, "parameters.graph", json!({}));
|
||||
assert!(g["edges"].as_array().unwrap().iter().any(|e| e[0] == "Feature:S" && e[1] == "a"), "{g}");
|
||||
let list = run(&mut s, "parameters.list", json!({"filter": "user"}));
|
||||
assert_eq!(row(&list, "a")["used_by"], json!(["Feature:S"]), "{list}");
|
||||
// `h` is read through the extrude's named input, not by the extrude itself.
|
||||
let h = row(&list, "h")["used_by"].clone();
|
||||
assert_eq!(h.as_array().map(Vec::len), Some(1), "{list}");
|
||||
assert!(h[0].as_str().is_some_and(|n| n.starts_with('d')), "{list}");
|
||||
// The sketch still reads `a` after `a` changes.
|
||||
run(&mut s, "parameters.change", json!({"name": "a", "expression": "30 mm"}));
|
||||
let list = run(&mut s, "parameters.list", json!({"filter": "user"}));
|
||||
assert_eq!(row(&list, "a")["used_by"], json!(["Feature:S"]), "{list}");
|
||||
}
|
||||
|
||||
/// #4420: sheet metal and plastic rules and the plane of a canvas hold expressions too. Renaming a
|
||||
/// parameter they use renames it there, and they count as its users (so it can't be deleted).
|
||||
#[test]
|
||||
@@ -325,6 +350,17 @@ fn completion_matches_parameters_anywhere_in_their_name() {
|
||||
let c = run(&mut s, "parameters.complete", json!({"prefix": "THICK"}));
|
||||
assert_eq!(texts(&c), ["cab_side_thickness"], "any case: {c}");
|
||||
assert!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "xyz"}))).is_empty());
|
||||
// #11978: the starts of the name's words, in order, find it; out of order they don't.
|
||||
let c = run(&mut s, "parameters.complete", json!({"prefix": "2 * cabthi"}));
|
||||
assert_eq!(texts(&c), ["cab_side_thickness"], "{c}");
|
||||
assert_eq!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "doowid"}))), ["door_width"]);
|
||||
assert!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "thicab"}))).is_empty());
|
||||
// A match by word starts alone comes after every name that contains the word, even a
|
||||
// favourite: `inner_diameter` has no `id` in it.
|
||||
run(&mut s, "parameters.add", json!({"name": "inner_diameter", "expression": "6 mm"}));
|
||||
run(&mut s, "parameters.favorite", json!({"name": "inner_diameter", "favorite": true}));
|
||||
let c = run(&mut s, "parameters.complete", json!({"prefix": "id"}));
|
||||
assert_eq!(texts(&c), ["cab_side_thickness", "side", "door_width", "inner_diameter"], "{c}");
|
||||
// Functions keep matching from the start: `in` is not `sin(`.
|
||||
let c = run(&mut s, "parameters.complete", json!({"prefix": "in"}));
|
||||
assert!(!c["suggestions"].as_array().unwrap().iter().any(|x| x["text"] == "sin("), "{c}");
|
||||
@@ -1071,6 +1107,38 @@ fn a_refused_definition_changes_nothing() {
|
||||
assert!(r.get("defined").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// Several holes made one command at a time, each with its depth typed as `ScrewDepth = 5`: the
|
||||
/// first defines `ScrewDepth`, the later ones name it instead of being refused because it
|
||||
/// already exists. Typed again with another value, it is still refused and changes nothing.
|
||||
#[test]
|
||||
fn the_same_definition_typed_again_uses_the_parameter() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 12}));
|
||||
let r = run(&mut s, "solid.hole", json!({"position": [15, 20, 12], "diameter": 5, "depth": "ScrewDepth = 5"}));
|
||||
assert_eq!(r["definitions"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let r = run(&mut s, "solid.hole", json!({"position": [45, 20, 12], "diameter": 5, "depth": "ScrewDepth = 5"}));
|
||||
assert!(r.get("definitions").is_none_or(|d| d.as_array().is_some_and(Vec::is_empty)), "nothing new is defined: {r}");
|
||||
assert_eq!(s.doc.params.iter().filter(|p| p.name == "ScrewDepth").count(), 1);
|
||||
assert_eq!(expr_of(&mut s, "ScrewDepth"), "5");
|
||||
let depths: Vec<&str> = s
|
||||
.doc
|
||||
.features
|
||||
.iter()
|
||||
.filter_map(|f| match &f.kind {
|
||||
solidcraft_doc::FeatureKind::Hole { depth, .. } => depth.as_ref().map(|d| d.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(depths, ["ScrewDepth", "ScrewDepth"]);
|
||||
run(&mut s, "parameters.change", json!({"changes": {"ScrewDepth": "8"}}));
|
||||
// Another value for the name is still a parameter that already exists.
|
||||
let undo = s.undo.len();
|
||||
let e = err(&mut s, "solid.hole", json!({"position": [30, 30, 12], "diameter": 5, "depth": "ScrewDepth = 6"}));
|
||||
assert!(e.contains("there is already a parameter `ScrewDepth`"), "{e}");
|
||||
assert_eq!(s.undo.len(), undo);
|
||||
assert_eq!(expr_of(&mut s, "ScrewDepth"), "8");
|
||||
}
|
||||
|
||||
/// Changing a parameter to `name = expression` names it (#4071): the dimension's or feature
|
||||
/// input's own parameter is renamed, references follow, and it takes the expression; no other
|
||||
/// parameter is made. One undo takes both back.
|
||||
|
||||
+145
-16
@@ -35,7 +35,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("fastener")
|
||||
.contract(&INSERT_CONTRACT)
|
||||
.output(output_schema_for::<InsertedPart>)
|
||||
.params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?"),
|
||||
.params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction? (from the shank's tip toward the head), name?"),
|
||||
CommandSpec::new("parts.insert", "Insert Part", crate::checked!("parts.insert", insert_atomic))
|
||||
.icon("fastener")
|
||||
.contract(&INSERT_CONTRACT)
|
||||
@@ -45,7 +45,9 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
hex_cap_screw_inch | hex_nut_inch | washer_sae | washer_uss); size (\"M6\", \"608\" for bearings, \"1/2-13 UNC\" for inch screws and nuts, \
|
||||
\"1/2\" for inch washers); length? (mm, inch parts too; 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), or a list of them (one component, \
|
||||
placed and seated once per hole) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name? → component, occurrence, joint?, \
|
||||
placed and seated once per hole) | point?: [x,y,z] with direction?: [x,y,z] (no joint: the part's seating plane, under a head or \
|
||||
the bottom of a nut, washer or bearing, the top of a set screw or pin, goes to point, and direction is its +z, from the shank's tip toward the head; default [0,0,1], \
|
||||
head up, shank down -z); name? → component, occurrence, joint?, \
|
||||
and with at: occurrences, joints (one per hole, in pick order)",
|
||||
),
|
||||
CommandSpec::new("parts.resize", "Change Part Size", crate::checked!("parts.resize", resize_atomic))
|
||||
@@ -750,18 +752,29 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A pick on a hole's rim also touches its end face: step onto the wall just inside the rim.
|
||||
// Each hole's occurrence is found before the part exists, so a pick off every body fails the
|
||||
// insert before anything is made.
|
||||
let mut holes = Vec::new();
|
||||
let mut seats: Vec<(u64, Vec3)> = Vec::new();
|
||||
let mut holes: Vec<(Vec3, u64)> = Vec::new();
|
||||
let mut seats: Vec<(u64, HoleWall)> = Vec::new();
|
||||
for a in hole_picks(p, cmd)? {
|
||||
let (a, seat) = hole_wall(s, a).unwrap_or((a, a));
|
||||
let host = super::joints::occurrence_at(s, a).ok_or_else(|| bad(cmd, "no body at `at` (pick a hole's rim or wall)"))?;
|
||||
// A rim is drawn as more than one edge, and one click on it picks them all: the picks
|
||||
// of one rim seat one part.
|
||||
if seats.iter().any(|(h, q)| *h == host && (*q - seat).len() < 1e-3) {
|
||||
continue;
|
||||
let wall = hole_wall(s, a).unwrap_or(HoleWall { at: a, seat: a, axis: None, ends: None, open: true });
|
||||
let host = super::joints::occurrence_at(s, wall.at).ok_or_else(|| bad(cmd, "no body at `at` (pick a hole's rim or wall)"))?;
|
||||
// A rim is drawn as more than one edge, and one click on it picks them all; a hole can
|
||||
// also be picked at both its ends (#12191). The picks of one hole seat one part, at an
|
||||
// open end: seated at a blind hole's floor it would stand on its head in the material.
|
||||
match seats.iter().position(|(h, w)| *h == host && w.same_hole(&wall)) {
|
||||
Some(i) => {
|
||||
if !seats.get(i).is_some_and(|(_, w)| w.open)
|
||||
&& wall.open
|
||||
&& let (Some(seat), Some(hole)) = (seats.get_mut(i), holes.get_mut(i))
|
||||
{
|
||||
*hole = (wall.at, host);
|
||||
seat.1 = wall;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
holes.push((wall.at, host));
|
||||
seats.push((host, wall));
|
||||
}
|
||||
}
|
||||
seats.push((host, seat));
|
||||
holes.push((a, host));
|
||||
}
|
||||
let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| part_name(&family, &size, &sh));
|
||||
let active = s.active_component;
|
||||
@@ -848,9 +861,43 @@ fn hole_picks(p: &Value, cmd: &str) -> Result<Vec<Vec3>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A point on the cylindrical wall of the hole at `a`, a little in from the picked rim, and the
|
||||
/// point on the hole's axis level with it (the same for every pick on one rim).
|
||||
fn hole_wall(s: &Session, a: Vec3) -> Option<(Vec3, Vec3)> {
|
||||
/// Where a pick on a hole's rim seats a part.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct HoleWall {
|
||||
/// A point on the hole's cylindrical wall, a little in from the picked rim.
|
||||
at: Vec3,
|
||||
/// The point on the hole's axis level with `at` (the same for every pick on one rim).
|
||||
seat: Vec3,
|
||||
/// The hole's axis, when the pick is on a hole.
|
||||
axis: Option<Vec3>,
|
||||
/// The two ends of the picked cylindrical wall, on the axis.
|
||||
ends: Option<[Vec3; 2]>,
|
||||
/// The picked rim opens onto air, not onto the floor of a blind hole.
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl HoleWall {
|
||||
/// The two picks seat on one hole: at one point, or on one axis line with walls that meet.
|
||||
/// Two blind holes drilled towards each other from opposite faces share an axis, but solid
|
||||
/// material between their walls keeps them two holes.
|
||||
fn same_hole(&self, other: &HoleWall) -> bool {
|
||||
if (self.seat - other.seat).len() < 1e-3 {
|
||||
return true;
|
||||
}
|
||||
match (self.axis, other.axis, self.ends, other.ends) {
|
||||
(Some(a), Some(b), Some(e), Some(f)) if a.cross(b).len() < 1e-6 && (other.seat - self.seat).cross(a).len() < 1e-3 => {
|
||||
let along = |p: Vec3| (p - self.seat).dot(a);
|
||||
let ([e0, e1], [f0, f1]) = (e.map(along), f.map(along));
|
||||
e0.min(e1) <= f0.max(f1) + 1e-3 && f0.min(f1) <= e0.max(e1) + 1e-3
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wall of the hole at `a`, a little in from the picked rim, and whether that rim is an open
|
||||
/// end of the hole: just past it along the axis is not the body's material.
|
||||
fn hole_wall(s: &Session, a: Vec3) -> Option<HoleWall> {
|
||||
// Picks are in world coordinates, including rims on already placed standard parts.
|
||||
let st = s.world_state().ok()?;
|
||||
let dirs = [Vec3::Z * -1.0, Vec3::Z, Vec3::X, Vec3::X * -1.0, Vec3::Y, Vec3::Y * -1.0];
|
||||
@@ -863,7 +910,13 @@ fn hole_wall(s: &Session, a: Vec3) -> Option<(Vec3, Vec3)> {
|
||||
let along = v.dot(c.axis);
|
||||
let on_wall = ((v - c.axis * along).len() - c.radius).abs() < 1e-3 && along > c.start && along < c.end;
|
||||
if on_wall {
|
||||
return Some((q, c.axis_point + c.axis * along));
|
||||
let axis: Vec3 = c.axis * 1.0;
|
||||
// The end of the wall nearer the pick, and a point on the axis just past it.
|
||||
let (end, out) = if along - c.start < c.end - along { (c.start, -1.0) } else { (c.end, 1.0) };
|
||||
let past = c.axis_point + axis * (end + out * (c.end - c.start).min(1.0) * 0.25);
|
||||
let open = !matches!(b.body.classify_point(past), Ok(solidcraft_doc::kernel::PointClass::Inside));
|
||||
let ends = [c.axis_point + axis * c.start, c.axis_point + axis * c.end];
|
||||
return Some(HoleWall { at: q, seat: c.axis_point + axis * along, axis: Some(axis), ends: Some(ends), open });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1211,6 +1264,27 @@ mod tests {
|
||||
assert!(hi.dist(solidcore_record::Vec3::new(49.6, 56.5, 66.5)) < 1e-6, "{hi:?}");
|
||||
}
|
||||
|
||||
/// #11729: placed at a point, the part's seating plane is at `point` and `direction` points
|
||||
/// from the shank's tip toward the head, as the help now says: `[0, 0, 1]` puts a screw head
|
||||
/// up with its shank down into a plate's top face, `[0, 0, -1]` upside down.
|
||||
#[test]
|
||||
fn a_part_placed_at_a_point_points_its_head_along_direction() {
|
||||
let help = super::COMMANDS.iter().find(|c| c.id == "parts.insert").map(|c| c.params).unwrap_or_default();
|
||||
assert!(help.contains("seating plane") && help.contains("from the shank's tip toward the head"), "{help}");
|
||||
for (direction, head_up) in [([0, 0, 1], true), ([0, 0, -1], false)] {
|
||||
let mut s = Session::default();
|
||||
run(
|
||||
&mut s,
|
||||
"parts.insert",
|
||||
json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20, "point": [5, 5, 10], "direction": direction}),
|
||||
);
|
||||
let (lo, hi) = bbox(&s, "SHCS M6x20");
|
||||
// The 6 mm head on one side of z = 10, the 20 mm shank on the other.
|
||||
let (head, shank) = if head_up { (hi.z - 10.0, 10.0 - lo.z) } else { (10.0 - lo.z, hi.z - 10.0) };
|
||||
assert!((head - 6.0).abs() < 1e-6 && (shank - 20.0).abs() < 1e-6, "{direction:?}: {lo:?} {hi:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Several holes in one insert: one component placed and seated once per hole, in one undo
|
||||
/// step (#9341); two picks of one rim are one hole; a pick off every body fails the whole
|
||||
/// insert.
|
||||
@@ -1259,6 +1333,61 @@ mod tests {
|
||||
assert_eq!((s.doc.components.len(), s.doc.occurrences.len()), (comps, occs));
|
||||
}
|
||||
|
||||
/// #12191: a hole picked at both ends (a blind hole's rim and its floor edge, a through
|
||||
/// hole's top and bottom rims) gets one fastener, head at the open end, not a second one
|
||||
/// turned over.
|
||||
#[test]
|
||||
fn a_hole_picked_at_both_ends_gets_one_fastener_at_its_open_end() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Block"}));
|
||||
let blind = [(8.0, 8.0), (32.0, 8.0), (32.0, 22.0)];
|
||||
for (x, y) in blind {
|
||||
run(&mut s, "solid.hole", json!({"position": [x, y, 20], "diameter": 3.4, "depth": 10}));
|
||||
}
|
||||
let through = (8.0, 22.0);
|
||||
run(&mut s, "solid.hole", json!({"position": [through.0, through.1, 20], "diameter": 3.4}));
|
||||
// The first blind hole is picked at its floor edge first, then at its rim; the second at
|
||||
// its rim, then its floor; the third at its rim only; the through hole at both rims.
|
||||
let rim = |(x, y): (f64, f64), z: f64| json!([x + 1.7, y, z]);
|
||||
let at = vec![
|
||||
rim(blind[0], 10.0),
|
||||
rim(blind[0], 20.0),
|
||||
rim(blind[1], 20.0),
|
||||
rim(blind[1], 10.0),
|
||||
rim(blind[2], 20.0),
|
||||
rim(through, 20.0),
|
||||
rim(through, 0.0),
|
||||
];
|
||||
let r = run(&mut s, "parts.fastener", json!({"family": "socket_head_cap_screw", "size": "M3", "length": 8, "at": at}));
|
||||
let comp = r["component"].as_u64().unwrap_or(0);
|
||||
assert_eq!(r["occurrences"].as_array().map(Vec::len), Some(4), "one screw per hole: {r}");
|
||||
let st = s.world_state().unwrap();
|
||||
let mut seated: Vec<(f64, f64)> = Vec::new();
|
||||
for b in st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp) {
|
||||
let (lo, hi) = (b.mesh().bounds().min, b.mesh().bounds().max);
|
||||
// Head on the top face (3 mm tall), shank 8 mm down the hole.
|
||||
assert!((hi.z - 23.0).abs() < 1e-6 && (lo.z - 12.0).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
seated.push(((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0));
|
||||
}
|
||||
assert_eq!(seated.len(), 4, "{seated:?}");
|
||||
for (x, y) in blind.into_iter().chain([through]) {
|
||||
assert!(seated.iter().any(|c| (c.0 - x).abs() < 1e-6 && (c.1 - y).abs() < 1e-6), "no screw at ({x}, {y}): {seated:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #12191: two blind holes drilled towards each other from opposite faces share an axis, but
|
||||
/// the material between them keeps them two holes: each rim picked gets its own fastener.
|
||||
#[test]
|
||||
fn coaxial_blind_holes_from_opposite_faces_get_a_fastener_each() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Block"}));
|
||||
run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 3.4, "depth": 6}));
|
||||
run(&mut s, "solid.hole", json!({"position": [20, 15, 0], "direction": [0, 0, 1], "diameter": 3.4, "depth": 6}));
|
||||
let at = json!([[21.7, 15, 20], [21.7, 15, 0]]);
|
||||
let r = run(&mut s, "parts.fastener", json!({"family": "socket_head_cap_screw", "size": "M3", "length": 6, "at": at}));
|
||||
assert_eq!(r["occurrences"].as_array().map(Vec::len), Some(2), "one screw per hole: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_sketch_of_a_standard_part_is_fully_defined() {
|
||||
for (family, size, resized) in [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Plastic (enclosure) features: Boss, Lip / Groove, Snap Fit and Rest, and plastic rules.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_doc::BodyName;
|
||||
use solidcraft_doc::FeatureKind;
|
||||
@@ -12,8 +12,16 @@ use solidcraft_geom::prelude::*;
|
||||
use super::CommandSpec;
|
||||
use super::features::{add_feature, check_expr};
|
||||
use crate::params::{bad, bool_, expr, req_expr, str_, string_list, vec3};
|
||||
use crate::schema::plastic::{
|
||||
AssignRuleParams, AssignRuleResult, ManageRulesParams, ManageRulesResult, RuleExpressions, RuleInfo, RuleValuesOrError, RulesParams, RulesResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const MANAGE_RULES_CONTRACT: TypedContract<ManageRulesParams> = TypedContract::new();
|
||||
const ASSIGN_RULE_CONTRACT: TypedContract<AssignRuleParams> = TypedContract::new();
|
||||
const RULES_CONTRACT: TypedContract<RulesParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("plastic.boss", "Boss", boss).at("PLASTIC", "CREATE").icon("boss").params(
|
||||
"position: [x,y,z] on a face; direction? (default: out of the face); diameter, height; hole_diameter?, hole_depth? (default: to the face); \
|
||||
@@ -30,30 +38,48 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"position: [x,y,z] on a face (the rest's centre); direction? (default: out of the face); width (round: the diameter); length? (a rectangle, along `along`); along?: [x,y,z]; \
|
||||
height; draft? (angle; default: the body's plastic rule); thickness? (wall of a hollow rest); body?",
|
||||
),
|
||||
CommandSpec::new("plastic.manage_rules", "Manage Plastic Rules", manage_rules).at("PLASTIC", "SETUP").icon("plastic_rule").params(
|
||||
CommandSpec::new("plastic.manage_rules", "Manage Plastic Rules", crate::checked!("plastic.manage_rules", manage_rules))
|
||||
.at("PLASTIC", "SETUP")
|
||||
.icon("plastic_rule")
|
||||
.contract(&MANAGE_RULES_CONTRACT)
|
||||
.output(output_schema_for::<ManageRulesResult>)
|
||||
.params(
|
||||
"name (library or new rule; a new one starts from `from`, default ABS (1.5mm)); from?; material?; thickness?, nominal_radius?, clearance?, knife_edge?, \
|
||||
reveal_height?, thickness_variation?, draft?, max_thickness?, min_thickness?, min_draft? (expressions; `Thickness` is the rule's); active?: bool (rule for bodies without one); \
|
||||
delete?: bool (a design rule; a library rule goes back to the library values)",
|
||||
),
|
||||
CommandSpec::new("plastic.assign_rule", "Assign Plastic Rule", assign_rule).at("PLASTIC", "SETUP").icon("plastic_assign").params(
|
||||
CommandSpec::new("plastic.assign_rule", "Assign Plastic Rule", crate::checked!("plastic.assign_rule", assign_rule))
|
||||
.at("PLASTIC", "SETUP")
|
||||
.icon("plastic_assign")
|
||||
.contract(&ASSIGN_RULE_CONTRACT)
|
||||
.output(output_schema_for::<AssignRuleResult>)
|
||||
.params(
|
||||
"bodies: [names]; rule: name (empty: no rule) — plastic features on these bodies take its draft and clearance as defaults",
|
||||
),
|
||||
CommandSpec::new("plastic.rules", "List Plastic Rules", list_rules).icon("plastic_rule").noundo().params("→ rules with their expressions and values, the active rule and the rules assigned to bodies"),
|
||||
CommandSpec::new("plastic.rules", "List Plastic Rules", crate::checked!("plastic.rules", list_rules))
|
||||
.icon("plastic_rule")
|
||||
.noundo()
|
||||
.contract(&RULES_CONTRACT)
|
||||
.output(output_schema_for::<RulesResult>)
|
||||
.params("→ rules with their expressions and values, the active rule and the rules assigned to bodies"),
|
||||
];
|
||||
|
||||
fn rule_json(s: &Session, r: &PlasticRule) -> Value {
|
||||
/// A rule as the rule commands give it back: its expressions, and its values evaluated against
|
||||
/// the design's parameters (or why they don't evaluate).
|
||||
fn rule_info(s: &Session, r: &PlasticRule) -> RuleInfo {
|
||||
let (vals, _) = s.doc.param_values();
|
||||
let values = s.doc.plastic_values(&vals, r).map(|v| {
|
||||
json!({"thickness": v.thickness, "nominal_radius": v.nominal_radius, "clearance": v.clearance, "knife_edge": v.knife_edge,
|
||||
"reveal_height": v.reveal_height, "thickness_variation": v.thickness_variation, "draft_deg": v.draft.to_degrees(),
|
||||
"max_thickness": v.max_thickness, "min_thickness": v.min_thickness, "min_draft_deg": v.min_draft.to_degrees()})
|
||||
});
|
||||
let values = match s.doc.plastic_values(&vals, r) {
|
||||
Ok(v) => RuleValuesOrError::Values(v.into()),
|
||||
Err(e) => RuleValuesOrError::Error { error: e.to_string() },
|
||||
};
|
||||
let library = PlasticRule::library().iter().any(|l| l.name == r.name);
|
||||
json!({
|
||||
"name": r.name, "material": r.material, "library": library,
|
||||
"expressions": r.fields().iter().map(|(k, e, _)| (k.to_string(), json!(e))).collect::<serde_json::Map<_, _>>(),
|
||||
"values": values.unwrap_or_else(|e| json!({"error": e.to_string()})),
|
||||
})
|
||||
RuleInfo { name: r.name.clone(), material: r.material.clone(), library, expressions: RuleExpressions::from(r), values }
|
||||
}
|
||||
|
||||
/// A reply built from its output schema's type (`schema::plastic`), so the two can't drift
|
||||
/// apart.
|
||||
fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -72,7 +98,7 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
doc.plastic.assigned.retain(|_, r| *r != name);
|
||||
}
|
||||
return Ok(json!({"deleted": name}));
|
||||
return typed_reply(cmd, ManageRulesResult::Deleted { deleted: name, param_warnings: Vec::new() });
|
||||
}
|
||||
let mut rule = match s.doc.plastic_rule(&name) {
|
||||
Some(r) => r,
|
||||
@@ -116,7 +142,8 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => {}
|
||||
}
|
||||
s.refresh();
|
||||
Ok(json!({"rule": rule_json(s, &rule), "active": s.doc.plastic.active}))
|
||||
let reply = ManageRulesResult::Changed { rule: Box::new(rule_info(s, &rule)), active: s.doc.plastic.active.clone(), param_warnings: Vec::new() };
|
||||
typed_reply(cmd, reply)
|
||||
}
|
||||
|
||||
fn assign_rule(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -142,12 +169,13 @@ fn assign_rule(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.refresh();
|
||||
Ok(json!({"bodies": bodies, "rule": if rule.is_empty() { Value::Null } else { json!(rule) }}))
|
||||
typed_reply(cmd, AssignRuleResult { bodies, rule: (!rule.is_empty()).then_some(rule), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn list_rules(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let rules: Vec<Value> = s.doc.plastic_rules().iter().map(|r| rule_json(s, r)).collect();
|
||||
Ok(json!({"rules": rules, "active": s.doc.plastic.active, "assigned": s.doc.plastic.assigned}))
|
||||
let rules = s.doc.plastic_rules().iter().map(|r| rule_info(s, r)).collect();
|
||||
let reply = RulesResult { rules, active: s.doc.plastic.active.clone(), assigned: s.doc.plastic.assigned.clone(), param_warnings: Vec::new() };
|
||||
typed_reply("plastic.rules", reply)
|
||||
}
|
||||
|
||||
fn rest(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -4,13 +4,17 @@
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::Mat;
|
||||
use solidcraft_doc::point_cloud::{
|
||||
ColorBy, Colors, Filter, Keep, MAX_COORD, MAX_FILTERS, MAX_NAMES, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale,
|
||||
ColorBy, Colors, Complex, Filter, Keep, MAX_COORD, MAX_FILTERS, MAX_NAMES, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale,
|
||||
};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_};
|
||||
use crate::schema::point_cloud::{PointCloudReloadParams, PointCloudReloadResult};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const RELOAD_CONTRACT: TypedContract<PointCloudReloadParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("pointcloud.insert", "Insert Point Cloud", insert)
|
||||
.at("SOLID", "INSERT")
|
||||
@@ -19,12 +23,17 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("pointcloud.edit", "Edit Point Cloud", edit)
|
||||
.icon("edit")
|
||||
.params("cloud: id or name; name?; visible?; point_size?: pixels (0.5…16); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; units?: mm|cm|m|in|ft (the file's length unit: the points are scaled from the unit they came in as); matrix?: [12 or 16 numbers] (where the cloud sits: a rigid row-major 3x4 or 4x4 matrix, as occurrence.move takes it); tolerance?; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown) → cloud"),
|
||||
CommandSpec::new("pointcloud.reload", "Reload Point Cloud", crate::checked!("pointcloud.reload", reload))
|
||||
.icon("import")
|
||||
.contract(&RELOAD_CONTRACT)
|
||||
.output(output_schema_for::<PointCloudReloadResult>)
|
||||
.params("cloud: id or name (its file is read again from where it was inserted; name, placement, units, colouring and the filters on properties it still has are kept; read under the limit it was inserted with, so a file that grew is thinned only past that limit) → cloud, points, segments, triangles, warnings"),
|
||||
CommandSpec::new("pointcloud.delete", "Delete Point Cloud", delete).icon("delete").params("cloud: id or name → deleted"),
|
||||
CommandSpec::new("pointcloud.list", "Point Clouds", list)
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.params("→ clouds: [{cloud, name, file, points, segments, triangles, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"),
|
||||
.params("→ clouds: [{cloud, name, file, source (the file's path, read again by pointcloud.reload), points, segments, triangles, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"),
|
||||
];
|
||||
|
||||
fn units_of(p: &Value, cmd: &str) -> Result<Option<(&'static str, f64)>> {
|
||||
@@ -123,13 +132,18 @@ fn check_properties(c: &PointCloud, cmd: &str) -> Result<()> {
|
||||
return Err(bad(cmd, format!("the point cloud has no property `{n}` (it has {})", names.join(", "))));
|
||||
}
|
||||
}
|
||||
// A set of values filters a label: a property with named whole numbers.
|
||||
if let Some(f) = c.filters.iter().find(|f| matches!(f.keep, Keep::Values { .. }) && c.complex.names(&f.property).is_none()) {
|
||||
if let Some(f) = c.filters.iter().find(|f| picks_from_no_names(&c.complex, f)) {
|
||||
return Err(bad(cmd, format!("`{}` has no named values: filter it with a range", f.property)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A set of values filters a label: a property with named whole numbers. Is this one a set of
|
||||
/// values on a property with no names?
|
||||
fn picks_from_no_names(complex: &Complex, f: &Filter) -> bool {
|
||||
matches!(f.keep, Keep::Values { .. }) && complex.names(&f.property).is_none()
|
||||
}
|
||||
|
||||
/// `height_range`: absent (`None`), null for the automatic one (`Some(None)`), or [low, high].
|
||||
fn height_range(p: &Value, cmd: &str) -> Result<Option<Option<[f64; 2]>>> {
|
||||
let refuse = || bad(cmd, "`height_range` (or `color_range`) must be [low, high], lowest first, or null");
|
||||
@@ -232,6 +246,8 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
complex: read.complex,
|
||||
color_property: None,
|
||||
filters: filters(p, cmd)?.unwrap_or_default(),
|
||||
source: std::path::absolute(path).map(|a| a.to_string_lossy().to_string()).unwrap_or_else(|_| path.to_string()),
|
||||
max_points: Some(max_points as u64),
|
||||
};
|
||||
set_colors(&mut cloud, colors.0, colors.1, colors.2);
|
||||
check_properties(&cloud, cmd)?;
|
||||
@@ -260,7 +276,7 @@ fn find(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
let key = match p.get("cloud") {
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
Some(Value::String(x)) => x.clone(),
|
||||
_ => return Err(bad(cmd, "`cloud` must be an id or a name")),
|
||||
_ => return Err(bad(cmd, "`cloud` must be an id or name")),
|
||||
};
|
||||
s.doc.point_clouds.iter().position(|c| c.id.to_string() == key || c.name == key).ok_or_else(|| bad(cmd, format!("no point cloud `{key}`")))
|
||||
}
|
||||
@@ -318,6 +334,56 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"cloud": id}))
|
||||
}
|
||||
|
||||
/// The most points a reload keeps: the limit the cloud was read under. A read is a function of
|
||||
/// the file and that limit, so an unchanged file reads as the very same points, and a file that
|
||||
/// grew is thinned only past the limit. The counts cannot say this: a cloud has fewer points than
|
||||
/// its file when some could not be read, too, thinned or not.
|
||||
fn reload_limit(c: &PointCloud) -> usize {
|
||||
c.max_points.map_or(solidcraft_io::DEFAULT_MAX_POINTS, |n| usize::try_from(n).unwrap_or(MAX_POINTS))
|
||||
}
|
||||
|
||||
/// Read the cloud's file again where it was read from, keeping its name, placement, units and
|
||||
/// how it is shown.
|
||||
/// The path comes from the design, which may be someone else's, so it is a design path: one on
|
||||
/// another computer is refused from its text until the user allows that server.
|
||||
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "pointcloud.reload";
|
||||
let i = find(s, p, cmd)?;
|
||||
let mut c = s.doc.point_clouds.get(i).cloned().ok_or_else(|| bad(cmd, "point cloud"))?;
|
||||
if c.source.is_empty() {
|
||||
return Err(bad(cmd, format!("point cloud `{}` does not remember its file", c.name)));
|
||||
}
|
||||
let path = c.source.clone();
|
||||
let scale = unit_scale(&c.units).unwrap_or(1.0);
|
||||
let max_points = reload_limit(&c);
|
||||
let bytes = solidcraft_io::vfs::read_design_path(&path, s.path.as_deref(), solidcraft_io::MAX_POINT_CLOUD_BYTES)
|
||||
.map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let read = solidcraft_io::read_point_cloud(&bytes, &path, scale, max_points).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
c.origin = read.origin;
|
||||
c.points = Points::new(read.points.into());
|
||||
c.colors = Colors(read.colors.into());
|
||||
c.source_points = read.source_points;
|
||||
c.complex = read.complex;
|
||||
// What the file no longer has is no longer coloured or filtered by.
|
||||
let names: Vec<String> = c.property_names().map(str::to_string).collect();
|
||||
c.filters.retain(|f| names.contains(&f.property) && !picks_from_no_names(&c.complex, f));
|
||||
if c.color_by == ColorBy::Property && !c.color_property.as_ref().is_some_and(|n| names.contains(n)) {
|
||||
(c.color_by, c.color_property) = (ColorBy::File, None);
|
||||
}
|
||||
c.check()?;
|
||||
let out = PointCloudReloadResult {
|
||||
cloud: c.id,
|
||||
points: c.len(),
|
||||
segments: c.complex.segment_count(),
|
||||
triangles: c.complex.triangle_count(),
|
||||
warnings: read.warnings,
|
||||
};
|
||||
let out = serde_json::to_value(out).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let slot = s.doc_mut().point_clouds.get_mut(i).ok_or_else(|| bad(cmd, "point cloud"))?;
|
||||
*slot = c;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = find(s, p, "pointcloud.delete")?;
|
||||
let c = s.doc_mut().point_clouds.remove(i);
|
||||
@@ -348,6 +414,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
.collect::<Vec<_>>(),
|
||||
"filters": c.filters,
|
||||
"color_range": solidcraft_doc::point_cloud_distribution::color_range(c, &solidcraft_doc::point_cloud_distribution::Geometry::of(c), &c.filters),
|
||||
"source": c.source,
|
||||
"color": c.color,
|
||||
"colored": !c.colors.is_empty(),
|
||||
"height_range": c.height_range_now(),
|
||||
@@ -464,6 +531,174 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A PLY in text with a `layer` property (or none) on each point.
|
||||
fn layered(path: &std::path::Path, points: usize, layer: bool) {
|
||||
let mut b = format!("ply\nformat ascii 1.0\nelement vertex {points}\nproperty float x\nproperty float y\nproperty float z\n");
|
||||
if layer {
|
||||
b.push_str("property int layer\n");
|
||||
}
|
||||
b.push_str("end_header\n");
|
||||
for i in 0..points {
|
||||
b.push_str(&if layer { format!("{i} 0 0 {i}\n") } else { format!("{i} 0 0\n") });
|
||||
}
|
||||
std::fs::write(path, b).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reload_reads_the_file_again_and_keeps_how_the_cloud_is_shown() {
|
||||
let d = dir("reload");
|
||||
let path = d.join("scan.ply");
|
||||
layered(&path, 3, true);
|
||||
let mut s = Session::default();
|
||||
let id = s.execute("pointcloud.insert", &json!({"path": path, "units": "m"})).unwrap()["cloud"].as_u64().unwrap();
|
||||
s.execute(
|
||||
"pointcloud.edit",
|
||||
&json!({"cloud": id, "name": "Scan", "point_size": 4, "matrix": [1, 0, 0, 100, 0, 1, 0, 0, 0, 0, 1, 0], "color_by": "layer", "filters": [{"property": "layer", "range": [0, 2]}]}),
|
||||
)
|
||||
.unwrap();
|
||||
let listed = s.execute("pointcloud.list", &json!({})).unwrap();
|
||||
assert_eq!(listed["clouds"][0]["source"], json!(std::path::absolute(&path).unwrap()));
|
||||
|
||||
layered(&path, 5, true);
|
||||
let r = s.execute("pointcloud.reload", &json!({"cloud": "Scan"})).unwrap();
|
||||
assert_eq!((r["cloud"].as_u64(), r["points"].as_u64()), (Some(id), Some(5)));
|
||||
let c = &s.doc.point_clouds[0];
|
||||
assert_eq!((c.name.as_str(), c.units.as_str(), c.point_size, c.color_by), ("Scan", "m", 4.0, ColorBy::Property));
|
||||
assert_eq!(c.color_property.as_deref(), Some("layer"));
|
||||
assert_eq!(c.filters.len(), 1);
|
||||
// In metres and moved, as before: the last point is at 4 m, plus 100 mm.
|
||||
assert_eq!(c.world_point(4).map(|p| p.x), Some(4100.0));
|
||||
// One undo step takes it back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.point_clouds[0].len(), 3);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.point_clouds[0].len(), 5);
|
||||
|
||||
// What the file no longer has is no longer coloured or filtered by.
|
||||
layered(&path, 2, false);
|
||||
s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
|
||||
let c = &s.doc.point_clouds[0];
|
||||
assert_eq!((c.len(), c.color_by, c.color_property.as_deref(), c.filters.len()), (2, ColorBy::File, None, 0));
|
||||
|
||||
// A file that is gone is refused, and the cloud is as it was, with no undo step.
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let (before, undo) = (s.doc.point_clouds.clone(), s.undo.len());
|
||||
assert!(s.execute("pointcloud.reload", &json!({"cloud": id})).is_err());
|
||||
assert_eq!((&s.doc.point_clouds, s.undo.len()), (&before, undo));
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A set of values filters a label, so it lasts as long as the file names that property's
|
||||
/// values: left behind, it would make every later `pointcloud.edit` of the cloud refused.
|
||||
#[test]
|
||||
fn a_reload_drops_a_value_filter_when_the_file_stops_naming_the_values() {
|
||||
let d = dir("reload-names");
|
||||
let path = d.join("scan.ply");
|
||||
let write = |comment: &str| {
|
||||
let head = "ply\nformat ascii 1.0\n";
|
||||
let body = "element vertex 2\nproperty float x\nproperty float y\nproperty float z\nproperty int layer\nend_header\n0 0 0 0\n1 0 0 1\n";
|
||||
std::fs::write(&path, format!("{head}{comment}{body}")).unwrap();
|
||||
};
|
||||
write("comment layer: 0 first, 1 second\n");
|
||||
let mut s = Session::default();
|
||||
let id = s.execute("pointcloud.insert", &json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
|
||||
s.execute("pointcloud.edit", &json!({"cloud": id, "filters": [{"property": "layer", "values": [1]}]})).unwrap();
|
||||
|
||||
// Still named: the filter stays.
|
||||
s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
|
||||
assert_eq!(s.doc.point_clouds[0].filters.len(), 1);
|
||||
|
||||
// The same property with no names: the filter goes, and the cloud can still be edited.
|
||||
write("");
|
||||
s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
|
||||
assert!(s.doc.point_clouds[0].filters.is_empty());
|
||||
s.execute("pointcloud.edit", &json!({"cloud": id, "point_size": 4})).unwrap();
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A design may come from anyone, and on Windows only asking about `\\\\host\\share\\x` connects
|
||||
/// to that computer with the user's sign-in: the path is refused from its text, with no file
|
||||
/// call, until the server is allowed.
|
||||
#[test]
|
||||
fn a_reload_reaches_no_network_location_until_its_server_is_allowed() {
|
||||
use solidcraft_io::vfs::{allowing_hosts, file_calls};
|
||||
let d = dir("reload-network");
|
||||
let path = d.join("scan.ply");
|
||||
layered(&path, 3, false);
|
||||
let mut s = Session::default();
|
||||
let id = s.execute("pointcloud.insert", &json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
|
||||
for (crafted, says) in [(r"\\evil.example\share\scan.ply", "evil.example"), (r"\\.\pipe\scan.ply", "device")] {
|
||||
s.doc_mut().point_clouds[0].source = crafted.into();
|
||||
let (before, undo, calls) = (s.doc.point_clouds.clone(), s.undo.len(), file_calls());
|
||||
let e = s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{e}");
|
||||
assert_eq!(file_calls(), calls, "{crafted}: nothing was asked of the disk or the network");
|
||||
assert_eq!((&s.doc.point_clouds, s.undo.len()), (&before, undo));
|
||||
}
|
||||
// Allowed, the read goes ahead (and fails here only because no such server answers).
|
||||
s.doc_mut().point_clouds[0].source = r"\\evil.example\share\scan.ply".into();
|
||||
let calls = file_calls();
|
||||
let allowed = allowing_hosts(&["evil.example".to_string()], || s.execute("pointcloud.reload", &json!({"cloud": id})));
|
||||
assert!(allowed.is_err());
|
||||
assert!(file_calls() > calls, "an allowed server is read");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reload_reads_a_grown_file_whole_and_keeps_a_thinned_cloud_thinned() {
|
||||
let d = dir("reload-limit");
|
||||
let (whole, thin) = (d.join("whole.ply"), d.join("thin.ply"));
|
||||
layered(&whole, 4, false);
|
||||
layered(&thin, 100, false);
|
||||
let mut s = Session::default();
|
||||
s.execute("pointcloud.insert", &json!({"path": whole, "name": "Whole"})).unwrap();
|
||||
// One point in ten is the fewest strides that fit in 11: ten points, under the limit.
|
||||
s.execute("pointcloud.insert", &json!({"path": thin, "name": "Thin", "max_points": 11})).unwrap();
|
||||
let thinned = s.doc.point_clouds[1].clone();
|
||||
assert_eq!((thinned.len(), thinned.source_points), (10, 100));
|
||||
|
||||
layered(&whole, 100, false);
|
||||
let r = s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
|
||||
assert_eq!(r["points"].as_u64(), Some(100), "a file that grew is not cut to the count it had");
|
||||
|
||||
// The same file reads as the very same points.
|
||||
s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
|
||||
assert_eq!(s.doc.point_clouds[1].points, thinned.points);
|
||||
// A grown one, thinned under the same limit.
|
||||
layered(&thin, 500, false);
|
||||
let r = s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
|
||||
assert_eq!(r["points"].as_u64(), Some(11));
|
||||
assert_eq!(s.doc.point_clouds[1].source_points, 500);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reload_takes_no_unreadable_point_for_thinning() {
|
||||
let d = dir("reload-unreadable");
|
||||
// `count` points in a line, with the one at `far` out of range, so it cannot be read.
|
||||
let line = |count: usize, far: usize| -> Vec<[f32; 3]> { (0..count).map(|i| [if i == far { 1e30 } else { i as f32 }, 0.0, 0.0]).collect() };
|
||||
let whole = ply(&d, "whole.ply", &line(4, 1), false);
|
||||
let thin = ply(&d, "thin.ply", &line(100, 10), false);
|
||||
let mut s = Session::default();
|
||||
s.execute("pointcloud.insert", &json!({"path": whole, "name": "Whole"})).unwrap();
|
||||
s.execute("pointcloud.insert", &json!({"path": thin, "name": "Thin", "max_points": 10})).unwrap();
|
||||
let (kept_whole, kept_thin) = (s.doc.point_clouds[0].clone(), s.doc.point_clouds[1].clone());
|
||||
assert_eq!((kept_whole.len(), kept_whole.source_points), (3, 4));
|
||||
assert_eq!((kept_thin.len(), kept_thin.source_points), (9, 100));
|
||||
|
||||
// The same files read as the very same points.
|
||||
s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
|
||||
s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
|
||||
assert_eq!(s.doc.point_clouds[0].points, kept_whole.points);
|
||||
assert_eq!(s.doc.point_clouds[1].points, kept_thin.points);
|
||||
|
||||
// A file that grew comes in whole, not cut to the count it had.
|
||||
ply(&d, "whole.ply", &line(100, 1), false);
|
||||
let r = s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
|
||||
assert_eq!(r["points"].as_u64(), Some(99));
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_point_cloud_params_never_panic() {
|
||||
let d = dir("hostile");
|
||||
@@ -511,6 +746,18 @@ mod tests {
|
||||
assert!(s.execute("pointcloud.edit", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.execute("pointcloud.delete", &json!({"cloud": "nope"})).is_err());
|
||||
for p in [json!({}), json!({"cloud": 999}), json!({"cloud": [1]})] {
|
||||
assert!(s.execute("pointcloud.reload", &p).is_err(), "{p}");
|
||||
}
|
||||
// A cloud from a design saved before it remembered its file, or naming a file not a scan.
|
||||
let source = s.doc.point_clouds[0].source.clone();
|
||||
for hostile in ["", bad.to_str().unwrap(), d.to_str().unwrap()] {
|
||||
s.doc_mut().point_clouds[0].source = hostile.into();
|
||||
let before = s.doc.point_clouds.clone();
|
||||
assert!(s.execute("pointcloud.reload", &json!({"cloud": id})).is_err(), "{hostile}");
|
||||
assert_eq!(s.doc.point_clouds, before);
|
||||
}
|
||||
s.doc_mut().point_clouds[0].source = source;
|
||||
// Scaled out of range: refused, and the cloud is as it was.
|
||||
let far = ply(&d, "far.ply", &[[2e6, 0.0, 0.0], [2e6, 1.0, 0.0]], false);
|
||||
let far = s.execute("pointcloud.insert", &json!({"path": far})).unwrap()["cloud"].as_u64().unwrap();
|
||||
|
||||
@@ -8,12 +8,15 @@ use solidcraft_doc::render_settings::{RenderSettings, RenderSetup};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::bad;
|
||||
use crate::schema::render_camera::{CameraApplied, CameraFitted, CameraInfo, CameraSet, RenderCamera};
|
||||
use crate::{Result, Session};
|
||||
|
||||
mod clear_coat;
|
||||
mod coat_bindings;
|
||||
mod effects;
|
||||
mod environment;
|
||||
mod jobs;
|
||||
pub(crate) use jobs::{Prepared as PreparedCapture, cancel_params as render_cancel_params, prepare_with_metadata as prepare_capture_with_metadata};
|
||||
mod library;
|
||||
mod library_data;
|
||||
#[cfg(test)]
|
||||
@@ -49,7 +52,7 @@ 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."),
|
||||
.params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU HDR/constant or 0..100 CPU/GPU Sky and GPU HDR. 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())
|
||||
@@ -79,24 +82,48 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.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()
|
||||
CommandSpec::new("render.coat.bind", "Save Clear Coat", crate::checked!("render.coat.bind", coat_bindings::bind)).icon("appearance").doc_only()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render::CoatBindParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render::CoatBindResult>)
|
||||
.params("name; set?: numerical setup patch; body_index/body_name: exact render.scene identity; expected_revision; coat:{weight:0..1,roughness:0.045..1,ior:1..3}; replace?:false. Stores up to the existing 64 target bound as stable definition/feature/component/occurrence bindings for CPU/GPU. Even zero-weight coats require opaque targets. Same-target Glass refuses. One undo; no geometry, engineering material or appearance mutation."),
|
||||
CommandSpec::new("render.coat.unbind", "Remove Clear Coat", crate::checked!("render.coat.unbind", coat_bindings::unbind)).icon("appearance").doc_only()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render::CoatUnbindParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render::CoatUnbindResult>)
|
||||
.params("name; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that stable coat assignment in one undo, without device or file access."),
|
||||
CommandSpec::new("render.optics.bind","Save Optical Binding",crate::checked!("render.optics.bind", optical_bindings::bind)).icon("appearance")
|
||||
.contract(&optical_bindings::BIND_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsBindingSaved>)
|
||||
.params("name: CPU or GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy},model?:{roughness:0..1,dispersion?:{abbe_number:5..200},thin_film?:{ior:1..3,thickness_nm:0..100000}}}; replace?:false. The optional model adds isotropic rough transmission, three-band dispersion and one lossless coherent film. CPU models require explicit Path; rough sheets require straight transmitted shadows off. See docs/render-glass-material-models.md. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. CPU consumes at most eight certified optical targets. Without options.path, sheets and axis-aligned boxes retain the existing transport. Explicit progressive options.path enables exact closed-mesh certification, bounded nested convex-parent media, Beer/Snell/Fresnel and thin transmitted shadows; touching or unproven boundaries and closed transmitted-shadow connections refuse explicitly. Existing subsurface parameters may be consumed on certified closed Path media with denoising explicitly off; scalar free-flight/HG walks and separate Beer absorption are supported without refracting-boundary next-event approximation. A zero scattering rate preserves transport. GPU nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."),
|
||||
CommandSpec::new("render.optics.unbind","Remove Optical Binding",crate::checked!("render.optics.unbind", optical_bindings::unbind)).icon("appearance").doc_only()
|
||||
.contract(&optical_bindings::UNBIND_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsUnbound>)
|
||||
.params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."),
|
||||
CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only()
|
||||
.params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."),
|
||||
CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only()
|
||||
CommandSpec::new("render.camera.set", "Set Render Camera", crate::checked!("render.camera.set", set_camera)).icon("camera").noundo().doc_only()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render_camera::SetParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_camera::CameraSet>)
|
||||
.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()
|
||||
CommandSpec::new("render.camera.get", "Inspect Render Camera", crate::checked!("render.camera.get", get_camera)).icon("camera").noundo()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render_camera::GetParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_camera::CameraInfo>)
|
||||
.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()
|
||||
CommandSpec::new("render.camera.fit", "Frame Render Subject", crate::checked!("render.camera.fit", fit_camera)).icon("camera").noundo()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render_camera::FitParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_camera::CameraFitted>)
|
||||
.params("aspect?: the picture's width over its height, 0.000001 to 1000000 (default 1). Fits the current camera to the visible product bounds through the shared Camera::fit contract, moving back for a picture taller than wide so its sides hold the product too; 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")
|
||||
CommandSpec::new("render.preset.resolve", "Review Native Studio", crate::checked!("render.preset.resolve", studio_presets::resolve)).icon("render_scene").noundo()
|
||||
.contract(&studio_presets::PRESET_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_presets::StudioComposition>)
|
||||
.params("id: NATIVE-STUDIO-001..025; name; set?: typed CPU/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", crate::checked!("render.preset.apply", studio_presets::apply)).icon("render_scene")
|
||||
.contract(&studio_presets::PRESET_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_presets::StudioComposition>)
|
||||
.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.quality.prepare", "Review Fixed Sampling Budget", crate::checked!("render.quality.prepare", studio_presets::quality)).icon("settings").noundo().doc_only()
|
||||
.contract(&studio_presets::QUALITY_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_presets::QualityResult>)
|
||||
.params("id: Q-*; variant:fixed_samples_png for the existing GPU projection, or cpu_progressive_png for Q-001/002/003 CPU cost budgets; acknowledge_omissions:true. Optional cpu:{minimum_budget:compact|studio|workstation,adaptive?:captured AdaptiveSampling} selects the smallest existing profile admitting pilots plus production without lowering minimum_budget. CPU budgets use authored sizes, 16/32/64 production samples and seed21026; preserve transport depth, denoise, optics and effects. Read-only numerical projections, not convergence/time guarantees or complete quality acceptance. Never switches executor, adopts fixed CPU sampling or mutates a shot."),
|
||||
CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", crate::checked!("render.shot.duplicate", shots::duplicate)).icon("copy").doc_only()
|
||||
.contract(&shots::CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_shots::ShotChange>)
|
||||
@@ -127,9 +154,13 @@ CommandSpec::new("render.stage.clear", "Remove Render Stage", crate::checked!("r
|
||||
.contract(&staging::CLEAR_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_stage::StageSaved>)
|
||||
.params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."),
|
||||
CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance")
|
||||
.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()
|
||||
CommandSpec::new("render.library.surface.bind", "Save Surface Binding", crate::checked!("render.library.surface.bind", surface_bindings::bind)).icon("appearance")
|
||||
.contract(&surface_bindings::BIND_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::SurfaceBindingSaved>)
|
||||
.params("name: CPU or GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."),
|
||||
CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", crate::checked!("render.library.surface.unbind", surface_bindings::unbind)).icon("appearance").doc_only()
|
||||
.contract(&surface_bindings::UNBIND_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::SurfaceBindingSaved>)
|
||||
.params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."),
|
||||
CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only()
|
||||
.params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
|
||||
@@ -150,17 +181,21 @@ CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appear
|
||||
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; rotation_rad?:0 (positive around the plane normal). 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."),
|
||||
.params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1; rotation_rad?:0 (positive around the plane normal). Returns an explicit GPU temporary planar binding and a source usable by saved CPU/GPU surface.bind, with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."),
|
||||
CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", library::prepare_studio).icon("inspect").noundo().doc_only()
|
||||
.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."),
|
||||
.params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius. Optional name and typed CPU set return the complete CPU projection and explicit indirect-lighting adoption plan; authored radiance beyond CPU intensity64 refuses without scaling. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."),
|
||||
CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", library::apply_studio).icon("settings")
|
||||
.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("rig: id, variant, center_mm and subject_extent_mm; name; set?: typed CPU/GPU setup patch; expected_revision?:u64; enable_indirect?:false (explicit CPU Sun adoption after review); replace_lighting_and_environment:true required. Saves the explicit rig projection in one undo, removing prior lighting/environment only with that confirmation. Subject clearance still needs review; passive cards are never silently omitted."),
|
||||
CommandSpec::new("render.hdr.inspect", "Inspect HDR Source", crate::checked!("render.hdr.inspect", resources::inspect)).icon("inspect").noundo().doc_only()
|
||||
.contract(&resources::INSPECT_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_hdr::HdrInspected>)
|
||||
.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()
|
||||
CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", crate::checked!("render.settings.capture_hdr", resources::capture_settings)).icon("settings").doc_only()
|
||||
.contract(&resources::CAPTURE_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_hdr::HdrCaptured>)
|
||||
.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"),
|
||||
.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.lens?: {aperture_radius_mm:0..10000000,focus_distance_mm:0.000001..1000000000}; positive aperture requires explicit CPU progressive sampling and a bounded perspective camera; absent/zero keeps the original CPU ray stream. See docs/render-thin-lens.md. CPU raytrace.volume?: one HomogeneousVolume box with world-mm min_mm/max_mm, extinction_per_mm:0..1000, RGB scattering_albedo:0..1 and anisotropy:-0.95..0.95. Positive extinction requires explicit Indirect lighting and cannot combine with Glass/SSS or surface Denoise. Physical eye/pupil prefixes and the orthographic line/box union preserve camera/model framing under existing ray/profile caps. See docs/render-cpu-volume.md. CPU raytrace.sun? uses the shared finite-disk Sun contract; raytrace.sky? uses {gradient,rotation_rad,intensity}. Both require explicit Indirect lighting, and gradient Sky excludes a constant/HDR environment. Their medium NEE uses the HG response/PDF and physical light source; see docs/render-cpu-celestial.md. CPU transparent_background?:false exports straight-alpha primary geometry coverage for fixed/progressive sampling; body/face opacity must remain 1, and active bloom/backdrop/photographic effects require opaque output. CPU raytrace.output?: {tone_map,finishing,backdrop,linear_exr}; shared presentation supports up to 8192 per side and 16777216 pixels, CPU exposure remains raytrace.exposure_ev; raw FLOAT32 EXR is retained only at final completion. 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; area/LED sources and certified planar anisotropy/thin-sheet/axis-aligned-box dielectric continuations share the existing bounded transport and compatibility checks. 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. Optional raytrace.path:{max_depth:1..16} enables CPU diffuse/specular GI with matched rectangle/HDR light and BSDF MIS plus certified closed-mesh Glass. It requires explicit progressive camera sampling, primary_samples:1 and traced shadows; selected reflections and certified anisotropy refuse before HDR IO without changing intent. CPU Path dielectric subsurface?:{scattering_per_mm:0..100,anisotropy:-0.95..0.95} enables homogeneous free-flight/HG walks inside certified closed media; positive rates require denoising off. Contained light connections include scattering survival; closed refractive light connections and combining Glass with external volume remain unsupported. Absent path keeps the old certified thin_sheet/closed_box producer and refuses subsurface intent explicitly. See docs/render-cpu-general-glass.md and render-raytrace-dielectrics.md. CPU emissions are visible radiance and may light neighbors through sampled Path continuation, without mesh-emitter next-event sampling; 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,
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()
|
||||
@@ -170,7 +205,7 @@ CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").
|
||||
CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only()
|
||||
.params("job?: completed JobId (default selected result). 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} (default selected result), 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"),
|
||||
.params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed CPU or 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()
|
||||
@@ -178,13 +213,21 @@ CommandSpec::new("render.backends", "Render Backends", backends).icon("list")
|
||||
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"),
|
||||
.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, optics, coats, 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()
|
||||
CommandSpec::new("render.settings.apply", "Apply Render Camera", crate::checked!("render.settings.apply", apply_settings)).icon("camera").noundo().doc_only()
|
||||
.contract(&crate::schema::TypedContract::<crate::schema::render_camera::ApplyParams>::new())
|
||||
.output(crate::schema::output_schema_for::<crate::schema::render_camera::CameraApplied>)
|
||||
.params("name: saved setup. Applies its existing Camera snapshot including roll/up as view state, without modifying the document or starting a render."),
|
||||
];
|
||||
|
||||
/// A reply built from its output schema's type (`schema::render_camera`), so the two can't
|
||||
/// drift apart.
|
||||
fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
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")) {
|
||||
@@ -194,14 +237,17 @@ fn set_camera(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
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}))
|
||||
typed_reply(cmd, CameraSet { camera: RenderCamera(setup.camera), document_changed: false, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn get_camera(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let cmd = "render.camera.get";
|
||||
if !params.as_object().is_some_and(|p| p.is_empty()) {
|
||||
return Err(bad("render.camera.get", "expected an empty parameter object"));
|
||||
return Err(bad(cmd, "expected an empty parameter object"));
|
||||
}
|
||||
Ok(json!({"camera":s.camera,"explicit_view":s.camera.is_some(),"document_changed":false}))
|
||||
let reply =
|
||||
CameraInfo { camera: s.camera.map(RenderCamera), explicit_view: s.camera.is_some(), document_changed: false, param_warnings: Vec::new() };
|
||||
typed_reply(cmd, reply)
|
||||
}
|
||||
|
||||
fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
@@ -210,9 +256,13 @@ fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
Some(p) if p.len() == 1 && p.contains_key("aspect") => match p["aspect"].as_f64() {
|
||||
// The range a preview frame can show (`frame_rect` in the Render workspace).
|
||||
Some(a) if (1e-6..=1e6).contains(&a) => a,
|
||||
_ => return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height")),
|
||||
_ => {
|
||||
return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height"));
|
||||
}
|
||||
},
|
||||
_ => return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}")),
|
||||
_ => {
|
||||
return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}"));
|
||||
}
|
||||
};
|
||||
let scene = crate::product_scene::extract(s)?;
|
||||
let mut camera = s.camera.unwrap_or_default();
|
||||
@@ -221,7 +271,8 @@ fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Err(bad("render.camera.fit", "the product cannot be framed at this aspect: the fitted camera is out of range"));
|
||||
}
|
||||
s.camera = Some(camera);
|
||||
Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false}))
|
||||
let reply = CameraFitted { camera: RenderCamera(camera), empty: scene.bounds.is_empty(), document_changed: false, param_warnings: Vec::new() };
|
||||
typed_reply("render.camera.fit", reply)
|
||||
}
|
||||
|
||||
fn scene(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
@@ -252,8 +303,9 @@ fn apply_settings(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
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}))
|
||||
let camera = setup.camera;
|
||||
s.camera = Some(camera);
|
||||
typed_reply("render.settings.apply", CameraApplied { name, camera: RenderCamera(camera), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -299,7 +351,10 @@ fn set_settings(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
|
||||
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"))?;
|
||||
// A full RenderSetup has 15 known fields, including maps, optics, coats and
|
||||
// stage. Bound the patch by that schema; decoding below still rejects any
|
||||
// unknown field instead of silently dropping saved intent.
|
||||
let patch = set.as_object().filter(|p| p.len() <= 15).ok_or_else(|| bad(cmd, "`set` must be an object with at most 15 fields"))?;
|
||||
let current = s.doc.render.setups.get(name).cloned().unwrap_or_default();
|
||||
let mut value = serde_json::to_value(¤t).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let object = value.as_object_mut().ok_or_else(|| bad(cmd, "invalid render setup"))?;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(super) struct Override {
|
||||
ior: f64,
|
||||
}
|
||||
pub(super) fn apply(scene: &mut ProductScene, overrides: &[Override], command: &str) -> Result<()> {
|
||||
if overrides.len() > 64 {
|
||||
if overrides.len() > solidcraft_doc::render_coat::MAX_COAT_BINDINGS {
|
||||
return Err(bad(command, "at most 64 runtime clear-coat overrides are supported"));
|
||||
}
|
||||
let mut ordinals = std::collections::BTreeSet::new();
|
||||
@@ -31,28 +31,33 @@ pub(super) fn apply(scene: &mut ProductScene, overrides: &[Override], command: &
|
||||
return Err(bad(command, "clear coats require bounded names and distinct captured body ordinals"));
|
||||
}
|
||||
let coat = ClearCoat::new(input.weight, input.roughness, input.ior).map_err(|e| bad(command, e.to_string()))?;
|
||||
let body = scene
|
||||
.meshes
|
||||
.get_mut(input.body_index)
|
||||
.filter(|m| m.name == input.body_name)
|
||||
.ok_or_else(|| bad(command, "clear-coat body ordinal and exact name must both match render.scene"))?;
|
||||
// A zero-weight override is a true no-op, including legacy appearances.
|
||||
if coat.weight() == 0.0 {
|
||||
continue;
|
||||
}
|
||||
if body.transmission.is_some() || body.faces.iter().any(|f| f.transmission.is_some()) {
|
||||
return Err(bad(command, "clear coat and transmission cannot share a body"));
|
||||
}
|
||||
let surface = |color: [u8; 3], existing: Option<OpaqueSurface>| -> Result<OpaqueSurface> {
|
||||
let [r, g, b] = color.map(srgb8_to_linear);
|
||||
let base =
|
||||
existing.map(Ok).unwrap_or_else(|| OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 0.5, 1.5)).map_err(|e| bad(command, e.to_string()))?;
|
||||
Ok(base.with_clear_coat(coat))
|
||||
};
|
||||
body.surface = Some(surface(body.color, body.surface)?);
|
||||
for face in &mut body.faces {
|
||||
face.surface = Some(surface(face.color, face.surface)?);
|
||||
}
|
||||
apply_one(scene, input.body_index, &input.body_name, coat, command)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn apply_one(scene: &mut ProductScene, body_index: usize, body_name: &str, coat: ClearCoat, command: &str) -> Result<()> {
|
||||
let body = scene
|
||||
.meshes
|
||||
.get_mut(body_index)
|
||||
.filter(|m| m.name == body_name)
|
||||
.ok_or_else(|| bad(command, "clear-coat body ordinal and exact name must both match render.scene"))?;
|
||||
// A zero-weight override is a true no-op, including legacy appearances.
|
||||
if coat.weight() == 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
if body.transmission.is_some() || body.faces.iter().any(|f| f.transmission.is_some()) {
|
||||
return Err(bad(command, "clear coat and transmission cannot share a body"));
|
||||
}
|
||||
let surface = |color: [u8; 3], existing: Option<OpaqueSurface>| -> Result<OpaqueSurface> {
|
||||
let [r, g, b] = color.map(srgb8_to_linear);
|
||||
let base =
|
||||
existing.map(Ok).unwrap_or_else(|| OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 0.5, 1.5)).map_err(|e| bad(command, e.to_string()))?;
|
||||
Ok(base.with_clear_coat(coat))
|
||||
};
|
||||
body.surface = Some(surface(body.color, body.surface)?);
|
||||
for face in &mut body.faces {
|
||||
face.surface = Some(surface(face.color, face.surface)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -85,3 +90,149 @@ mod tests {
|
||||
assert!(apply(&mut original.clone(), &duplicate, "render.start").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stable_tests {
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
use solidcraft_doc::render_coat::{CoatBindings, CoatMaterial, SavedCoat};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn stable_coats_save_reopen_replace_and_undo_offline_for_cpu_and_gpu_without_changing_sources() {
|
||||
for method in ["cpu_raytrace", "gpu_path"] {
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Housing"})).unwrap();
|
||||
s.execute("material.assign", &json!({"bodies":["Housing"],"material":"Steel"})).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Coat","set":{"width":8,"height":8,"job":{"method":method}}})).unwrap();
|
||||
let physical = s.execute("component.properties", &json!({})).unwrap();
|
||||
let model = s.model.state();
|
||||
let before = s.doc.clone();
|
||||
let undo = s.undo.len();
|
||||
let evaluations = s.evaluations;
|
||||
let coat = json!({"weight":0.63,"roughness":0.61,"ior":1.7});
|
||||
s.execute("render.coat.bind", &json!({"name":"Coat","body_index":0,"body_name":"Housing","coat":coat,"expected_revision":s.revision}))
|
||||
.unwrap();
|
||||
assert_eq!(s.undo.len(), undo + 1);
|
||||
assert_eq!(s.evaluations, evaluations);
|
||||
assert!(Arc::ptr_eq(&model, &s.model.state()));
|
||||
assert_eq!(s.doc.features, before.features);
|
||||
assert_eq!(s.doc.materials, before.materials);
|
||||
assert_eq!(physical, s.execute("component.properties", &json!({})).unwrap());
|
||||
let saved = s.doc.clone();
|
||||
let loaded = solidcraft_doc::Document::from_json(&saved.to_json()).unwrap();
|
||||
assert_eq!(loaded.render, saved.render);
|
||||
let original = crate::product_scene::extract(&s).unwrap();
|
||||
let mut scene = original.clone();
|
||||
let faces_capacity = scene.meshes[0].faces.capacity();
|
||||
let cpu = solidcraft_render::job::RaytraceOptions::default();
|
||||
super::super::coat_bindings::apply(
|
||||
&s,
|
||||
&mut scene,
|
||||
&saved.render.setups["Coat"].coats,
|
||||
(method == "cpu_raytrace").then_some(&cpu),
|
||||
"check",
|
||||
)
|
||||
.unwrap();
|
||||
let actual = scene.meshes[0].surface.unwrap().clear_coat().unwrap();
|
||||
assert_eq!((actual.weight(), actual.roughness(), actual.ior()), (0.63, 0.61, 1.7));
|
||||
assert!(Arc::ptr_eq(&original.meshes[0].mesh, &scene.meshes[0].mesh));
|
||||
assert_eq!(original.meshes[0].faces.len(), scene.meshes[0].faces.len());
|
||||
assert_eq!(faces_capacity, scene.meshes[0].faces.capacity());
|
||||
assert_eq!(s.doc, saved, "captured coat never changes the source appearance");
|
||||
for face in &scene.meshes[0].faces {
|
||||
assert_eq!(face.surface.unwrap().clear_coat(), Some(actual));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc, before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc, saved);
|
||||
let replacement = json!({"name":"Coat","body_index":0,"body_name":"Housing","coat":{"weight":0.4,"roughness":0.3,"ior":1.8},"expected_revision":s.revision});
|
||||
assert!(s.execute("render.coat.bind", &replacement).is_err());
|
||||
assert_eq!(s.doc, saved);
|
||||
let mut explicit = replacement;
|
||||
explicit["replace"] = json!(true);
|
||||
s.execute("render.coat.bind", &explicit).unwrap();
|
||||
assert_eq!(s.doc.render.setups["Coat"].coats.iter().next().unwrap().coat.ior, 1.8);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc, saved);
|
||||
let target = saved.render.setups["Coat"].coats.iter().next().unwrap().target.clone();
|
||||
s.execute("render.coat.unbind", &json!({"name":"Coat","target":target,"expected_revision":s.revision})).unwrap();
|
||||
assert!(s.doc.render.setups["Coat"].coats.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc, saved);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stable_coat_source_replacement_hidden_and_glass_guards_never_guess_or_mutate_a_binding() {
|
||||
for method in ["cpu_raytrace", "gpu_path"] {
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap();
|
||||
s.execute(
|
||||
"render.coat.bind",
|
||||
&json!({"name":"Coat","set":{"width":4,"height":4,"job":{"method":method}},
|
||||
"body_index":0,"body_name":"Housing","coat":{"weight":0},"expected_revision":s.revision}),
|
||||
)
|
||||
.unwrap();
|
||||
let saved = s.doc.render.setups["Coat"].coats.clone();
|
||||
let target = saved.iter().next().unwrap().target.clone();
|
||||
let original = crate::product_scene::extract(&s).unwrap();
|
||||
let mut zero = original.clone();
|
||||
super::super::coat_bindings::apply(&s, &mut zero, &saved, None, "check").unwrap();
|
||||
assert_eq!(zero.meshes[0].surface, original.meshes[0].surface);
|
||||
assert!(Arc::ptr_eq(&zero.meshes[0].mesh, &original.meshes[0].mesh));
|
||||
let before = s.doc.clone();
|
||||
assert!(
|
||||
s.execute(
|
||||
"render.optics.bind",
|
||||
&json!({"name":"Coat","body_index":0,"body_name":"Housing","optics":{},"expected_revision":s.revision})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(s.doc, before, "zero weight is authored opaque intent, not permission to silently drop it on Glass");
|
||||
let mut glass = original;
|
||||
glass.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap());
|
||||
assert!(super::super::coat_bindings::apply(&s, &mut glass, &saved, None, "check").unwrap_err().to_string().contains("opaque"));
|
||||
s.execute("browser.visibility", &json!({"items":["Housing"],"visible":false})).unwrap();
|
||||
let mut hidden = crate::product_scene::extract(&s).unwrap();
|
||||
assert!(super::super::coat_bindings::apply(&s, &mut hidden, &saved, None, "check").unwrap_err().to_string().contains("hidden"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("timeline.delete", &json!({"feature":target.feature.to_string()})).unwrap();
|
||||
s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap();
|
||||
let mut replaced = crate::product_scene::extract(&s).unwrap();
|
||||
assert_eq!((replaced.meshes.len(), replaced.meshes[0].name.as_str()), (1, "Housing"));
|
||||
assert!(super::super::coat_bindings::apply(&s, &mut replaced, &saved, None, "check").unwrap_err().to_string().contains("changed"));
|
||||
assert_eq!(s.doc.render.setups["Coat"].coats, saved);
|
||||
// Empty means the original capture path, even when no old target survives.
|
||||
super::super::coat_bindings::apply(&s, &mut replaced, &CoatBindings::default(), None, "check").unwrap();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stable_cpu_coats_refuse_selected_transport_but_leave_authored_values_and_scene_sources_intact() {
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap();
|
||||
let target = super::super::surface_bindings::targets(&s, "check").unwrap().into_keys().next().unwrap();
|
||||
let mut bindings = CoatBindings::default();
|
||||
bindings.set(SavedCoat { target, coat: CoatMaterial::default() }, false).unwrap();
|
||||
let scene = crate::product_scene::extract(&s).unwrap();
|
||||
let options = solidcraft_render::job::RaytraceOptions {
|
||||
reflections: Some(solidcraft_render::job::ReflectionOptions {
|
||||
samples: 1,
|
||||
max_bounces: 1,
|
||||
bodies: vec![solidcraft_render::job::ReflectionBody {
|
||||
body: "Housing".into(),
|
||||
mode: solidcraft_render::job::ReflectionMode::RoughSpecular,
|
||||
}],
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let before = s.doc.clone();
|
||||
let mut captured = scene.clone();
|
||||
let error = super::super::coat_bindings::apply(&s, &mut captured, &bindings, Some(&options), "check").unwrap_err().to_string();
|
||||
assert!(error.contains("selected reflection"));
|
||||
assert_eq!(captured.meshes[0].surface, scene.meshes[0].surface);
|
||||
assert_eq!(bindings.iter().next().unwrap().coat, CoatMaterial::default());
|
||||
assert_eq!(s.doc, before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Stable opaque clear-coat bindings shared by CPU and GPU scene capture.
|
||||
//! Lowering changes only already-sized captured surface fields, never render options.
|
||||
use crate::{Result, Session, params::bad};
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::{
|
||||
render_coat::{CoatBindings, SavedCoat},
|
||||
render_settings::RenderJob,
|
||||
render_surface::RenderBodyTarget,
|
||||
};
|
||||
use solidcraft_render::{ProductScene, job::RaytraceOptions};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
/// No bindings is the original zero-allocation capture path. Even zero-weight
|
||||
/// authored bindings require a current opaque target; they cannot mask Glass.
|
||||
pub(super) fn apply(s: &Session, scene: &mut ProductScene, bindings: &CoatBindings, cpu: Option<&RaytraceOptions>, command: &str) -> Result<()> {
|
||||
if bindings.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
bindings.validate().map_err(|e| bad(command, e.to_string()))?;
|
||||
let identities = super::surface_bindings::targets(s, command)?;
|
||||
// The shared resolver indexes authored source identity. This additional
|
||||
// captured-name index is bounded by the 64 requested targets, not scene size.
|
||||
let mut visible = BTreeMap::new();
|
||||
for binding in bindings.iter() {
|
||||
let name = identities.get(&binding.target).ok_or_else(|| bad(command, "saved clear-coat target changed; explicit rebinding required"))?;
|
||||
if visible.insert(name.as_str(), None).is_some() {
|
||||
return Err(bad(command, "ambiguous stable clear-coat world target"));
|
||||
}
|
||||
}
|
||||
for (index, body) in scene.meshes.iter().enumerate() {
|
||||
if let Some(slot) = visible.get_mut(body.name.as_str())
|
||||
&& slot.replace(index).is_some()
|
||||
{
|
||||
return Err(bad(command, "ambiguous captured clear-coat target"));
|
||||
}
|
||||
}
|
||||
let mut resolved = Vec::new();
|
||||
resolved.try_reserve_exact(bindings.len()).map_err(|_| bad(command, "could not reserve clear-coat capture metadata"))?;
|
||||
if resolved.capacity() != bindings.len() {
|
||||
return Err(bad(command, "clear-coat capture capacity exceeds admission"));
|
||||
}
|
||||
for binding in bindings.iter() {
|
||||
let name = identities.get(&binding.target).ok_or_else(|| bad(command, "saved clear-coat target changed; explicit rebinding required"))?;
|
||||
let index = visible.get(name.as_str()).copied().flatten().ok_or_else(|| bad(command, "saved clear-coat target is hidden or absent"))?;
|
||||
let body = scene.meshes.get(index).ok_or_else(|| bad(command, "clear-coat target disappeared"))?;
|
||||
if body.transmission.is_some() || body.faces.iter().any(|face| face.transmission.is_some()) {
|
||||
return Err(bad(command, "saved clear coat requires an opaque target, including zero-weight authored coats"));
|
||||
}
|
||||
if cpu.is_some_and(|options| {
|
||||
options.dielectrics.iter().any(|entry| entry.body_index == index)
|
||||
|| options.reflections.as_ref().is_some_and(|overrides| overrides.bodies.iter().any(|entry| entry.body == *name))
|
||||
|| options.anisotropic_faces.iter().flatten().any(|entry| entry.body_index == index)
|
||||
}) {
|
||||
return Err(bad(command, "CPU clear-coat targets cannot share Glass, selected reflection or anisotropy overrides"));
|
||||
}
|
||||
resolved.push((index, name.as_str(), binding.coat.to_runtime().map_err(|e| bad(command, e.to_string()))?));
|
||||
}
|
||||
drop(visible);
|
||||
for (index, name, coat) in resolved {
|
||||
super::clear_coat::apply_one(scene, index, name, coat, command)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let command = "render.coat.bind";
|
||||
let input: crate::schema::render::CoatBindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
|
||||
let coat = input.coat.material();
|
||||
coat.validate().map_err(|e| bad(command, e.to_string()))?;
|
||||
if input.expected_revision != s.revision {
|
||||
return Err(bad(command, "clear-coat binding review is stale"));
|
||||
}
|
||||
let mut setup = super::patched_settings(s, &input.name, &input.set, command)?;
|
||||
if s.doc.render.setups.get(&input.name).is_some_and(|old| old.coats != setup.coats) {
|
||||
return Err(bad(command, "setup patch cannot replace saved clear coats; use explicit bind/unbind"));
|
||||
}
|
||||
if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) {
|
||||
return Err(bad(command, "saved clear coats require an explicit CPU or GPU raytrace setup"));
|
||||
}
|
||||
let mut scene = crate::product_scene::extract(s)?;
|
||||
let name = &scene
|
||||
.meshes
|
||||
.get(input.body_index)
|
||||
.filter(|body| body.name == input.body_name)
|
||||
.ok_or_else(|| bad(command, "clear-coat target ordinal and exact name do not match"))?
|
||||
.name;
|
||||
let identities = super::surface_bindings::targets(s, command)?;
|
||||
let mut candidates = identities.iter().filter(|(_, world)| *world == name);
|
||||
let target =
|
||||
candidates.next().map(|(target, _)| target.clone()).ok_or_else(|| bad(command, "clear-coat target has no stable source identity"))?;
|
||||
if candidates.next().is_some() {
|
||||
return Err(bad(command, "ambiguous clear-coat target identity"));
|
||||
}
|
||||
setup.coats.set(SavedCoat { target, coat }, input.replace).map_err(|e| bad(command, e.to_string()))?;
|
||||
setup.validate().map_err(|e| bad(command, e.to_string()))?;
|
||||
// Verify the actual opaque source even for inactive authored values. Runtime
|
||||
// options are not invented while saving an offline stable numerical setup.
|
||||
apply(s, &mut scene, &setup.coats, None, command)?;
|
||||
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 settings != *s.doc.render {
|
||||
s.doc_mut().render = Arc::new(settings);
|
||||
}
|
||||
Ok(json!({"name":input.name,"setup":setup,"geometry_and_engineering_unchanged":true}))
|
||||
}
|
||||
|
||||
pub(super) fn unbind(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let command = "render.coat.unbind";
|
||||
let input: crate::schema::render::CoatUnbindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
|
||||
let target: RenderBodyTarget = serde_json::from_value(input.target).map_err(|e| bad(command, e.to_string()))?;
|
||||
target.validate().map_err(|e| bad(command, e.to_string()))?;
|
||||
if input.expected_revision != s.revision {
|
||||
return Err(bad(command, "clear-coat removal review is stale"));
|
||||
}
|
||||
let mut settings = (*s.doc.render).clone();
|
||||
let setup = settings.setups.get_mut(&input.name).ok_or_else(|| bad(command, "unknown clear-coat setup"))?;
|
||||
let removed = setup.coats.remove(&target);
|
||||
settings.validate().map_err(|e| bad(command, e.to_string()))?;
|
||||
if settings != *s.doc.render {
|
||||
s.doc_mut().render = Arc::new(settings);
|
||||
}
|
||||
Ok(json!({"name":input.name,"removed":removed}))
|
||||
}
|
||||
Loaded 100 of 535 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user