Keep portable links for unchanged library functions on save

This commit is contained in:
chasse20 committed 2026-11-21 10:57:43 -05:00
1 parent f9d37a0153
commit dc5b37c68f
5 files changed
+116 -2

No files matched your search

+26 -1
View File
@@ -214,15 +214,40 @@ fn package_for_save(session: &Session, path: Option<&str>) -> Package {
}
}
let mut packages = std::collections::BTreeMap::new();
for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) {
if !instance.package.is_empty() {
instance.package = crate::document_path::relative(path, &instance.package);
let source = std::mem::take(&mut instance.package);
let reference = packages.entry(source).or_insert_with_key(|source| package_reference(&session.pkg, path, source));
instance.package.clone_from(reference);
}
}
}
package
}
fn package_reference(_package: &Package, destination: &str, source: &str) -> String {
#[cfg(not(target_arch = "wasm32"))]
{
use materialcraft_formats::sbs::library;
use std::path::Path;
// A function library with external calls or resources can rely on other local edits.
if Path::new(source).is_absolute()
&& let Some(dependency) = _package.dependencies.get(source)
&& dependency.resources.is_empty()
&& !dependency.graphs.is_empty()
&& dependency.graphs.iter().all(|graph| graph.function.is_some() && graph.instances().all(|instance| instance.package.is_empty()))
&& !library::contains_file(Path::new(destination))
&& let Ok(root) = library::root().canonicalize()
&& let Some(uri) = library::bundled_package_uri(&root, Path::new(source))
{
return uri;
}
}
crate::document_path::relative(destination, source)
}
pub fn save_files_at(session: &Session, path: &str) -> Result<materialcraft_formats::project::ProjectFiles> {
session.package(session.document_id)?;
let archive = is_mcraft(path);
+36
View File
@@ -170,6 +170,42 @@ fn native_sbs_is_the_default_save_format() {
assert_eq!(run(&mut session, "file.save", json!({}))["path"], json!(saved));
}
#[test]
fn saving_a_library_graph_opened_from_disk_keeps_its_portable_function_links() {
let directory = TempDir::new("library-function-export");
let name = "waveform_01_v2.sbs";
let library = materialcraft_engine::formats::sbs::library::root();
let mut session = sample_session();
for (index, source) in [library.join(name).to_str().unwrap().to_string(), format!("sbs://{name}")].into_iter().enumerate() {
run(&mut session, "file.open", json!({ "path": source }));
let saved = directory.file(&format!("caller-{index}.sbs"));
run(&mut session, "file.saveAs", json!({ "path": saved }));
let xml = std::fs::read_to_string(&saved).unwrap();
for helper in ["functions.sbs", "functions_hash.sbs"] {
assert!(xml.contains(&format!(r#"<filename v="sbs://{helper}""#)), "{helper}");
}
let mut reopened = sample_session();
run(&mut reopened, "file.open", json!({ "path": saved }));
assert!(reopened.pkg.dependencies.contains_key("sbs://functions_hash.sbs"));
}
}
#[test]
fn a_changed_or_detached_function_file_keeps_its_disk_identity() {
use materialcraft_engine::formats::sbs::library;
use std::path::Path;
let directory = TempDir::new("local-function-source");
let name = "functions_hash.sbs";
let path = directory.file(name);
let mut changed = library::read(&format!("sbs://{name}")).unwrap();
changed[0] = b' ';
std::fs::write(&path, changed).unwrap();
assert!(library::bundled_package_uri(&directory.0.canonicalize().unwrap(), Path::new(&path)).is_none());
std::fs::copy(library::root().join(name), &path).unwrap();
assert!(library::bundled_package_uri(&library::root().canonicalize().unwrap(), Path::new(&path)).is_none());
}
/// Saving an SBS file another program wrote must not overwrite it: MaterialCraft can't write back what it couldn't read
#[test]
fn saving_an_sbs_file_from_another_program_needs_a_new_name() {
+31
View File
@@ -84,6 +84,37 @@ pub fn contains_file(path: &std::path::Path) -> bool {
path.parent().and_then(|parent| parent.canonicalize().ok()).is_some_and(|parent| parent.starts_with(root))
}
/// Return a portable package link for an unchanged bundled file beneath the canonical library root.
#[cfg(not(target_arch = "wasm32"))]
pub fn bundled_package_uri(canonical_root: &std::path::Path, path: &std::path::Path) -> Option<String> {
use std::io::Read;
if !path.is_absolute() {
return None;
}
let file = path.canonicalize().ok()?;
let relative = file.strip_prefix(canonical_root).ok()?.to_str()?.replace('\\', "/");
let uri = format!("sbs://{relative}");
relative_path(&uri).ok()?;
BUNDLED.binary_search(&uri.as_str()).ok()?;
// A locally edited package at a shipped path must keep pointing to those edits.
let mut file = std::fs::File::open(file).ok()?;
let expected = read_embedded(&relative).ok()?;
if file.metadata().ok()?.len() != expected.len() as u64 {
return None;
}
let mut buffer = [0; 8192];
for chunk in expected.chunks(buffer.len()) {
let actual = buffer.get_mut(..chunk.len())?;
file.read_exact(actual).ok()?;
if actual != chunk {
return None;
}
}
(file.read(&mut buffer).ok()? == 0).then_some(uri)
}
/// Read a validated library alias from the configured directory or the embedded fallback.
pub fn read(uri: &str) -> Result<Vec<u8>, String> {
let relative = relative_path(uri)?;
+22
View File
@@ -1246,6 +1246,28 @@ The six-setting authored-shape and disc controls from the earlier branch compari
Splatter Color and Weave 2 have measured parity across the reported settings. Pattern Weave 2 still differs on 351 whole pixels. Grayscale Splatter differs on the 16 × 64 default fed by the 32 × 16 field at seed 811492. Its input bridge matched all 1,024 U16 words. The following pattern draw differed on all 1,024 words, maximum 9,366. Rebinding the measured bridge levels as a 16 × 64 original-field input gave 1,024/1,024 matching F32 output pixels, maximum zero.
### Portable function links when opening a library graph from disk
Open the physical `waveform_01_v2.sbs` beneath the configured package library in MaterialCraft. Save to a directory outside that library with `file.saveAs`. Close and reopen the new file directly in both applications. Repeat the [seven-size and fixed-field waveform comparisons](#waveform-v2-with-library-and-file-based-hash-functions). Include a second save and reopen.
Before the fix, opening the graph through its physical path wrote relative links to the two local function packages. Opening through the library alias preserved both portable links. At the 16² default and the changed 64 × 32 and 128 × 32 F32 controls, the two saved files produced the following results.
| How MaterialCraft opened the original | Saved F32 pixels exact / compared | Maximum error |
|---|---:|---:|
| Physical path | 4,712/6,400 | 1 |
| Library alias | 6,400/6,400 | 0 |
When a graph is saved outside the configured library, unchanged, self-contained function packages from that library use portable URIs. The positive control uses the package files bundled with the tested build. The second library contains the earlier general math file from revision `97f2e06` and the unchanged hash file. The earlier math file differs byte-for-byte from the bundled version and keeps its relative link.
| Source directory used to open the waveform | Saved general math link | Saved hash link | First save, 20 renders | Second save, 10 renders | Fixed-field reopens, 13 renders |
|---|---|---|---:|---:|---:|
| Bundled files | Library URI | Library URI | 109,056/109,056 | 44,288/44,288 | 26,624/26,624 |
| Earlier file for general math | Relative file path | Library URI | 109,056/109,056 | 44,288/44,288 | 26,624/26,624 |
All **179,968/179,968** pixels on each route matched across applications and repeated the original render in each application. The U8, U16, F16 and F32 maxima were zero. Saving within the same configured library to a child directory wrote relative links resolving to both original functions. A detached older hash file still has the [separate measured handoff difference](#waveform-v2-with-library-and-file-based-hash-functions). Waveform v2 remains in progress for that case.
The normal open/save/reopen regression failed before the change and passed after it. Separate controls retain file identity for a same-length edit and a byte-identical copy outside the library. The release engine and format suites passed, along with the hostile-command check, formatting, strict workspace Clippy, dependency layering and WebAssembly.
## 2026-11-20 root comparisons
### Hue, saturation, lightness and Replace Color
+1 -1
View File
@@ -652,7 +652,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug
| [vector_morph.sbs/vector_morph](../assets/sbs/vector_morph.sbs) | 2 | No | [Parity · 171,264/171,264 pixels in 18 renders](parity-fixes.md#quad-swirl-trapezoid-and-vector-morph-comparisons) |
| [vector_morph.sbs/vector_morph_grayscale](../assets/sbs/vector_morph.sbs) | 2 | No | [Parity · 171,264/171,264 pixels in 18 renders](parity-fixes.md#quad-swirl-trapezoid-and-vector-morph-comparisons) |
| [vertical_noise.sbs/vertical_noise](../assets/sbs/vertical_noise.sbs) | 0 | Yes | [In progress · 142,088/142,592 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) |
| [waveform_01_v2.sbs/waveform_01_v2](../assets/sbs/waveform_01_v2.sbs) | 0 | No | [In progress · 313,088/313,088 originals, 179,968/179,968 library reopens](parity-fixes.md#waveform-v2-with-library-and-file-based-hash-functions) · [Older relative hash dependency, 167,194/179,968](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [waveform_01_v2.sbs/waveform_01_v2](../assets/sbs/waveform_01_v2.sbs) | 0 | No | [In progress · 313,088/313,088 originals, 179,968/179,968 reopens from a library path](parity-fixes.md#portable-function-links-when-opening-a-library-graph-from-disk) · [Function-link controls](parity-fixes.md#waveform-v2-with-library-and-file-based-hash-functions) · [Older relative hash dependency, 167,194/179,968](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [waveform_1.sbs/waveform_1](../assets/sbs/waveform_1.sbs) | 0 | Yes | [Parity · 313,088/313,088 pixels across 54 distinct settings](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [weave_1.sbs/weave_1](../assets/sbs/weave_1.sbs) | 0 | Yes | [Parity · 332,032/332,032 pixels across 39 distinct settings](parity-fixes.md#reopened-perlin-scratches-shape-and-weave-generators) · [Earlier measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) |
| [weave_2.sbs/weave_2](../assets/sbs/weave_2.sbs) | 0 | Yes | [Parity · 3,139,840/3,139,840 pixels across 95 distinct settings](parity-fixes.md#saved-splatter-and-weave-graphs-across-independent-fields) · [Earlier measurements](parity-fixes.md#fixed-and-input-driven-rotation-bounds-for-oblique-stamps) |