Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions assets/locales/pending/open-keeps-saved-model.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"en": {
"file_load.provisional_waits": "Rebuilding {name}… Showing the saved model. What you do meanwhile runs once this version of SolidCraft has rebuilt it.",
"file_load.waits_for_rebuild": "Waiting for {name} to finish rebuilding: this runs then."
},
"ar": {
"file_load.provisional_waits": "جارٍ إعادة بناء {name}… يُعرض النموذج المحفوظ. ما تفعله في هذه الأثناء يُنفَّذ بعد أن يُكمل هذا الإصدار من SolidCraft إعادة بنائه.",
"file_load.waits_for_rebuild": "بانتظار انتهاء إعادة بناء {name}: يُنفَّذ هذا عندها."
},
"he": {
"file_load.provisional_waits": "בונה מחדש את {name}… המודל השמור מוצג. מה שתעשה בינתיים יתבצע כשגרסה זו של SolidCraft תסיים לבנות אותו מחדש.",
"file_load.waits_for_rebuild": "ממתין לסיום הבנייה מחדש של {name}: הפעולה תתבצע אז."
},
"ja": {
"file_load.provisional_waits": "{name} を再構築しています… 保存されたモデルを表示しています。その間の操作は、このバージョンの SolidCraft が再構築を終えてから実行されます。",
"file_load.waits_for_rebuild": "{name} の再構築が終わるのを待っています。終わり次第実行します。"
},
"vi": {
"file_load.provisional_waits": "Đang dựng lại {name}… Đang hiển thị mô hình đã lưu. Những gì bạn làm trong lúc này sẽ chạy khi phiên bản SolidCraft này dựng lại xong.",
"file_load.waits_for_rebuild": "Đang chờ {name} dựng lại xong: thao tác này sẽ chạy khi đó."
},
"zh": {
"file_load.provisional_waits": "正在重建 {name}… 正在显示已保存的模型。在此期间的操作将在此版本的 SolidCraft 完成重建后执行。",
"file_load.waits_for_rebuild": "正在等待 {name} 完成重建:完成后执行此操作。"
}
}
59 changes: 59 additions & 0 deletions crates/engine/src/cmd/edit_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3626,6 +3626,65 @@ fn remove_history_saves_and_reopens_the_same_body() {
assert!(reopened.model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()));
}

/// Direct modeling by removing the history again and again: each time the design is saved and
/// opened again with nothing kept but its file (no model cache), every body comes back as the
/// session had it, exactly (vertices and faces within tolerance), and no feature fails. A
/// removed-history body is stored data: replaying it gives the same body every time.
#[test]
fn remove_history_again_and_again_reopens_the_same_body_every_time() {
fn reopened(s: &Session) -> Session {
let bytes = solidcraft_io::write_design_container(&s.doc).unwrap();
let mut reopened = Session::new(solidcraft_io::read_design(&bytes).unwrap());
reopened.refresh();
reopened
}
fn same_as(s: &Session, reopened: &Session, when: &str) {
let (a, b) = (s.model.state(), reopened.model.state());
assert_eq!(a.bodies.len(), b.bodies.len(), "{when}");
for body in &a.bodies {
let differs = crate::cmd::open_saved_model::difference(body, b.body(&body.name));
assert!(differs.is_none(), "{when}: {} {differs:?}", body.name);
}
let failing: Vec<_> = reopened.model.results.iter().filter(|r| r.error.is_some()).map(|r| (r.name.clone(), r.error.clone())).collect();
assert!(failing.is_empty(), "{when}: {failing:?}");
}
let mut s = Session::default();
let cycles: [&[(&str, Value)]; 4] = [
&[
("solid.box", json!({"body_name": "Block", "length": 60, "width": 40, "height": 20})),
("solid.cylinder", json!({"radius": 5, "height": 40, "base": [15, 20, -10], "operation": "cut"})),
("solid.fillet", json!({"edges": [[60, 0, 10]], "radius": 5})),
],
&[
("solid.hole", json!({"position": [45, 20, 20], "diameter": 6, "depth": 10})),
("solid.press_pull", json!({"face": [30, 30, 20], "distance": 3})),
("solid.box", json!({"corner": [30, 0, 23], "length": 10, "width": 10, "height": 8, "operation": "join"})),
("solid.fillet", json!({"edges": [[35, 10, 31]], "radius": 1})),
],
&[
("solid.offset_face", json!({"faces": [[15, 25, 10]], "distance": -1})),
("solid.transform_face", json!({"face": [0, 20, 10], "translate": [-4, 0, 0]})),
],
&[("solid.chamfer", json!({"edges": [[30, 40, 0]], "distance": 2})), ("solid.shell", json!({"faces": [[30, 20, 0]], "thickness": 2}))],
];
for (k, cycle) in cycles.iter().enumerate() {
for (command, params) in cycle.iter() {
run(&mut s, command, params.clone());
}
let before = body_shape(&s, "Block");
let out = run(&mut s, "body.remove_history", json!({"body": "Block"}));
assert_eq!(out["broken"], json!([]), "cycle {k}: {out}");
same_body_shape(before, body_shape(&s, "Block"));
let once = reopened(&s);
same_as(&s, &once, &format!("cycle {k}, reopened"));
// Opened again from what the reopened design saves: still the same.
same_as(&s, &reopened(&once), &format!("cycle {k}, reopened twice"));
}
// Edits after the last removal replay too.
run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 6, "base": [50, 30, 23], "operation": "join"}));
same_as(&s, &reopened(&s), "after the last removal");
}

/// A design saved in an older format still opens, and Remove History works on it.
#[test]
fn remove_history_on_an_older_format_design() {
Expand Down
117 changes: 114 additions & 3 deletions crates/engine/src/cmd/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2495,9 +2495,8 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
provisional.disk = disk;
show(provisional);
}
drop(file.stale);
let opened = Session::opened_validating(doc, file.model.as_ref(), s.validation()).located_with(Some(path), checked.chain.clone());
opened_design(s, opened, path, read_only, disk, checked, linked)
opened_design(s, opened, path, read_only, disk, checked, linked, file.stale.as_ref())
}

/// `doc.open` with a drawing file (`.scdwg`): the design it draws opens as `doc.open` opens it,
Expand Down Expand Up @@ -2625,6 +2624,7 @@ struct OpenChecks {

/// `doc.open` of a design: `opened`, the design read from `path` and evaluated, takes `s`'s
/// place, and the reply says what it is.
#[allow(clippy::too_many_arguments)]
fn opened_design(
s: &mut Session,
opened: Session,
Expand All @@ -2633,6 +2633,7 @@ fn opened_design(
disk: Option<solidcraft_io::design_lock::FileStamp>,
checked: OpenChecks,
linked: Vec<String>,
saved: Option<&solidcraft_doc::SavedModel>,
) -> Result<Value> {
s.replace_design(opened);
s.disk = disk;
Expand All @@ -2648,6 +2649,8 @@ fn opened_design(
s.doc_mut().print_faces.clear();
s.mark_saved();
}
// A saved model another build computed: a body the rebuild changed is kept as it was saved.
let kept = saved.map(|saved| super::open_saved_model::keep_saved_model(s, saved)).unwrap_or_default();
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
let now = solidcraft_io::design_lock::now_secs();
// A lock left behind by an app that is gone is cleared before the question of who has the
Expand Down Expand Up @@ -2676,7 +2679,7 @@ fn opened_design(
warnings: opened_warnings(
checked.link_warning.as_ref(),
s.doc.newer_file.as_ref().map(|file| file.warnings()),
s.doc.load_warnings.iter().cloned().chain(linked).collect(),
s.doc.load_warnings.iter().cloned().chain(linked).chain(kept).collect(),
stale_lock,
),
link_warning: checked.link_warning,
Expand Down Expand Up @@ -7082,6 +7085,114 @@ Shape { geometry Box { size 2 2 2 } }",
assert_eq!(provisional.world_state().unwrap().bodies.len(), shown);
}

/// The model a design file keeps, computed by another build, as `doc.open` reads it: the
/// bytes of `doc` saved with `saved` as its model cache, stamped as another build's.
fn with_stale_model(dir: &std::path::Path, name: &str, doc: &Document, saved: &solidcraft_doc::SavedModel) -> std::path::PathBuf {
use std::io::{Read as _, Write as _};
let bytes = solidcraft_io::write_design_container_with_cache(doc, solidcraft_io::DesignCompression::Fast, None, Some(saved)).unwrap();
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut out = std::io::Cursor::new(Vec::new());
let mut zip = zip::ZipWriter::new(&mut out);
for i in 0..archive.len() {
let mut entry = archive.by_index(i).unwrap();
let entry_name = entry.name().unwrap().to_string();
let mut data = Vec::new();
entry.read_to_end(&mut data).unwrap();
if entry_name == "cache/model.json" {
let mut manifest: Value = serde_json::from_slice(&data).unwrap();
manifest["evaluation"] = json!(format!("{}/x86_64-windows", "0".repeat(64)));
data = serde_json::to_vec(&manifest).unwrap();
}
zip.start_file(entry_name, zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated)).unwrap();
zip.write_all(&data).unwrap();
}
zip.finish().unwrap();
let path = dir.join(name);
std::fs::write(&path, out.into_inner()).unwrap();
path
}

fn volumes(s: &Session) -> Vec<(String, f64)> {
s.model.state().bodies.iter().map(|b| (b.name.clone(), solidcraft_kernel::measure(&b.body).unwrap().volume)).collect()
}

/// A design opened from a model another build saved, whose rebuild here gives a body another
/// shape, keeps the body as it was saved (the model the user saw): a Remove feature and a base
/// feature holding the saved B-rep, one undo step that gives the rebuilt body back, an unsaved
/// design, and a warning naming the body and what differed. A rebuild that matches changes
/// nothing.
#[test]
fn a_rebuild_that_differs_from_the_saved_model_keeps_the_saved_model() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::default();
s.execute("solid.box", &json!({"body_name": "Block", "length": 10, "width": 20, "height": 30})).unwrap();
s.execute("solid.fillet", &json!({"edges": [[10, 10, 30]], "radius": 2})).unwrap();
let rebuilt = volumes(&s);
// The same timeline, built as the other build built it: 40 tall.
let mut other = Session::default();
other.execute("solid.box", &json!({"body_name": "Block", "length": 10, "width": 20, "height": 40})).unwrap();
other.execute("solid.fillet", &json!({"edges": [[10, 10, 40]], "radius": 2})).unwrap();
let as_saved = volumes(&other);
assert!((as_saved[0].1 - rebuilt[0].1).abs() > 1.0);

// The rebuild matches the saved model: the design opens as it is, nothing to undo.
let same = with_stale_model(dir.path(), "same.sc", &s.doc, &s.model.saved(&s.doc).unwrap());
let mut opened = Session::default();
let reply = opened.execute("doc.open", &json!({"path": same})).unwrap();
assert_eq!(opened.doc.features.len(), 2, "{reply}");
assert!(opened.undo.is_empty() && !opened.is_dirty());
assert!(reply.get("warnings").is_none(), "{reply}");

// It differs: the saved model wins.
let differs = with_stale_model(dir.path(), "differs.sc", &s.doc, &other.model.saved(&other.doc).unwrap());
let mut opened = Session::default();
let reply = opened.execute("doc.open", &json!({"path": differs})).unwrap();
let names: Vec<&str> = opened.doc.features.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["Box1", "Fillet1", "Remove Block", "Block Saved Model"], "{reply}");
assert!(opened.model.results.iter().all(|r| r.error.is_none()));
let kept = volumes(&opened);
assert_eq!(kept.len(), 1);
assert!((kept[0].1 - as_saved[0].1).abs() < 1e-6, "{kept:?} {as_saved:?}");
let saved_state = other.model.state();
assert!(crate::cmd::open_saved_model::difference(saved_state.body("Block").unwrap(), opened.model.state().body("Block")).is_none());
let warning = reply["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" ");
assert!(warning.contains("Block") && warning.contains("Undo") && warning.contains("Block Saved Model"), "{warning}");
assert!(warning.contains("volume"), "says what differed: {warning}");
assert!(opened.is_dirty(), "keeping the saved model is a change to save");
assert_eq!(opened.undo.len(), 1, "one undo step");
// Editable at once, and Undo gives the rebuilt body.
opened.execute("edit.undo", &json!({})).unwrap();
assert_eq!(opened.doc.features.len(), 2);
assert!((volumes(&opened)[0].1 - rebuilt[0].1).abs() < 1e-6);
opened.execute("edit.redo", &json!({})).unwrap();
assert!((volumes(&opened)[0].1 - as_saved[0].1).abs() < 1e-6);

// Saved and opened again (by this build), the kept body stays as it was saved.
let again = dir.path().join("again.sc");
opened.execute("file.save_as", &json!({"path": again})).unwrap();
let mut reopened = Session::default();
reopened.execute("doc.open", &json!({"path": again})).unwrap();
reopened.model = solidcraft_doc::Model::default();
reopened.refresh();
assert!((volumes(&reopened)[0].1 - as_saved[0].1).abs() < 1e-6);

// Hostile: a saved model with a body the timeline no longer builds at all, and one the
// design never had: each comes back as it was saved, nothing panics.
let mut extra = Session::default();
extra.execute("solid.box", &json!({"body_name": "Block", "length": 10, "width": 20, "height": 30})).unwrap();
extra.execute("solid.fillet", &json!({"edges": [[10, 10, 30]], "radius": 2})).unwrap();
extra
.execute("solid.box", &json!({"body_name": "Ghost", "corner": [50, 0, 0], "length": 5, "width": 5, "height": 5, "operation": "new_body"}))
.unwrap();
let hostile = with_stale_model(dir.path(), "hostile.sc", &s.doc, &extra.model.saved(&extra.doc).unwrap());
let mut opened = Session::default();
let reply = opened.execute("doc.open", &json!({"path": hostile})).unwrap();
let names: Vec<&str> = opened.doc.features.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["Box1", "Fillet1", "Ghost Saved Model"], "Block matches; Ghost is brought back: {reply}");
assert!(reply["warnings"].to_string().contains("Ghost"), "{reply}");
assert_eq!(opened.model.state().bodies.len(), 2);
}

#[test]
fn save_uses_only_warm_meshes_and_open_preview_does_not_replace_evaluation() {
let mut s = Session::default();
Expand Down
8 changes: 6 additions & 2 deletions crates/engine/src/cmd/file_open_steps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ pub struct OpenSteps {
/// The design as a model cache another build computed has it, to show while it is
/// evaluated here ([`Self::take_provisional`]).
provisional: Option<Session>,
/// That cache, which the design keeps where its rebuild here differs from it
/// (`open_saved_model`).
stale: Option<solidcraft_doc::SavedModel>,
}

impl OpenSteps {
Expand Down Expand Up @@ -81,7 +84,7 @@ impl OpenSteps {
provisional.disk = disk;
provisional
});
drop(file.stale);
let stale = file.stale.filter(|_| !file.signed);
let linked_bodies = !std::mem::take(&mut doc.linked_bodies_left_out);
// What `Session::opened` does before it evaluates.
solidcraft_io::vfs::install_checks();
Expand All @@ -106,6 +109,7 @@ impl OpenSteps {
linked,
linked_bodies,
provisional,
stale,
};
Ok(Some(steps))
}
Expand Down Expand Up @@ -176,7 +180,7 @@ impl OpenSteps {
}
let opened = Session { linked_bodies: self.linked_bodies, ..Session::with_model(self.doc, self.visibility, self.model) }
.located_with(Some(&self.path), self.checked.chain.clone());
opened_design(s, opened, &self.path, self.read_only, self.disk, self.checked, self.linked)
opened_design(s, opened, &self.path, self.read_only, self.disk, self.checked, self.linked, self.stale.as_ref())
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ pub(crate) mod motion;
mod motion_simulate;
mod named_selection;
mod notes;
mod open_saved_model;
mod parts;
mod plugin;
#[cfg(test)]
Expand Down
Loading
Loading