From 88b5da22bc5e962c33d0d92a803d7dda45a98ad1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:46:29 -0800 Subject: [PATCH] DXF: Use Artboards applies live effects once for all the drawings DXF export with Use Artboards baked the whole document's live effects and placed symbol art again for every artboard. export_drawings now checks the options and every region, bakes once, and writes each drawing from the same baked document. export calls it with one drawing, and the encoder makes one call for all the chosen artboards. Each drawing's bytes, linked images, warnings and setting notes are the same as before; the tests compare them with drawings baked one at a time. --- crates/cad/src/lib.rs | 39 ++++- crates/cad/src/tests.rs | 198 ++++++++++++++++++++++ crates/engine/src/cmd/fileio/dxf.rs | 5 +- crates/engine/src/cmd/fileio/tests_dxf.rs | 18 ++ docs/target-app-parity.md | 1 + 5 files changed, 253 insertions(+), 8 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option, +) -> Result, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec, Vec<(String, Vec)>, Vec, Vec); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option, f64)], cpu: bool| { + let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..193fbbfb56 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2055,6 +2055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE; a closed four-cubic ellipse, or a circle scaled out of proportion, exports as a native ELLIPSE in R13 and later (an ellipse whose minor-to-major ratio is below 1e-6 is still written as a polyline or spline), and R12 keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, placed images and fill hatches left out), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. + - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`).