Merge pull request #8206 from dotCooCoo/feat/packaging-fold-preview

Packaging Tools: Fold Preview folds the blank in 3D with the printed art on its panels
This commit is contained in:
BFlat
2026-11-18 10:30:50 +07:00
committed by GitHub
51 changed files with 3423 additions and 31 deletions
+1
View File
@@ -138,6 +138,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
+2
View File
@@ -821,6 +821,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
+1
View File
@@ -17,6 +17,7 @@ mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{fold_source, print_hidden};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
@@ -6,8 +6,10 @@
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod check;
mod fold;
mod roles;
pub use fold::{fold_source, print_hidden};
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
@@ -15,6 +17,7 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = roles::specs();
v.extend(check::specs());
v.extend(fold::specs());
v
}
+63 -22
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
@@ -14,7 +14,7 @@ use crate::{Result, Session};
const CHECK: &str = "addon.packaging.check";
/// How far apart the ends of two lines may be and still be joined, in points.
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind {
}
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = match length_given(p, "tolerance", CHECK)? {
None => TOLERANCE.1,
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
};
/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or
/// `document`), the lines, and the ids of those on a non-printing layer.
pub(super) struct Lines {
pub scope: &'static str,
pub lines: Vec<FoldLine>,
pub non_printing: Vec<u64>,
}
/// The tolerance `p` gives for `cmd`, or the default.
pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> {
match length_given(p, "tolerance", cmd)? {
None => Ok(TOLERANCE.1),
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t),
Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
}
}
/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while
/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines
/// are left out in every scope, members of a selected group included.
pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, CHECK)?;
let roots = checked_ids_or_selection(s, p, cmd)?;
let d = &s.doc()?.doc;
// Hidden lines are left out in every scope, members of a selected group included.
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
let (scope, targets) = match (given, roots.is_empty()) {
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
(false, true) => ("document", shown_targets(d)),
};
Ok(match (given, roots.is_empty()) {
(true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)),
(false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)),
(false, true) => document_lines(d),
})
}
/// Every shown fold line of `d`.
pub(super) fn document_lines(d: &Document) -> Lines {
lines_of(d, "document", shown_targets(d))
}
fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
let table = RoleTable::of(d);
let mut lines = vec![];
let mut non_printing = vec![];
@@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
}
let (found, mut issues) = blanks(&lines, tolerance);
if !non_printing.is_empty() {
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
Lines { scope, lines, non_printing }
}
/// The blanks `lines` make and their issues, the non-printing one last.
pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) {
let (found, mut issues) = blanks(&lines.lines, tolerance);
if !lines.non_printing.is_empty() {
issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None });
}
let ok = !issues.iter().any(|i| i.code.is_error());
let rows: Vec<Value> = issues
(found, issues)
}
/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with.
pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> {
issues
.iter()
.map(|i| {
let mut row = json!({
@@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
}
row
})
.collect();
.collect()
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = tolerance(p, CHECK)?;
let lines = lines(s, p, CHECK)?;
let scope = lines.scope;
let (found, issues) = found(&lines, tolerance);
let d = &s.doc()?.doc;
let ok = !issues.iter().any(|i| i.code.is_error());
let rows = issue_rows(&issues, scope);
if select {
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
ids.sort_unstable_by_key(|id| id.0);
@@ -0,0 +1,110 @@
//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by
//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the
//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]).
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_three_d::fold::{Blank, Issue, fold, pick};
use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or};
use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance};
use super::roles::{RoleTable, can_carry};
use crate::{Result, Session};
const FOLD: &str = "addon.packaging.fold";
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "addon.packaging.fold",
"Fold",
[],
None,
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
has_doc,
fold_command
)]
}
/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the
/// whole document): what the Fold Preview window folds.
pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) {
found(&document_lines(d), TOLERANCE.1)
}
/// The objects the print on a folded blank leaves out: the layers that do not print and, unless
/// `fold_lines`, every object with a line role.
pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> {
fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { printable: false, .. } => out.push(n.id),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)),
_ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id),
_ => {}
}
}
let table = RoleTable::of(d);
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out));
out
}
fn fold_command(s: &mut Session, p: &Value) -> Result<Value> {
let tolerance = tolerance(p, FOLD)?;
let amount = number_or(p, "amount", 1.0, FOLD)?;
if !(0.0..=1.0).contains(&amount) {
return Err(bad(FOLD, "`amount` must be from 0 to 1"));
}
let base = match p.get("base") {
None | Some(Value::Null) => None,
Some(v) => {
let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?;
Some(vectorcraft_geom::Point::new(x, y))
}
};
let lines = lines(s, p, FOLD)?;
let (blanks, issues) = found(&lines, tolerance);
let ok = !issues.iter().any(|i| i.code.is_error());
let picked = pick(&blanks, base);
if base.is_some() && picked.is_none() {
return Err(bad(FOLD, "`base` is in no panel"));
}
let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?)));
let Some((index, blank, f)) = folded else {
return Ok(json!({
"ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [],
"issues": issue_rows(&issues, lines.scope),
}));
};
let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]);
let panels: Vec<Value> = blank
.panels
.iter()
.zip(&f.panels)
.map(|(panel, placed)| {
json!({
"outline": panel.outline.to_bezpath().to_svg(),
"frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t},
"parent": placed.parent,
"depth": placed.depth,
})
})
.collect();
let hinges: Vec<Value> = f
.hinges
.iter()
.map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap}))
.collect();
Ok(json!({
"ok": ok,
"blank": index,
"blanks": blanks.len(),
"base": f.base,
"panels": panels,
"hinges": hinges,
"collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(),
"issues": issue_rows(&issues, lines.scope),
}))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,157 @@
//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn fold(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.fold", &p).unwrap()
}
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
/// (outline, creases).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
fn vector(v: &Value) -> [f64; 3] {
let a = v.as_array().unwrap();
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
}
/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only).
fn middle(d: &str) -> [f64; 2] {
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
let ((x0, x1), (y0, y1)) = (span(0), span(1));
[(x0 + x1) / 2.0, (y0 + y1) / 2.0]
}
fn near(a: [f64; 3], b: [f64; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
}
#[test]
fn a_tray_folds_its_walls_up_round_the_base() {
let mut s = session();
tray(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let r = fold(&mut s, json!({}));
assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}");
let panels = r["panels"].as_array().unwrap();
assert_eq!(panels.len(), 5);
let base = r["base"].as_u64().unwrap() as usize;
let frame = &panels[base]["frame"];
assert!(
near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]),
"{frame}"
);
assert!(panels[base]["parent"].is_null());
assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data");
for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) {
assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}");
// Each wall stands square to the base, below it (away from the print), its print facing out:
// away from the base's middle (190, 190), toward the side the wall lies on.
let [cx, cy] = middle(p["outline"].as_str().unwrap());
let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"]));
let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy);
let (dx, dy) = (cx - 190.0, 190.0 - cy);
let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] };
assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}");
assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}");
}
let hinges = r["hinges"].as_array().unwrap();
assert_eq!(hinges.len(), 4);
assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}");
assert_eq!(r["collisions"], json!([]));
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step");
// Flat, every frame is the flat blank's own.
let r = fold(&mut s, json!({ "amount": 0 }));
for p in r["panels"].as_array().unwrap() {
assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}");
}
}
#[test]
fn the_base_is_the_panel_under_a_point() {
let mut s = session();
tray(&mut s);
// The left wall: x 100 to 140, y 140 to 240.
let r = fold(&mut s, json!({ "base": [120, 190] }));
let base = r["base"].as_u64().unwrap() as usize;
let panels = r["panels"].as_array().unwrap();
assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0]));
// The tray's base is now a child of the wall, and the other walls its children.
let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect();
let mut sorted = depths.clone();
sorted.sort_unstable();
assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}");
let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string();
assert!(e.contains("`base` is in no panel"), "{e}");
}
#[test]
fn bad_values_are_refused() {
let mut s = session();
tray(&mut s);
for (p, want) in [
(json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"),
(json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"),
(json!({ "amount": "1" }), "`amount` must be a number"),
(json!({ "base": [1] }), "`base` must be a point"),
(json!({ "base": "middle" }), "`base` must be a point"),
(json!({ "tolerance": 50 }), "`tolerance` must be from"),
] {
let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
}
#[test]
fn without_a_blank_nothing_is_folded_and_the_issues_say_why() {
let mut s = session();
let r = fold(&mut s, json!({}));
assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}");
assert_eq!(r["panels"], json!([]));
assert_eq!(r["issues"][0]["code"], "noCut");
}
#[test]
fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let art = path(&mut s, "M150 150 L200 150 L200 200 Z");
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
let d = &s.doc().unwrap().doc;
let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect();
for id in creases.iter().chain([&outline, &notes]) {
assert!(hidden.contains(id), "{id} in {hidden:?}");
}
assert!(!hidden.contains(&art));
let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect();
assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out");
let (blanks, issues) = cmd::fold_source(d);
assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5));
assert!(issues.is_empty(), "{issues:?}");
}
@@ -41,6 +41,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.check",
"addon.packaging.fold",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
+6
View File
@@ -1170,6 +1170,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it",
),
(
"ui.foldPreview",
"Fold Preview",
"",
"{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null",
),
(
"ui.copyScriptConsole",
"Copy Script Console",
+31 -4
View File
@@ -34,6 +34,18 @@ pub enum LineKind {
Perforation,
}
impl LineKind {
/// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for
/// a Partial Cut. A positive angle folds away from the printed side; none for a Cut.
pub fn fold_angle(self) -> Option<f64> {
match self {
LineKind::Cut => None,
LineKind::Crease | LineKind::Perforation => Some(90.0),
LineKind::PartialCut => Some(-90.0),
}
}
}
/// A fold line: the path (document coordinates), its kind, and a key the issues name it by.
#[derive(Clone, Debug)]
pub struct FoldLine {
@@ -57,10 +69,18 @@ pub struct Panel {
pub area: f64,
}
impl Panel {
/// A point inside the panel, or the middle of its bounds for one too thin to find one in.
pub fn point_inside(&self) -> Option<Point> {
point_in(&self.outline)
}
}
/// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight
/// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on
/// one straight line within the tolerance; `from` and `to` are then on the line through its longest
/// piece.
/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is
/// ([`LineKind::fold_angle`]).
#[derive(Clone, Debug)]
pub struct Hinge {
pub a: usize,
@@ -69,6 +89,7 @@ pub struct Hinge {
pub to: Point,
pub keys: Vec<u64>,
pub straight: bool,
pub angle: f64,
}
/// What can be wrong with fold lines, in the order [`blanks`] lists them.
@@ -1276,7 +1297,9 @@ impl Context<'_> {
let sp = p.path.subpaths.first()?;
Some((sp.anchors.first()?.p, sp.anchors.last()?.p))
};
let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?;
let ((p0, p1), longest) =
group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?;
let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0);
let len = p0.distance(p1);
// The longest piece only sets the direction; the length check is on the whole hinge below.
if len.is_nan() || len <= 1e-9 {
@@ -1308,7 +1331,7 @@ impl Context<'_> {
let mut keys = self.keys(lines);
keys.sort_unstable();
keys.dedup();
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight })
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle })
}
/// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a
@@ -1426,7 +1449,7 @@ impl Context<'_> {
/// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of
/// the larger tie, and the tie goes to the one whose inside point is highest on the page, then
/// leftmost.
fn base_panel(panels: &[Panel]) -> Option<usize> {
pub fn base_panel(panels: &[Panel]) -> Option<usize> {
let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max);
if !top.is_finite() {
return None;
@@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option<usize> {
.map(|(i, _)| i)
}
mod pose;
pub mod raster;
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon};
#[cfg(test)]
mod tests;
+407
View File
@@ -0,0 +1,407 @@
//! A blank folded into its 3D shape ([`fold`]).
//!
//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up;
//! the printed side faces +z. The base panel stays in place. The other panels are reached from it
//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y,
//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child
//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it
//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree
//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when
//! the blank is folded all the way.
use std::collections::{HashSet, VecDeque};
use vectorcraft_geom::{PathData, PathEl, Point, Shape as _};
use super::{Blank, base_panel, point_in};
/// Most points a panel's outline is flattened to; a panel with more is left out of the collision
/// test and the preview.
pub const MAX_POLYGON_POINTS: usize = 1 << 16;
type V3 = [f64; 3];
fn sub(a: V3, b: V3) -> V3 {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn add(a: V3, b: V3) -> V3 {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
fn scale(a: V3, s: f64) -> V3 {
[a[0] * s, a[1] * s, a[2] * s]
}
fn dot(a: V3, b: V3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: V3, b: V3) -> V3 {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn length(a: V3) -> f64 {
dot(a, a).sqrt()
}
/// A document point on the flat blank (y flipped so it points up, z = 0).
pub(super) fn flat(p: Point) -> V3 {
[p.x, -p.y, 0.0]
}
/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat
/// blank (see [`flat`]) to its place in 3D.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pose {
pub m: [[f64; 3]; 3],
pub t: [f64; 3],
}
impl Pose {
/// The flat blank's own place.
pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] };
/// Where the flat point `v` goes.
pub fn apply(&self, v: [f64; 3]) -> [f64; 3] {
add(self.turn(v), self.t)
}
/// The direction `v` turned by the rotation alone.
pub fn turn(&self, v: [f64; 3]) -> [f64; 3] {
let [a, b, c] = self.m;
[dot(a, v), dot(b, v), dot(c, v)]
}
/// Where the document point `p` goes.
pub fn place(&self, p: Point) -> [f64; 3] {
self.apply(flat(p))
}
/// The direction the printed side faces.
pub fn normal(&self) -> [f64; 3] {
self.turn([0.0, 0.0, 1.0])
}
/// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians
/// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to
/// this one there.
fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose {
let (s, c) = theta.sin_cos();
let [x, y, z] = axis;
// Rodrigues' rotation matrix.
let r = [
[c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s],
[y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s],
[z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)],
];
let mut m = [[0.0; 3]; 3];
for (i, row) in m.iter_mut().enumerate() {
for (j, cell) in row.iter_mut().enumerate() {
*cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum();
}
}
// p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t
let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)];
Pose { m, t: add(self.turn(sub(at, r_at)), self.t) }
}
}
/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no
/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it
/// and the base.
#[derive(Clone, Debug)]
pub struct FoldedPanel {
pub pose: Pose,
pub parent: Option<usize>,
pub depth: usize,
}
/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the
/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at
/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call
/// it closed.
#[derive(Clone, Debug)]
pub struct FoldedHinge {
pub a: usize,
pub b: usize,
pub angle: f64,
pub tree: bool,
pub closes: bool,
pub gap: f64,
}
/// A blank folded at one amount.
#[derive(Clone, Debug)]
pub struct Folded {
pub base: usize,
pub panels: Vec<FoldedPanel>,
/// The panels in breadth-first order from the base, the panels not joined to it last.
pub order: Vec<usize>,
pub hinges: Vec<FoldedHinge>,
/// Pairs of panels (`a` < `b`) that pass through each other.
pub collisions: Vec<(usize, usize)>,
}
/// The panel of `blank` that `p` (document coordinates) lies in.
pub fn panel_at(blank: &Blank, p: Point) -> Option<usize> {
blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0)
}
/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document
/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals)
/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel.
pub fn pick(blanks: &[Blank], at: Option<Point>) -> Option<(usize, usize)> {
match at {
Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))),
None => {
let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max);
let (i, b) =
blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best {
Some((_, kept)) if largest(kept) >= largest(b) => best,
_ => Some((i, b)),
})?;
Some((i, base_panel(&b.panels)?))
}
}
}
/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every
/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end
/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in
/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no
/// panels, `base` is not one of them, or `amount` is not from 0 to 1.
pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) -> Option<Folded> {
let base = match base {
Some(b) => b,
None => base_panel(&blank.panels)?,
};
if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) {
return None;
}
let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 };
let n = blank.panels.len();
// Each panel's hinges, by the place they start (y, then x), then by the other panel.
let mut by_panel: Vec<Vec<usize>> = vec![vec![]; n];
for (i, h) in blank.hinges.iter().enumerate() {
for p in [h.a, h.b] {
if let Some(list) = by_panel.get_mut(p) {
list.push(i);
}
}
}
// A hinge's ends, the one first by (y, x) first.
let ends = |i: &usize| {
blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| {
let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) };
[s.y, s.x, e.y, e.x]
})
};
for list in &mut by_panel {
list.sort_by(|a, b| {
let (ka, kb) = (ends(a), ends(b));
ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b))
});
}
let centers: Vec<Option<V3>> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect();
let (panels, tree, order) = place(blank, &by_panel, &centers, base, amount);
// Closing hinges are measured with every hinge at its full angle, so a blank that closes when
// folded is not reported open part of the way there.
let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, &centers, base, 1.0).0) };
let measured = full.as_deref().unwrap_or(&panels);
let hinges = blank
.hinges
.iter()
.zip(&tree)
.map(|(h, &tree)| {
let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose));
let gap = match (pa, pb) {
(Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max),
_ => 0.0,
};
let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to));
FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap }
})
.collect();
let collisions = collisions(blank, &panels, tolerance);
Some(Folded { base, panels, order, hinges, collisions })
}
/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its
/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not
/// joined to the base last).
fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) {
let n = blank.panels.len();
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n];
let mut reached = vec![false; n];
let mut tree = vec![false; blank.hinges.len()];
let mut order = Vec::with_capacity(n);
let mut queue = VecDeque::from([base]);
if let Some(r) = reached.get_mut(base) {
*r = true;
}
while let Some(p) = queue.pop_front() {
order.push(p);
let Some(parent) = panels.get(p).cloned() else { continue };
for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() {
let Some(h) = blank.hinges.get(hi) else { continue };
let child = if h.a == p { h.b } else { h.a };
if reached.get(child) != Some(&false) {
continue;
}
let (mut from, mut to) = (flat(h.from), flat(h.to));
let len = length(sub(to, from));
if !(len.is_finite() && len > 0.0) {
continue;
}
// The parent on the left of the hinge's direction, the child on its right. The side is
// read next to the hinge, so a parent with a notch or an arm past the hinge's line still
// turns the child the right way; the panel's inside point is the fallback.
let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) {
Some(left) => left,
None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0),
};
if !left {
std::mem::swap(&mut from, &mut to);
}
let axis = scale(sub(to, from), 1.0 / len);
let theta = (h.angle * amount).to_radians();
if !theta.is_finite() {
continue;
}
if let Some(slot) = panels.get_mut(child) {
*slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 };
}
if let Some(r) = reached.get_mut(child) {
*r = true;
}
if let Some(t) = tree.get_mut(hi) {
*t = true;
}
queue.push_back(child);
}
}
order.extend((0..n).filter(|&i| reached.get(i) == Some(&false)));
(panels, tree, order)
}
/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart)
/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and
/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset
/// tells them apart. The nearest offset is tried first.
fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option<bool> {
let bp = outline.to_bezpath();
let mid = scale(add(from, to), 0.5);
let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0];
let doc = |v: V3| Point::new(v[0], -v[1]);
let mut offsets = [1e-3, 0.25, len * 0.01];
offsets.sort_by(f64::total_cmp);
offsets.into_iter().find_map(|off| {
let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0);
(l != r).then_some(l)
})
}
/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past
/// [`MAX_POLYGON_POINTS`] points.
pub fn polygon(path: &PathData, tolerance: f64) -> Option<Vec<Vec<Point>>> {
let mut rings: Vec<Vec<Point>> = vec![];
let mut count = 0usize;
let mut fits = true;
vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| {
if !fits {
return;
}
match el {
PathEl::MoveTo(p) => rings.push(vec![p]),
PathEl::LineTo(p) => match rings.last_mut() {
Some(r) => r.push(p),
None => rings.push(vec![p]),
},
_ => return,
}
count += 1;
fits = count <= MAX_POLYGON_POINTS;
});
rings.retain(|r| r.len() >= 3);
(fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings)
}
/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds.
struct Placed {
rings: Vec<Vec<V3>>,
normal: V3,
offset: f64,
lo: V3,
hi: V3,
}
/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not
/// tested, nor two in parallel planes (stacked in one plane, or apart).
fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> {
let placed: Vec<Option<Placed>> = blank
.panels
.iter()
.zip(panels)
.map(|(panel, f)| {
let rings: Vec<Vec<V3>> =
polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect();
let all = rings.iter().flatten();
let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]);
let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]);
let normal = f.pose.normal();
let offset = dot(normal, f.pose.t);
Some(Placed { rings, normal, offset, lo, hi })
})
.collect();
let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect();
let mut out = vec![];
for (i, a) in placed.iter().enumerate() {
let Some(a) = a else { continue };
for (j, b) in placed.iter().enumerate().skip(i + 1) {
let Some(b) = b else { continue };
if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) {
continue;
}
let line = cross(a.normal, b.normal);
let along = length(line);
if along.is_nan() || along <= 1e-9 {
continue;
}
let u = scale(line, 1.0 / along);
let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance);
let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance);
if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) {
out.push((i, j));
}
}
}
out
}
/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie
/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side
/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it
/// count as on its positive side.
fn crossings(rings: &[Vec<V3>], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> {
let side = |p: V3| dot(normal, p) - offset;
let sides = rings.iter().flatten().map(|&p| side(p));
let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance));
if !(above && below) {
return vec![];
}
let mut at = vec![];
for ring in rings {
for (k, &p) in ring.iter().enumerate() {
let Some(&q) = ring.get((k + 1) % ring.len()) else { continue };
let (sp, sq) = (side(p), side(q));
if (sp >= -tolerance) != (sq >= -tolerance) {
let t = (sp / (sp - sq)).clamp(0.0, 1.0);
at.push(dot(u, add(p, scale(sub(q, p), t))));
}
}
}
at.retain(|x| x.is_finite());
at.sort_by(f64::total_cmp);
at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect()
}
+495
View File
@@ -0,0 +1,495 @@
//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled
//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print
//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed
//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the
//! print is drawn without seams under perspective. With perspective, each panel is cut at a near
//! plane in front of the eye before it is projected.
use vectorcraft_geom::{Point, Rect};
use super::pose::{Folded, polygon};
use super::{Blank, Panel};
/// Most pixels a side of the view or of the print raster may have.
pub const MAX_SIDE: u32 = 4096;
/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers).
pub const MAX_PIXELS: u32 = 1 << 21;
/// The share of the eye's distance a panel is cut at in front of the eye.
const NEAREST: f64 = 1e-3;
/// How far apart (points of view depth) two panels may be and still tie.
const TIE: f64 = 1e-4;
/// The light's direction: above, to the left of and toward the viewer.
const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74];
type V3 = [f64; 3];
fn dot(a: V3, b: V3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer,
/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's
/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none)
/// and the 3D point at its middle.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera {
pub width: u32,
pub height: u32,
pub rotate_x: f64,
pub rotate_y: f64,
pub scale: f64,
pub pan: [f64; 2],
pub perspective: f64,
pub center: [f64; 3],
}
impl Camera {
/// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows.
fn rotation(&self) -> [[f64; 3]; 3] {
let (sx, cx) = self.rotate_x.to_radians().sin_cos();
let (sy, cy) = (-self.rotate_y).to_radians().sin_cos();
// Rx · Ry
[[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]]
}
/// The point `p` in the view's own axes, its middle at the origin.
pub fn to_view(&self, p: V3) -> V3 {
let r = self.rotation();
let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]];
[dot(r[0], d), dot(r[1], d), dot(r[2], d)]
}
/// The distance (points) from the eye to the view's middle and the focal length (pixels) under
/// perspective; `None` without it.
fn eye(&self) -> Option<(f64, f64)> {
if self.perspective <= 0.0 || self.perspective >= 180.0 {
return None;
}
let half = f64::from(self.width.min(self.height)) / 2.0;
let focal = half / (self.perspective.to_radians() / 2.0).tan();
let eye = focal / self.scale;
(focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal))
}
fn usable(&self) -> bool {
let finite =
[self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite());
let pixels = u64::from(self.width) * u64::from(self.height);
finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS)
}
}
/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel.
#[derive(Clone, Debug)]
pub struct Level {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
impl Level {
/// The color at pixel `(x, y)`, clamped to the edges.
fn at(&self, x: i64, y: i64) -> [f32; 4] {
let x = x.clamp(0, i64::from(self.width) - 1);
let y = y.clamp(0, i64::from(self.height) - 1);
let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX);
match self.pixels.get(i..i.saturating_add(4)) {
Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)],
_ => [0.0; 4],
}
}
/// The color at `(x, y)` (pixels), between the four nearest pixels.
fn sample(&self, x: f64, y: f64) -> [f32; 4] {
let (fx, fy) = (x - 0.5, y - 0.5);
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32);
let (x0, y0) = (x0 as i64, y0 as i64);
let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1));
let mut out = [0.0; 4];
for (k, o) in out.iter_mut().enumerate() {
let top = a[k] + (b[k] - a[k]) * tx;
let bottom = c[k] + (d[k] - c[k]) * tx;
*o = top + (bottom - top) * ty;
}
out
}
/// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted
/// by the area of the full print they cover. A pixel of this level is `step` pixels of the full
/// print (`base` pixels across and down) on a side, and fewer in the last column and row when
/// `base` is not a multiple of `step`.
fn half(&self, base: (u32, u32), step: u32) -> Option<Level> {
let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2));
if (w, h) == (self.width, self.height) {
return None;
}
// The pixels of the full print that column or row `i` of this level covers, or 0 past it.
let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32;
let mut pixels = Vec::with_capacity(w as usize * h as usize * 4);
for y in 0..h {
for x in 0..w {
let mut sum = [0.0f32; 4];
let mut area = 0.0;
for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] {
if sx >= self.width || sy >= self.height {
continue;
}
let a = covers(sx, base.0) * covers(sy, base.1);
let p = self.at(i64::from(sx), i64::from(sy));
for (s, c) in sum.iter_mut().zip(p) {
*s += c * a;
}
area += a;
}
for s in sum {
pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 });
}
}
}
Some(Level { width: w, height: h, pixels })
}
}
/// The flat print: the document rect it covers and its raster at full size and halved again and
/// again down to one pixel.
#[derive(Clone, Debug)]
pub struct Print {
pub region: Rect,
pub levels: Vec<Level>,
}
impl Print {
/// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when
/// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty.
pub fn new(region: Rect, width: u32, height: u32, pixels: Vec<u8>) -> Option<Print> {
let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height);
let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite());
if !fits || empty || pixels.len() != width as usize * height as usize * 4 {
return None;
}
let mut levels = vec![Level { width, height, pixels }];
let mut step = 1;
while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) {
levels.push(next);
step *= 2;
}
Some(Print { region, levels })
}
/// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose
/// pixels are closest to `footprint` points across; transparent outside the region.
fn sample(&self, p: Point, footprint: f64) -> [f32; 4] {
let Some(base) = self.levels.first() else { return [0.0; 4] };
if !self.region.contains(p) {
return [0.0; 4];
}
let per_point = f64::from(base.width) / self.region.width();
let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 };
let level = level.min(self.levels.len() - 1);
let Some(l) = self.levels.get(level) else { return [0.0; 4] };
// Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's.
let shrink = f64::from(1u32 << level);
let sx = f64::from(base.width) / self.region.width() / shrink;
let sy = f64::from(base.height) / self.region.height() / shrink;
l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy)
}
}
/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of
/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha
/// is not used), and the view.
pub struct Scene<'a> {
pub blank: &'a Blank,
pub folded: &'a Folded,
pub print: Option<&'a Print>,
pub inside: [u8; 4],
pub outside: [u8; 4],
pub camera: Camera,
}
/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each
/// pixel the panel drawn there plus 1 (0 for none).
#[derive(Clone, Debug)]
pub struct Image {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
pub panels: Vec<u16>,
}
impl Image {
/// The panel drawn at pixel `(x, y)`.
pub fn panel_at(&self, x: u32, y: u32) -> Option<usize> {
if x >= self.width || y >= self.height {
return None;
}
let i = y as usize * self.width as usize + x as usize;
self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1))
}
}
/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners).
pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> {
let mut lo = [f64::INFINITY; 3];
let mut hi = [f64::NEG_INFINITY; 3];
for (panel, f) in blank.panels.iter().zip(&folded.panels) {
let Some(b) = panel.outline.bounds() else { continue };
for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] {
let p = f.pose.place(c);
for k in 0..3 {
lo[k] = lo[k].min(p[k]);
hi[k] = hi[k].max(p[k]);
}
}
}
lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi))
}
/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth
/// plane in view terms, and its color factors.
struct Mapped {
/// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows.
forward: [[f64; 3]; 3],
/// The inverse of `forward`.
inverse: [[f64; 3]; 3],
/// View depth at flat (u, v): u a + v b + c.
depth: [f64; 3],
printed: bool,
shade: f32,
}
fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 {
[dot(m[0], v), dot(m[1], v), dot(m[2], v)]
}
fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
let [[a, b, c], [d, e, f], [g, h, i]] = *m;
let co = [e * i - f * h, f * g - d * i, d * h - e * g];
let det = a * co[0] + b * co[1] + c * co[2];
if !(det.is_finite() && det.abs() > 1e-300) {
return None;
}
let inv = [
[co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det],
[co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det],
[co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det],
];
inv.iter().flatten().all(|v| v.is_finite()).then_some(inv)
}
fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> {
let r = camera.rotation();
let turn = |v: V3| mul(&r, f.pose.turn(v));
let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0]));
let o = camera.to_view(f.pose.t);
let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]);
let normal = turn([0.0, 0.0, 1.0]);
let (w, k, printed) = match camera.eye() {
Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0),
None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0),
};
let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]];
let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]];
let forward = [x, y, w];
let inverse = invert(&forward)?;
let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] };
let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32;
Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade })
}
/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`.
fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> {
let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near;
let mut out = Vec::with_capacity(ring.len() + 4);
for (k, &p) in ring.iter().enumerate() {
let Some(&q) = ring.get((k + 1) % ring.len()) else { continue };
let (dp, dq) = (at(p), at(q));
if dp >= 0.0 {
out.push(p);
}
if (dp >= 0.0) != (dq >= 0.0) {
let t = dp / (dp - dq);
out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
}
}
out
}
/// The buffers [`render`] fills.
struct Target {
width: usize,
height: usize,
color: Vec<u8>,
depth: Vec<f64>,
rank: Vec<u16>,
panel: Vec<u16>,
}
/// One panel's fill: its map, rank (for ties), panel number and colors.
struct Fill<'a> {
mapped: &'a Mapped,
rank: u16,
panel: u16,
print: Option<&'a Print>,
inside: [f32; 4],
outside: [f32; 4],
}
impl Fill<'_> {
/// The document point under pixel center `(x, y)`, or `None` behind the eye.
fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]);
(w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite())
}
/// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel.
fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] {
let base = if self.mapped.printed {
let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint));
let under = 1.0 - p[3] / 255.0;
[p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0]
} else {
self.inside
};
let s = self.mapped.shade;
[base[0] * s, base[1] * s, base[2] * s, base[3]]
}
/// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`.
fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) {
let first = (x0 - 0.5).ceil().max(0.0);
let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0);
if first > last {
return;
}
let y = row as f64 + 0.5;
for col in first as usize..=last as usize {
let x = col as f64 + 0.5;
let Some((u, v)) = self.flat_at(x, y) else { continue };
let [a, b, c] = self.mapped.depth;
let z = u * a + v * b + c;
let i = row * target.width + col;
let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue };
let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb);
if !wins {
continue;
}
// The print's footprint is the longer of a pixel's two sides in flat terms.
let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v));
let footprint = across(1.0, 0.0).max(across(0.0, 1.0));
let color = self.color(u, v, footprint);
if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) {
for (o, c) in px.iter_mut().zip(color) {
*o = c.round().clamp(0.0, 255.0) as u8;
}
}
if let Some(d) = target.depth.get_mut(i) {
*d = z;
}
if let Some(r) = target.rank.get_mut(i) {
*r = self.rank;
}
if let Some(p) = target.panel.get_mut(i) {
*p = self.panel;
}
}
}
/// Fill the projected `rings` (pixel coordinates), even-odd, into `target`.
fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) {
let ys = rings.iter().flatten().map(|p| p[1]);
let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y)));
if !(lo.is_finite() && hi.is_finite()) {
return;
}
let first = (lo - 0.5).ceil().max(0.0);
let last = (hi - 0.5).floor().min(target.height as f64 - 1.0);
if first > last {
return;
}
let mut xs = vec![];
for row in first as usize..=last as usize {
let y = row as f64 + 0.5;
xs.clear();
for ring in rings {
for (k, p) in ring.iter().enumerate() {
let Some(q) = ring.get((k + 1) % ring.len()) else { continue };
if (p[1] <= y) != (q[1] <= y) {
xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1]));
}
}
}
xs.retain(|x| x.is_finite());
xs.sort_by(f64::total_cmp);
for &[a, b] in xs.as_chunks::<2>().0 {
self.span(target, row, a, b);
}
}
}
}
/// The board color `c` as drawn: its RGB, opaque.
fn opaque(c: [u8; 4]) -> [f32; 4] {
[f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0]
}
/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a
/// point.
fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> {
let b = panel.outline.bounds()?;
let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6);
Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect())
}
/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more
/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than
/// [`super::MAX_POLYGON_POINTS`] points, are left out.
pub fn render(scene: &Scene) -> Option<Image> {
let camera = scene.camera;
if !camera.usable() {
return None;
}
let (width, height) = (camera.width as usize, camera.height as usize);
let pixels = width * height;
let mut target =
Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] };
let (inside, outside) = (opaque(scene.inside), opaque(scene.outside));
let near = camera.eye().map(|(eye, _)| eye * NEAREST);
for (rank, &pi) in scene.folded.order.iter().enumerate() {
let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue };
let Some(mapped) = map_panel(&camera, f) else { continue };
let Some(rings) = flat_rings(panel, camera.scale) else { continue };
let projected: Vec<Vec<[f64; 2]>> = rings
.iter()
.map(|r| match near {
Some(near) => clip(r, mapped.forward[2], near),
None => r.clone(),
})
.filter(|r| r.len() >= 3)
.map(|r| {
r.into_iter()
.filter_map(|[u, v]| {
let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]);
let p = [x / w, y / w];
(w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p)
})
.collect::<Vec<_>>()
})
.filter(|r| r.len() >= 3)
.collect();
let fill = Fill {
mapped: &mapped,
rank: u16::try_from(rank + 1).unwrap_or(u16::MAX),
panel: u16::try_from(pi + 1).unwrap_or(u16::MAX),
print: scene.print,
inside,
outside,
};
fill.rings(&mut target, &projected);
}
Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel })
}
#[cfg(test)]
mod tests;
+257
View File
@@ -0,0 +1,257 @@
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
use super::super::{Blank, Folded, FoldedPanel, Panel, Pose};
use super::*;
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true)
}
fn panel(subpaths: Vec<SubPath>) -> Panel {
Panel { outline: PathData::new(subpaths), area: 0.0 }
}
/// A blank of `panels` and a fold that places each at `poses`, in the order given.
fn scene_of(panels: Vec<Panel>, poses: Vec<Pose>) -> (Blank, Folded) {
let n = panels.len();
let folded = Folded {
base: 0,
panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(),
order: (0..n).collect(),
hinges: vec![],
collisions: vec![],
};
(Blank { panels, hinges: vec![], holes: vec![] }, folded)
}
/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it.
fn front() -> Camera {
Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] }
}
fn moved(z: f64) -> Pose {
Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY }
}
fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] {
let i = (y * img.width + x) as usize * 4;
[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]
}
/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below.
fn quads() -> Print {
let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]];
Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print")
}
const WHITE: [u8; 4] = [255, 255, 255, 255];
#[test]
fn a_flat_panel_takes_the_print_s_color_under_each_pixel() {
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
let print = quads();
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
let shade = 0.6 + 0.4 * 0.74;
let lit = |c: f64| (c * shade).round() as u8;
assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red");
assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green");
assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue");
assert_eq!(img.panel_at(50, 50), Some(0));
// Where the print has no art, the board's printed side shows.
let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print");
let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() })
.expect("drawn");
assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]);
}
#[test]
fn the_board_is_opaque_whatever_the_alpha_of_its_colors() {
let shade = 0.6 + 0.4 * 0.74;
let lit = |c: f64| (c * shade).round() as u8;
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
for a in [0, 128] {
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() })
.expect("drawn");
assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}");
}
// A transparent inside color draws opaque too, on the nearer of two panels seen from the back.
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]);
let camera = Camera { rotate_y: 180.0, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn");
let [r, g, bl, a] = pixel(&img, 50, 50);
assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]);
}
#[test]
fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() {
// 64 × 64, rows alternating black and white: halved, they average to gray.
let mut px = vec![];
for y in 0..64 {
for _ in 0..64 {
px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
}
}
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print");
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
// Tipped 80°: about 5.8 points a pixel up and down, 1 across.
let camera = Camera { rotate_x: 80.0, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
let reds: Vec<u8> = (0..img.height)
.flat_map(|y| (0..img.width).map(move |x| (x, y)))
.filter(|&(x, y)| img.panel_at(x, y).is_some())
.map(|(x, y)| pixel(&img, x, y)[0])
.collect();
assert!(!reds.is_empty());
let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0));
assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}");
}
#[test]
fn the_back_of_a_panel_shows_the_inside_color() {
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
let print = quads();
let camera = Camera { rotate_y: 180.0, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn");
let [r, g, bl, a] = pixel(&img, 50, 50);
assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]);
}
#[test]
fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() {
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
let draw = |z: f64| {
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]);
render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn")
};
assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front");
assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind");
assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order");
// Panels that cross: each shows where it is nearer.
let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] };
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]);
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left");
assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right");
}
#[test]
fn a_hole_in_a_panel_is_left_empty() {
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]);
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
assert_eq!(img.panel_at(50, 50), None);
assert_eq!(pixel(&img, 50, 50), [0; 4]);
assert_eq!(img.panel_at(10, 50), Some(0));
}
#[test]
fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() {
// A long panel standing out of the page toward the viewer, through the eye.
let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] };
let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]);
for perspective in [1.0, 60.0, 160.0, 179.0] {
let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn");
let drawn = img.panels.iter().filter(|&&p| p != 0).count();
assert!(drawn > 0, "{perspective}°: some of it shows");
assert_eq!(img.pixels.len(), 100 * 100 * 4);
}
}
#[test]
fn unusable_views_and_prints_are_refused() {
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
for camera in [
Camera { width: 0, ..front() },
Camera { height: MAX_SIDE + 1, ..front() },
Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() },
Camera { scale: 0.0, ..front() },
Camera { rotate_x: f64::NAN, ..front() },
Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() },
] {
assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}");
}
let region = Rect::new(0.0, 0.0, 10.0, 10.0);
assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes");
assert!(Print::new(region, 0, 2, vec![]).is_none());
assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none());
assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region");
let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print");
assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]);
}
#[test]
fn halving_an_odd_sized_print_keeps_its_last_row_and_column() {
// 3 × 3, transparent but for an opaque white last column and last row.
let mut px = vec![0u8; 3 * 3 * 4];
for i in [2, 5, 6, 7, 8] {
px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]);
}
let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print");
let half = &p.levels[1];
assert_eq!((half.width, half.height), (2, 2));
// The bottom right pixel of the half level covers only the corner pixel.
assert_eq!(&half.pixels[12..16], &[255; 4]);
assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels");
}
#[test]
fn a_print_far_smaller_on_screen_samples_a_halved_level() {
// Columns alternate black and white: halved, they average to gray.
let mut px = vec![];
for _ in 0..4 {
for x in 0..4 {
px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
}
}
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print");
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
// 100 points in 2 pixels: 2 print pixels a view pixel.
let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
let [r, ..] = pixel(&img, 0, 0);
assert!((80..=150).contains(&r), "gray, not a black or white column: {r}");
}
#[test]
fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() {
// 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate;
// halved four times, they average to gray.
let mut px = vec![];
for _ in 0..64 {
for x in 0..64 {
px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
}
}
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print");
assert_eq!(print.levels.len(), 7, "64 down to 1");
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
// 100 points in 3 pixels: about 21 print pixels a view pixel.
let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() };
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
let [r, ..] = pixel(&img, 0, 1);
assert!((90..=140).contains(&r), "gray, not a black or white band: {r}");
}
#[test]
fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() {
// 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is
// a ninth white (255 / 9 is about 28), not half.
let mut px = vec![];
for _ in 0..9 {
for x in 0..9 {
px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] });
}
}
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print");
assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]);
assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255]));
}
#[test]
fn the_bounds_take_in_every_folded_panel() {
let (b, f) =
scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]);
let (lo, hi) = bounds(&b, &f).expect("bounds");
assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0]));
}
+319
View File
@@ -913,4 +913,323 @@ proptest! {
sorted.sort_by_key(|i| i.code);
prop_assert_eq!(sorted, issues);
}
/// Random fold lines fold at any amount without a panic, every pose finite and every panel
/// keeping its shape.
#[test]
fn random_blanks_fold_to_finite_poses(
segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8),
amount in 0.0f64..=1.0,
) {
let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation];
let mut lines: Vec<FoldLine> = segs
.iter()
.enumerate()
.map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64))
.collect();
lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99));
let (blanks, _) = blanks(&lines, TOL);
for b in &blanks {
let Some(f) = fold(b, None, amount, TOL) else { continue };
prop_assert_eq!(f.panels.len(), b.panels.len());
prop_assert_eq!(f.order.len(), b.panels.len());
for p in &f.panels {
prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite()));
let n = p.pose.normal();
prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9);
}
}
}
}
/// The 3D corners of panel `i` of `b` folded as `f` places them.
fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> {
let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon");
rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect()
}
fn flat_center(b: &Blank, i: usize) -> [f64; 3] {
let c = point_in(&b.panels[i].outline).expect("a point inside");
[c.x, -c.y, 0.0]
}
#[test]
fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() {
let (b, issues) = check(&notched_box());
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
// The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110.
let base = &b.panels[f.base];
assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0)));
// The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width).
let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]);
let middle = [70.0, -70.0, -30.0];
for i in 0..b.panels.len() {
let points = corners(b, &f, i);
let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at)));
let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}"));
for p in &points {
for j in 0..3 {
assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}");
}
}
// The printed side faces out of the box.
let n = f.panels[i].pose.normal();
assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}");
assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}");
}
assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges);
assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions);
assert_eq!(f.order.first(), Some(&f.base));
assert_eq!(f.order.len(), 13);
}
#[test]
fn at_amount_0_the_blank_is_flat() {
let (b, _) = check(&notched_box());
let f = fold(&b[0], None, 0.0, TOL).expect("folds");
for p in &f.panels {
for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) {
assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose);
}
assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose);
}
}
/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by
/// `quarter` quarter turns about the origin and mirrored in x when `mirror`.
fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec<FoldLine> {
let at = |(x, y): (f64, f64)| {
let x = if mirror { -x } else { x };
(0..quarter).fold((x, y), |(x, y), _| (-y, x))
};
let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect();
let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) };
vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)]
}
#[test]
fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() {
for quarter in 0..4 {
for mirror in [false, true] {
for up in [false, true] {
for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] {
let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}");
let (b, issues) = check(&two_panels(kind, quarter, mirror, up));
assert!(issues.is_empty(), "{case}: {issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
let child = 1 - f.base;
let h = &b.hinges[0];
let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0];
let c = flat_center(b, child);
let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0];
let along = [h.to.x - h.from.x, h.from.y - h.to.y];
let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]);
let placed = f.panels[child].pose.apply(c);
// The child stands up out of the plane: behind it for a crease, in front of it
// for a partial cut, at its distance from the hinge.
assert!(placed[2] * sign > 0.0, "{case}: {placed:?}");
assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}");
// Its printed side faces away from the base panel after a crease, back toward
// it after a partial cut.
let n = f.panels[child].pose.normal();
assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}");
// Half way, the child is half way round.
let half = fold(b, None, 0.5, TOL).expect("folds");
let z = half.panels[child].pose.normal()[2];
assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}");
}
}
}
}
}
/// A 100 × 100 square divided into four panels by a crease across it each way.
fn crossed() -> Vec<FoldLine> {
vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
crease((50.0, 0.0), (50.0, 100.0), 2),
crease((0.0, 50.0), (100.0, 50.0), 3),
]
}
#[test]
fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() {
let (b, issues) = check(&crossed());
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
assert_eq!((b.panels.len(), b.hinges.len()), (4, 4));
let folded = fold(b, None, 1.0, TOL).expect("folds");
let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect();
assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop");
assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}");
// The gap is measured folded all the way, whatever the amount: flat or half way, the loop is
// still reported open by the same gap.
for amount in [0.0, 0.5] {
let part = fold(b, None, amount, TOL).expect("folds");
let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge");
assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}");
}
// The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins.
assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0)));
}
#[test]
fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() {
// About the bottom-right panel, its two hinges both start at the middle of the square.
let lines = crossed();
let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]];
let mut seen = None;
for order in orders {
let lines: Vec<FoldLine> = order.iter().map(|&i| lines[i].clone()).collect();
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{order:?}: {issues:?}");
let b = &b[0];
let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel");
let f = fold(b, Some(base), 1.0, TOL).expect("folds");
let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0));
let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel");
let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round());
let got = (closing, placed);
assert_eq!(seen.get_or_insert(got), &got, "{order:?}");
}
}
/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the
/// line between them bends by `lean` pt over its lower half.
fn leaning(lean: f64) -> Vec<FoldLine> {
vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1),
crease((60.0, 0.0), (60.0, 30.0), 2),
crease((60.0, 30.0), (60.0 + lean, 60.0), 3),
crease((60.0, 30.0), (100.0, 30.0), 4),
]
}
#[test]
fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() {
// Both right panels turn about one line, so the hinge between them closes exactly.
let gap = |lean: f64, amount: f64| {
let (b, issues) = check(&leaning(lean));
assert!(issues.is_empty(), "{lean}: {issues:?}");
let b = &b[0];
assert_eq!((b.panels.len(), b.hinges.len()), (3, 3));
let base = panel_at(b, p(30.0, 30.0)).expect("the left panel");
let f = fold(b, Some(base), amount, TOL).expect("folds");
let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone();
(h.closes, h.gap)
};
let (closes, at) = gap(0.0, 1.0);
assert!(closes && at < 1e-9, "{at}");
// A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt
// length (0.2 pt): still closed.
let (closes, at) = gap(0.1, 1.0);
assert!(closes && at > TOL && at <= 0.2, "{at}");
// A larger lean opens it past both, flat or folded.
for amount in [0.0, 1.0] {
let (closes, at) = gap(1.0, amount);
assert!(!closes && at > 0.2, "{amount}: {at}");
}
}
#[test]
fn a_panel_no_hinge_joins_stays_flat_where_it_is() {
let lines = vec![
cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1),
crease((50.0, 49.95), (50.0, 50.0), 2),
];
let (b, _) = check(&lines);
let b = &b[0];
assert_eq!((b.panels.len(), b.hinges.len()), (2, 0));
let f = fold(b, None, 1.0, TOL).expect("folds");
let loose = 1 - f.base;
assert_eq!(f.panels[loose].parent, None);
assert_eq!(f.panels[loose].pose, Pose::IDENTITY);
assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last");
}
#[test]
fn a_child_of_a_notched_panel_folds_away_from_the_print() {
// The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300.
// The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30.
let lines = vec![
cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1),
crease((30.0, 82.0), (30.0, 140.0), 2),
];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let base = panel_at(b, p(15.0, 110.0)).expect("the L");
let child = panel_at(b, p(150.0, 110.0)).expect("the child");
// The L's inside point lies in its arm, on the child's side of the hinge's line.
let inside = b.panels[base].point_inside().expect("a point inside");
assert!(inside.x > 30.0, "{inside:?}");
for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] {
let mut lines = lines.clone();
lines[1].kind = kind;
let (b, _) = check(&lines);
let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds");
let placed = f.panels[child].pose.place(p(150.0, 110.0));
assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}");
}
}
#[test]
fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() {
// A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep.
let lines = vec![
cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1),
crease((120.0, 0.0), (120.0, 50.0), 2),
crease((150.0, 0.0), (150.0, 50.0), 3),
crease((250.0, 0.0), (250.0, 50.0), 4),
];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let base = panel_at(b, p(200.0, 25.0)).expect("the base panel");
let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap());
let f = fold(b, Some(base), 1.0, TOL).expect("folds");
assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]);
// Half folded, nothing crosses yet.
assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty());
}
#[test]
fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() {
let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)];
let (b, _) = check(&lines);
assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel");
let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel");
assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right);
let mut reversed = lines.clone();
reversed.reverse();
let (r, _) = check(&reversed);
for blank in [&b[0], &r[0]] {
let f = fold(blank, None, 1.0, TOL).expect("folds");
// Equal panels: the leftmost wins.
assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0));
}
assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9");
assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1");
assert!(fold(&b[0], None, f64::NAN, TOL).is_none());
assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels");
}
#[test]
fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() {
let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false));
assert_eq!(b[0].hinges[0].angle, -90.0);
let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false));
assert_eq!(b[0].hinges[0].angle, 90.0);
// A crease and a short partial cut on one line: the crease is the longer piece.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1),
line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2),
crease((60.0, 10.0), (60.0, 60.0), 3),
];
let (b, _) = check(&lines);
assert_eq!(b[0].hinges.len(), 1);
assert_eq!(b[0].hinges[0].angle, 90.0);
}
+13 -1
View File
@@ -4,7 +4,8 @@
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; each document's list is kept until that document changes.
//! with a Select button; each document's list is kept until that document changes. Its Fold Preview
//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`).
use std::collections::HashMap;
use std::sync::{Arc, Weak};
@@ -26,6 +27,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole";
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The command that shows the Fold Preview window.
pub const PREVIEW: &str = "ui.foldPreview";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
pub const ROLES: &[(&str, &str)] =
&[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")];
@@ -47,6 +50,8 @@ pub fn menu() -> Vec<Item> {
make("Make Perforation Line", "perforation"),
Item::Sep,
Item::Cmd("Check Fold Lines", CHECK, Value::Null),
Item::Sep,
Item::Cmd("Fold Preview", PREVIEW, json!({})),
]
}
@@ -160,6 +165,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) {
if widgets::flat_button(ui, tl!("Check"), width).clicked() {
run_check(app, ui.ctx(), json!({}));
}
if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked()
&& let Err(e) = app.run(PREVIEW, json!({}))
{
app.status(e);
}
let Some(checked) = last_check(app, ui.ctx()) else { return };
ui.add_space(4.0);
dim_label(ui, &crate::i18n::msg(&checked.summary()));
@@ -285,5 +295,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
pub mod preview;
#[cfg(test)]
mod tests;
@@ -0,0 +1,705 @@
//! The Fold Preview window: the document's blank folded into its 3D shape
//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the
//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`].
//!
//! The window folds the blank that the document's shown fold lines make, about its largest panel
//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines
//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered
//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and
//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag
//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a
//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus.
//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them.
use std::sync::Arc;
use egui::{Color32, Rect, Sense, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_geom::{Point, Rect as DRect};
use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print};
use vectorcraft_three_d::fold::{Blank, Folded, fold, pick};
use crate::VectorcraftApp;
use crate::thumb_worker::{Settle, ThumbWorker};
use crate::widgets::{self, dim_label};
/// The window's id (`window.panel {panel: "foldPreview"}`).
pub const ID: &str = "foldPreview";
/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the
/// right side toward the viewer), in degrees.
pub const VIEWS: [(&str, &str, f64, f64); 7] = [
("Front", "front", 0.0, 0.0),
("Back", "back", 0.0, 180.0),
("Left", "left", 0.0, -90.0),
("Right", "right", 0.0, 90.0),
("Top", "top", 90.0, 0.0),
("Bottom", "bottom", -90.0, 0.0),
("Three-Quarter", "threeQuarter", 25.0, 35.0),
];
/// The tolerance the window folds with (points), as Check Fold Lines' default.
const TOLERANCE: f64 = 0.1;
/// The share of the view's shorter side the folded blank fills at a zoom of 1.
const FIT: f64 = 0.45;
/// The print raster's longest side, in pixels, and the fewest pixels it gives a point.
const PRINT_SIDE: f64 = 2048.0;
/// Degrees the view turns for each point dragged, and for each arrow key press.
const DRAG_TURN: f64 = 0.5;
const KEY_TURN: f64 = 5.0;
/// The window's settings (kept with the UI state).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Settings {
/// How far the blank is folded: 0 flat, 1 every hinge at its angle.
pub amount: f64,
/// The view's turn, in degrees (see [`VIEWS`]).
pub rotate_x: f64,
pub rotate_y: f64,
/// The zoom: 1 fits the folded blank in the view.
pub zoom: f64,
/// How far the view is moved, in points.
pub pan: [f64; 2],
/// The field of view in degrees; 0 for none.
pub perspective: f64,
/// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white.
pub inside: String,
/// Draw the fold lines on the print.
pub show_fold_lines: bool,
/// The base panel: the one under this point (document coordinates); the largest when `None`.
pub base: Option<[f64; 2]>,
}
impl Default for Settings {
fn default() -> Self {
let (_, _, rotate_x, rotate_y) = VIEWS[6];
Self {
amount: 1.0,
rotate_x,
rotate_y,
zoom: 1.0,
pan: [0.0; 2],
perspective: 0.0,
inside: String::new(),
show_fold_lines: false,
base: None,
}
}
}
impl Settings {
/// The view preset these settings show, if any.
fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> {
VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9)
}
/// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read
/// as it was stored. A value that is not a number takes its default.
fn clamped(mut self) -> Self {
let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or };
let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) };
let fresh = Settings::default();
self.amount = within(self.amount, 0.0, 1.0, fresh.amount);
self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom);
self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective);
(self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y));
self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 });
self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite()));
self
}
}
/// `angle` (degrees) brought into -180 to 180.
fn wrapped(angle: f64) -> f64 {
let a = (angle + 180.0).rem_euclid(360.0) - 180.0;
if a.is_finite() { a } else { 0.0 }
}
/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and
/// the region and size.
#[derive(Clone, Copy, Debug, PartialEq)]
struct PrintKey {
uid: u64,
revision: u64,
fold_lines: bool,
region: [u64; 4],
width: u32,
height: u32,
}
/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms).
#[derive(Clone, Copy, Debug, Default)]
struct Frame {
width: u32,
height: u32,
fold_ms: f64,
draw_ms: f64,
}
/// A document's blanks and whether its fold lines have an error, by (uid, revision).
type Blanks = ((u64, u64), Arc<Vec<Blank>>, bool);
/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits.
type FoldKey = (u64, u64, usize, usize, u64);
/// What the last image shows: the fold, the camera, the inside color and the print.
#[derive(Clone, Copy, Debug, PartialEq)]
struct DrawKey {
fold: FoldKey,
camera: Camera,
inside: [u8; 4],
print: Option<PrintKey>,
}
#[derive(Default)]
struct Cache {
blanks: Option<Blanks>,
/// The last fold, what it folds and how long it took (ms).
folded: Option<(FoldKey, Arc<Folded>, f64)>,
/// What the texture shows.
drawn: Option<DrawKey>,
/// Folds worked out and images rendered (tests count them).
folds: u64,
renders: u64,
/// The print shown and what it shows.
print: Option<(PrintKey, Arc<Print>)>,
/// Renders the print off the UI thread (None: on this thread).
worker: Option<ThumbWorker<(), PrintKey>>,
worker_started: bool,
pending: Option<PrintKey>,
settle: Settle,
tex: Option<egui::TextureHandle>,
/// The last frame's image, for double-click picking, and the screen rect it filled.
image: Option<(Image, Rect)>,
frame: Option<Frame>,
/// Prints rendered (tests count them).
prints: u64,
}
thread_local! {
static CACHE: crate::graphics::TexCache<Cache> = crate::graphics::TexCache::default();
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
}
/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d`
/// with a plain color, or else `#rrggbb`; `None` for anything else.
fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> {
if inside.is_empty() {
return Some([255; 4]);
}
match d.swatch(inside).map(|s| &s.paint) {
Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)),
_ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)),
_ => None,
}
}
/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare.
fn print_region(blank: &Blank) -> Option<DRect> {
let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?;
let r = r.inflate(1.0, 1.0);
(r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r)
}
/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`].
fn print_size(region: DRect) -> (u32, u32, f64) {
let scale = PRINT_SIDE / region.width().max(region.height());
let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE);
(side(region.width()), side(region.height()), scale)
}
impl Cache {
/// The blanks of document `uid` at `revision`, worked out again only when it changed.
fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc<Vec<Blank>>, bool) {
if let Some((key, blanks, errors)) = &self.blanks
&& *key == (uid, revision)
{
return (blanks.clone(), *errors);
}
let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d);
let errors = issues.iter().any(|i| i.code.is_error());
let blanks = Arc::new(blanks);
self.blanks = Some(((uid, revision), blanks.clone(), errors));
(blanks, errors)
}
/// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the
/// key changed, and how long that took (ms).
fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc<Folded>, f64)> {
if let Some((k, f, ms)) = &self.folded
&& *k == key
{
return Some((f.clone(), *ms));
}
let t0 = crate::now_ms();
let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?);
let ms = crate::now_ms() - t0;
self.folded = Some((key, f.clone(), ms));
self.folds += 1;
Some((f, ms))
}
/// Bring the print up to `key`: on the worker when there is one, else here, and not before the
/// document has settled unless there is no print of it yet.
fn update_print(&mut self, ctx: &egui::Context, doc: &Arc<vectorcraft_engine::doc::Document>, key: PrintKey, region: DRect, scale: f64) {
if !self.worker_started {
self.worker_started = true;
self.worker = ThumbWorker::spawn(ctx, "fold-preview");
}
let done = match self.worker.as_ref().map(ThumbWorker::poll) {
Some(Some(done)) => done,
Some(None) => {
(self.worker, self.pending) = (None, None);
vec![]
}
None => vec![],
};
for d in done {
if self.pending == Some(d.key) {
self.pending = None;
}
if let Some(img) = d.img {
self.keep_print(d.key, img);
}
}
let shown = self.print.as_ref().map(|(k, _)| *k);
if shown == Some(key) || self.pending == Some(key) {
return;
}
let have = shown.is_some_and(|k| k.uid == key.uid);
if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) {
return;
}
let opts = vectorcraft_render::RenderOptions {
skip_templates: true,
image_mips: true,
hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines),
..Default::default()
};
if let Some(w) = &self.worker {
let (doc, opts) = (doc.clone(), opts.clone());
if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) {
self.pending = Some(key);
return;
}
self.worker = None;
}
let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts));
self.keep_print(key, img);
}
/// The print to draw for `want`: the one shown when it is of the same document, blank region and
/// Show Fold Lines setting (an older revision while the new one renders), else none.
fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc<Print>)> {
let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region);
self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone()))
}
fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) {
let region =
DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3]));
if let Some(print) = Print::new(region, img.width, img.height, img.pixels) {
self.print = Some((key, Arc::new(print)));
self.prints += 1;
}
}
}
/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?,
/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last
/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is
/// set.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let mut set = app.ui.fold_preview.clone();
let number = |key: &str, lo: f64, hi: f64| -> Result<Option<f64>, String> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)),
_ => Err(format!("`{key}` must be a number from {lo} to {hi}")),
},
}
};
if let Some(a) = number("amount", 0.0, 1.0)? {
set.amount = a;
}
match p.get("view") {
None | Some(Value::Null) => {}
Some(v) => {
let (_, _, x, y) = v
.as_str()
.and_then(|v| VIEWS.iter().find(|view| view.1 == v))
.ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::<Vec<_>>().join(", ")))?;
(set.rotate_x, set.rotate_y) = (*x, *y);
}
}
if let Some(x) = number("rotateX", -180.0, 180.0)? {
set.rotate_x = x;
}
if let Some(y) = number("rotateY", -180.0, 180.0)? {
set.rotate_y = y;
}
if let Some(z) = number("zoom", 0.1, 8.0)? {
set.zoom = z;
}
if let Some(v) = number("perspective", 0.0, 160.0)? {
set.perspective = v;
}
match p.get("inside") {
None | Some(Value::Null) => {}
Some(v) => {
let inside = v.as_str().filter(|inside| {
inside.is_empty()
|| app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some()
|| (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some())
});
let Some(inside) = inside else {
return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}"));
};
set.inside = inside.to_string();
}
}
match p.get("showFoldLines") {
None | Some(Value::Null) => {}
Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?,
}
match p.get("base") {
None => {}
Some(Value::Null) => set.base = None,
Some(v) => {
let a = v.as_array().filter(|a| a.len() == 2);
let xy: Option<Vec<f64>> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect());
let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) };
let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default();
if pick(&blanks, Some(Point::new(x, y))).is_none() {
return Err("`base` is in no panel".into());
}
set.base = Some([x, y]);
}
}
if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) {
set.pan = [0.0; 2];
}
app.ui.fold_preview = set;
crate::panel_docking::reveal_panel(app, ID)?;
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
Ok(state(app))
}
/// The window's settings and the last frame's size and times.
fn state(app: &VectorcraftApp) -> Value {
let frame = CACHE.with(|c| c.borrow().frame);
let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default();
if let Some(o) = out.as_object_mut() {
o.insert(
"frame".into(),
frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})),
);
}
out
}
/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset.
fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) {
ui.horizontal_wrapped(|ui| {
let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect();
let current = set.view().map_or("", |v| v.0);
if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0)
&& let Some(&(_, _, x, y)) = VIEWS.get(i)
{
(set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]);
}
let swatches: Vec<String> = app.session.active().map_or_else(Vec::new, |st| {
st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect()
});
let mut names: Vec<&str> = vec![tl!("White")];
names.extend(swatches.iter().map(String::as_str));
let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() };
ui.label(tl!("Inside"));
if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) {
set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default();
}
if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) {
set.show_fold_lines = !set.show_fold_lines;
}
if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() {
let fresh = Settings::default();
(set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0);
}
});
ui.horizontal(|ui| {
ui.label(tl!("Perspective"));
widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0));
});
}
/// The Fold and Zoom sliders.
fn sliders(ui: &mut Ui, set: &mut Settings) {
ui.horizontal(|ui| {
ui.label(tl!("Fold"));
let mut percent = set.amount * 100.0;
if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() {
set.amount = (percent / 100.0).clamp(0.0, 1.0);
}
});
ui.horizontal(|ui| {
ui.label(tl!("Zoom"));
let mut percent = set.zoom * 100.0;
if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() {
set.zoom = (percent / 100.0).clamp(0.1, 8.0);
}
});
}
/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the
/// base panel of `blank` (the blank `key` folds) on a double-click.
fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) {
if response.clicked() || response.drag_started() {
response.request_focus();
}
let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space)));
let delta = response.drag_delta();
if delta != egui::Vec2::ZERO {
if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) {
set.pan[0] += f64::from(delta.x);
set.pan[1] += f64::from(delta.y);
} else if response.dragged_by(egui::PointerButton::Primary) {
let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y));
if shift {
if dx.abs() >= dy.abs() {
dy = 0.0;
} else {
dx = 0.0;
}
}
set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN);
set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN);
}
}
if response.hovered() {
let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0));
if scroll != 0.0 {
set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0);
}
}
if response.has_focus() {
// The view keeps the arrow keys, so they turn it rather than move the focus on.
ui.memory_mut(|m| {
m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
});
let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN;
let (left, right, up, down) =
(presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown));
if left + right + up + down > 0.0 {
set.rotate_y = wrapped(set.rotate_y + right - left);
set.rotate_x = wrapped(set.rotate_x + down - up);
}
}
if response.double_clicked()
&& let Some(pos) = response.interact_pointer_pos()
&& let Some((blank, key)) = blank
{
// The image on screen is the last one drawn; its panel numbers are used only while it shows
// the same blank of the same document revision.
let picked = CACHE.with(|c| {
let c = c.borrow();
let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2));
if shown != Some((key.0, key.1, key.2)) {
return None;
}
let (img, rect) = c.image.as_ref()?;
let x = (pos.x - rect.left()) / rect.width() * img.width as f32;
let y = (pos.y - rect.top()) / rect.height() * img.height as f32;
img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32)
});
if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) {
set.base = Some([p.x, p.y]);
}
}
}
/// The status line under the view, in English (shown translated).
fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec<String> {
let Some((blank, f)) = folded else {
return vec!["Check the fold lines first.".into()];
};
let mut out = vec![crate::i18n::fmt(
"Panels: {panels}, hinges: {hinges}",
&[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())],
)];
if errors {
out.push("Check the fold lines first.".into());
}
if blanks > 1 {
out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())]));
}
if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) {
out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))]));
}
if !f.collisions.is_empty() {
out.push("Two panels pass through each other.".into());
}
out
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(st) = app.session.active() else {
crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape."));
return;
};
let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone());
let mut set = app.ui.fold_preview.clone().clamped();
toolbar(app, ui, &mut set);
let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc));
let base_point = set.base.map(|[x, y]| Point::new(x, y));
let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None));
let folded = picked.and_then(|(b, panel)| {
let blank = blanks.get(b)?;
let key = (uid, revision, b, panel, set.amount.to_bits());
let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?;
Some((blank, f, key, ms))
});
let bottom = ui.spacing().interact_size.y * 3.0 + 12.0;
let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0));
let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag());
let view_name = set.view().map_or("", |v| v.0);
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview"));
info.current_text_value = Some(crate::i18n::t(view_name).to_string());
info
});
interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key)));
let t = crate::theme::Tokens::get(ui.ctx());
ui.painter().rect_filled(rect, 2.0, t.pasteboard);
if let Some((blank, f, key, fold_ms)) = &folded {
draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms);
}
if response.has_focus() {
ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
}
for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) {
dim_label(ui, &crate::i18n::msg(&line));
}
sliders(ui, &mut set);
if set != app.ui.fold_preview {
app.ui.fold_preview = set;
}
}
/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image
/// is rendered again only when the fold, the view, the inside color or the print changed.
#[allow(clippy::too_many_arguments)]
fn draw(ui: &Ui, rect: Rect, doc: &Arc<vectorcraft_engine::doc::Document>, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) {
// Pixels per point of the view, lowered when the window has more pixels than the view may have
// in all or along either side, so the image keeps the window's proportions.
let (w, h) = (f64::from(rect.width()), f64::from(rect.height()));
let mut ppp = f64::from(ui.ctx().pixels_per_point());
let area = w * h * ppp * ppp;
if area > f64::from(MAX_PIXELS) {
ppp *= (f64::from(MAX_PIXELS) / area).sqrt();
}
ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0));
let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE);
let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE);
let Some((lo, hi)) = raster::bounds(blank, f) else { return };
let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0];
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0;
let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6);
if set.perspective > 0.0 {
// The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in
// front of it.
let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan();
fit = fit.min(focal / (2.0 * radius.max(1e-6)));
}
let camera = Camera {
width,
height,
rotate_x: set.rotate_x,
rotate_y: set.rotate_y,
scale: fit * set.zoom,
pan: [set.pan[0] * ppp, set.pan[1] * ppp],
perspective: set.perspective,
center,
};
let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]);
// While the print of a new revision renders, the last one of the same blank and setting is
// drawn; a print of another document, blank or Show Fold Lines setting is not.
let print = CACHE.with(|c| {
let mut c = c.borrow_mut();
let region = print_region(blank)?;
let (pw, ph, scale) = print_size(region);
let pkey = PrintKey {
uid: key.0,
revision: key.1,
fold_lines: set.show_fold_lines,
region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()],
width: pw,
height: ph,
};
c.update_print(ui.ctx(), doc, pkey, region, scale);
c.print_for(&pkey)
});
let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) };
let kept = CACHE.with(|c| {
let mut c = c.borrow_mut();
let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false };
ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
if let Some((_, at)) = &mut c.image {
*at = rect;
}
true
});
if kept {
return;
}
let t0 = crate::now_ms();
let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera };
let Some(img) = raster::render(&scene) else { return };
let draw_ms = crate::now_ms() - t0;
let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
CACHE.with(|c| {
let mut c = c.borrow_mut();
c.drawn = Some(draw_key);
c.renders += 1;
match &mut c.tex {
Some(tex) => tex.set(color, egui::TextureOptions::LINEAR),
None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)),
}
if let Some(tex) = &c.tex {
let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
ui.painter().image(tex.id(), rect, uv, Color32::WHITE);
}
c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms });
c.image = Some((img, rect));
});
}
#[cfg(test)]
pub(crate) fn prints_rendered() -> u64 {
CACHE.with(|c| c.borrow().prints)
}
#[cfg(test)]
pub(crate) fn last_image() -> Option<Image> {
CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone()))
}
/// The folds worked out and the images rendered so far.
#[cfg(test)]
pub(crate) fn work_done() -> (u64, u64) {
CACHE.with(|c| (c.borrow().folds, c.borrow().renders))
}
/// The screen rect the last image filled.
#[cfg(test)]
pub(crate) fn last_rect() -> Option<Rect> {
CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,505 @@
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use std::sync::Arc;
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done};
use crate::{VectorcraftApp, menus};
/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each
/// side) and a red square printed on the base, nothing selected → (app, the red square's id).
fn app() -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = [
path(&mut app, "M140 140 L240 140"),
path(&mut app, "M240 140 L240 240"),
path(&mut app, "M240 240 L140 240"),
path(&mut app, "M140 240 L140 140"),
];
app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap();
let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [red] })).unwrap();
app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap();
app.run("paint.setStroke", json!({ "none": true })).unwrap();
app.run("object.arrange.sendToBack", json!({})).unwrap();
app.run("select.none", json!({})).unwrap();
(app, red)
}
/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first).
fn frame(app: &mut VectorcraftApp) {
frame_at(app, 1.0);
}
/// [`frame`] at `zoom` pixels per point.
fn frame_at(app: &mut VectorcraftApp, zoom: f32) {
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
ctx.set_pixels_per_point(zoom);
crate::theme::install_fonts(&ctx);
for time in [0.0, 1.0] {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0));
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
}
}
fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] {
let i = (y * img.width + x) as usize * 4;
[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]
}
/// The color at the middle of the window's last image.
fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] {
color_at(img, img.width / 2, img.height / 2)
}
#[test]
fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() {
let (mut app, _) = app();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed");
assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({})));
assert!(!crate::panel_docking::showing(&app.ui, ID));
menus::invoke(&mut app, "ui.foldPreview", json!({}));
assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens");
menus::invoke(&mut app, "ui.foldPreview", json!({}));
assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open");
let text = crate::tests_labels::painted_text(&mut app, super::super::show);
assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}");
}
#[test]
fn ui_fold_preview_sets_the_window_and_refuses_bad_values() {
let (mut app, _) = app();
let r = app
.run(
"ui.foldPreview",
json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}),
)
.unwrap();
let want = Settings {
amount: 0.5,
rotate_x: 90.0,
rotate_y: 0.0,
zoom: 2.0,
pan: [0.0; 2],
perspective: 40.0,
inside: "#00ff00".into(),
show_fold_lines: true,
base: Some([120.0, 190.0]),
};
assert_eq!(app.ui.fold_preview, want);
assert_eq!(r["rotateX"], 90.0, "{r}");
assert!(r.get("frame").is_some(), "{r}");
app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap();
assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None));
let kept = app.ui.fold_preview.clone();
for (p, want) in [
(json!({"amount": 2}), "`amount` must be a number from 0 to 1"),
(json!({"amount": "half"}), "`amount` must be a number from 0 to 1"),
(json!({"view": "sideways"}), "`view` must be one of"),
(json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"),
(json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"),
(json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"),
(json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"),
(json!({"inside": 7}), "`inside` must be #rrggbb"),
(json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"),
(json!({"base": [1, "2"]}), "`base` must be a point"),
(json!({"base": [5, 5]}), "`base` is in no panel"),
(json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"),
] {
let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing");
}
// A swatch with a plain color names the inside.
app.run("ui.foldPreview", json!({"inside": "White"})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "White");
// So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same.
app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap();
app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap();
app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "#brand");
let doc = &app.session.active().expect("a document").doc;
assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255]));
assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255]));
assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255]));
// White, the default, stays white beside a swatch named #ffffff.
app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap();
let doc = &app.session.active().expect("a document").doc;
assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4]));
assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255]));
app.run("ui.foldPreview", json!({"inside": ""})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "");
}
#[test]
fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() {
let (mut app, _) = app();
// Flat, from the front: the base's print, red, fills the middle.
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
let before = prints_rendered();
frame(&mut app);
assert!(prints_rendered() > before, "the print is rendered on this thread without a worker");
let img = last_image().expect("a frame");
let [r, g, b, a] = middle(&img);
assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]);
let state = app.run("ui.foldPreview", json!({})).unwrap();
assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height))));
// From the back, the base's inside shows in the inside color.
app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap();
frame(&mut app);
let [r, g, b, _] = middle(&last_image().expect("a frame"));
assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]);
// Folded and seen from the front, the walls stand edge on: the base fills the same place.
app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap();
frame(&mut app);
let img = last_image().expect("a frame");
let [r, ..] = middle(&img);
assert!(r > 150, "the base still shows its print: {:?}", middle(&img));
// The same print is not rendered again while the document does not change.
let prints = prints_rendered();
frame(&mut app);
assert_eq!(prints_rendered(), prints);
}
#[test]
fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() {
let (mut app, _) = app();
// Without perspective, the base and the two walls behind it that face the viewer show.
let mut flat = None;
for perspective in [0, 60, 160] {
app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap();
frame(&mut app);
let img = last_image().expect("a frame");
let mut shown: Vec<usize> =
(0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect();
shown.sort_unstable();
shown.dedup();
let flat = flat.get_or_insert_with(|| shown.clone());
assert_eq!(flat.len(), 3);
assert_eq!(&shown, flat, "{perspective}°: the same panels show");
let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)]));
assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view");
}
}
#[test]
fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
frame_at(&mut app, 8.0);
let img = last_image().expect("a frame");
assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height);
assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width);
let [r, ..] = middle(&img);
assert!(r > 150, "the base's print shows: {:?}", middle(&img));
}
#[test]
fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() {
let (mut app, red) = app();
// Without the red square, the base's middle shows the board with no art; with a crease drawn
// across the middle and the fold lines shown, the crease's color shows there.
app.run("select.set", json!({ "ids": [red] })).unwrap();
app.run("edit.clear", json!({})).unwrap();
let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap();
app.run("select.set", json!({ "ids": [mid] })).unwrap();
app.run("stroke.set", json!({ "weight": 20 })).unwrap();
app.run("select.none", json!({})).unwrap();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap();
frame(&mut app);
let plain = middle(&last_image().expect("a frame"));
app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap();
frame(&mut app);
let lined = middle(&last_image().expect("a frame"));
assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on");
assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}");
}
#[test]
fn the_window_says_when_there_is_nothing_to_fold() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Check the fold lines first."), "{text}");
let mut none = VectorcraftApp::new(Session::new(), Default::default());
let text = crate::tests_labels::painted_text(&mut none, show);
assert!(text.contains("Open a document to preview its folded shape."), "{text}");
}
#[test]
fn the_settings_are_kept_with_the_ui_state() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap();
let saved: Value = serde_json::to_value(&app.ui).unwrap();
assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]);
let back: crate::state::UiState = serde_json::from_value(saved).unwrap();
assert_eq!(back.fold_preview, app.ui.fold_preview);
}
#[test]
fn saved_settings_out_of_range_are_brought_into_range() {
let (mut app, _) = app();
app.ui.fold_preview = Settings {
amount: 3.0,
rotate_x: 200.0,
rotate_y: 180.0,
zoom: 0.0,
pan: [f64::NAN, 4.0],
perspective: -5.0,
base: Some([f64::INFINITY, 0.0]),
..Settings::default()
};
frame(&mut app);
let set = &app.ui.fold_preview;
assert_eq!(
(set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base),
(1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None)
);
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}");
assert!(last_image().is_some(), "and is drawn");
}
/// A window kept open over frames, as the app draws it.
struct View {
ctx: egui::Context,
time: f64,
}
impl View {
fn new(app: &mut VectorcraftApp) -> Self {
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut v = View { ctx, time: 0.0 };
v.idle(app);
v
}
fn step(&mut self, app: &mut VectorcraftApp, events: Vec<Event>, modifiers: Modifiers) {
self.time += 0.05;
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0));
let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() };
let mut out = self.ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
}
fn idle(&mut self, app: &mut VectorcraftApp) {
for _ in 0..3 {
self.step(app, vec![], Modifiers::NONE);
}
}
/// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`.
fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) {
let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers };
self.step(app, vec![Event::PointerMoved(at)], modifiers);
self.step(app, vec![press(at, true)], modifiers);
for k in 1..=4 {
self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers);
}
self.step(app, vec![press(at + by, false)], modifiers);
self.idle(app);
}
fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) {
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE);
self.step(app, vec![press(true)], Modifiers::NONE);
self.step(app, vec![press(false)], Modifiers::NONE);
}
fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) {
let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
self.step(app, vec![press], Modifiers::NONE);
self.step(app, vec![], Modifiers::NONE);
}
}
/// The app showing the tray flat from the front, in a [`View`], and the middle of the view.
fn front_view() -> (VectorcraftApp, View, Pos2) {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
let view = View::new(&mut app);
let at = last_rect().expect("the view is drawn").center();
(app, view, at)
}
#[test]
fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() {
let (mut app, mut view, at) = front_view();
view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE);
let set = app.ui.fold_preview.clone();
assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}");
assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}");
app.run("ui.foldPreview", json!({"view": "front"})).unwrap();
view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT);
let set = app.ui.fold_preview.clone();
assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}");
}
#[test]
fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() {
let (mut app, mut view, at) = front_view();
view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE);
let set = app.ui.fold_preview.clone();
assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}");
assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn");
let wheel = Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, 60.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
};
view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE);
for _ in 0..20 {
view.step(&mut app, vec![], Modifiers::NONE);
}
assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview);
}
#[test]
fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() {
let (mut app, mut view, at) = front_view();
view.click(&mut app, at);
view.idle(&mut app);
// Up first: the toolbar is above the view, where the focus would go if the view let it.
view.key(&mut app, egui::Key::ArrowUp);
view.key(&mut app, egui::Key::ArrowRight);
view.key(&mut app, egui::Key::ArrowRight);
let set = &app.ui.fold_preview;
assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°");
// A focused view seen from the back stays there until a key turns it.
app.run("ui.foldPreview", json!({"view": "back"})).unwrap();
view.idle(&mut app);
assert_eq!(app.ui.fold_preview.rotate_y, 180.0);
}
#[test]
fn a_double_click_on_a_panel_makes_it_the_base() {
let (mut app, mut view, at) = front_view();
// The left wall is the base; the middle of the view shows the tray's base panel.
app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap();
view.idle(&mut app);
view.click(&mut app, at);
view.click(&mut app, at);
let [x, y] = app.ui.fold_preview.base.expect("a base");
assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}");
}
#[test]
fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() {
let (mut app, mut view, at) = front_view();
app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap();
view.idle(&mut app);
view.click(&mut app, at);
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
view.step(&mut app, vec![press(true)], Modifiers::NONE);
// The document changes between the image on screen and the release that ends the double-click.
app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap();
view.step(&mut app, vec![press(false)], Modifiers::NONE);
assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept");
}
#[test]
fn the_view_is_folded_and_drawn_again_only_when_something_changes() {
let (mut app, mut view, _) = front_view();
let (folds, renders) = work_done();
view.idle(&mut app);
assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render");
app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap();
view.idle(&mut app);
assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again");
app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap();
view.idle(&mut app);
assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once");
}
#[test]
fn a_short_wide_window_keeps_its_proportions() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
ctx.set_pixels_per_point(2.0);
crate::theme::install_fonts(&ctx);
for time in [0.0, 1.0] {
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0));
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(&mut app, ui));
out.textures_delta.clear();
}
let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect"));
let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height()));
assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width);
assert!((image - window).abs() / window < 0.02, "image {image}, window {window}");
}
#[test]
fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() {
let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 };
let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0);
let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print");
let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() };
assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print");
for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] {
assert!(cache.print_for(&other).is_none(), "{other:?}");
}
}
#[test]
fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge};
let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap };
let f = Folded {
base: 0,
panels: vec![],
order: vec![],
hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)],
collisions: vec![(0, 1)],
};
let lines = status(3, Some((&Blank::default(), &f)), true);
assert_eq!(
lines,
[
"Panels: 0, hinges: 0",
"Check the fold lines first.",
"Other blanks not shown: 2",
"A joint does not close by 12.3 pt.",
"Two panels pass through each other."
]
);
let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f };
assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]);
}
#[test]
fn the_window_says_when_folded_panels_pass_through_each_other() {
// A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded
// about the base, the lid crosses the taller wall.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z");
let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")];
app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap();
app.run("select.none", json!({})).unwrap();
app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Two panels pass through each other."), "{text}");
assert!(!text.contains("A joint does not close"), "{text}");
}
+10
View File
@@ -7313,4 +7313,14 @@ breakText Glyphs Глифи
@msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане.
@msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings}
Fold Preview Преглед на сгъването
Fold Сгъване
Show Fold Lines Покажи линиите на сгъване
Three-Quarter Три четвърти
Open a document to preview its folded shape. Отворете документ, за да прегледате сгънатата му форма.
@msg Check the fold lines first. Първо проверете линиите на сгъване.
@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, панти: {hinges}
@msg Other blanks not shown: {count} Други разкрои не са показани: {count}
@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt.
@msg Two panels pass through each other. Два панела минават един през друг.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+10
View File
@@ -7368,4 +7368,14 @@ shape Open Otvoren
@msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja.
@msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings}
Fold Preview Pregled savijanja
Fold Savijanje
Show Fold Lines Prikaži linije savijanja
Three-Quarter Tri četvrtine
Open a document to preview its folded shape. Otvorite dokument da pregledate njegov savijeni oblik.
@msg Check the fold lines first. Prvo provjerite linije savijanja.
@msg Panels: {panels}, hinges: {hinges} Paneli: {panels}, šarke: {hinges}
@msg Other blanks not shown: {count} Ostali krojevi nisu prikazani: {count}
@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt.
@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -8247,4 +8247,14 @@ breakText Glyphs Glifs
@msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit.
@msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings}
Fold Preview Previsualització del plegat
Fold Plegat
Show Fold Lines Mostra les línies de plegat
Three-Quarter Tres quarts
Open a document to preview its folded shape. Obre un document per previsualitzar-ne la forma plegada.
@msg Check the fold lines first. Primer comprova les línies de plegat.
@msg Panels: {panels}, hinges: {hinges} Panells: {panels}, frontisses: {hinges}
@msg Other blanks not shown: {count} Altres troquelats no mostrats: {count}
@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt.
@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -10042,3 +10042,13 @@ breakText Glyphs Glyfy
@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu.
@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings}
Fold Preview Náhled skládání
Fold Složení
Show Fold Lines Zobrazit linie skladu
Three-Quarter Tři čtvrtě
Open a document to preview its folded shape. Otevřete dokument, abyste zobrazili náhled jeho složeného tvaru.
@msg Check the fold lines first. Nejprve zkontrolujte linie skladu.
@msg Panels: {panels}, hinges: {hinges} Panely: {panels}, panty: {hinges}
@msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count}
@msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt.
@msg Two panels pass through each other. Dva panely procházejí jeden druhým.
Can't render this file because it is too large.
+10
View File
@@ -10140,4 +10140,14 @@ breakText Glyphs Glyffer
@msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje.
@msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings}
Fold Preview Forhåndsvisning af foldning
Fold Foldning
Show Fold Lines Vis foldelinjer
Three-Quarter Trekvart
Open a document to preview its folded shape. Åbn et dokument for at se dets foldede form.
@msg Check the fold lines first. Kontrollér foldelinjerne først.
@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, hængsler: {hinges}
@msg Other blanks not shown: {count} Andre emner vises ikke: {count}
@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt.
@msg Two panels pass through each other. To paneler går gennem hinanden.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
Can't render this file because it is too large.
+10
View File
@@ -9644,3 +9644,13 @@ breakText Glyphs Glyphen
@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden.
@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings}
Fold Preview Faltvorschau
Fold Falten
Show Fold Lines Faltlinien einblenden
Three-Quarter Dreiviertelansicht
Open a document to preview its folded shape. Öffnen Sie ein Dokument, um seine gefaltete Form in der Vorschau zu sehen.
@msg Check the fold lines first. Prüfen Sie zuerst die Faltlinien.
@msg Panels: {panels}, hinges: {hinges} Felder: {panels}, Scharniere: {hinges}
@msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count}
@msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht.
@msg Two panels pass through each other. Zwei Felder durchdringen einander.
Can't render this file because it is too large.
+10
View File
@@ -8221,4 +8221,14 @@ breakText Glyphs Γλύφοι
@msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης.
@msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings}
Fold Preview Προεπισκόπηση δίπλωσης
Fold Δίπλωση
Show Fold Lines Εμφάνιση γραμμών δίπλωσης
Three-Quarter Τρία τέταρτα
Open a document to preview its folded shape. Ανοίξτε ένα έγγραφο για να δείτε σε προεπισκόπηση το διπλωμένο σχήμα του.
@msg Check the fold lines first. Ελέγξτε πρώτα τις γραμμές δίπλωσης.
@msg Panels: {panels}, hinges: {hinges} Πάνελ: {panels}, μεντεσέδες: {hinges}
@msg Other blanks not shown: {count} Άλλα αναπτύγματα δεν εμφανίζονται: {count}
@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt.
@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine"
Can't render this file because it is too large.
+10
View File
@@ -8208,4 +8208,14 @@ breakText Glyphs Glifos
@msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido.
@msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings}
Fold Preview Vista previa del plegado
Fold Plegado
Show Fold Lines Mostrar líneas de plegado
Three-Quarter Tres cuartos
Open a document to preview its folded shape. Abre un documento para previsualizar su forma plegada.
@msg Check the fold lines first. Comprueba primero las líneas de plegado.
@msg Panels: {panels}, hinges: {hinges} Paneles: {panels}, bisagras: {hinges}
@msg Other blanks not shown: {count} Otros troquelados no mostrados: {count}
@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt.
@msg Two panels pass through each other. Dos paneles se atraviesan entre sí.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -8304,4 +8304,14 @@ breakText Glyphs Merkit
@msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla.
@msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings}
Fold Preview Taiton esikatselu
Fold Taitto
Show Fold Lines Näytä taittoviivat
Three-Quarter Kolme neljäsosaa
Open a document to preview its folded shape. Avaa asiakirja, niin voit esikatsella sen taitettua muotoa.
@msg Check the fold lines first. Tarkista ensin taittoviivat.
@msg Panels: {panels}, hinges: {hinges} Paneelit: {panels}, saranat: {hinges}
@msg Other blanks not shown: {count} Muita aihioita ei näytetä: {count}
@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt.
@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -10026,4 +10026,14 @@ breakText Glyphs Glyphes
@msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage.
@msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s)
Fold Preview Aperçu du pliage
Fold Pliage
Show Fold Lines Afficher les lignes de pliage
Three-Quarter Trois-quarts
Open a document to preview its folded shape. Ouvrez un document pour prévisualiser sa forme pliée.
@msg Check the fold lines first. Vérifiez d’abord les lignes de pliage.
@msg Panels: {panels}, hinges: {hinges} {panels} panneau(x), {hinges} charnière(s)
@msg Other blanks not shown: {count} {count} autre(s) flan(s) non affiché(s)
@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt.
@msg Two panels pass through each other. Deux panneaux se traversent.
@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution
Can't render this file because it is too large.
+10
View File
@@ -5052,6 +5052,16 @@ swatch [Registration] [રજિસ્ટ્રેશન]
@msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી.
@msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings}
Fold Preview ફોલ્ડ પ્રિવ્યૂ
Fold ફોલ્ડ
Show Fold Lines ફોલ્ડ લાઇન્સ બતાવો
Three-Quarter ત્રણ-ચતુર્થાંશ
Open a document to preview its folded shape. તેનો ફોલ્ડ કરેલો આકાર જોવા દસ્તાવેજ ખોલો.
@msg Check the fold lines first. પહેલાં ફોલ્ડ લાઇન્સ ચેક કરો.
@msg Panels: {panels}, hinges: {hinges} પેનલ: {panels}, હિન્જ: {hinges}
@msg Other blanks not shown: {count} બીજા બ્લેન્ક બતાવ્યા નથી: {count}
@msg A joint does not close by {gap} pt. એક સાંધો {gap} pt થી બંધ થતો નથી.
@msg Two panels pass through each other. બે પેનલ એકબીજામાંથી પસાર થાય છે.
Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
Can't render this file because it contains an unexpected character in line 72 and column 5.
+10
View File
@@ -9650,3 +9650,13 @@ theme Appearance अपीयरेंस
@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है।
@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है।
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings}
Fold Preview फ़ोल्ड प्रीव्यू
Fold फ़ोल्ड
Show Fold Lines फ़ोल्ड लाइनें दिखाएँ
Three-Quarter तीन-चौथाई
Open a document to preview its folded shape. इसका फ़ोल्ड किया हुआ आकार देखने के लिए कोई डॉक्यूमेंट ओपन करें।
@msg Check the fold lines first. पहले फ़ोल्ड लाइनें चेक करें।
@msg Panels: {panels}, hinges: {hinges} पैनल: {panels}, हिंज: {hinges}
@msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count}
@msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता।
@msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं।
Can't render this file because it is too large.
+10
View File
@@ -10030,3 +10030,13 @@ breakText Glyphs Glifák
@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez.
@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings}
Fold Preview Hajtás előnézete
Fold Hajtás
Show Fold Lines Hajtásvonalak megjelenítése
Three-Quarter Háromnegyed
Open a document to preview its folded shape. Nyiss meg egy dokumentumot a hajtogatott alakja előnézetéhez.
@msg Check the fold lines first. Előbb ellenőrizd a hajtásvonalakat.
@msg Panels: {panels}, hinges: {hinges} Panelek: {panels}, zsanérok: {hinges}
@msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count}
@msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik.
@msg Two panels pass through each other. Két panel áthatol egymáson.
Can't render this file because it is too large.
+10
View File
@@ -7330,4 +7330,14 @@ breakText Glyphs Glif
@msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun.
@msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings}
Fold Preview Pratinjau lipatan
Fold Lipat
Show Fold Lines Tampilkan garis lipat
Three-Quarter Tiga perempat
Open a document to preview its folded shape. Buka dokumen untuk melihat pratinjau bentuk terlipatnya.
@msg Check the fold lines first. Periksa garis lipat terlebih dahulu.
@msg Panels: {panels}, hinges: {hinges} Panel: {panels}, engsel: {hinges}
@msg Other blanks not shown: {count} Bentangan lain tidak ditampilkan: {count}
@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt.
@msg Two panels pass through each other. Dua panel saling menembus.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2528 and column 5.
+10
View File
@@ -9679,3 +9679,13 @@ breakText Glyphs Glifi
@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura.
@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings}
Fold Preview Anteprima piegatura
Fold Piegatura
Show Fold Lines Mostra linee di piega
Three-Quarter Tre quarti
Open a document to preview its folded shape. Apri un documento per vederne in anteprima la forma piegata.
@msg Check the fold lines first. Verifica prima le linee di piega.
@msg Panels: {panels}, hinges: {hinges} Pannelli: {panels}, cerniere: {hinges}
@msg Other blanks not shown: {count} Altri fustellati non mostrati: {count}
@msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt.
@msg Two panels pass through each other. Due pannelli si attraversano.
Can't render this file because it is too large.
+10
View File
@@ -9746,3 +9746,13 @@ breakText Glyphs 字形
@msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。
@msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings}
Fold Preview 折りプレビュー
Fold 折り
Show Fold Lines 折り線を表示
Three-Quarter 斜め
Open a document to preview its folded shape. ドキュメントを開くと折った形をプレビューできます。
@msg Check the fold lines first. 先に折り線をチェックしてください。
@msg Panels: {panels}, hinges: {hinges} パネル: {panels}、ヒンジ: {hinges}
@msg Other blanks not shown: {count} 表示されていない他の展開図: {count}
@msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。
@msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。
Can't render this file because it is too large.
+10
View File
@@ -10399,4 +10399,14 @@ font-script Japanese იაპონური
@msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება.
@msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings}
Fold Preview მოკეცვის გადახედვა
Fold მოკეცვა
Show Fold Lines მოკეცვის ხაზების ჩვენება
Three-Quarter სამი მეოთხედი
Open a document to preview its folded shape. გახსენით დოკუმენტი მისი მოკეცილი ფორმის სანახავად.
@msg Check the fold lines first. ჯერ შეამოწმეთ მოკეცვის ხაზები.
@msg Panels: {panels}, hinges: {hinges} პანელები: {panels}, ანჯამები: {hinges}
@msg Other blanks not shown: {count} სხვა ნამზადები არ ჩანს: {count}
@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით.
@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის.
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine"
Can't render this file because it is too large.
+10
View File
@@ -9643,3 +9643,13 @@ breakText Glyphs 글리프
@msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다.
@msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings}
Fold Preview 접기 미리 보기
Fold 접기
Show Fold Lines 접는 선 표시
Three-Quarter 3/4 보기
Open a document to preview its folded shape. 접은 모양을 미리 보려면 문서를 여세요.
@msg Check the fold lines first. 먼저 접는 선을 검사하세요.
@msg Panels: {panels}, hinges: {hinges} 패널: {panels}, 힌지: {hinges}
@msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count}
@msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다.
@msg Two panels pass through each other. 두 패널이 서로 관통합니다.
Can't render this file because it is too large.
+10
View File
@@ -10079,3 +10079,13 @@ breakText Glyphs Glyphs
@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden.
@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings}
Fold Preview Vouwvoorbeeld
Fold Vouwen
Show Fold Lines Vouwlijnen tonen
Three-Quarter Driekwart
Open a document to preview its folded shape. Open een document om de gevouwen vorm te bekijken.
@msg Check the fold lines first. Controleer eerst de vouwlijnen.
@msg Panels: {panels}, hinges: {hinges} Panelen: {panels}, scharnieren: {hinges}
@msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count}
@msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet.
@msg Two panels pass through each other. Twee panelen gaan door elkaar heen.
Can't render this file because it is too large.
+10
View File
@@ -9902,3 +9902,13 @@ breakText Glyphs Glify
@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania.
@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings}
Fold Preview Podgląd złożenia
Fold Złożenie
Show Fold Lines Pokaż linie zgięcia
Three-Quarter Trzy czwarte
Open a document to preview its folded shape. Otwórz dokument, aby zobaczyć podgląd jego złożonego kształtu.
@msg Check the fold lines first. Najpierw sprawdź linie zgięcia.
@msg Panels: {panels}, hinges: {hinges} Panele: {panels}, zawiasy: {hinges}
@msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count}
@msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt.
@msg Two panels pass through each other. Dwa panele przechodzą przez siebie.
Can't render this file because it is too large.
+10
View File
@@ -10113,3 +10113,13 @@ swatch Yellow Green Verde-amarelado
@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco.
@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings}
Fold Preview Visualização da Dobra
Fold Dobra
Show Fold Lines Mostrar Linhas de Dobra
Three-Quarter Três Quartos
Open a document to preview its folded shape. Abra um documento para visualizar sua forma dobrada.
@msg Check the fold lines first. Verifique primeiro as linhas de dobra.
@msg Panels: {panels}, hinges: {hinges} Painéis: {panels}, dobradiças: {hinges}
@msg Other blanks not shown: {count} Outras planificações não exibidas: {count}
@msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt.
@msg Two panels pass through each other. Dois painéis se atravessam.
Can't render this file because it is too large.
+10
View File
@@ -10128,5 +10128,15 @@ shape Open Открытый
@msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки.
@msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings}
Fold Preview Предпросмотр сгиба
Fold Сгиб
Show Fold Lines Показать линии сгиба
Three-Quarter Три четверти
Open a document to preview its folded shape. Откройте документ, чтобы просмотреть его в сложенном виде.
@msg Check the fold lines first. Сначала проверьте линии сгиба.
@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, шарниры: {hinges}
@msg Other blanks not shown: {count} Другие развёртки не показаны: {count}
@msg A joint does not close by {gap} pt. Стык не смыкается на {gap} pt.
@msg Two panels pass through each other. Две панели проходят друг сквозь друга.
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+10
View File
@@ -9732,4 +9732,14 @@ digits Hindi Hindi
@msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje.
@msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings}
Fold Preview Förhandsgranskning av falsning
Fold Falsning
Show Fold Lines Visa falslinjer
Three-Quarter Trekvarts
Open a document to preview its folded shape. Öppna ett dokument för att förhandsgranska dess falsade form.
@msg Check the fold lines first. Kontrollera falslinjerna först.
@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, gångjärn: {hinges}
@msg Other blanks not shown: {count} Andra ämnen visas inte: {count}
@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt.
@msg Two panels pass through each other. Två paneler går igenom varandra.
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen
Can't render this file because it is too large.
+10
View File
@@ -10000,3 +10000,13 @@ breakText Glyphs Glifler
@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil.
@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings}
Fold Preview Katlama Önizlemesi
Fold Katlama
Show Fold Lines Katlama Çizgilerini Göster
Three-Quarter Dörtte Üç
Open a document to preview its folded shape. Katlanmış şeklini önizlemek için bir belgeyi açın.
@msg Check the fold lines first. Önce katlama çizgilerini denetleyin.
@msg Panels: {panels}, hinges: {hinges} Paneller: {panels}, menteşeler: {hinges}
@msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count}
@msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor.
@msg Two panels pass through each other. İki panel birbirinin içinden geçiyor.
Can't render this file because it is too large.
+10
View File
@@ -9655,3 +9655,13 @@ breakText Glyphs Гліфи
@msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки.
@msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings}
Fold Preview Перегляд згину
Fold Згин
Show Fold Lines Показати лінії згину
Three-Quarter Три чверті
Open a document to preview its folded shape. Відкрийте документ, щоб переглянути його у складеному вигляді.
@msg Check the fold lines first. Спершу перевірте лінії згину.
@msg Panels: {panels}, hinges: {hinges} Панелі: {panels}, шарніри: {hinges}
@msg Other blanks not shown: {count} Інші розгортки не показано: {count}
@msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt.
@msg Two panels pass through each other. Дві панелі проходять одна крізь одну.
Can't render this file because it is too large.
+10
View File
@@ -7766,6 +7766,16 @@ breakText Glyphs Glyph
@msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào.
@msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings}
Fold Preview Xem trước nếp gấp
Fold Gấp
Show Fold Lines Hiện đường gấp
Three-Quarter Ba phần tư
Open a document to preview its folded shape. Mở tài liệu để xem trước hình dạng đã gấp của nó.
@msg Check the fold lines first. Hãy kiểm tra đường gấp trước.
@msg Panels: {panels}, hinges: {hinges} Mặt: {panels}, bản lề: {hinges}
@msg Other blanks not shown: {count} Các khuôn trải khác không được hiển thị: {count}
@msg A joint does not close by {gap} pt. Một mối nối hở {gap} pt.
@msg Two panels pass through each other. Hai mặt xuyên qua nhau.
# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import.
@msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm
Can't render this file because it contains an unexpected character in line 206 and column 5.
+10
View File
@@ -9884,4 +9884,14 @@ breakText Glyphs 字形
@msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。
@msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings}
Fold Preview 折叠预览
Fold 折叠
Show Fold Lines 显示折线
Three-Quarter 四分之三视图
Open a document to preview its folded shape. 打开文档以预览其折叠后的形状。
@msg Check the fold lines first. 请先检查折线。
@msg Panels: {panels}, hinges: {hinges} 面板:{panels},铰链:{hinges}
@msg Other blanks not shown: {count} 未显示的其他展开图:{count}
@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。
@msg Two panels pass through each other. 两个面板相互穿插。
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率
Can't render this file because it is too large.
+10
View File
@@ -9696,4 +9696,14 @@ breakText Glyphs 字符
@msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。
@msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings}
Fold Preview 摺疊預覽
Fold 摺疊
Show Fold Lines 顯示摺線
Three-Quarter 四分之三視圖
Open a document to preview its folded shape. 開啟文件以預覽其摺疊後的形狀。
@msg Check the fold lines first. 請先檢查摺線。
@msg Panels: {panels}, hinges: {hinges} 面板:{panels},鉸鏈:{hinges}
@msg Other blanks not shown: {count} 未顯示的其他展開圖:{count}
@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。
@msg Two panels pass through each other. 兩個面板相互穿插。
@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小
Can't render this file because it is too large.
+1
View File
@@ -867,6 +867,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
}
"ui.imageTracePresetDialog" => crate::dialogs::trace_presets::open(app, p),
"ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p),
"ui.foldPreview" => crate::addons::packaging::preview::command(app, p),
"ui.copyScriptConsole" => crate::panels::script_console::copy(app, p),
"window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p),
"ui.libraryPanel" => crate::panels::library_panel::command(app, p),
+6
View File
@@ -1171,6 +1171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it",
),
(
"ui.foldPreview",
"Fold Preview",
"",
"{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null",
),
(
"ui.copyScriptConsole",
"Copy Script Console",
+1
View File
@@ -1378,6 +1378,7 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 {
// Tall enough to show its Corners and Shared Edges sections, last in it, which the Corner
// Tool's and Shared Edge Merge Tool's menu items open.
crate::addons::pathtools::ID => egui::vec2(260.0, 660.0),
crate::addons::packaging::preview::ID => egui::vec2(520.0, 440.0),
_ => egui::vec2(260.0, 360.0),
}
}
+1
View File
@@ -195,6 +195,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui),
crate::addons::color::ID => crate::addons::color::show(app, ui),
crate::addons::packaging::ID => crate::addons::packaging::show(app, ui),
crate::addons::packaging::preview::ID => crate::addons::packaging::preview::show(app, ui),
crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui),
crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui),
crate::addons::pen::ID => crate::addons::pen::show(app, ui),
+6
View File
@@ -228,6 +228,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
(crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"),
(crate::addons::color::ID, "Color Effects", "sun"),
(crate::addons::packaging::ID, "Fold Lines", "scissors"),
(crate::addons::packaging::preview::ID, "Fold Preview", "box"),
(crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"),
(crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"),
(crate::addons::pen::ID, "Smart Pen", "spline-pointer"),
@@ -719,6 +720,10 @@ pub struct UiState {
/// Flattener Preview panel: highlight, overprints, preset and options (`ui.flattenerPreview`).
#[serde(default)]
pub flattener_preview: crate::panels::flattener_preview::Settings,
/// Fold Preview window: fold amount, view, zoom, perspective, inside color, fold lines and
/// base panel (`ui.foldPreview`).
#[serde(default)]
pub fold_preview: crate::addons::packaging::preview::Settings,
/// Color Guide panel: Limit to Library, a swatch library id, "document" (the document's
/// swatches) or "" (none) (`ui.colorGuideLimit`).
#[serde(default)]
@@ -1259,6 +1264,7 @@ impl Default for UiState {
color_guide: Default::default(),
library_panels: vec![],
flattener_preview: Default::default(),
fold_preview: Default::default(),
color_guide_limit: String::new(),
color_guide_base: None,
color_guide_spot: None,
+52 -4
View File
@@ -13694,10 +13694,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la
## Packaging Tools add-on
Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are
`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the
desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line,
Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs
`addon.packaging.check`.
`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and
`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel,
Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the
selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`.
### Fold line roles
@@ -13793,6 +13793,54 @@ The list is shown until the document changes.
{"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}}
```
### Fold Preview
`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads
the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or
the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it
to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from
the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of
panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way,
whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of
hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything
else is an error. The command does not change the document.
Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b,
angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document
coordinates. `frame` gives where the flat blank's x and y directions, its printed side and its origin end up, in points,
with x to the right, y up and z toward the printed side of the flat blank. `kind` is `tree` for the hinges the panels
turn about and `closing` for the others. `collisions` lists the panels that pass through each other; panels stacked in
one plane, such as the top flaps of a closed box, are not listed. Without a blank (`ok` false), `blank` and `base` are
null and the lists are empty; `issues` are those of `addon.packaging.check`.
The Fold Preview window (Object › Plug-ins › Packaging Tools › Fold Preview, or the Fold Lines panel's Fold Preview
button) shows the blank that the document's shown fold lines make, folded, with the document's printed art on the
outside of each panel and the board's inside color on the back. The print leaves out the fold lines, unless Show Fold
Lines is on, and the layers that do not print. Under the view, the Fold slider sets the amount and the Zoom slider the
zoom; a status line gives the panels and hinges and says when a joint does not close, when two panels pass through each
other, when other blanks are not shown and when the fold lines have an error. Dragging in the view turns it, a
Shift-drag keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a panel makes it
the base, and the arrow keys turn the view by 5° when it has the keyboard focus. The view is drawn at the display's
pixel density up to 2,097,152 pixels (2,048 × 1,024) and 4,096 pixels along a side, and at a lower density past either,
and the print is a raster whose longest side is 2,048 pixels, rendered again when the document changes.
`ui.foldPreview` (`{amount?, view?: front|back|left|right|top|bottom|threeQuarter, rotateX?, rotateY?, zoom?,
perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the
window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side
toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to
160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`, or `""` for white; `base` is a point in a panel
of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice
the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing.
VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the
fold lines hidden. Saved settings out of range are brought into range when the window is drawn. Result: the window's
settings, and `frame`: the last frame's `{width, height}` in pixels and how long the fold and the drawing took (`foldMs`,
`drawMs`), or null before the first frame. The view is folded and drawn again only when the document, the settings or
the window's size change.
```json
{"name":"run_command","arguments":{"command":"ui.foldPreview","params":{"amount":0.5,"view":"threeQuarter","perspective":30}}}
```
## Image Tools add-on
Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`,