Preserve remaining Drawings original source proposals and canonical code index
Canonical preservation of W10, W21, X4 and supporting W38 source proposals. Sources remain deliberately unregistered and unexecuted, with real bases and alternatives documented in proposals/drawings/README.md. Existing contributor claims and PRs remain authoritative; this is not a merge-ready integration candidate.
This commit is contained in:
1 parent
d8e7a8690a
commit
0b3bc6e968
33 files changed
+5505
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# Preserve remaining Drawings original source proposals and canonical code index
|
||||
|
||||
Canonical preservation of W10, W21, X4 and supporting W38 source proposals. Sources remain deliberately unregistered and unexecuted, with real bases and alternatives documented in proposals/drawings/README.md. Existing contributor claims and PRs remain authoritative; this is not a merge-ready integration candidate.
|
||||
|
||||
This branch preserves unfinished work at Judit's request. It does not replace the existing contributor claims or PRs, and is not ready for merge. Original parent history and authorship are retained. No tests were run to create this preservation branch.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Drawings code checkpoints — 29 October 2026
|
||||
|
||||
All links below refer directly to branches in **tangency-labs/solidcraft**. Existing PRs remain the coordination/review threads. These snapshots preserve unfinished work at Judit's request; they do not create new claims, transfer ownership or imply readiness for merge.
|
||||
|
||||
| Unit | Canonical branch | Existing discussion | Qualification |
|
||||
| --- | --- | --- | --- |
|
||||
| X1 / #5318 | [X1 checkpoint](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-x1-checkpoint-20261029) | #6184 | Exact existing `3fb2eef9` head; draft/conflicted, original-output failure remains. |
|
||||
| X2 / #5319 | [X2 checkpoint](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-x2-checkpoint-20261029) | #8435 | Exact `fac00435`; preserve its failed wasm gate separately from later D8. |
|
||||
| X3 / #5320 and integrated X4 subset | [D8 checkpoint](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-x3-checkpoint-20261029) | #8515 | Exact `d8e7a869`; Windows local full gate passed: 82 native binaries, 9603 passed, 0 failed, 69 existing ignored; strict Clippy, wasm, docs and offline web passed. This evidence applies only to this exact source. Draft/unmerged. |
|
||||
| PDF / W22 P1/P3 + P2 original tests | [PDF P2 WIP](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-pdf-p2-wip-20261029) | #7626 and #4890 | `bf2a6fd5` preserves nine new P2 files on `506d4190`. 77 PDF test declarations, none executed on this new source. New dev dependency unresolved in Cargo.lock; production font/text integration pending. Parent history retains P1/P3. |
|
||||
| X2/X3 command follow-ups | [Tests and connect-only stage A](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-dxf-command-followups-wip-20261029) | #5319, #5320 | `8eec0bf6`: four files, static review only. Parent D8 results do not qualify this source. |
|
||||
| X2 conditional producer alternatives | [Owned-writer alternatives](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-dxf-owned-adapters-conditional-20261029) | #5319 comment6482559607 | `a211e61c`; NOT for integration before owner admission-policy decision. Unrun. |
|
||||
| PDF prerequisite | [Original serial-runner proposal](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-pdf-serial-runner-proposal-20261029) | #5425 comment6415005697 | `e65a33d3`; isolated original #5494 delta, pending owner response; unapplied to PDF and unrun. |
|
||||
| W38a | [Existing implementation](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-w38a-checkpoint-20261029) | #7608 | Exact `80e5bb34`; corrective five-file patch is preserved below, not applied to the PR or tested. |
|
||||
| W38d | [Existing implementation](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-w38d-checkpoint-20261029) | #7064 | Exact `5741c5d2`; D7 acceptance proposals below are unexecuted; no full-unit completion claim. |
|
||||
| W00b | [Existing documentation](https://github.com/tangency-labs/solidcraft/tree/codex/drawings-w00b-checkpoint-20261029) | #6163 | Exact `514ad79e`; validation route remains pending. |
|
||||
|
||||
## Unintegrated original sources in this branch
|
||||
|
||||
- [W10](W10/README.md): circular conversion helper, original tests, grid and Seg2 adapter proposals. Actual owner seam and integration remain pending.
|
||||
- [W21](W21/README.md): five original SVG/PNG acceptance proposals and alternative patches against the identified owner source. Test-file handoff remains pending.
|
||||
- [X4 / #5321](X4/README.md): full encoder, decoder, exact length quantizer and test-only bridge. Separate from the narrower adapter already in D8; do not overlay alternatives blindly.
|
||||
- [W38a corrective patch](W38a/README.md): five-file corrective WIP against the exact published head.
|
||||
- [W38d acceptance cases](W38d/README.md): original source-bound identity fixtures, not an implemented saved-fill pipeline.
|
||||
|
||||
These folders deliberately remain outside production module registration. Each README binds the actual source/base and distinguishes full-file copies, incremental patches and alternative implementations. Do not apply every alternative together. No compilation or runtime was performed for this preservation branch. Repository licensing, notices, original authorship and contributor scopes remain in force. Private operational launchers, grants, receipts, credentials, caches and binaries are excluded.
|
||||
@@ -0,0 +1,175 @@
|
||||
# Circular cubic candidate: derivation and limitations
|
||||
|
||||
Private source review, NOT RUN. This is a derivation for independent review,
|
||||
not an executed formal proof or a qualified public API.
|
||||
|
||||
## Provenance
|
||||
|
||||
The construction is the standard tangent/midpoint circular cubic. Its
|
||||
mathematical context was read in A. Riskus, “Approximation of a Cubic Bezier
|
||||
Curve by Circular Arcs and Vice Versa”, Information Technology and Control
|
||||
35(4), 2006, section3:
|
||||
https://www.itc.ktu.lt/index.php/ITC/article/view/11812
|
||||
https://doi.org/10.5755/j01.itc.35.4.11812
|
||||
|
||||
Only mathematical context is used from that primary paper; no external code,
|
||||
figures, templates or assets are imported. The bound below is derived here.
|
||||
The original project reference is CamWight's P1, retained with its authorship:
|
||||
https://github.com/CamWight/solidcraft/blob/7dc82dc7/crates/io/src/paper/pdf.rs
|
||||
and its continuation:
|
||||
https://github.com/0xlillith/solidcraft/blob/effaf49113dadafc2e16663972ed97e015cb5bf4/crates/io/src/paper/pdf.rs
|
||||
Those project contributions are MIT OR Apache-2.0. The new enclosure/Taylor
|
||||
implementation and tests are original SolidCraft contributor work.
|
||||
No GPL-family implementation is used or copied.
|
||||
|
||||
## 1. Exact-real construction and a radial polynomial
|
||||
|
||||
Let one positive subarc have angle theta<=pi/2, unit radius and centre0.
|
||||
Put alpha=theta/2, beta=theta/4, c=cos(alpha), s=sin(alpha),
|
||||
k=(4/3)tan(beta). Rotate the arc symmetrically about the positive x-axis.
|
||||
|
||||
Its ideal cubic controls are
|
||||
P0=(c,-s),
|
||||
P1=(c+k*s,-s+k*c),
|
||||
P2=(c+k*s,s-k*c),
|
||||
P3=(c,s).
|
||||
|
||||
They interpolate both endpoints, have the circle's endpoint tangents, and
|
||||
interpolate the arc midpoint at t=1/2. For the Bernstein cubic B(t), direct
|
||||
polynomial expansion gives
|
||||
|
||||
||B(t)||^2 - 1
|
||||
= 16*sin(beta)^6/cos(beta)^2 * t^2*(1-t)^2*(2*t-1)^2.
|
||||
|
||||
A check on the coefficient: the cubic's leading y coefficient is
|
||||
6*k*c-4*s = -8*sin(beta)^3/cos(beta). Its square equals the leading
|
||||
degree6 coefficient on the right. Both endpoint double roots and the
|
||||
midpoint double root determine the remaining polynomial.
|
||||
|
||||
Write z=t*(1-t), so 0<=z<=1/4. The remaining factor is
|
||||
z^2*(1-4*z), whose derivative is 2*z*(1-6*z); hence its maximum
|
||||
is1/108 at z=1/6. Therefore
|
||||
|
||||
0 <= ||B(t)||^2-1 <= (4/27)*sin(beta)^6/cos(beta)^2 = Q.
|
||||
|
||||
The identity sqrt(1+q)-1=q/(sqrt(1+q)+1)<=q/2 gives an outward
|
||||
radial error no greater than
|
||||
|
||||
radius*(2/27)*sin(beta)^6/cos(beta)^2.
|
||||
|
||||
For this sector the ideal cubic remains inside the angular wedge, has
|
||||
positive distance from the centre, and its continuous angle covers both
|
||||
endpoint angles. Radial projection and the intermediate value theorem
|
||||
therefore supply both directions of a Hausdorff bound to the true circular
|
||||
subarc. Reflection, translation and scaling preserve the argument; a
|
||||
negative sweep uses the reflected construction.
|
||||
|
||||
## 2. A looser bound needing no transcendental estimate
|
||||
|
||||
For 0<=beta<=pi/8, sin(beta)<=beta and
|
||||
cos(beta)^2=1-sin(beta)^2>=1-beta^2>0. Thus
|
||||
|
||||
Eideal <= radius*(2/27)*beta^6/(1-beta^2).
|
||||
|
||||
The candidate uses this larger quantity, not a claim that the tight maximum
|
||||
is attained. Every multiplication/division/addition used to evaluate it is
|
||||
outward-rounded. The interval for theta/n contains the exact-real quotient
|
||||
of the represented input sweep. Using its largest absolute endpoint gives
|
||||
a conservative beta for the inequality.
|
||||
|
||||
This deliberately refuses some tolerances that the tighter exact formula
|
||||
could meet. That is an explicit limitation, not a license to coarsen output.
|
||||
|
||||
## 3. Enclosing the actual stored control points
|
||||
|
||||
An exact f64 input denotes its exact real number. Each arithmetic operation
|
||||
encloses the two rounded endpoints by their next representable neighbours.
|
||||
Multiplication takes all endpoint products. Division rejects intervals
|
||||
containing zero, encloses reciprocal endpoints and multiplies. Nonfinite
|
||||
enclosures refuse.
|
||||
|
||||
The scalar model is ordinary IEEE754 binary64 round-to-nearest with gradual
|
||||
underflow, as required by the source's Rust floating operations. No
|
||||
fast-math/flush-to-zero transformation is qualified by this derivation.
|
||||
No numerical enclosure assertion was executed in this preparation.
|
||||
|
||||
For the trigonometric expressions the implementation calls no system
|
||||
sin/cos/tan. It uses24 Maclaurin terms with outward interval recurrence:
|
||||
sin through degree47 and cos through degree46. The next zero coefficients
|
||||
allow Taylor/Lagrange remainder bounds
|
||||
|
||||
|Rsin| <= |x|^49/49!,
|
||||
|Rcos| <= |x|^48/48!.
|
||||
|
||||
The derivatives have absolute value at most1 globally. An outward recurrence
|
||||
computes those tails from the interval's largest absolute x. This covers
|
||||
both arithmetic roundoff and the truncation remainder, without assuming a
|
||||
platform libm accuracy. Tangent is the enclosed sin/cos quotient of the
|
||||
small half-step; division refuses if its denominator enclosure crosses0.
|
||||
|
||||
Each exact ideal control has an enclosing x and y interval. The stored
|
||||
control is a representable midpoint clipped into those intervals; its
|
||||
maximum x displacement plus maximum y displacement bounds its Euclidean
|
||||
displacement. The nonnegative Bernstein weights sum to1, so
|
||||
|
||||
Econtrols = max over four controls of (x_displacement+y_displacement)
|
||||
|
||||
bounds the entire stored cubic's perturbation from the ideal cubic.
|
||||
The outward sum Eideal+Econtrols therefore bounds the emitted piece against
|
||||
the exact-real circular subarc. The greatest such bound covers the result.
|
||||
|
||||
Uniform subarc endpoints use the same represented inputs and the same
|
||||
expression for the same j/n; adjacent pieces therefore store identical
|
||||
endpoints. Different n values can choose slightly different endpoint
|
||||
midpoints, still covered by their bounds. Collapsed endpoints or endpoint
|
||||
handles are refused rather than emitted as a degenerate success.
|
||||
|
||||
## 4. Caps, failures and unconnected consumers
|
||||
|
||||
The existing Seg2::check admission is retained. This candidate further
|
||||
admits only start angles in[-PI,PI], nonzero signed sweeps at most a quarter
|
||||
turn, positive finite mm allowances, and caller caps in1..=64.
|
||||
It tries at most64 subdivisions; trial storage is at most64 segments,
|
||||
using try_reserve_exact. If a trial cannot meet the complete allowance,
|
||||
it is discarded. No partial Vec is returned as success. Allocation and
|
||||
arithmetic refusal propagate, with no input mutation.
|
||||
|
||||
The64-trial search has at most2080 trial pieces; the24-term trigonometric
|
||||
recurrences and49/48 remainder recurrences have fixed bounds per piece.
|
||||
A later scene consumer still owns aggregate work/output budgets over many
|
||||
arcs; this single-arc helper does not qualify them.
|
||||
|
||||
An admitted Arc checks its stored centre and radius, not the future cubic's
|
||||
control-point box. Returned controls are finite writer geometry, not a claim
|
||||
that reinserting them as authored Scene cubics passes the original Scene
|
||||
coordinate cap. No Scene cap is changed; a future adapter must respect its
|
||||
actual destination's admission rules.
|
||||
|
||||
Later grid snapping, replacing endpoints with walked endpoints, unit
|
||||
conversion, SVG ellipse support and PDF writing are NOT included. A caller
|
||||
must reserve their own additional error, preserve each walked endpoint,
|
||||
and prove its adapter. In particular the existing PDF subdivision works in
|
||||
grid STEPS while this candidate uses MILLIMETRES; raw transplantation is
|
||||
incorrect. No existing grid rule, PDF tolerance, writer, record or schema
|
||||
was changed.
|
||||
|
||||
## 5. Test scope
|
||||
|
||||
Eleven original tests are written, not run. They cover independent unit
|
||||
quarter controls/tangents, conservative-cap refusal, literal mm budgets at
|
||||
small and5000mm radii, joins, reverse/translation, repeatability, budgets,
|
||||
hostile inputs and precision collapse. The boundary increment covers refusal of
|
||||
the least-positive-subnormal allowance at cap64, subnormal radius/sweep rejection
|
||||
by existing Seg2 admission, and required ordinary-radius success with a subnormal
|
||||
centre and finite f64::MAX allowance. Independent Bernstein radial samples
|
||||
supplement the derivation; they are not a between-sample error certificate.
|
||||
The allocation-failure branch is fallible by source, not exercised by a
|
||||
fabricated out-of-memory test. Compiler, formatter, Clippy, wasm, runtime
|
||||
are pending. Kernel's bounded independent source review5c60c859 found no
|
||||
demonstrated defect in the admitted domain; this is not formal verification or
|
||||
executed acceptance. Final review of the three boundary tests remains pending.
|
||||
|
||||
Production paper.rs is byte-identical before/after. Only the existing
|
||||
test file has a path inclusion for the private candidate. The eventual
|
||||
module declaration is shown in a separate pending-adapter patch, NOT
|
||||
integrated into the after source. Its signature remains internal/proposed.
|
||||
@@ -0,0 +1,5 @@
|
||||
# W10 circular conversion proposals — preservation only
|
||||
|
||||
Exact original helper, eleven helper tests, three paper-grid endpoint tests and seven Seg2 adapter tests. NOT integrated, compiled or run. The helper/test patch is based on effaf49113dadafc2e16663972ed97e015cb5bf4; grid tests bind PDF506d419084a1cd6463c3117ea34d15f805a6ce37. The Seg2 adapter depends on the included cubics.rs SHA22e634fd8380f80fcdec09cccba52d45d309c44ab2f614bceab79f557da4e0e7.
|
||||
|
||||
Source copies and corresponding new-file patches are alternatives; hooks are separate unapplied proposals. Rebind all hooks to the agreed actual receiver. Owner/shared seam, grid allowance, cumulative scene budgets and real SVG/PDF use remain pending at issue4890 comment6476417296. DERIVATION.md is original analysis, not an executed proof. Existing contributor ownership and repository notices remain in force.
|
||||
@@ -0,0 +1,229 @@
|
||||
//! PRIVATE CANDIDATE: circular arcs to cubic pieces, in paper millimetres.
|
||||
//!
|
||||
//! Internal proposed signature, not an agreed paper API or a connected writer.
|
||||
//! The construction is the midpoint/tangent circular cubic used by CamWight's
|
||||
//! original P1 PDF implementation (MIT OR Apache-2.0). The enclosure code here
|
||||
//! is original; no third-party implementation is imported.
|
||||
//!
|
||||
//! Mathematical context: A. Riskus, Information Technology and Control 35(4),
|
||||
//! 2006, section3, doi:10.5755/j01.itc.35.4.11812.
|
||||
//! See the private derivation for the radial polynomial and rounding argument.
|
||||
//!
|
||||
//! At beta=abs(sweep)/(4*n), the ideal cubic has radial error at most
|
||||
//! r*(2/27)*sin(beta)^6/cos(beta)^2. This candidate uses the larger bound
|
||||
//! r*(2/27)*beta^6/(1-beta^2), so choosing pieces needs no transcendental call.
|
||||
//! Control points use outward-rounded Taylor enclosures, including explicit
|
||||
//! Lagrange remainders; their L1 uncertainty bounds the emitted cubic's
|
||||
//! positional perturbation by Bernstein convexity. No platform trig accuracy
|
||||
//! assumption is used. Scalar operations require Rust's ordinary IEEE754
|
||||
//! binary64 round-to-nearest semantics, not a fast-math/flush-to-zero rewrite.
|
||||
//!
|
||||
//! This bound excludes later writer-grid snapping and endpoint replacement.
|
||||
//! A consumer must reserve and qualify those separately. No adapter is supplied.
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
use crate::paper::{Invalid, MAX_COORDINATE_MM};
|
||||
use crate::{Seg2, Vec2};
|
||||
|
||||
type Result<T> = std::result::Result<T, Invalid>;
|
||||
|
||||
/// The inherited P1 per-arc ceiling; caller limits may only tighten it.
|
||||
pub(crate) const MAX_ARC_CUBICS: usize = 64;
|
||||
|
||||
/// A private candidate result, not a serialized record or a prepared scene.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ArcCubics {
|
||||
pub(crate) pieces: Vec<Seg2>,
|
||||
/// Geometric approximation plus stored-control-point uncertainty, in mm.
|
||||
/// Not a writer's gridding/physical-print error or an achieved API promise.
|
||||
pub(crate) error_bound_mm: f64,
|
||||
}
|
||||
|
||||
/// Converts one admitted circular arc, with a caller-supplied absolute error
|
||||
/// allowance in mm. Every output curve is a cubic. More than a quarter turn,
|
||||
/// starts outside [-PI,PI], non-arcs and hostile fields are explicitly refused.
|
||||
/// No silent angle normalization, grid policy or input mutation occurs.
|
||||
pub(crate) fn circular_arc(arc: &Seg2, error_mm: f64, max_pieces: usize) -> Result<ArcCubics> {
|
||||
let Seg2::Arc { center, radius, start, sweep } = *arc else {
|
||||
return Err(Invalid("cubic arc candidate: only a circular arc is supported"));
|
||||
};
|
||||
arc.check(MAX_COORDINATE_MM).map_err(Invalid)?;
|
||||
if !error_mm.is_finite() || error_mm <= 0.0 {
|
||||
return Err(Invalid("cubic arc candidate: the mm error allowance is finite and positive"));
|
||||
}
|
||||
if !(1..=MAX_ARC_CUBICS).contains(&max_pieces) {
|
||||
return Err(Invalid("cubic arc candidate: the piece cap is from1 to64"));
|
||||
}
|
||||
if !start.is_finite() || start.abs() > PI || !sweep.is_finite() || sweep == 0.0 || sweep.abs() > FRAC_PI_2 {
|
||||
return Err(Invalid("cubic arc candidate: start in [-PI,PI], nonzero sweep at most a quarter turn"));
|
||||
}
|
||||
|
||||
for n in 1..=max_pieces {
|
||||
let h = Enclosure::point(sweep).div(Enclosure::point(n as f64))?;
|
||||
let ideal_error = radial_bound(radius, h)?;
|
||||
if ideal_error > error_mm {
|
||||
continue;
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
pieces.try_reserve_exact(n).map_err(|_| Invalid("cubic arc candidate: cannot allocate bounded pieces"))?;
|
||||
let mut error_bound_mm: f64 = 0.0;
|
||||
for i in 0..n {
|
||||
// The same expression evaluates each shared end once per neighbour,
|
||||
// yielding bit-identical stored endpoints, with no endpoint snap.
|
||||
let angle = |j: usize| {
|
||||
Enclosure::point(start).add(
|
||||
Enclosure::point(sweep).mul(Enclosure::point(j as f64).div(Enclosure::point(n as f64))?)?,
|
||||
)
|
||||
};
|
||||
let (cubic, control_error) = make_cubic(center, radius, angle(i)?, angle(i + 1)?, h)?;
|
||||
let total = Enclosure::point(ideal_error).add(Enclosure::point(control_error))?.hi;
|
||||
error_bound_mm = error_bound_mm.max(total);
|
||||
pieces.push(cubic);
|
||||
}
|
||||
if error_bound_mm <= error_mm {
|
||||
return Ok(ArcCubics { pieces, error_bound_mm });
|
||||
}
|
||||
// Numerical uncertainty is part of the error, never an excuse to use a
|
||||
// looser tolerance. A later n may qualify; at the caller cap refuse all.
|
||||
}
|
||||
Err(Invalid("cubic arc candidate: cannot certify the requested mm error within the piece cap"))
|
||||
}
|
||||
|
||||
/// The exact-real radial bound with sin(beta)<=beta and
|
||||
/// cos(beta)^2>=1-beta^2, evaluated outwards. The domain is beta<=PI/8.
|
||||
fn radial_bound(radius: f64, h: Enclosure) -> Result<f64> {
|
||||
let beta = Enclosure::point(h.abs_upper()).div(Enclosure::point(4.0))?;
|
||||
let squared = beta.mul(beta)?;
|
||||
let sixth = squared.mul(squared)?.mul(squared)?;
|
||||
let denominator = Enclosure::point(1.0).sub(squared)?;
|
||||
let coefficient = Enclosure::point(2.0).div(Enclosure::point(27.0))?;
|
||||
let bound = Enclosure::point(radius).mul(coefficient)?.mul(sixth)?.div(denominator)?;
|
||||
Ok(bound.hi)
|
||||
}
|
||||
|
||||
fn make_cubic(center: Vec2, radius: f64, a0: Enclosure, a1: Enclosure, h: Enclosure) -> Result<(Seg2, f64)> {
|
||||
let (s0, c0) = sin_cos(a0)?;
|
||||
let (s1, c1) = sin_cos(a1)?;
|
||||
let (sh, ch) = sin_cos(h.div(Enclosure::point(4.0))?)?;
|
||||
let r = Enclosure::point(radius);
|
||||
let handle = r.mul(Enclosure::point(4.0).div(Enclosure::point(3.0))?)?.mul(sh.div(ch)?)?;
|
||||
let cx = Enclosure::point(center.x);
|
||||
let cy = Enclosure::point(center.y);
|
||||
let x0 = cx.add(r.mul(c0)?)?;
|
||||
let y0 = cy.add(r.mul(s0)?)?;
|
||||
let x3 = cx.add(r.mul(c1)?)?;
|
||||
let y3 = cy.add(r.mul(s1)?)?;
|
||||
let (p0, e0) = stored_point(x0, y0)?;
|
||||
let (p1, e1) = stored_point(x0.sub(handle.mul(s0)?)?, y0.add(handle.mul(c0)?)?)?;
|
||||
let (p2, e2) = stored_point(x3.add(handle.mul(s1)?)?, y3.sub(handle.mul(c1)?)?)?;
|
||||
let (p3, e3) = stored_point(x3, y3)?;
|
||||
if p0 == p3 || p0 == p1 || p2 == p3 {
|
||||
return Err(Invalid("cubic arc candidate: coordinate precision collapses an endpoint or tangent"));
|
||||
}
|
||||
Ok((Seg2::Cubic { p0, p1, p2, p3 }, e0.max(e1).max(e2).max(e3)))
|
||||
}
|
||||
|
||||
/// Nonnegative Bernstein coefficients sum to1, so the greatest control
|
||||
/// displacement bounds the complete curve displacement. L1 bounds Euclidean
|
||||
/// distance without trusting a rounded sqrt.
|
||||
fn stored_point(x: Enclosure, y: Enclosure) -> Result<(Vec2, f64)> {
|
||||
let px = x.midpoint();
|
||||
let py = y.midpoint();
|
||||
let ex = x.sub(Enclosure::point(px))?.abs_upper();
|
||||
let ey = y.sub(Enclosure::point(py))?.abs_upper();
|
||||
let error = Enclosure::point(ex).add(Enclosure::point(ey))?.hi;
|
||||
Ok((Vec2::new(px, py), error))
|
||||
}
|
||||
|
||||
/// Twenty-four terms, then an explicit Taylor/Lagrange remainder. Input
|
||||
/// angles stay inside +/-3PI/2; no period reduction or system trig is needed.
|
||||
/// sin's polynomial has degree47 (degree48 coefficient0), cos's degree46
|
||||
/// (degree47 coefficient0), giving remainder orders49 and48 respectively.
|
||||
fn sin_cos(x: Enclosure) -> Result<(Enclosure, Enclosure)> {
|
||||
let negative_square = x.mul(x)?.neg();
|
||||
let mut sine_term = x;
|
||||
let mut cosine_term = Enclosure::point(1.0);
|
||||
let mut sine = sine_term;
|
||||
let mut cosine = cosine_term;
|
||||
for k in 1..24 {
|
||||
let twice = (2 * k) as f64;
|
||||
sine_term = sine_term.mul(negative_square)?.div(Enclosure::point(twice * (twice + 1.0)))?;
|
||||
cosine_term = cosine_term.mul(negative_square)?.div(Enclosure::point((twice - 1.0) * twice))?;
|
||||
sine = sine.add(sine_term)?;
|
||||
cosine = cosine.add(cosine_term)?;
|
||||
}
|
||||
let sine_tail = taylor_tail(x.abs_upper(), 49)?;
|
||||
let cosine_tail = taylor_tail(x.abs_upper(), 48)?;
|
||||
Ok((
|
||||
sine.add(Enclosure { lo: -sine_tail, hi: sine_tail })?,
|
||||
cosine.add(Enclosure { lo: -cosine_tail, hi: cosine_tail })?,
|
||||
))
|
||||
}
|
||||
|
||||
fn taylor_tail(magnitude: f64, order: usize) -> Result<f64> {
|
||||
let mut tail = Enclosure::point(1.0);
|
||||
for j in 1..=order {
|
||||
tail = tail.mul(Enclosure::point(magnitude))?.div(Enclosure::point(j as f64))?;
|
||||
}
|
||||
Ok(tail.hi)
|
||||
}
|
||||
|
||||
/// Local private arithmetic for this helper, not a second public interval API.
|
||||
/// Exact f64 inputs denote single real numbers. Every operation expands each
|
||||
/// rounded endpoint by one representable neighbour; nonfinite endpoints and
|
||||
/// division by an interval containing zero fail closed.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Enclosure {
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
}
|
||||
|
||||
impl Enclosure {
|
||||
fn point(value: f64) -> Self {
|
||||
Self { lo: value, hi: value }
|
||||
}
|
||||
|
||||
fn outward(lo: f64, hi: f64) -> Result<Self> {
|
||||
let (lo, hi) = (lo.next_down(), hi.next_up());
|
||||
if lo.is_finite() && hi.is_finite() && lo <= hi {
|
||||
Ok(Self { lo, hi })
|
||||
} else {
|
||||
Err(Invalid("cubic arc candidate: arithmetic enclosure unavailable"))
|
||||
}
|
||||
}
|
||||
|
||||
fn add(self, rhs: Self) -> Result<Self> {
|
||||
Self::outward(self.lo + rhs.lo, self.hi + rhs.hi)
|
||||
}
|
||||
|
||||
fn neg(self) -> Self {
|
||||
Self { lo: -self.hi, hi: -self.lo }
|
||||
}
|
||||
|
||||
fn sub(self, rhs: Self) -> Result<Self> {
|
||||
self.add(rhs.neg())
|
||||
}
|
||||
|
||||
fn mul(self, rhs: Self) -> Result<Self> {
|
||||
let (lo, hi) = [self.lo * rhs.lo, self.lo * rhs.hi, self.hi * rhs.lo, self.hi * rhs.hi]
|
||||
.into_iter()
|
||||
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)));
|
||||
Self::outward(lo, hi)
|
||||
}
|
||||
|
||||
fn div(self, rhs: Self) -> Result<Self> {
|
||||
if rhs.lo <= 0.0 && rhs.hi >= 0.0 {
|
||||
return Err(Invalid("cubic arc candidate: denominator contains zero"));
|
||||
}
|
||||
self.mul(Self::outward(1.0 / rhs.hi, 1.0 / rhs.lo)?)
|
||||
}
|
||||
|
||||
fn abs_upper(self) -> f64 {
|
||||
self.lo.abs().max(self.hi.abs())
|
||||
}
|
||||
|
||||
fn midpoint(self) -> f64 {
|
||||
(self.lo * 0.5 + self.hi * 0.5).max(self.lo).min(self.hi)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
diff --git a/crates/geom/src/paper/grid_endpoint_acceptance.rs b/crates/geom/src/paper/grid_endpoint_acceptance.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/geom/src/paper/grid_endpoint_acceptance.rs
|
||||
@@ -0,0 +1,171 @@
|
||||
+//! PRIVATE TEST-ONLY proposal for PDF506d, not a production adapter.
|
||||
+//! Include as a sibling of circular_arc_candidate in paper_tests.rs.
|
||||
+//! Explicit source arcs are mandatory: Piece::Arc alone loses their provenance.
|
||||
+
|
||||
+use super::circular_arc_candidate;
|
||||
+use crate::paper::{Grid, GridPath, GridPoint, Invalid, Piece};
|
||||
+use crate::{Seg2, Vec2};
|
||||
+use std::f64::consts::{FRAC_PI_2, PI};
|
||||
+
|
||||
+type Result<T> = std::result::Result<T, Invalid>;
|
||||
+const MAX_ARCS: usize = 4;
|
||||
+const MAX_INTEGER: i64 = 1_i64 << 40;
|
||||
+
|
||||
+#[derive(Debug)]
|
||||
+struct Accepted {
|
||||
+ path: GridPath,
|
||||
+ bound_mm: f64,
|
||||
+}
|
||||
+
|
||||
+// Integer cast is exact in this deliberately small domain. Division by the
|
||||
+// actual PDF grid scale is enclosed by neighbouring f64s; it is not assumed exact.
|
||||
+fn displacement(point: GridPoint, source: Vec2) -> Result<f64> {
|
||||
+ fn coordinate(n: i64, value: f64) -> Result<f64> {
|
||||
+ if !(-MAX_INTEGER..=MAX_INTEGER).contains(&n) || !value.is_finite() {
|
||||
+ return Err(Invalid("private acceptance: uncertified coordinate conversion"));
|
||||
+ }
|
||||
+ let q = n as f64 / Grid::TEN_NANOMETRES.per_mm();
|
||||
+ let lo = (q.next_down() - value).abs().next_up();
|
||||
+ let hi = (q.next_up() - value).abs().next_up();
|
||||
+ Ok(lo.max(hi))
|
||||
+ }
|
||||
+ let bound = (coordinate(point.x, source.x)? + coordinate(point.y, source.y)?).next_up();
|
||||
+ if !bound.is_finite() {
|
||||
+ return Err(Invalid("private acceptance: nonfinite displacement"));
|
||||
+ }
|
||||
+ Ok(bound)
|
||||
+}
|
||||
+
|
||||
+fn rounded(point: Vec2) -> Result<GridPoint> {
|
||||
+ // Bounds keep the grid multiplication/round/cast far from saturation.
|
||||
+ // Its actual emitted result is then charged by displacement, without
|
||||
+ // assuming that the multiplication or the rounding was exact.
|
||||
+ if !point.is_finite() || point.x.abs() > 1e6 || point.y.abs() > 1e6 {
|
||||
+ return Err(Invalid("private acceptance: control outside bounded fixture"));
|
||||
+ }
|
||||
+ Grid::TEN_NANOMETRES.point(point)
|
||||
+}
|
||||
+
|
||||
+fn controls(piece: &Seg2) -> Result<[Vec2; 4]> {
|
||||
+ match *piece {
|
||||
+ Seg2::Cubic { p0, p1, p2, p3 } => Ok([p0, p1, p2, p3]),
|
||||
+ _ => Err(Invalid("private acceptance: helper returned a noncubic")),
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+// This accepts a bounded test recipe, not an arbitrary post-walk arc.
|
||||
+// It proves error against explicit source arcs only, not Piece::seg geometry
|
||||
+// or the unavailable original scene recovered from Piece metadata.
|
||||
+fn accept(source: &[Seg2], walked: &GridPath, allowance_mm: f64) -> Result<Accepted> {
|
||||
+ if source.is_empty() || source.len() > MAX_ARCS || source.len() != walked.pieces.len()
|
||||
+ || !allowance_mm.is_finite() || allowance_mm <= 0.0
|
||||
+ {
|
||||
+ return Err(Invalid("private acceptance: explicit bounded arc provenance required"));
|
||||
+ }
|
||||
+ let mut pieces = Vec::new();
|
||||
+ pieces.try_reserve_exact(MAX_ARCS * 64)
|
||||
+ .map_err(|_| Invalid("private acceptance: allocation refused"))?;
|
||||
+ let mut at = walked.start;
|
||||
+ let mut bound_mm: f64 = 0.0;
|
||||
+ for (arc, walked_piece) in source.iter().zip(&walked.pieces) {
|
||||
+ let Piece::Arc { radius, to, .. } = *walked_piece else {
|
||||
+ return Err(Invalid("private acceptance: only explicit arc recipes"));
|
||||
+ };
|
||||
+ if radius <= 0 {
|
||||
+ return Err(Invalid("private acceptance: nonpositive walked radius"));
|
||||
+ }
|
||||
+ let converted = circular_arc_candidate::circular_arc(arc, allowance_mm / 2.0, 64)?;
|
||||
+ if converted.pieces.is_empty() || converted.pieces.len() > 64 {
|
||||
+ return Err(Invalid("private acceptance: invalid helper output size"));
|
||||
+ }
|
||||
+ for (i, cubic) in converted.pieces.iter().enumerate() {
|
||||
+ let [p0, p1, p2, p3] = controls(cubic)?;
|
||||
+ let c1 = rounded(p1)?;
|
||||
+ let c2 = rounded(p2)?;
|
||||
+ let end = if i + 1 == converted.pieces.len() { to } else { rounded(p3)? };
|
||||
+ let change = displacement(at, p0)?
|
||||
+ .max(displacement(c1, p1)?)
|
||||
+ .max(displacement(c2, p2)?)
|
||||
+ .max(displacement(end, p3)?);
|
||||
+ let total = (converted.error_bound_mm + change).next_up();
|
||||
+ if !total.is_finite() || total > allowance_mm {
|
||||
+ return Err(Invalid("private acceptance: endpoint/rounding debit exceeds allowance"));
|
||||
+ }
|
||||
+ if at == end {
|
||||
+ return Err(Invalid("private acceptance: collapsed gridded cubic"));
|
||||
+ }
|
||||
+ bound_mm = bound_mm.max(total);
|
||||
+ pieces.push(Piece::Cubic { c1, c2, to: end });
|
||||
+ at = end;
|
||||
+ }
|
||||
+ }
|
||||
+ if walked.closed && at != walked.start {
|
||||
+ return Err(Invalid("private acceptance: walked closure absent"));
|
||||
+ }
|
||||
+ Ok(Accepted { path: GridPath { start: walked.start, pieces, closed: walked.closed }, bound_mm })
|
||||
+}
|
||||
+
|
||||
+fn fixture() -> ([Seg2; 4], GridPath) {
|
||||
+ let center = Vec2::new(10.0, 10.0);
|
||||
+ let source = [0.0, FRAC_PI_2, PI, -FRAC_PI_2]
|
||||
+ .map(|start| Seg2::Arc { center, radius: 1.0, start, sweep: FRAC_PI_2 });
|
||||
+ // Literal, already-walked endpoints: no trigonometric oracle is reused.
|
||||
+ let start = GridPoint { x: 1_100_000, y: 1_000_000 };
|
||||
+ let pieces = [
|
||||
+ GridPoint { x: 1_000_000, y: 1_100_000 },
|
||||
+ GridPoint { x: 900_000, y: 1_000_000 },
|
||||
+ GridPoint { x: 1_000_000, y: 900_000 },
|
||||
+ start,
|
||||
+ ].map(|to| Piece::Arc { radius: 100_000, clockwise: false, to }).to_vec();
|
||||
+ (source, GridPath { start, pieces, closed: true })
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn private_closed_arc_recipe_keeps_walked_joints_and_debits_all_controls() {
|
||||
+ let (source, walked) = fixture();
|
||||
+ let before = walked.clone();
|
||||
+ // Existing PDF tolerance, not a new production tolerance.
|
||||
+ let accepted = accept(&source, &walked, 1e-4).unwrap();
|
||||
+ assert!(accepted.bound_mm.is_finite() && accepted.bound_mm > 0.0 && accepted.bound_mm <= 1e-4);
|
||||
+ assert_eq!(walked, before);
|
||||
+ assert_eq!(accepted.path.start, walked.start);
|
||||
+ assert!(accepted.path.closed);
|
||||
+ assert_eq!(accepted.path.pieces.last().unwrap().to(), walked.start);
|
||||
+ let mut ends = accepted.path.pieces.iter().map(Piece::to);
|
||||
+ for original in &walked.pieces {
|
||||
+ assert!(ends.by_ref().any(|end| end == original.to()));
|
||||
+ }
|
||||
+ assert!(accepted.path.pieces.len() <= MAX_ARCS * 64);
|
||||
+ assert!(accepted.path.pieces.iter().all(|piece| matches!(piece, Piece::Cubic { .. })));
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn private_endpoint_change_is_charged_or_refused_without_partial_output() {
|
||||
+ let (source, mut walked) = fixture();
|
||||
+ if let Some(Piece::Arc { to, .. }) = walked.pieces.first_mut() {
|
||||
+ to.x += 1;
|
||||
+ }
|
||||
+ let accepted = accept(&source, &walked, 1e-4).unwrap();
|
||||
+ assert!(accepted.bound_mm >= 1e-5 && accepted.bound_mm <= 1e-4);
|
||||
+ assert!(accepted.path.pieces.iter().any(|piece| piece.to() == walked.pieces[0].to()));
|
||||
+ if let Some(Piece::Arc { to, .. }) = walked.pieces.first_mut() {
|
||||
+ to.x += 100;
|
||||
+ }
|
||||
+ assert!(accept(&source, &walked, 1e-4).is_err());
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn private_unproven_input_conversion_and_missing_provenance_are_refused() {
|
||||
+ let (source, mut walked) = fixture();
|
||||
+ walked.start.x = i64::MAX;
|
||||
+ assert!(accept(&source, &walked, 1e-4).is_err());
|
||||
+ let (_, walked) = fixture();
|
||||
+ assert!(accept(&[], &walked, 1e-4).is_err());
|
||||
+ assert!(accept(&source, &walked, f64::from_bits(1)).is_err());
|
||||
+ assert!(accept(&source, &walked, f64::INFINITY).is_err());
|
||||
+ let mut open_end = walked.clone();
|
||||
+ if let Some(Piece::Arc { to, .. }) = open_end.pieces.last_mut() {
|
||||
+ to.x += 1;
|
||||
+ }
|
||||
+ assert!(accept(&source, &open_end, 1e-4).is_err());
|
||||
+}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! PRIVATE TEST-ONLY proposal for PDF506d, not a production adapter.
|
||||
//! Include as a sibling of circular_arc_candidate in paper_tests.rs.
|
||||
//! Explicit source arcs are mandatory: Piece::Arc alone loses their provenance.
|
||||
|
||||
use super::circular_arc_candidate;
|
||||
use crate::paper::{Grid, GridPath, GridPoint, Invalid, Piece};
|
||||
use crate::{Seg2, Vec2};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
type Result<T> = std::result::Result<T, Invalid>;
|
||||
const MAX_ARCS: usize = 4;
|
||||
const MAX_INTEGER: i64 = 1_i64 << 40;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Accepted {
|
||||
path: GridPath,
|
||||
bound_mm: f64,
|
||||
}
|
||||
|
||||
// Integer cast is exact in this deliberately small domain. Division by the
|
||||
// actual PDF grid scale is enclosed by neighbouring f64s; it is not assumed exact.
|
||||
fn displacement(point: GridPoint, source: Vec2) -> Result<f64> {
|
||||
fn coordinate(n: i64, value: f64) -> Result<f64> {
|
||||
if !(-MAX_INTEGER..=MAX_INTEGER).contains(&n) || !value.is_finite() {
|
||||
return Err(Invalid("private acceptance: uncertified coordinate conversion"));
|
||||
}
|
||||
let q = n as f64 / Grid::TEN_NANOMETRES.per_mm();
|
||||
let lo = (q.next_down() - value).abs().next_up();
|
||||
let hi = (q.next_up() - value).abs().next_up();
|
||||
Ok(lo.max(hi))
|
||||
}
|
||||
let bound = (coordinate(point.x, source.x)? + coordinate(point.y, source.y)?).next_up();
|
||||
if !bound.is_finite() {
|
||||
return Err(Invalid("private acceptance: nonfinite displacement"));
|
||||
}
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
fn rounded(point: Vec2) -> Result<GridPoint> {
|
||||
// Bounds keep the grid multiplication/round/cast far from saturation.
|
||||
// Its actual emitted result is then charged by displacement, without
|
||||
// assuming that the multiplication or the rounding was exact.
|
||||
if !point.is_finite() || point.x.abs() > 1e6 || point.y.abs() > 1e6 {
|
||||
return Err(Invalid("private acceptance: control outside bounded fixture"));
|
||||
}
|
||||
Grid::TEN_NANOMETRES.point(point)
|
||||
}
|
||||
|
||||
fn controls(piece: &Seg2) -> Result<[Vec2; 4]> {
|
||||
match *piece {
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => Ok([p0, p1, p2, p3]),
|
||||
_ => Err(Invalid("private acceptance: helper returned a noncubic")),
|
||||
}
|
||||
}
|
||||
|
||||
// This accepts a bounded test recipe, not an arbitrary post-walk arc.
|
||||
// It proves error against explicit source arcs only, not Piece::seg geometry
|
||||
// or the unavailable original scene recovered from Piece metadata.
|
||||
fn accept(source: &[Seg2], walked: &GridPath, allowance_mm: f64) -> Result<Accepted> {
|
||||
if source.is_empty() || source.len() > MAX_ARCS || source.len() != walked.pieces.len()
|
||||
|| !allowance_mm.is_finite() || allowance_mm <= 0.0
|
||||
{
|
||||
return Err(Invalid("private acceptance: explicit bounded arc provenance required"));
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
pieces.try_reserve_exact(MAX_ARCS * 64)
|
||||
.map_err(|_| Invalid("private acceptance: allocation refused"))?;
|
||||
let mut at = walked.start;
|
||||
let mut bound_mm: f64 = 0.0;
|
||||
for (arc, walked_piece) in source.iter().zip(&walked.pieces) {
|
||||
let Piece::Arc { radius, to, .. } = *walked_piece else {
|
||||
return Err(Invalid("private acceptance: only explicit arc recipes"));
|
||||
};
|
||||
if radius <= 0 {
|
||||
return Err(Invalid("private acceptance: nonpositive walked radius"));
|
||||
}
|
||||
let converted = circular_arc_candidate::circular_arc(arc, allowance_mm / 2.0, 64)?;
|
||||
if converted.pieces.is_empty() || converted.pieces.len() > 64 {
|
||||
return Err(Invalid("private acceptance: invalid helper output size"));
|
||||
}
|
||||
for (i, cubic) in converted.pieces.iter().enumerate() {
|
||||
let [p0, p1, p2, p3] = controls(cubic)?;
|
||||
let c1 = rounded(p1)?;
|
||||
let c2 = rounded(p2)?;
|
||||
let end = if i + 1 == converted.pieces.len() { to } else { rounded(p3)? };
|
||||
let change = displacement(at, p0)?
|
||||
.max(displacement(c1, p1)?)
|
||||
.max(displacement(c2, p2)?)
|
||||
.max(displacement(end, p3)?);
|
||||
let total = (converted.error_bound_mm + change).next_up();
|
||||
if !total.is_finite() || total > allowance_mm {
|
||||
return Err(Invalid("private acceptance: endpoint/rounding debit exceeds allowance"));
|
||||
}
|
||||
if at == end {
|
||||
return Err(Invalid("private acceptance: collapsed gridded cubic"));
|
||||
}
|
||||
bound_mm = bound_mm.max(total);
|
||||
pieces.push(Piece::Cubic { c1, c2, to: end });
|
||||
at = end;
|
||||
}
|
||||
}
|
||||
if walked.closed && at != walked.start {
|
||||
return Err(Invalid("private acceptance: walked closure absent"));
|
||||
}
|
||||
Ok(Accepted { path: GridPath { start: walked.start, pieces, closed: walked.closed }, bound_mm })
|
||||
}
|
||||
|
||||
fn fixture() -> ([Seg2; 4], GridPath) {
|
||||
let center = Vec2::new(10.0, 10.0);
|
||||
let source = [0.0, FRAC_PI_2, PI, -FRAC_PI_2]
|
||||
.map(|start| Seg2::Arc { center, radius: 1.0, start, sweep: FRAC_PI_2 });
|
||||
// Literal, already-walked endpoints: no trigonometric oracle is reused.
|
||||
let start = GridPoint { x: 1_100_000, y: 1_000_000 };
|
||||
let pieces = [
|
||||
GridPoint { x: 1_000_000, y: 1_100_000 },
|
||||
GridPoint { x: 900_000, y: 1_000_000 },
|
||||
GridPoint { x: 1_000_000, y: 900_000 },
|
||||
start,
|
||||
].map(|to| Piece::Arc { radius: 100_000, clockwise: false, to }).to_vec();
|
||||
(source, GridPath { start, pieces, closed: true })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_closed_arc_recipe_keeps_walked_joints_and_debits_all_controls() {
|
||||
let (source, walked) = fixture();
|
||||
let before = walked.clone();
|
||||
// Existing PDF tolerance, not a new production tolerance.
|
||||
let accepted = accept(&source, &walked, 1e-4).unwrap();
|
||||
assert!(accepted.bound_mm.is_finite() && accepted.bound_mm > 0.0 && accepted.bound_mm <= 1e-4);
|
||||
assert_eq!(walked, before);
|
||||
assert_eq!(accepted.path.start, walked.start);
|
||||
assert!(accepted.path.closed);
|
||||
assert_eq!(accepted.path.pieces.last().unwrap().to(), walked.start);
|
||||
let mut ends = accepted.path.pieces.iter().map(Piece::to);
|
||||
for original in &walked.pieces {
|
||||
assert!(ends.by_ref().any(|end| end == original.to()));
|
||||
}
|
||||
assert!(accepted.path.pieces.len() <= MAX_ARCS * 64);
|
||||
assert!(accepted.path.pieces.iter().all(|piece| matches!(piece, Piece::Cubic { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_endpoint_change_is_charged_or_refused_without_partial_output() {
|
||||
let (source, mut walked) = fixture();
|
||||
if let Some(Piece::Arc { to, .. }) = walked.pieces.first_mut() {
|
||||
to.x += 1;
|
||||
}
|
||||
let accepted = accept(&source, &walked, 1e-4).unwrap();
|
||||
assert!(accepted.bound_mm >= 1e-5 && accepted.bound_mm <= 1e-4);
|
||||
assert!(accepted.path.pieces.iter().any(|piece| piece.to() == walked.pieces[0].to()));
|
||||
if let Some(Piece::Arc { to, .. }) = walked.pieces.first_mut() {
|
||||
to.x += 100;
|
||||
}
|
||||
assert!(accept(&source, &walked, 1e-4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_unproven_input_conversion_and_missing_provenance_are_refused() {
|
||||
let (source, mut walked) = fixture();
|
||||
walked.start.x = i64::MAX;
|
||||
assert!(accept(&source, &walked, 1e-4).is_err());
|
||||
let (_, walked) = fixture();
|
||||
assert!(accept(&[], &walked, 1e-4).is_err());
|
||||
assert!(accept(&source, &walked, f64::from_bits(1)).is_err());
|
||||
assert!(accept(&source, &walked, f64::INFINITY).is_err());
|
||||
let mut open_end = walked.clone();
|
||||
if let Some(Piece::Arc { to, .. }) = open_end.pieces.last_mut() {
|
||||
to.x += 1;
|
||||
}
|
||||
assert!(accept(&source, &open_end, 1e-4).is_err());
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
diff --git a/crates/geom/src/paper/cubics.rs b/crates/geom/src/paper/cubics.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/geom/src/paper/cubics.rs
|
||||
@@ -0,0 +1,229 @@
|
||||
+//! PRIVATE CANDIDATE: circular arcs to cubic pieces, in paper millimetres.
|
||||
+//!
|
||||
+//! Internal proposed signature, not an agreed paper API or a connected writer.
|
||||
+//! The construction is the midpoint/tangent circular cubic used by CamWight's
|
||||
+//! original P1 PDF implementation (MIT OR Apache-2.0). The enclosure code here
|
||||
+//! is original; no third-party implementation is imported.
|
||||
+//!
|
||||
+//! Mathematical context: A. Riskus, Information Technology and Control 35(4),
|
||||
+//! 2006, section3, doi:10.5755/j01.itc.35.4.11812.
|
||||
+//! See the private derivation for the radial polynomial and rounding argument.
|
||||
+//!
|
||||
+//! At beta=abs(sweep)/(4*n), the ideal cubic has radial error at most
|
||||
+//! r*(2/27)*sin(beta)^6/cos(beta)^2. This candidate uses the larger bound
|
||||
+//! r*(2/27)*beta^6/(1-beta^2), so choosing pieces needs no transcendental call.
|
||||
+//! Control points use outward-rounded Taylor enclosures, including explicit
|
||||
+//! Lagrange remainders; their L1 uncertainty bounds the emitted cubic's
|
||||
+//! positional perturbation by Bernstein convexity. No platform trig accuracy
|
||||
+//! assumption is used. Scalar operations require Rust's ordinary IEEE754
|
||||
+//! binary64 round-to-nearest semantics, not a fast-math/flush-to-zero rewrite.
|
||||
+//!
|
||||
+//! This bound excludes later writer-grid snapping and endpoint replacement.
|
||||
+//! A consumer must reserve and qualify those separately. No adapter is supplied.
|
||||
+
|
||||
+use std::f64::consts::{FRAC_PI_2, PI};
|
||||
+
|
||||
+use crate::paper::{Invalid, MAX_COORDINATE_MM};
|
||||
+use crate::{Seg2, Vec2};
|
||||
+
|
||||
+type Result<T> = std::result::Result<T, Invalid>;
|
||||
+
|
||||
+/// The inherited P1 per-arc ceiling; caller limits may only tighten it.
|
||||
+pub(crate) const MAX_ARC_CUBICS: usize = 64;
|
||||
+
|
||||
+/// A private candidate result, not a serialized record or a prepared scene.
|
||||
+#[derive(Clone, Debug, PartialEq)]
|
||||
+pub(crate) struct ArcCubics {
|
||||
+ pub(crate) pieces: Vec<Seg2>,
|
||||
+ /// Geometric approximation plus stored-control-point uncertainty, in mm.
|
||||
+ /// Not a writer's gridding/physical-print error or an achieved API promise.
|
||||
+ pub(crate) error_bound_mm: f64,
|
||||
+}
|
||||
+
|
||||
+/// Converts one admitted circular arc, with a caller-supplied absolute error
|
||||
+/// allowance in mm. Every output curve is a cubic. More than a quarter turn,
|
||||
+/// starts outside [-PI,PI], non-arcs and hostile fields are explicitly refused.
|
||||
+/// No silent angle normalization, grid policy or input mutation occurs.
|
||||
+pub(crate) fn circular_arc(arc: &Seg2, error_mm: f64, max_pieces: usize) -> Result<ArcCubics> {
|
||||
+ let Seg2::Arc { center, radius, start, sweep } = *arc else {
|
||||
+ return Err(Invalid("cubic arc candidate: only a circular arc is supported"));
|
||||
+ };
|
||||
+ arc.check(MAX_COORDINATE_MM).map_err(Invalid)?;
|
||||
+ if !error_mm.is_finite() || error_mm <= 0.0 {
|
||||
+ return Err(Invalid("cubic arc candidate: the mm error allowance is finite and positive"));
|
||||
+ }
|
||||
+ if !(1..=MAX_ARC_CUBICS).contains(&max_pieces) {
|
||||
+ return Err(Invalid("cubic arc candidate: the piece cap is from1 to64"));
|
||||
+ }
|
||||
+ if !start.is_finite() || start.abs() > PI || !sweep.is_finite() || sweep == 0.0 || sweep.abs() > FRAC_PI_2 {
|
||||
+ return Err(Invalid("cubic arc candidate: start in [-PI,PI], nonzero sweep at most a quarter turn"));
|
||||
+ }
|
||||
+
|
||||
+ for n in 1..=max_pieces {
|
||||
+ let h = Enclosure::point(sweep).div(Enclosure::point(n as f64))?;
|
||||
+ let ideal_error = radial_bound(radius, h)?;
|
||||
+ if ideal_error > error_mm {
|
||||
+ continue;
|
||||
+ }
|
||||
+ let mut pieces = Vec::new();
|
||||
+ pieces.try_reserve_exact(n).map_err(|_| Invalid("cubic arc candidate: cannot allocate bounded pieces"))?;
|
||||
+ let mut error_bound_mm: f64 = 0.0;
|
||||
+ for i in 0..n {
|
||||
+ // The same expression evaluates each shared end once per neighbour,
|
||||
+ // yielding bit-identical stored endpoints, with no endpoint snap.
|
||||
+ let angle = |j: usize| {
|
||||
+ Enclosure::point(start).add(
|
||||
+ Enclosure::point(sweep).mul(Enclosure::point(j as f64).div(Enclosure::point(n as f64))?)?,
|
||||
+ )
|
||||
+ };
|
||||
+ let (cubic, control_error) = make_cubic(center, radius, angle(i)?, angle(i + 1)?, h)?;
|
||||
+ let total = Enclosure::point(ideal_error).add(Enclosure::point(control_error))?.hi;
|
||||
+ error_bound_mm = error_bound_mm.max(total);
|
||||
+ pieces.push(cubic);
|
||||
+ }
|
||||
+ if error_bound_mm <= error_mm {
|
||||
+ return Ok(ArcCubics { pieces, error_bound_mm });
|
||||
+ }
|
||||
+ // Numerical uncertainty is part of the error, never an excuse to use a
|
||||
+ // looser tolerance. A later n may qualify; at the caller cap refuse all.
|
||||
+ }
|
||||
+ Err(Invalid("cubic arc candidate: cannot certify the requested mm error within the piece cap"))
|
||||
+}
|
||||
+
|
||||
+/// The exact-real radial bound with sin(beta)<=beta and
|
||||
+/// cos(beta)^2>=1-beta^2, evaluated outwards. The domain is beta<=PI/8.
|
||||
+fn radial_bound(radius: f64, h: Enclosure) -> Result<f64> {
|
||||
+ let beta = Enclosure::point(h.abs_upper()).div(Enclosure::point(4.0))?;
|
||||
+ let squared = beta.mul(beta)?;
|
||||
+ let sixth = squared.mul(squared)?.mul(squared)?;
|
||||
+ let denominator = Enclosure::point(1.0).sub(squared)?;
|
||||
+ let coefficient = Enclosure::point(2.0).div(Enclosure::point(27.0))?;
|
||||
+ let bound = Enclosure::point(radius).mul(coefficient)?.mul(sixth)?.div(denominator)?;
|
||||
+ Ok(bound.hi)
|
||||
+}
|
||||
+
|
||||
+fn make_cubic(center: Vec2, radius: f64, a0: Enclosure, a1: Enclosure, h: Enclosure) -> Result<(Seg2, f64)> {
|
||||
+ let (s0, c0) = sin_cos(a0)?;
|
||||
+ let (s1, c1) = sin_cos(a1)?;
|
||||
+ let (sh, ch) = sin_cos(h.div(Enclosure::point(4.0))?)?;
|
||||
+ let r = Enclosure::point(radius);
|
||||
+ let handle = r.mul(Enclosure::point(4.0).div(Enclosure::point(3.0))?)?.mul(sh.div(ch)?)?;
|
||||
+ let cx = Enclosure::point(center.x);
|
||||
+ let cy = Enclosure::point(center.y);
|
||||
+ let x0 = cx.add(r.mul(c0)?)?;
|
||||
+ let y0 = cy.add(r.mul(s0)?)?;
|
||||
+ let x3 = cx.add(r.mul(c1)?)?;
|
||||
+ let y3 = cy.add(r.mul(s1)?)?;
|
||||
+ let (p0, e0) = stored_point(x0, y0)?;
|
||||
+ let (p1, e1) = stored_point(x0.sub(handle.mul(s0)?)?, y0.add(handle.mul(c0)?)?)?;
|
||||
+ let (p2, e2) = stored_point(x3.add(handle.mul(s1)?)?, y3.sub(handle.mul(c1)?)?)?;
|
||||
+ let (p3, e3) = stored_point(x3, y3)?;
|
||||
+ if p0 == p3 || p0 == p1 || p2 == p3 {
|
||||
+ return Err(Invalid("cubic arc candidate: coordinate precision collapses an endpoint or tangent"));
|
||||
+ }
|
||||
+ Ok((Seg2::Cubic { p0, p1, p2, p3 }, e0.max(e1).max(e2).max(e3)))
|
||||
+}
|
||||
+
|
||||
+/// Nonnegative Bernstein coefficients sum to1, so the greatest control
|
||||
+/// displacement bounds the complete curve displacement. L1 bounds Euclidean
|
||||
+/// distance without trusting a rounded sqrt.
|
||||
+fn stored_point(x: Enclosure, y: Enclosure) -> Result<(Vec2, f64)> {
|
||||
+ let px = x.midpoint();
|
||||
+ let py = y.midpoint();
|
||||
+ let ex = x.sub(Enclosure::point(px))?.abs_upper();
|
||||
+ let ey = y.sub(Enclosure::point(py))?.abs_upper();
|
||||
+ let error = Enclosure::point(ex).add(Enclosure::point(ey))?.hi;
|
||||
+ Ok((Vec2::new(px, py), error))
|
||||
+}
|
||||
+
|
||||
+/// Twenty-four terms, then an explicit Taylor/Lagrange remainder. Input
|
||||
+/// angles stay inside +/-3PI/2; no period reduction or system trig is needed.
|
||||
+/// sin's polynomial has degree47 (degree48 coefficient0), cos's degree46
|
||||
+/// (degree47 coefficient0), giving remainder orders49 and48 respectively.
|
||||
+fn sin_cos(x: Enclosure) -> Result<(Enclosure, Enclosure)> {
|
||||
+ let negative_square = x.mul(x)?.neg();
|
||||
+ let mut sine_term = x;
|
||||
+ let mut cosine_term = Enclosure::point(1.0);
|
||||
+ let mut sine = sine_term;
|
||||
+ let mut cosine = cosine_term;
|
||||
+ for k in 1..24 {
|
||||
+ let twice = (2 * k) as f64;
|
||||
+ sine_term = sine_term.mul(negative_square)?.div(Enclosure::point(twice * (twice + 1.0)))?;
|
||||
+ cosine_term = cosine_term.mul(negative_square)?.div(Enclosure::point((twice - 1.0) * twice))?;
|
||||
+ sine = sine.add(sine_term)?;
|
||||
+ cosine = cosine.add(cosine_term)?;
|
||||
+ }
|
||||
+ let sine_tail = taylor_tail(x.abs_upper(), 49)?;
|
||||
+ let cosine_tail = taylor_tail(x.abs_upper(), 48)?;
|
||||
+ Ok((
|
||||
+ sine.add(Enclosure { lo: -sine_tail, hi: sine_tail })?,
|
||||
+ cosine.add(Enclosure { lo: -cosine_tail, hi: cosine_tail })?,
|
||||
+ ))
|
||||
+}
|
||||
+
|
||||
+fn taylor_tail(magnitude: f64, order: usize) -> Result<f64> {
|
||||
+ let mut tail = Enclosure::point(1.0);
|
||||
+ for j in 1..=order {
|
||||
+ tail = tail.mul(Enclosure::point(magnitude))?.div(Enclosure::point(j as f64))?;
|
||||
+ }
|
||||
+ Ok(tail.hi)
|
||||
+}
|
||||
+
|
||||
+/// Local private arithmetic for this helper, not a second public interval API.
|
||||
+/// Exact f64 inputs denote single real numbers. Every operation expands each
|
||||
+/// rounded endpoint by one representable neighbour; nonfinite endpoints and
|
||||
+/// division by an interval containing zero fail closed.
|
||||
+#[derive(Clone, Copy, Debug)]
|
||||
+struct Enclosure {
|
||||
+ lo: f64,
|
||||
+ hi: f64,
|
||||
+}
|
||||
+
|
||||
+impl Enclosure {
|
||||
+ fn point(value: f64) -> Self {
|
||||
+ Self { lo: value, hi: value }
|
||||
+ }
|
||||
+
|
||||
+ fn outward(lo: f64, hi: f64) -> Result<Self> {
|
||||
+ let (lo, hi) = (lo.next_down(), hi.next_up());
|
||||
+ if lo.is_finite() && hi.is_finite() && lo <= hi {
|
||||
+ Ok(Self { lo, hi })
|
||||
+ } else {
|
||||
+ Err(Invalid("cubic arc candidate: arithmetic enclosure unavailable"))
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ fn add(self, rhs: Self) -> Result<Self> {
|
||||
+ Self::outward(self.lo + rhs.lo, self.hi + rhs.hi)
|
||||
+ }
|
||||
+
|
||||
+ fn neg(self) -> Self {
|
||||
+ Self { lo: -self.hi, hi: -self.lo }
|
||||
+ }
|
||||
+
|
||||
+ fn sub(self, rhs: Self) -> Result<Self> {
|
||||
+ self.add(rhs.neg())
|
||||
+ }
|
||||
+
|
||||
+ fn mul(self, rhs: Self) -> Result<Self> {
|
||||
+ let (lo, hi) = [self.lo * rhs.lo, self.lo * rhs.hi, self.hi * rhs.lo, self.hi * rhs.hi]
|
||||
+ .into_iter()
|
||||
+ .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)));
|
||||
+ Self::outward(lo, hi)
|
||||
+ }
|
||||
+
|
||||
+ fn div(self, rhs: Self) -> Result<Self> {
|
||||
+ if rhs.lo <= 0.0 && rhs.hi >= 0.0 {
|
||||
+ return Err(Invalid("cubic arc candidate: denominator contains zero"));
|
||||
+ }
|
||||
+ self.mul(Self::outward(1.0 / rhs.hi, 1.0 / rhs.lo)?)
|
||||
+ }
|
||||
+
|
||||
+ fn abs_upper(self) -> f64 {
|
||||
+ self.lo.abs().max(self.hi.abs())
|
||||
+ }
|
||||
+
|
||||
+ fn midpoint(self) -> f64 {
|
||||
+ (self.lo * 0.5 + self.hi * 0.5).max(self.lo).min(self.hi)
|
||||
+ }
|
||||
+}
|
||||
diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs
|
||||
--- a/crates/geom/src/paper_tests.rs
|
||||
+++ b/crates/geom/src/paper_tests.rs
|
||||
@@ -459,3 +459,235 @@
|
||||
// 2.7 rounds to 3, past the rounded pattern's 2: a step into it.
|
||||
assert_eq!(stroke(&[1.4, 1.4], 2.7, millimetre), (grid_dashes(&[1, 1], 1), 0));
|
||||
}
|
||||
+
|
||||
+
|
||||
+// Private candidate acceptance only. Production paper.rs deliberately declares
|
||||
+// no cubics module: this source is included solely by the existing test file.
|
||||
+// The signature is not an agreed public API and no writer adapter is connected.
|
||||
+#[path = "paper/cubics.rs"]
|
||||
+mod circular_arc_candidate;
|
||||
+
|
||||
+fn candidate_arc(center: Vec2, radius: f64, start: f64, sweep: f64) -> Seg2 {
|
||||
+ Seg2::Arc { center, radius, start, sweep }
|
||||
+}
|
||||
+
|
||||
+fn candidate_controls(piece: &Seg2) -> [Vec2; 4] {
|
||||
+ let Seg2::Cubic { p0, p1, p2, p3 } = *piece else { panic!("candidate did not return a cubic: {piece:?}") };
|
||||
+ [p0, p1, p2, p3]
|
||||
+}
|
||||
+
|
||||
+/// Independent Bernstein evaluation, not the converter's code or a PDF reader.
|
||||
+fn candidate_bernstein(piece: &Seg2, t: f64) -> Vec2 {
|
||||
+ let [a, b, c, d] = candidate_controls(piece);
|
||||
+ let u = 1.0 - t;
|
||||
+ a * (u * u * u) + b * (3.0 * u * u * t) + c * (3.0 * u * t * t) + d * (t * t * t)
|
||||
+}
|
||||
+
|
||||
+fn candidate_near(actual: Vec2, expected: Vec2, allowance: f64) {
|
||||
+ assert!((actual - expected).len() <= allowance, "{actual:?} is not within {allowance} of {expected:?}");
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_quarter_has_independent_controls_and_endpoint_tangents() {
|
||||
+ // Unit-circle endpoints, midpoint interpolation and their tangent lines give
|
||||
+ // k=4*(sqrt(2)-1)/3, independently of the converter's subdivision/bound.
|
||||
+ let arc = candidate_arc(Vec2::ZERO, 1.0, 0.0, FRAC_PI_2);
|
||||
+ let before = arc;
|
||||
+ let result = circular_arc_candidate::circular_arc(&arc, 4e-4, 1).unwrap();
|
||||
+ assert_eq!(result.pieces.len(), 1);
|
||||
+ assert!(result.error_bound_mm.is_finite() && result.error_bound_mm > 0.0 && result.error_bound_mm <= 4e-4);
|
||||
+ let [a, b, c, d] = candidate_controls(&result.pieces[0]);
|
||||
+ let k = 4.0 * (2.0_f64.sqrt() - 1.0) / 3.0;
|
||||
+ for (actual, expected) in [(a, p(1.0, 0.0)), (b, p(1.0, k)), (c, p(k, 1.0)), (d, p(0.0, 1.0))] {
|
||||
+ candidate_near(actual, expected, 1e-11);
|
||||
+ }
|
||||
+ assert!((b.x - a.x).abs() < 1e-11 && b.y > a.y);
|
||||
+ assert!((d.y - c.y).abs() < 1e-11 && d.x < c.x);
|
||||
+ candidate_near(candidate_bernstein(&result.pieces[0], 0.5), p(0.5_f64.sqrt(), 0.5_f64.sqrt()), 1e-11);
|
||||
+ assert_eq!(arc, before);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_cap_refuses_instead_of_coarsening_or_truncating() {
|
||||
+ let arc = candidate_arc(Vec2::ZERO, 1.0, 0.0, FRAC_PI_2);
|
||||
+ // The candidate deliberately uses an algebraic upper bound larger than the
|
||||
+ // tight radial maximum. Refusal with one piece is part of that contract.
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 3e-4, 1).is_err());
|
||||
+ let result = circular_arc_candidate::circular_arc(&arc, 3e-4, 2).unwrap();
|
||||
+ assert_eq!(result.pieces.len(), 2);
|
||||
+ assert!(result.error_bound_mm <= 3e-4);
|
||||
+ assert_eq!(result.pieces[0].end(), result.pieces[1].start());
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 1e-300, 64).is_err());
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_controls_and_sampled_radial_positions_fit_literal_mm_budgets() {
|
||||
+ for (center, radius, start, sweep) in [
|
||||
+ (Vec2::ZERO, 0.5, 0.0, FRAC_PI_2),
|
||||
+ (Vec2::ZERO, 5000.0, 0.0, FRAC_PI_2),
|
||||
+ (p(11.0, -7.0), 100.0, 0.25, -FRAC_PI_2),
|
||||
+ (p(-20.0, 30.0), 12.0, PI, FRAC_PI_2),
|
||||
+ ] {
|
||||
+ let arc = candidate_arc(center, radius, start, sweep);
|
||||
+ let before = arc;
|
||||
+ // Reserve 1e-5 mm for a later writer's gridding. This helper does not
|
||||
+ // perform that gridding or claim complete PDF error by itself.
|
||||
+ let result = circular_arc_candidate::circular_arc(&arc, 1e-4 - 1e-5, 64).unwrap();
|
||||
+ assert!(!result.pieces.is_empty() && result.pieces.len() <= 64);
|
||||
+ assert!(result.error_bound_mm <= 1e-4 - 1e-5);
|
||||
+ for pair in result.pieces.windows(2) {
|
||||
+ assert_eq!(pair[0].end(), pair[1].start());
|
||||
+ }
|
||||
+ for piece in &result.pieces {
|
||||
+ assert!(candidate_controls(piece).into_iter().all(Vec2::is_finite));
|
||||
+ for j in 0..=256 {
|
||||
+ let point = candidate_bernstein(piece, j as f64 / 256.0);
|
||||
+ let deviation = ((point - center).len() - radius).abs();
|
||||
+ assert!(deviation <= result.error_bound_mm, "{deviation} > {}", result.error_bound_mm);
|
||||
+ }
|
||||
+ }
|
||||
+ // Endpoint checks use the independent circle equations in the test,
|
||||
+ // with their f64 evaluation accounted for by a modest comparison scale.
|
||||
+ let end = start + sweep;
|
||||
+ candidate_near(result.pieces.first().unwrap().start(), center + p(start.cos(), start.sin()) * radius, 1e-8);
|
||||
+ candidate_near(result.pieces.last().unwrap().end(), center + p(end.cos(), end.sin()) * radius, 1e-8);
|
||||
+ assert_eq!(arc, before);
|
||||
+ }
|
||||
+ // These samples supplement the analytical derivation. They are not the
|
||||
+ // certificate for between-sample deviation or an external viewer's grid.
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_reversal_and_translation_keep_geometry_and_tangent_direction() {
|
||||
+ let start = FRAC_PI_2 - 0.4;
|
||||
+ let sweep = 0.7;
|
||||
+ let original = candidate_arc(Vec2::ZERO, 12.0, start, sweep);
|
||||
+ let reverse = candidate_arc(Vec2::ZERO, 12.0, start + sweep, -sweep);
|
||||
+ let translation = p(11.0, -7.0);
|
||||
+ let shifted = candidate_arc(translation, 12.0, start, sweep);
|
||||
+ let a = circular_arc_candidate::circular_arc(&original, 1e-6, 64).unwrap();
|
||||
+ let b = circular_arc_candidate::circular_arc(&reverse, 1e-6, 64).unwrap();
|
||||
+ let c = circular_arc_candidate::circular_arc(&shifted, 1e-6, 64).unwrap();
|
||||
+ assert_eq!(a.pieces.len(), b.pieces.len());
|
||||
+ assert_eq!(a.pieces.len(), c.pieces.len());
|
||||
+ for ((forward, backward), translated) in a.pieces.iter().zip(b.pieces.iter().rev()).zip(&c.pieces) {
|
||||
+ for ((x, y), z) in candidate_controls(forward)
|
||||
+ .into_iter()
|
||||
+ .zip(candidate_controls(backward).into_iter().rev())
|
||||
+ .zip(candidate_controls(translated))
|
||||
+ {
|
||||
+ candidate_near(x, y, 1e-9);
|
||||
+ candidate_near(x + translation, z, 1e-9);
|
||||
+ }
|
||||
+ }
|
||||
+ let [p0, p1, _, _] = candidate_controls(a.pieces.first().unwrap());
|
||||
+ let radial = p0;
|
||||
+ let tangent = p1 - p0;
|
||||
+ assert!(radial.x * tangent.y - radial.y * tangent.x > 0.0);
|
||||
+ let [q0, q1, _, _] = candidate_controls(b.pieces.first().unwrap());
|
||||
+ let tangent = q1 - q0;
|
||||
+ assert!(q0.x * tangent.y - q0.y * tangent.x < 0.0);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_calls_are_deterministic_and_tighter_budget_never_loosens_output() {
|
||||
+ let arc = candidate_arc(p(30.0, -12.0), 100.0, -0.5, 1.25);
|
||||
+ let loose = circular_arc_candidate::circular_arc(&arc, 1e-3, 64).unwrap();
|
||||
+ let tight = circular_arc_candidate::circular_arc(&arc, 1e-5, 64).unwrap();
|
||||
+ assert_eq!(tight, circular_arc_candidate::circular_arc(&arc, 1e-5, 64).unwrap());
|
||||
+ assert!(tight.error_bound_mm <= 1e-5);
|
||||
+ assert!(tight.pieces.len() >= loose.pieces.len());
|
||||
+ candidate_near(loose.pieces.first().unwrap().start(), tight.pieces.first().unwrap().start(), 1e-9);
|
||||
+ candidate_near(loose.pieces.last().unwrap().end(), tight.pieces.last().unwrap().end(), 1e-9);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_invalid_budgets_and_caps_are_refused_before_large_allocation() {
|
||||
+ let arc = candidate_arc(Vec2::ZERO, 1.0, 0.0, FRAC_PI_2);
|
||||
+ for error in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, error, 64).is_err());
|
||||
+ }
|
||||
+ for cap in [0, 65, usize::MAX] {
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 1e-4, cap).is_err());
|
||||
+ }
|
||||
+ // Allocation uses try_reserve_exact under the fixed64 ceiling. No allocator
|
||||
+ // failure is manufactured here; that fallible path remains source-reviewed.
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_hostile_fields_and_unadmitted_encodings_are_refused() {
|
||||
+ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, -f64::MAX] {
|
||||
+ for arc in [
|
||||
+ candidate_arc(p(value, 0.0), 1.0, 0.0, FRAC_PI_2),
|
||||
+ candidate_arc(p(0.0, value), 1.0, 0.0, FRAC_PI_2),
|
||||
+ candidate_arc(Vec2::ZERO, value, 0.0, FRAC_PI_2),
|
||||
+ candidate_arc(Vec2::ZERO, 1.0, value, FRAC_PI_2),
|
||||
+ candidate_arc(Vec2::ZERO, 1.0, 0.0, value),
|
||||
+ ] {
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 1e-4, 64).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+ for radius in [0.0, -0.0, -1.0] {
|
||||
+ assert!(circular_arc_candidate::circular_arc(&candidate_arc(Vec2::ZERO, radius, 0.0, FRAC_PI_2), 1e-4, 64).is_err());
|
||||
+ }
|
||||
+ for (start, sweep) in [
|
||||
+ (0.0, 0.0),
|
||||
+ (0.0, -0.0),
|
||||
+ (0.0, FRAC_PI_2.next_up()),
|
||||
+ (0.0, -FRAC_PI_2.next_up()),
|
||||
+ (PI.next_up(), 0.5),
|
||||
+ (-PI.next_up(), 0.5),
|
||||
+ ] {
|
||||
+ assert!(circular_arc_candidate::circular_arc(&candidate_arc(Vec2::ZERO, 1.0, start, sweep), 1e-4, 64).is_err());
|
||||
+ }
|
||||
+ assert!(circular_arc_candidate::circular_arc(&line(Vec2::ZERO, Vec2::X), 1e-4, 64).is_err());
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_coordinate_collapse_is_a_refusal_not_a_degenerate_success() {
|
||||
+ let arc = candidate_arc(p(100_000.0, 100_000.0), 1e-12, 0.5, 1e-12);
|
||||
+ let before = arc;
|
||||
+ arc.check(MAX_COORDINATE_MM).unwrap();
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 1e-4, 64).is_err());
|
||||
+ assert_eq!(arc, before);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_least_subnormal_allowance_is_refused_at_fixed_cap() {
|
||||
+ let arc = candidate_arc(Vec2::ZERO, 1.0, 0.0, FRAC_PI_2);
|
||||
+ let before = arc;
|
||||
+ arc.check(MAX_COORDINATE_MM).unwrap();
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, f64::from_bits(1), 64).is_err());
|
||||
+ assert_eq!(arc, before);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_subnormal_radius_and_sweep_fail_existing_admission() {
|
||||
+ let least = f64::from_bits(1);
|
||||
+ for arc in [
|
||||
+ candidate_arc(Vec2::ZERO, least, 0.0, FRAC_PI_2),
|
||||
+ candidate_arc(Vec2::ZERO, 1.0, 0.0, least),
|
||||
+ candidate_arc(Vec2::ZERO, 1.0, 0.0, -least),
|
||||
+ ] {
|
||||
+ let before = arc;
|
||||
+ assert!(arc.check(MAX_COORDINATE_MM).is_err());
|
||||
+ assert!(circular_arc_candidate::circular_arc(&arc, 1e-4, 64).is_err());
|
||||
+ assert_eq!(arc, before);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn candidate_circular_subnormal_center_accepts_finite_maximum_allowance() {
|
||||
+ let least = f64::from_bits(1);
|
||||
+ let arc = candidate_arc(p(least, -least), 1.0, 0.0, FRAC_PI_2);
|
||||
+ let before = arc;
|
||||
+ arc.check(MAX_COORDINATE_MM).unwrap();
|
||||
+ let result = circular_arc_candidate::circular_arc(&arc, f64::MAX, 1).unwrap();
|
||||
+ assert_eq!(result.pieces.len(), 1);
|
||||
+ assert!(result.error_bound_mm.is_finite() && result.error_bound_mm > 0.0);
|
||||
+ for piece in &result.pieces {
|
||||
+ assert!(candidate_controls(piece).into_iter().all(Vec2::is_finite));
|
||||
+ }
|
||||
+ assert_eq!(arc, before);
|
||||
+}
|
||||
+
|
||||
@@ -0,0 +1,7 @@
|
||||
diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs
|
||||
--- a/crates/geom/src/paper_tests.rs
|
||||
+++ b/crates/geom/src/paper_tests.rs
|
||||
@@ -693,0 +694,3 @@
|
||||
+
|
||||
+#[path = "paper/grid_endpoint_acceptance.rs"]
|
||||
+mod grid_endpoint_acceptance;
|
||||
@@ -0,0 +1,11 @@
|
||||
diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs
|
||||
--- a/crates/geom/src/paper.rs
|
||||
+++ b/crates/geom/src/paper.rs
|
||||
@@ -46,6 +46,7 @@
|
||||
|
||||
use crate::{EPS, Region2, Seg2, Vec2};
|
||||
|
||||
+pub(crate) mod cubics;
|
||||
pub mod flatten;
|
||||
pub mod grid;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
diff --git a/crates/geom/src/paper/cubics.rs b/crates/geom/src/paper/cubics.rs
|
||||
--- a/crates/geom/src/paper/cubics.rs
|
||||
+++ b/crates/geom/src/paper/cubics.rs
|
||||
@@ -20,6 +20,8 @@
|
||||
//!
|
||||
//! This bound excludes later writer-grid snapping and endpoint replacement.
|
||||
//! A consumer must reserve and qualify those separately. No adapter is supplied.
|
||||
+
|
||||
+pub(crate) mod segments;
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
diff --git a/crates/geom/src/paper/cubics/segments.rs b/crates/geom/src/paper/cubics/segments.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/geom/src/paper/cubics/segments.rs
|
||||
@@ -0,0 +1,250 @@
|
||||
+//! Private proposed Seg2 adapter; not an existing or connected upstream API.
|
||||
+//! Geometry is already in local paper millimetres. No placement, grid snapping,
|
||||
+//! endpoint replacement, closure repair, style or writer operation occurs.
|
||||
+//! Line/Cubic fields are copied bit for bit if finite, including signed zero;
|
||||
+//! this is not Scene admission and does not impose its coordinate/collapse rules.
|
||||
+//! Arcs inherit circular_arc's stricter admission and conservative mm bound.
|
||||
+//! Conics and higher-degree Beziers are explicitly unsupported.
|
||||
+
|
||||
+use super::{MAX_ARC_CUBICS, circular_arc};
|
||||
+use crate::paper::Invalid;
|
||||
+use crate::Seg2;
|
||||
+
|
||||
+type Result<T> = std::result::Result<T, Invalid>;
|
||||
+
|
||||
+/// Caller ceilings, independently required to be in1..=64; never clamped.
|
||||
+/// Work counts one unit per copied segment and the worst-case number of trial
|
||||
+/// cubic slots across a helper call (1+...+helper_cap), even on early success.
|
||||
+/// Fixed per-slot interval recurrences are inherited from the frozen helper.
|
||||
+/// Input validation/iteration is separately bounded by input, also <=64.
|
||||
+#[derive(Clone, Copy, Debug)]
|
||||
+pub(crate) struct SegmentCaps {
|
||||
+ pub(crate) input: usize,
|
||||
+ pub(crate) output: usize,
|
||||
+ pub(crate) work: usize,
|
||||
+}
|
||||
+
|
||||
+/// Return only Lines/Cubics, preserving input sequence and arc sweep direction.
|
||||
+/// Each arc independently satisfies error_mm in local mm; this is a maximum
|
||||
+/// geometric displacement bound, not a sum over paths or a writer error budget.
|
||||
+/// No partial output is returned if any field, cap, allocation or arc refuses.
|
||||
+/// Conservative worst-case work charging may refuse otherwise convertible data.
|
||||
+pub(crate) fn segments(source: &[Seg2], error_mm: f64, caps: SegmentCaps) -> Result<Vec<Seg2>> {
|
||||
+ if [caps.input, caps.output, caps.work].into_iter().any(|cap| !(1..=MAX_ARC_CUBICS).contains(&cap)) {
|
||||
+ return Err(Invalid("segment candidate: every caller cap must be from1 to64"));
|
||||
+ }
|
||||
+ if source.len() > caps.input {
|
||||
+ return Err(Invalid("segment candidate: input cap exceeded"));
|
||||
+ }
|
||||
+ if !error_mm.is_finite() || error_mm <= 0.0 {
|
||||
+ return Err(Invalid("segment candidate: finite positive mm error required"));
|
||||
+ }
|
||||
+ let mut output = Vec::new();
|
||||
+ output.try_reserve_exact(caps.output)
|
||||
+ .map_err(|_| Invalid("segment candidate: cannot allocate bounded output"))?;
|
||||
+ let mut work = 0;
|
||||
+ for segment in source {
|
||||
+ let remaining_output = caps.output.checked_sub(output.len())
|
||||
+ .ok_or(Invalid("segment candidate: output accounting exceeded"))?;
|
||||
+ let remaining_work = caps.work.checked_sub(work)
|
||||
+ .ok_or(Invalid("segment candidate: work accounting exceeded"))?;
|
||||
+ if remaining_output == 0 || remaining_work == 0 {
|
||||
+ return Err(Invalid("segment candidate: output or work cap exhausted"));
|
||||
+ }
|
||||
+ match *segment {
|
||||
+ Seg2::Line { a, b } => {
|
||||
+ if !a.is_finite() || !b.is_finite() {
|
||||
+ return Err(Invalid("segment candidate: nonfinite line coordinate"));
|
||||
+ }
|
||||
+ output.push(*segment);
|
||||
+ work += 1;
|
||||
+ }
|
||||
+ Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
+ if ![p0, p1, p2, p3].into_iter().all(|point| point.is_finite()) {
|
||||
+ return Err(Invalid("segment candidate: nonfinite cubic coordinate"));
|
||||
+ }
|
||||
+ output.push(*segment);
|
||||
+ work += 1;
|
||||
+ }
|
||||
+ Seg2::Arc { .. } => {
|
||||
+ // Each candidate k can attempt k(k+1)/2 trial cubic slots.
|
||||
+ // Select an internal budget within the unmodified caller caps.
|
||||
+ // k<=64 makes these integer calculations bounded and exact.
|
||||
+ let mut helper_cap = 0;
|
||||
+ let mut charge = 0;
|
||||
+ for candidate in 1..=MAX_ARC_CUBICS {
|
||||
+ let trial_slots = candidate * (candidate + 1) / 2;
|
||||
+ if candidate <= remaining_output && trial_slots <= remaining_work {
|
||||
+ helper_cap = candidate;
|
||||
+ charge = trial_slots;
|
||||
+ }
|
||||
+ }
|
||||
+ if helper_cap == 0 {
|
||||
+ return Err(Invalid("segment candidate: no certified helper work budget"));
|
||||
+ }
|
||||
+ let converted = circular_arc(segment, error_mm, helper_cap)?;
|
||||
+ if converted.pieces.is_empty() || converted.pieces.len() > helper_cap
|
||||
+ || !converted.error_bound_mm.is_finite() || converted.error_bound_mm > error_mm
|
||||
+ || converted.pieces.iter().any(|piece| !matches!(piece, Seg2::Cubic { .. }))
|
||||
+ {
|
||||
+ return Err(Invalid("segment candidate: unexpected helper result"));
|
||||
+ }
|
||||
+ // Reserved output capacity covers every push; no hidden extend allocation.
|
||||
+ for piece in converted.pieces {
|
||||
+ output.push(piece);
|
||||
+ }
|
||||
+ work += charge;
|
||||
+ }
|
||||
+ Seg2::Conic { .. } | Seg2::Bezier { .. } => {
|
||||
+ return Err(Invalid("not supported yet: conic or higher-degree Bezier segment conversion"));
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(output)
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::*;
|
||||
+ use crate::{MAX_BEZIER_CTRL, Vec2};
|
||||
+ use std::f64::consts::{FRAC_PI_2, PI};
|
||||
+
|
||||
+ fn caps() -> SegmentCaps {
|
||||
+ SegmentCaps { input: 64, output: 64, work: 64 }
|
||||
+ }
|
||||
+
|
||||
+ fn arc(sweep: f64) -> Seg2 {
|
||||
+ Seg2::Arc { center: Vec2::ZERO, radius: 1.0, start: 0.0, sweep }
|
||||
+ }
|
||||
+
|
||||
+ fn bits(segment: &Seg2) -> Vec<u64> {
|
||||
+ let points = match *segment {
|
||||
+ Seg2::Line { a, b } => vec![a, b],
|
||||
+ Seg2::Cubic { p0, p1, p2, p3 } => vec![p0, p1, p2, p3],
|
||||
+ _ => panic!("test expects a line or cubic"),
|
||||
+ };
|
||||
+ points.into_iter().flat_map(|point| [point.x.to_bits(), point.y.to_bits()]).collect()
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn finite_passthrough_is_bit_exact_including_signed_zero_and_large_coordinates() {
|
||||
+ let source = [
|
||||
+ Seg2::Line { a: Vec2::new(-0.0, f64::MAX), b: Vec2::new(0.0, -f64::MAX) },
|
||||
+ Seg2::Cubic {
|
||||
+ p0: Vec2::new(-0.0, 0.0), p1: Vec2::new(f64::from_bits(1), -0.0),
|
||||
+ p2: Vec2::new(-f64::MAX, f64::MAX), p3: Vec2::new(0.0, -0.0),
|
||||
+ },
|
||||
+ Seg2::Line { a: Vec2::ZERO, b: Vec2::ZERO },
|
||||
+ ];
|
||||
+ let before: Vec<_> = source.iter().map(bits).collect();
|
||||
+ let result = segments(&source, 1e-4, caps()).unwrap();
|
||||
+ assert_eq!(result.len(), source.len());
|
||||
+ assert_eq!(result.iter().map(bits).collect::<Vec<_>>(), before);
|
||||
+ assert_eq!(source.iter().map(bits).collect::<Vec<_>>(), before);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mixed_input_keeps_order_and_inputs_without_applying_a_placement() {
|
||||
+ let line = Seg2::Line { a: Vec2::new(20.0, 30.0), b: Vec2::new(21.0, 30.0) };
|
||||
+ let cubic = Seg2::Cubic {
|
||||
+ p0: Vec2::new(40.0, 0.0), p1: Vec2::new(41.0, 1.0),
|
||||
+ p2: Vec2::new(42.0, 1.0), p3: Vec2::new(43.0, 0.0),
|
||||
+ };
|
||||
+ let source = [line, arc(-FRAC_PI_2), cubic, line];
|
||||
+ let before = source;
|
||||
+ let result = segments(&source, 1e-4, caps()).unwrap();
|
||||
+ assert!(result.len() > source.len() && result.len() <= 64);
|
||||
+ assert_eq!(bits(result.first().unwrap()), bits(&line));
|
||||
+ let tail = result.get(result.len() - 2..).unwrap();
|
||||
+ assert_eq!(bits(tail.first().unwrap()), bits(&cubic));
|
||||
+ assert_eq!(bits(tail.last().unwrap()), bits(&line));
|
||||
+ for piece in result.iter().skip(1).take(result.len() - 3) {
|
||||
+ assert!(matches!(piece, Seg2::Cubic { .. }));
|
||||
+ }
|
||||
+ assert_eq!(source, before);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn positive_and_negative_sweeps_keep_independent_endpoint_and_tangent_direction() {
|
||||
+ for sign in [-1.0, 1.0] {
|
||||
+ let result = segments(&[arc(sign * FRAC_PI_2)], 1e-4, caps()).unwrap();
|
||||
+ assert!((result.first().unwrap().start() - Vec2::new(1.0, 0.0)).len() < 1e-10);
|
||||
+ assert!((result.last().unwrap().end() - Vec2::new(0.0, sign)).len() < 1e-10);
|
||||
+ let Seg2::Cubic { p0, p1, .. } = *result.first().unwrap() else { panic!("cubic required") };
|
||||
+ let tangent = p1 - p0;
|
||||
+ assert!(sign * (p0.x * tangent.y - p0.y * tangent.x) > 0.0);
|
||||
+ for pair in result.windows(2) {
|
||||
+ assert_eq!(pair[0].end(), pair[1].start());
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn all_caller_caps_are_validated_without_clamping() {
|
||||
+ for bad in [0, 65, usize::MAX] {
|
||||
+ for limit in [
|
||||
+ SegmentCaps { input: bad, ..caps() },
|
||||
+ SegmentCaps { output: bad, ..caps() },
|
||||
+ SegmentCaps { work: bad, ..caps() },
|
||||
+ ] {
|
||||
+ assert!(segments(&[], 1e-4, limit).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+ let line = Seg2::Line { a: Vec2::ZERO, b: Vec2::new(1.0, 0.0) };
|
||||
+ assert!(segments(&[line, line], 1e-4, SegmentCaps { input: 1, ..caps() }).is_err());
|
||||
+ assert!(segments(&[line, line], 1e-4, SegmentCaps { output: 1, ..caps() }).is_err());
|
||||
+ assert!(segments(&[line, line], 1e-4, SegmentCaps { work: 1, ..caps() }).is_err());
|
||||
+ assert_eq!(segments(&[line; 64], 1e-4, caps()).unwrap().len(), 64);
|
||||
+ assert!(segments(&[line; 65], 1e-4, caps()).is_err());
|
||||
+ assert!(segments(&[], 1e-4, caps()).unwrap().is_empty());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn arc_output_and_global_trial_work_exhaustion_refuse() {
|
||||
+ let quarter = arc(FRAC_PI_2);
|
||||
+ assert!(segments(&[quarter], 1e-4, SegmentCaps { output: 1, ..caps() }).is_err());
|
||||
+ // At work2 only helper_cap1 is permitted, and this quarter needs more.
|
||||
+ assert!(segments(&[quarter], 1e-4, SegmentCaps { work: 2, ..caps() }).is_err());
|
||||
+ // Two one-cubic calls cost1 each; a third exceeds the global work cap.
|
||||
+ assert_eq!(segments(&[quarter; 2], 4e-4, SegmentCaps { work: 2, ..caps() }).unwrap().len(), 2);
|
||||
+ assert!(segments(&[quarter; 3], 4e-4, SegmentCaps { work: 2, ..caps() }).is_err());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn every_passthrough_coordinate_refuses_nan_or_infinity() {
|
||||
+ for hostile in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
+ for slot in 0..8 {
|
||||
+ let mut values = [1.0; 8];
|
||||
+ values[slot] = hostile;
|
||||
+ let points = [
|
||||
+ Vec2::new(values[0], values[1]), Vec2::new(values[2], values[3]),
|
||||
+ Vec2::new(values[4], values[5]), Vec2::new(values[6], values[7]),
|
||||
+ ];
|
||||
+ let cubic = Seg2::Cubic { p0: points[0], p1: points[1], p2: points[2], p3: points[3] };
|
||||
+ assert!(segments(&[cubic], 1e-4, caps()).is_err());
|
||||
+ if slot < 4 {
|
||||
+ let line = Seg2::Line { a: points[0], b: points[1] };
|
||||
+ assert!(segments(&[line], 1e-4, caps()).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn unsupported_and_hostile_arcs_refuse_instead_of_returning_a_partial_prefix() {
|
||||
+ let line = Seg2::Line { a: Vec2::ZERO, b: Vec2::new(1.0, 0.0) };
|
||||
+ for refused in [
|
||||
+ Seg2::Conic { a: Vec2::ZERO, apex: Vec2::new(1.0, 1.0), b: Vec2::new(2.0, 0.0), w: 1.0 },
|
||||
+ Seg2::Bezier { n: 4, p: [Vec2::ZERO; MAX_BEZIER_CTRL] },
|
||||
+ Seg2::Arc { center: Vec2::ZERO, radius: 0.0, start: 0.0, sweep: FRAC_PI_2 },
|
||||
+ Seg2::Arc { center: Vec2::new(f64::NAN, 0.0), radius: 1.0, start: 0.0, sweep: FRAC_PI_2 },
|
||||
+ arc(PI),
|
||||
+ ] {
|
||||
+ assert!(segments(&[line, refused, line], 1e-4, caps()).is_err());
|
||||
+ }
|
||||
+ for error in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
+ assert!(segments(&[line], error, caps()).is_err());
|
||||
+ }
|
||||
+ assert!(segments(&[arc(FRAC_PI_2)], f64::from_bits(1), caps()).is_err());
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Private proposed Seg2 adapter; not an existing or connected upstream API.
|
||||
//! Geometry is already in local paper millimetres. No placement, grid snapping,
|
||||
//! endpoint replacement, closure repair, style or writer operation occurs.
|
||||
//! Line/Cubic fields are copied bit for bit if finite, including signed zero;
|
||||
//! this is not Scene admission and does not impose its coordinate/collapse rules.
|
||||
//! Arcs inherit circular_arc's stricter admission and conservative mm bound.
|
||||
//! Conics and higher-degree Beziers are explicitly unsupported.
|
||||
|
||||
use super::{MAX_ARC_CUBICS, circular_arc};
|
||||
use crate::paper::Invalid;
|
||||
use crate::Seg2;
|
||||
|
||||
type Result<T> = std::result::Result<T, Invalid>;
|
||||
|
||||
/// Caller ceilings, independently required to be in1..=64; never clamped.
|
||||
/// Work counts one unit per copied segment and the worst-case number of trial
|
||||
/// cubic slots across a helper call (1+...+helper_cap), even on early success.
|
||||
/// Fixed per-slot interval recurrences are inherited from the frozen helper.
|
||||
/// Input validation/iteration is separately bounded by input, also <=64.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct SegmentCaps {
|
||||
pub(crate) input: usize,
|
||||
pub(crate) output: usize,
|
||||
pub(crate) work: usize,
|
||||
}
|
||||
|
||||
/// Return only Lines/Cubics, preserving input sequence and arc sweep direction.
|
||||
/// Each arc independently satisfies error_mm in local mm; this is a maximum
|
||||
/// geometric displacement bound, not a sum over paths or a writer error budget.
|
||||
/// No partial output is returned if any field, cap, allocation or arc refuses.
|
||||
/// Conservative worst-case work charging may refuse otherwise convertible data.
|
||||
pub(crate) fn segments(source: &[Seg2], error_mm: f64, caps: SegmentCaps) -> Result<Vec<Seg2>> {
|
||||
if [caps.input, caps.output, caps.work].into_iter().any(|cap| !(1..=MAX_ARC_CUBICS).contains(&cap)) {
|
||||
return Err(Invalid("segment candidate: every caller cap must be from1 to64"));
|
||||
}
|
||||
if source.len() > caps.input {
|
||||
return Err(Invalid("segment candidate: input cap exceeded"));
|
||||
}
|
||||
if !error_mm.is_finite() || error_mm <= 0.0 {
|
||||
return Err(Invalid("segment candidate: finite positive mm error required"));
|
||||
}
|
||||
let mut output = Vec::new();
|
||||
output.try_reserve_exact(caps.output)
|
||||
.map_err(|_| Invalid("segment candidate: cannot allocate bounded output"))?;
|
||||
let mut work = 0;
|
||||
for segment in source {
|
||||
let remaining_output = caps.output.checked_sub(output.len())
|
||||
.ok_or(Invalid("segment candidate: output accounting exceeded"))?;
|
||||
let remaining_work = caps.work.checked_sub(work)
|
||||
.ok_or(Invalid("segment candidate: work accounting exceeded"))?;
|
||||
if remaining_output == 0 || remaining_work == 0 {
|
||||
return Err(Invalid("segment candidate: output or work cap exhausted"));
|
||||
}
|
||||
match *segment {
|
||||
Seg2::Line { a, b } => {
|
||||
if !a.is_finite() || !b.is_finite() {
|
||||
return Err(Invalid("segment candidate: nonfinite line coordinate"));
|
||||
}
|
||||
output.push(*segment);
|
||||
work += 1;
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
if ![p0, p1, p2, p3].into_iter().all(|point| point.is_finite()) {
|
||||
return Err(Invalid("segment candidate: nonfinite cubic coordinate"));
|
||||
}
|
||||
output.push(*segment);
|
||||
work += 1;
|
||||
}
|
||||
Seg2::Arc { .. } => {
|
||||
// Each candidate k can attempt k(k+1)/2 trial cubic slots.
|
||||
// Select an internal budget within the unmodified caller caps.
|
||||
// k<=64 makes these integer calculations bounded and exact.
|
||||
let mut helper_cap = 0;
|
||||
let mut charge = 0;
|
||||
for candidate in 1..=MAX_ARC_CUBICS {
|
||||
let trial_slots = candidate * (candidate + 1) / 2;
|
||||
if candidate <= remaining_output && trial_slots <= remaining_work {
|
||||
helper_cap = candidate;
|
||||
charge = trial_slots;
|
||||
}
|
||||
}
|
||||
if helper_cap == 0 {
|
||||
return Err(Invalid("segment candidate: no certified helper work budget"));
|
||||
}
|
||||
let converted = circular_arc(segment, error_mm, helper_cap)?;
|
||||
if converted.pieces.is_empty() || converted.pieces.len() > helper_cap
|
||||
|| !converted.error_bound_mm.is_finite() || converted.error_bound_mm > error_mm
|
||||
|| converted.pieces.iter().any(|piece| !matches!(piece, Seg2::Cubic { .. }))
|
||||
{
|
||||
return Err(Invalid("segment candidate: unexpected helper result"));
|
||||
}
|
||||
// Reserved output capacity covers every push; no hidden extend allocation.
|
||||
for piece in converted.pieces {
|
||||
output.push(piece);
|
||||
}
|
||||
work += charge;
|
||||
}
|
||||
Seg2::Conic { .. } | Seg2::Bezier { .. } => {
|
||||
return Err(Invalid("not supported yet: conic or higher-degree Bezier segment conversion"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{MAX_BEZIER_CTRL, Vec2};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
fn caps() -> SegmentCaps {
|
||||
SegmentCaps { input: 64, output: 64, work: 64 }
|
||||
}
|
||||
|
||||
fn arc(sweep: f64) -> Seg2 {
|
||||
Seg2::Arc { center: Vec2::ZERO, radius: 1.0, start: 0.0, sweep }
|
||||
}
|
||||
|
||||
fn bits(segment: &Seg2) -> Vec<u64> {
|
||||
let points = match *segment {
|
||||
Seg2::Line { a, b } => vec![a, b],
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => vec![p0, p1, p2, p3],
|
||||
_ => panic!("test expects a line or cubic"),
|
||||
};
|
||||
points.into_iter().flat_map(|point| [point.x.to_bits(), point.y.to_bits()]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_passthrough_is_bit_exact_including_signed_zero_and_large_coordinates() {
|
||||
let source = [
|
||||
Seg2::Line { a: Vec2::new(-0.0, f64::MAX), b: Vec2::new(0.0, -f64::MAX) },
|
||||
Seg2::Cubic {
|
||||
p0: Vec2::new(-0.0, 0.0), p1: Vec2::new(f64::from_bits(1), -0.0),
|
||||
p2: Vec2::new(-f64::MAX, f64::MAX), p3: Vec2::new(0.0, -0.0),
|
||||
},
|
||||
Seg2::Line { a: Vec2::ZERO, b: Vec2::ZERO },
|
||||
];
|
||||
let before: Vec<_> = source.iter().map(bits).collect();
|
||||
let result = segments(&source, 1e-4, caps()).unwrap();
|
||||
assert_eq!(result.len(), source.len());
|
||||
assert_eq!(result.iter().map(bits).collect::<Vec<_>>(), before);
|
||||
assert_eq!(source.iter().map(bits).collect::<Vec<_>>(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_input_keeps_order_and_inputs_without_applying_a_placement() {
|
||||
let line = Seg2::Line { a: Vec2::new(20.0, 30.0), b: Vec2::new(21.0, 30.0) };
|
||||
let cubic = Seg2::Cubic {
|
||||
p0: Vec2::new(40.0, 0.0), p1: Vec2::new(41.0, 1.0),
|
||||
p2: Vec2::new(42.0, 1.0), p3: Vec2::new(43.0, 0.0),
|
||||
};
|
||||
let source = [line, arc(-FRAC_PI_2), cubic, line];
|
||||
let before = source;
|
||||
let result = segments(&source, 1e-4, caps()).unwrap();
|
||||
assert!(result.len() > source.len() && result.len() <= 64);
|
||||
assert_eq!(bits(result.first().unwrap()), bits(&line));
|
||||
let tail = result.get(result.len() - 2..).unwrap();
|
||||
assert_eq!(bits(tail.first().unwrap()), bits(&cubic));
|
||||
assert_eq!(bits(tail.last().unwrap()), bits(&line));
|
||||
for piece in result.iter().skip(1).take(result.len() - 3) {
|
||||
assert!(matches!(piece, Seg2::Cubic { .. }));
|
||||
}
|
||||
assert_eq!(source, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_and_negative_sweeps_keep_independent_endpoint_and_tangent_direction() {
|
||||
for sign in [-1.0, 1.0] {
|
||||
let result = segments(&[arc(sign * FRAC_PI_2)], 1e-4, caps()).unwrap();
|
||||
assert!((result.first().unwrap().start() - Vec2::new(1.0, 0.0)).len() < 1e-10);
|
||||
assert!((result.last().unwrap().end() - Vec2::new(0.0, sign)).len() < 1e-10);
|
||||
let Seg2::Cubic { p0, p1, .. } = *result.first().unwrap() else { panic!("cubic required") };
|
||||
let tangent = p1 - p0;
|
||||
assert!(sign * (p0.x * tangent.y - p0.y * tangent.x) > 0.0);
|
||||
for pair in result.windows(2) {
|
||||
assert_eq!(pair[0].end(), pair[1].start());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_caller_caps_are_validated_without_clamping() {
|
||||
for bad in [0, 65, usize::MAX] {
|
||||
for limit in [
|
||||
SegmentCaps { input: bad, ..caps() },
|
||||
SegmentCaps { output: bad, ..caps() },
|
||||
SegmentCaps { work: bad, ..caps() },
|
||||
] {
|
||||
assert!(segments(&[], 1e-4, limit).is_err());
|
||||
}
|
||||
}
|
||||
let line = Seg2::Line { a: Vec2::ZERO, b: Vec2::new(1.0, 0.0) };
|
||||
assert!(segments(&[line, line], 1e-4, SegmentCaps { input: 1, ..caps() }).is_err());
|
||||
assert!(segments(&[line, line], 1e-4, SegmentCaps { output: 1, ..caps() }).is_err());
|
||||
assert!(segments(&[line, line], 1e-4, SegmentCaps { work: 1, ..caps() }).is_err());
|
||||
assert_eq!(segments(&[line; 64], 1e-4, caps()).unwrap().len(), 64);
|
||||
assert!(segments(&[line; 65], 1e-4, caps()).is_err());
|
||||
assert!(segments(&[], 1e-4, caps()).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_output_and_global_trial_work_exhaustion_refuse() {
|
||||
let quarter = arc(FRAC_PI_2);
|
||||
assert!(segments(&[quarter], 1e-4, SegmentCaps { output: 1, ..caps() }).is_err());
|
||||
// At work2 only helper_cap1 is permitted, and this quarter needs more.
|
||||
assert!(segments(&[quarter], 1e-4, SegmentCaps { work: 2, ..caps() }).is_err());
|
||||
// Two one-cubic calls cost1 each; a third exceeds the global work cap.
|
||||
assert_eq!(segments(&[quarter; 2], 4e-4, SegmentCaps { work: 2, ..caps() }).unwrap().len(), 2);
|
||||
assert!(segments(&[quarter; 3], 4e-4, SegmentCaps { work: 2, ..caps() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_passthrough_coordinate_refuses_nan_or_infinity() {
|
||||
for hostile in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
for slot in 0..8 {
|
||||
let mut values = [1.0; 8];
|
||||
values[slot] = hostile;
|
||||
let points = [
|
||||
Vec2::new(values[0], values[1]), Vec2::new(values[2], values[3]),
|
||||
Vec2::new(values[4], values[5]), Vec2::new(values[6], values[7]),
|
||||
];
|
||||
let cubic = Seg2::Cubic { p0: points[0], p1: points[1], p2: points[2], p3: points[3] };
|
||||
assert!(segments(&[cubic], 1e-4, caps()).is_err());
|
||||
if slot < 4 {
|
||||
let line = Seg2::Line { a: points[0], b: points[1] };
|
||||
assert!(segments(&[line], 1e-4, caps()).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_hostile_arcs_refuse_instead_of_returning_a_partial_prefix() {
|
||||
let line = Seg2::Line { a: Vec2::ZERO, b: Vec2::new(1.0, 0.0) };
|
||||
for refused in [
|
||||
Seg2::Conic { a: Vec2::ZERO, apex: Vec2::new(1.0, 1.0), b: Vec2::new(2.0, 0.0), w: 1.0 },
|
||||
Seg2::Bezier { n: 4, p: [Vec2::ZERO; MAX_BEZIER_CTRL] },
|
||||
Seg2::Arc { center: Vec2::ZERO, radius: 0.0, start: 0.0, sweep: FRAC_PI_2 },
|
||||
Seg2::Arc { center: Vec2::new(f64::NAN, 0.0), radius: 1.0, start: 0.0, sweep: FRAC_PI_2 },
|
||||
arc(PI),
|
||||
] {
|
||||
assert!(segments(&[line, refused, line], 1e-4, caps()).is_err());
|
||||
}
|
||||
for error in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert!(segments(&[line], error, caps()).is_err());
|
||||
}
|
||||
assert!(segments(&[arc(FRAC_PI_2)], f64::from_bits(1), caps()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# W21 SVG/PNG original acceptance — preservation only
|
||||
|
||||
Five original test proposals against PR7591 headfd3c289a1ea7d4b1cb1c8fb62e18dff2bb3837e5, crates/io/src/paper/png_tests.rs, base blob39e4bc69c53f4cefe1f6b4cba8a23ec29af93502. NOT applied, compiled or run.
|
||||
|
||||
Choose picture-five-tests.patch against the owner original; or w21-parity-tests.patch followed by picture-three-tests-increment.patch. The whole-file copy is another alternative, never a blanket overlay onto newer owner edits. The two earlier stroke/pixel-grid cases plus three picture crop/origin/alpha cases use actual exporters, but do not rasterize SVG. Exclusive owner test-file handoff remains pending in issue4890 comment6476417296. No A5/dash implementation or qualification is claimed.
|
||||
@@ -0,0 +1,284 @@
|
||||
--- a/crates/io/src/paper/png_tests.rs
|
||||
+++ b/crates/io/src/paper/png_tests.rs
|
||||
@@ -426,3 +426,281 @@
|
||||
pictured(&scene(p(20.0, 10.0), vec![picture(1, p(30.0, 30.0), p(40.0, 40.0), 1.0)]), RGB_254, &provider);
|
||||
assert!(provider.asked.borrow().is_empty());
|
||||
}
|
||||
+
|
||||
+/// One authored 100 mm length is already placed on paper at 1:2 and 1:4.
|
||||
+/// These are consumer fixtures, not a model-view transform or a new view kind.
|
||||
+fn mixed_scale_paper_pair() -> Scene {
|
||||
+ Scene {
|
||||
+ size_mm: p(100.0, 80.0),
|
||||
+ groups: [(101, p(10.0, 20.0), p(60.0, 20.0)), (202, p(10.0, 40.0), p(35.0, 40.0))]
|
||||
+ .into_iter()
|
||||
+ .map(|(object, a, b)| Group {
|
||||
+ object,
|
||||
+ kind: ObjectKind::DrawingBorder,
|
||||
+ items: vec![Item::Stroke { path: vec![line(a, b)], closed: false, width_mm: 0.2 }],
|
||||
+ })
|
||||
+ .collect(),
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Both real writers consume this same checked scene; no picture source is needed.
|
||||
+fn svg_png_pair(scene: &Scene) -> (String, Image, PngReport) {
|
||||
+ let prepared = scene.prepare().unwrap();
|
||||
+ let (svg, svg_report) = crate::paper::paper_svg(&prepared, &NoPictures, 300.0).unwrap();
|
||||
+ let mut png = Vec::new();
|
||||
+ let png_report = paper_png(&prepared, AT_254, &NoPictures, &mut png).unwrap();
|
||||
+ assert_eq!(svg_report, png_report.grid, "both consumers use the same number-grid rules");
|
||||
+ let image = read(&png);
|
||||
+ assert_eq!((image.info.color_type, image.info.bit_depth), (png::ColorType::Grayscale, png::BitDepth::Eight));
|
||||
+ (String::from_utf8(svg).unwrap(), image, png_report)
|
||||
+}
|
||||
+
|
||||
+/// 254 dpi is 10 px/mm: 50/25 mm occupy 500/250 px while both 0.2 mm widths stay 2 px.
|
||||
+/// All coordinates are hand-derived from the preplaced fixture, not recorded output.
|
||||
+#[test]
|
||||
+fn svg_and_png_keep_mixed_scale_paper_lengths_and_fixed_width() {
|
||||
+ let (svg, image, report) = svg_png_pair(&mixed_scale_paper_pair());
|
||||
+ assert!(svg.contains("width=\"100mm\" height=\"80mm\" viewBox=\"0 0 100 80\""));
|
||||
+ assert_eq!(svg.matches("<g data-object=").count(), 2);
|
||||
+ assert_eq!(svg.matches("<path ").count(), 2);
|
||||
+ for path in [
|
||||
+ "<path stroke-width=\"0.2\" d=\"M10 60L60 60\"/>",
|
||||
+ "<path stroke-width=\"0.2\" d=\"M10 40L35 40\"/>",
|
||||
+ ] {
|
||||
+ assert_eq!(svg.matches(path).count(), 1, "{path}");
|
||||
+ }
|
||||
+ let first = svg.find("<g data-object=\"101\" data-kind=\"drawing_border\">").unwrap();
|
||||
+ let second = svg.find("<g data-object=\"202\" data-kind=\"drawing_border\">").unwrap();
|
||||
+ assert!(first < second, "group order is retained");
|
||||
+ assert_eq!(report.pixels, [1000, 800]);
|
||||
+ assert_eq!((image.info.width, image.info.height), (1000, 800));
|
||||
+ // Butt ends are [100,600) and [100,350). After the y flip, their two complete
|
||||
+ // black rows are 599/600 and 399/400. Every other pixel is white.
|
||||
+ for y in 0..800 {
|
||||
+ for x in 0..1000 {
|
||||
+ let ink = ((599..601).contains(&y) && (100..600).contains(&x)) || ((399..401).contains(&y) && (100..350).contains(&x));
|
||||
+ assert_eq!(image.at(x, y), if ink { &[0][..] } else { &[255][..] }, "pixel ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// The vector sheet is exactly 100.08 by 80.08 mm. At 254 dpi its 1000.8 by
|
||||
+/// 800.8 pixel extent needs an outward 1001 by 801 image. Ink reaches both last
|
||||
+/// partial pixels; rounding away that row/column or moving the origin loses it.
|
||||
+#[test]
|
||||
+fn svg_and_png_keep_fractional_sheet_edges_on_the_outward_grid() {
|
||||
+ let sheet = scene(
|
||||
+ p(100.08, 80.08),
|
||||
+ vec![Item::Fill { region: Region2 { outer: rectangle(p(99.0, 0.0), p(100.08, 1.0)), holes: vec![] } }],
|
||||
+ );
|
||||
+ let (svg, image, report) = svg_png_pair(&sheet);
|
||||
+ assert!(svg.contains("width=\"100.08mm\" height=\"80.08mm\" viewBox=\"0 0 100.08 80.08\""));
|
||||
+ assert_eq!(svg.matches("<path ").count(), 1);
|
||||
+ assert!(svg.contains("<path fill=\"#000\" stroke=\"none\" fill-rule=\"evenodd\" d=\"M99 80.08L100.08 80.08L100.08 79.08L99 79.08Z\"/>"));
|
||||
+ assert_eq!(report.pixels, [1001, 801]);
|
||||
+ assert_eq!((image.info.width, image.info.height), (1001, 801));
|
||||
+ assert_eq!(image.at(995, 795), [0], "inside the fill");
|
||||
+ assert_eq!(image.at(989, 795), [255], "left of the fill");
|
||||
+ assert_eq!(image.at(995, 789), [255], "above the fill");
|
||||
+ // The last column/row have 0.8 coverage and the corner 0.64. They are
|
||||
+ // partial dark pixels, not fully black and not white; no exact AA byte is
|
||||
+ // assumed. The existing PNG tests use the same mid-grey ink distinction.
|
||||
+ for (x, y) in [(1000, 795), (995, 800), (1000, 800)] {
|
||||
+ let grey = image.at(x, y)[0];
|
||||
+ assert!(grey > 0 && grey < 128, "ink in the last partial pixel ({x},{y}): {grey}");
|
||||
+ }
|
||||
+ let top = image.at(995, 790)[0];
|
||||
+ assert!(top > 128 && top < 255, "the first partial row has only 0.2 coverage: {top}");
|
||||
+}
|
||||
+
|
||||
+const PICTURE_ACCEPTANCE_DPI: f64 = 25.4;
|
||||
+
|
||||
+/// Original pixels, top row first: each atlas corner and its middle differ.
|
||||
+const PAPER_ATLAS_RGBA: [[u8; 4]; 6] = [
|
||||
+ [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255],
|
||||
+ [0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255],
|
||||
+];
|
||||
+const PAPER_ALPHA_RGBA: [[u8; 4]; 4] = [
|
||||
+ [255, 0, 0, 255], [0, 255, 0, 128],
|
||||
+ [0, 0, 255, 0], [255, 255, 255, 255],
|
||||
+];
|
||||
+const PAPER_BLUE_RGBA: [[u8; 4]; 4] = [[0, 0, 255, 255]; 4];
|
||||
+
|
||||
+/// At 25.4 dpi one pixel is exactly one millimetre. No image resampling oracle.
|
||||
+fn paper_picture_pixels(source: u64) -> (Aabb2, [usize; 2], &'static [[u8; 4]]) {
|
||||
+ let (min, max, size, rgba) = match source {
|
||||
+ 901 => (p(3.0, 3.0), p(6.0, 5.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
+ 902 => (p(-1.0, 7.0), p(2.0, 9.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
+ 903 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_ALPHA_RGBA[..]),
|
||||
+ 904 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_BLUE_RGBA[..]),
|
||||
+ _ => panic!("unknown original acceptance picture {source}"),
|
||||
+ };
|
||||
+ (Aabb2 { min, max }, size, rgba)
|
||||
+}
|
||||
+
|
||||
+fn paper_picture_item(source: u64, opacity: f64) -> Item {
|
||||
+ let (rect, _, _) = paper_picture_pixels(source);
|
||||
+ Item::Picture(Picture { source, rect, opacity })
|
||||
+}
|
||||
+
|
||||
+#[derive(Default)]
|
||||
+struct PaperPicturePixels {
|
||||
+ asked: RefCell<Vec<(u64, PixelGrid, GridWindow)>>,
|
||||
+}
|
||||
+
|
||||
+impl Pictures for PaperPicturePixels {
|
||||
+ fn rows(&self, source: u64, grid: &PixelGrid, window: GridWindow) -> std::result::Result<Vec<u8>, String> {
|
||||
+ self.asked.borrow_mut().push((source, *grid, window));
|
||||
+ let (rect, size, rgba) = paper_picture_pixels(source);
|
||||
+ let mut out = Vec::new();
|
||||
+ // A provider reads the requested world grid: PNG asks on the sheet's
|
||||
+ // grid, SVG on the picture's own. Both sample the same original pixels.
|
||||
+ for y in window.y0..window.y1 {
|
||||
+ let (low, high) = grid.row(y);
|
||||
+ let row = (rect.max.y - (low + high) * 0.5).floor() as usize;
|
||||
+ for x in window.x0..window.x1 {
|
||||
+ let (low, high) = grid.column(x);
|
||||
+ let col = ((low + high) * 0.5 - rect.min.x).floor() as usize;
|
||||
+ if col >= size[0] || row >= size[1] {
|
||||
+ return Err(format!("outside original {source} at ({col},{row})"));
|
||||
+ }
|
||||
+ out.extend_from_slice(&rgba[row * size[0] + col]);
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(out)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Both exports consume one Prepared, with the actual Pictures interface.
|
||||
+fn paper_picture_exports(sheet: &Scene, pixels: &PaperPicturePixels, colour: PngColour) -> (String, Image) {
|
||||
+ let prepared = sheet.prepare().unwrap();
|
||||
+ let (svg, svg_report) = crate::paper::paper_svg(&prepared, pixels, PICTURE_ACCEPTANCE_DPI).unwrap();
|
||||
+ let mut png = Vec::new();
|
||||
+ let report = paper_png(&prepared, PngOptions { dpi: PICTURE_ACCEPTANCE_DPI, colour }, pixels, &mut png).unwrap();
|
||||
+ assert_eq!(svg_report, report.grid);
|
||||
+ assert_eq!(report.pixels, [10, 8]);
|
||||
+ (String::from_utf8(svg).unwrap(), read(&png))
|
||||
+}
|
||||
+
|
||||
+/// Decode the actual embedded PNG, not a separately generated reference file.
|
||||
+fn paper_embedded_images(svg: &str) -> Vec<(&str, Image)> {
|
||||
+ svg.split("<image ").skip(1).map(|rest| {
|
||||
+ let tag = rest.split_once("/>").unwrap().0;
|
||||
+ let encoded = tag.split_once("href=\"data:image/png;base64,").unwrap().1.split('"').next().unwrap();
|
||||
+ let bytes = solidcraft_doc::canvas::base64_decode(encoded).unwrap();
|
||||
+ (tag, read(&bytes))
|
||||
+ }).collect()
|
||||
+}
|
||||
+
|
||||
+/// A non-square, asymmetric colour atlas distinguishes y reversal, reflection,
|
||||
+/// transposition and placement. PNG starts at (3,3); SVG embeds exactly 3 by 2.
|
||||
+#[test]
|
||||
+fn svg_and_png_place_the_same_asymmetric_original_picture() {
|
||||
+ let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(901, 1.0)]);
|
||||
+ let pixels = PaperPicturePixels::default();
|
||||
+ let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ let (tag, image) = &embedded[0];
|
||||
+ assert!(tag.starts_with("x=\"3\" y=\"3\" width=\"3\" height=\"2\" preserveAspectRatio=\"none\""));
|
||||
+ assert_eq!((image.info.width, image.info.height, image.info.color_type), (3, 2, png::ColorType::Rgba));
|
||||
+ for y in 0..8 {
|
||||
+ for x in 0..10 {
|
||||
+ let expected = if (3..6).contains(&x) && (3..5).contains(&y) {
|
||||
+ &PAPER_ATLAS_RGBA[(y - 3) * 3 + x - 3][..3]
|
||||
+ } else { &[255, 255, 255][..] };
|
||||
+ assert_eq!(png.at(x, y), expected, "sheet ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..3 {
|
||||
+ assert_eq!(image.at(x, y), PAPER_ATLAS_RGBA[y * 3 + x]);
|
||||
+ }
|
||||
+ }
|
||||
+ let asked = pixels.asked.borrow();
|
||||
+ assert_eq!(asked.len(), 2, "one small image request per export");
|
||||
+ assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (0, 0, 3, 2));
|
||||
+ assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (3, 3, 6, 5));
|
||||
+}
|
||||
+
|
||||
+/// Cropping left and above the sheet retains the atlas's bottom middle/right
|
||||
+/// pixels (magenta/yellow), not its top-left pixels or a stretched whole image.
|
||||
+#[test]
|
||||
+fn svg_and_png_crop_an_original_picture_without_resetting_its_pixel_origin() {
|
||||
+ let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(902, 1.0)]);
|
||||
+ let pixels = PaperPicturePixels::default();
|
||||
+ let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ let (tag, image) = &embedded[0];
|
||||
+ assert!(tag.starts_with("x=\"0\" y=\"0\" width=\"2\" height=\"1\" preserveAspectRatio=\"none\""));
|
||||
+ assert_eq!((image.info.width, image.info.height), (2, 1));
|
||||
+ assert_eq!(image.at(0, 0), PAPER_ATLAS_RGBA[4]);
|
||||
+ assert_eq!(image.at(1, 0), PAPER_ATLAS_RGBA[5]);
|
||||
+ for y in 0..8 {
|
||||
+ for x in 0..10 {
|
||||
+ let expected = match (x, y) {
|
||||
+ (0, 0) => &[255, 0, 255][..],
|
||||
+ (1, 0) => &[255, 255, 0][..],
|
||||
+ _ => &[255, 255, 255][..],
|
||||
+ };
|
||||
+ assert_eq!(png.at(x, y), expected, "cropped sheet ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ let asked = pixels.asked.borrow();
|
||||
+ assert_eq!(asked.len(), 2);
|
||||
+ assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (1, 1, 3, 2));
|
||||
+ assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (0, 0, 2, 1));
|
||||
+}
|
||||
+
|
||||
+/// Straight source alpha and item opacity multiply. Two Pictures in different
|
||||
+/// groups use source-over in group order, independently of image colour order.
|
||||
+#[test]
|
||||
+fn original_picture_alpha_and_opacity_compose_across_groups_in_paint_order() {
|
||||
+ let alpha = paper_picture_item(903, 0.5);
|
||||
+ let (svg, clear) = paper_picture_exports(&scene(p(10.0, 8.0), vec![alpha.clone()]), &PaperPicturePixels::default(), PngColour::Transparent);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ assert!(embedded[0].0.contains(" opacity=\"0.5\""));
|
||||
+ let expected_clear = [[255, 0, 0, 128], [0, 255, 0, 64], [0, 0, 0, 0], [255, 255, 255, 128]];
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ assert_eq!(clear.at(6 + x, 4 + y), expected_clear[y * 2 + x]);
|
||||
+ assert_eq!(embedded[0].1.at(x, y), PAPER_ALPHA_RGBA[y * 2 + x], "SVG keeps straight pixels; opacity stays on the image");
|
||||
+ }
|
||||
+ }
|
||||
+ assert_eq!(clear.at(0, 0), [0, 0, 0, 0]);
|
||||
+ let expected_over_blue = [[128, 0, 128], [0, 64, 191], [0, 0, 255], [128, 128, 255]];
|
||||
+ for reverse in [false, true] {
|
||||
+ let mut groups = vec![
|
||||
+ Group { object: 401, kind: ObjectKind::DrawingBorder, items: vec![paper_picture_item(904, 1.0)] },
|
||||
+ Group { object: 402, kind: ObjectKind::DrawingBorder, items: vec![alpha.clone()] },
|
||||
+ ];
|
||||
+ if reverse { groups.reverse(); }
|
||||
+ let (svg, png) = paper_picture_exports(&Scene { size_mm: p(10.0, 8.0), groups }, &PaperPicturePixels::default(), PngColour::Rgb);
|
||||
+ let first = svg.find(if reverse { "<g data-object=\"402\"" } else { "<g data-object=\"401\"" }).unwrap();
|
||||
+ let last = svg.find(if reverse { "<g data-object=\"401\"" } else { "<g data-object=\"402\"" }).unwrap();
|
||||
+ assert!(first < last);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 2);
|
||||
+ for (index, (_, image)) in embedded.iter().enumerate() {
|
||||
+ let expected = match (reverse, index) {
|
||||
+ (true, 0) | (false, 1) => &PAPER_ALPHA_RGBA,
|
||||
+ _ => &PAPER_BLUE_RGBA,
|
||||
+ };
|
||||
+ assert_eq!((image.info.width, image.info.height), (2, 2));
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ assert_eq!(image.at(x, y), expected[y * 2 + x], "embedded order, reverse={reverse}, image={index}");
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ let expected = if reverse { [0, 0, 255] } else { expected_over_blue[y * 2 + x] };
|
||||
+ assert_eq!(png.at(6 + x, 4 + y), expected, "reverse={reverse}, ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ assert_eq!(png.at(0, 0), [255, 255, 255]);
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,198 @@
|
||||
--- a/crates/io/src/paper/png_tests.rs
|
||||
+++ b/crates/io/src/paper/png_tests.rs
|
||||
@@ -512,3 +512,195 @@
|
||||
let top = image.at(995, 790)[0];
|
||||
assert!(top > 128 && top < 255, "the first partial row has only 0.2 coverage: {top}");
|
||||
}
|
||||
+
|
||||
+const PICTURE_ACCEPTANCE_DPI: f64 = 25.4;
|
||||
+
|
||||
+/// Original pixels, top row first: each atlas corner and its middle differ.
|
||||
+const PAPER_ATLAS_RGBA: [[u8; 4]; 6] = [
|
||||
+ [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255],
|
||||
+ [0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255],
|
||||
+];
|
||||
+const PAPER_ALPHA_RGBA: [[u8; 4]; 4] = [
|
||||
+ [255, 0, 0, 255], [0, 255, 0, 128],
|
||||
+ [0, 0, 255, 0], [255, 255, 255, 255],
|
||||
+];
|
||||
+const PAPER_BLUE_RGBA: [[u8; 4]; 4] = [[0, 0, 255, 255]; 4];
|
||||
+
|
||||
+/// At 25.4 dpi one pixel is exactly one millimetre. No image resampling oracle.
|
||||
+fn paper_picture_pixels(source: u64) -> (Aabb2, [usize; 2], &'static [[u8; 4]]) {
|
||||
+ let (min, max, size, rgba) = match source {
|
||||
+ 901 => (p(3.0, 3.0), p(6.0, 5.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
+ 902 => (p(-1.0, 7.0), p(2.0, 9.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
+ 903 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_ALPHA_RGBA[..]),
|
||||
+ 904 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_BLUE_RGBA[..]),
|
||||
+ _ => panic!("unknown original acceptance picture {source}"),
|
||||
+ };
|
||||
+ (Aabb2 { min, max }, size, rgba)
|
||||
+}
|
||||
+
|
||||
+fn paper_picture_item(source: u64, opacity: f64) -> Item {
|
||||
+ let (rect, _, _) = paper_picture_pixels(source);
|
||||
+ Item::Picture(Picture { source, rect, opacity })
|
||||
+}
|
||||
+
|
||||
+#[derive(Default)]
|
||||
+struct PaperPicturePixels {
|
||||
+ asked: RefCell<Vec<(u64, PixelGrid, GridWindow)>>,
|
||||
+}
|
||||
+
|
||||
+impl Pictures for PaperPicturePixels {
|
||||
+ fn rows(&self, source: u64, grid: &PixelGrid, window: GridWindow) -> std::result::Result<Vec<u8>, String> {
|
||||
+ self.asked.borrow_mut().push((source, *grid, window));
|
||||
+ let (rect, size, rgba) = paper_picture_pixels(source);
|
||||
+ let mut out = Vec::new();
|
||||
+ // A provider reads the requested world grid: PNG asks on the sheet's
|
||||
+ // grid, SVG on the picture's own. Both sample the same original pixels.
|
||||
+ for y in window.y0..window.y1 {
|
||||
+ let (low, high) = grid.row(y);
|
||||
+ let row = (rect.max.y - (low + high) * 0.5).floor() as usize;
|
||||
+ for x in window.x0..window.x1 {
|
||||
+ let (low, high) = grid.column(x);
|
||||
+ let col = ((low + high) * 0.5 - rect.min.x).floor() as usize;
|
||||
+ if col >= size[0] || row >= size[1] {
|
||||
+ return Err(format!("outside original {source} at ({col},{row})"));
|
||||
+ }
|
||||
+ out.extend_from_slice(&rgba[row * size[0] + col]);
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(out)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Both exports consume one Prepared, with the actual Pictures interface.
|
||||
+fn paper_picture_exports(sheet: &Scene, pixels: &PaperPicturePixels, colour: PngColour) -> (String, Image) {
|
||||
+ let prepared = sheet.prepare().unwrap();
|
||||
+ let (svg, svg_report) = crate::paper::paper_svg(&prepared, pixels, PICTURE_ACCEPTANCE_DPI).unwrap();
|
||||
+ let mut png = Vec::new();
|
||||
+ let report = paper_png(&prepared, PngOptions { dpi: PICTURE_ACCEPTANCE_DPI, colour }, pixels, &mut png).unwrap();
|
||||
+ assert_eq!(svg_report, report.grid);
|
||||
+ assert_eq!(report.pixels, [10, 8]);
|
||||
+ (String::from_utf8(svg).unwrap(), read(&png))
|
||||
+}
|
||||
+
|
||||
+/// Decode the actual embedded PNG, not a separately generated reference file.
|
||||
+fn paper_embedded_images(svg: &str) -> Vec<(&str, Image)> {
|
||||
+ svg.split("<image ").skip(1).map(|rest| {
|
||||
+ let tag = rest.split_once("/>").unwrap().0;
|
||||
+ let encoded = tag.split_once("href=\"data:image/png;base64,").unwrap().1.split('"').next().unwrap();
|
||||
+ let bytes = solidcraft_doc::canvas::base64_decode(encoded).unwrap();
|
||||
+ (tag, read(&bytes))
|
||||
+ }).collect()
|
||||
+}
|
||||
+
|
||||
+/// A non-square, asymmetric colour atlas distinguishes y reversal, reflection,
|
||||
+/// transposition and placement. PNG starts at (3,3); SVG embeds exactly 3 by 2.
|
||||
+#[test]
|
||||
+fn svg_and_png_place_the_same_asymmetric_original_picture() {
|
||||
+ let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(901, 1.0)]);
|
||||
+ let pixels = PaperPicturePixels::default();
|
||||
+ let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ let (tag, image) = &embedded[0];
|
||||
+ assert!(tag.starts_with("x=\"3\" y=\"3\" width=\"3\" height=\"2\" preserveAspectRatio=\"none\""));
|
||||
+ assert_eq!((image.info.width, image.info.height, image.info.color_type), (3, 2, png::ColorType::Rgba));
|
||||
+ for y in 0..8 {
|
||||
+ for x in 0..10 {
|
||||
+ let expected = if (3..6).contains(&x) && (3..5).contains(&y) {
|
||||
+ &PAPER_ATLAS_RGBA[(y - 3) * 3 + x - 3][..3]
|
||||
+ } else { &[255, 255, 255][..] };
|
||||
+ assert_eq!(png.at(x, y), expected, "sheet ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..3 {
|
||||
+ assert_eq!(image.at(x, y), PAPER_ATLAS_RGBA[y * 3 + x]);
|
||||
+ }
|
||||
+ }
|
||||
+ let asked = pixels.asked.borrow();
|
||||
+ assert_eq!(asked.len(), 2, "one small image request per export");
|
||||
+ assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (0, 0, 3, 2));
|
||||
+ assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (3, 3, 6, 5));
|
||||
+}
|
||||
+
|
||||
+/// Cropping left and above the sheet retains the atlas's bottom middle/right
|
||||
+/// pixels (magenta/yellow), not its top-left pixels or a stretched whole image.
|
||||
+#[test]
|
||||
+fn svg_and_png_crop_an_original_picture_without_resetting_its_pixel_origin() {
|
||||
+ let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(902, 1.0)]);
|
||||
+ let pixels = PaperPicturePixels::default();
|
||||
+ let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ let (tag, image) = &embedded[0];
|
||||
+ assert!(tag.starts_with("x=\"0\" y=\"0\" width=\"2\" height=\"1\" preserveAspectRatio=\"none\""));
|
||||
+ assert_eq!((image.info.width, image.info.height), (2, 1));
|
||||
+ assert_eq!(image.at(0, 0), PAPER_ATLAS_RGBA[4]);
|
||||
+ assert_eq!(image.at(1, 0), PAPER_ATLAS_RGBA[5]);
|
||||
+ for y in 0..8 {
|
||||
+ for x in 0..10 {
|
||||
+ let expected = match (x, y) {
|
||||
+ (0, 0) => &[255, 0, 255][..],
|
||||
+ (1, 0) => &[255, 255, 0][..],
|
||||
+ _ => &[255, 255, 255][..],
|
||||
+ };
|
||||
+ assert_eq!(png.at(x, y), expected, "cropped sheet ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ let asked = pixels.asked.borrow();
|
||||
+ assert_eq!(asked.len(), 2);
|
||||
+ assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (1, 1, 3, 2));
|
||||
+ assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (0, 0, 2, 1));
|
||||
+}
|
||||
+
|
||||
+/// Straight source alpha and item opacity multiply. Two Pictures in different
|
||||
+/// groups use source-over in group order, independently of image colour order.
|
||||
+#[test]
|
||||
+fn original_picture_alpha_and_opacity_compose_across_groups_in_paint_order() {
|
||||
+ let alpha = paper_picture_item(903, 0.5);
|
||||
+ let (svg, clear) = paper_picture_exports(&scene(p(10.0, 8.0), vec![alpha.clone()]), &PaperPicturePixels::default(), PngColour::Transparent);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 1);
|
||||
+ assert!(embedded[0].0.contains(" opacity=\"0.5\""));
|
||||
+ let expected_clear = [[255, 0, 0, 128], [0, 255, 0, 64], [0, 0, 0, 0], [255, 255, 255, 128]];
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ assert_eq!(clear.at(6 + x, 4 + y), expected_clear[y * 2 + x]);
|
||||
+ assert_eq!(embedded[0].1.at(x, y), PAPER_ALPHA_RGBA[y * 2 + x], "SVG keeps straight pixels; opacity stays on the image");
|
||||
+ }
|
||||
+ }
|
||||
+ assert_eq!(clear.at(0, 0), [0, 0, 0, 0]);
|
||||
+ let expected_over_blue = [[128, 0, 128], [0, 64, 191], [0, 0, 255], [128, 128, 255]];
|
||||
+ for reverse in [false, true] {
|
||||
+ let mut groups = vec![
|
||||
+ Group { object: 401, kind: ObjectKind::DrawingBorder, items: vec![paper_picture_item(904, 1.0)] },
|
||||
+ Group { object: 402, kind: ObjectKind::DrawingBorder, items: vec![alpha.clone()] },
|
||||
+ ];
|
||||
+ if reverse { groups.reverse(); }
|
||||
+ let (svg, png) = paper_picture_exports(&Scene { size_mm: p(10.0, 8.0), groups }, &PaperPicturePixels::default(), PngColour::Rgb);
|
||||
+ let first = svg.find(if reverse { "<g data-object=\"402\"" } else { "<g data-object=\"401\"" }).unwrap();
|
||||
+ let last = svg.find(if reverse { "<g data-object=\"401\"" } else { "<g data-object=\"402\"" }).unwrap();
|
||||
+ assert!(first < last);
|
||||
+ let embedded = paper_embedded_images(&svg);
|
||||
+ assert_eq!(embedded.len(), 2);
|
||||
+ for (index, (_, image)) in embedded.iter().enumerate() {
|
||||
+ let expected = match (reverse, index) {
|
||||
+ (true, 0) | (false, 1) => &PAPER_ALPHA_RGBA,
|
||||
+ _ => &PAPER_BLUE_RGBA,
|
||||
+ };
|
||||
+ assert_eq!((image.info.width, image.info.height), (2, 2));
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ assert_eq!(image.at(x, y), expected[y * 2 + x], "embedded order, reverse={reverse}, image={index}");
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ for y in 0..2 {
|
||||
+ for x in 0..2 {
|
||||
+ let expected = if reverse { [0, 0, 255] } else { expected_over_blue[y * 2 + x] };
|
||||
+ assert_eq!(png.at(6 + x, 4 + y), expected, "reverse={reverse}, ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+ assert_eq!(png.at(0, 0), [255, 255, 255]);
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,706 @@
|
||||
use std::cell::RefCell;
|
||||
use std::f64::consts::{FRAC_PI_2, TAU};
|
||||
|
||||
use solidcraft_geom::paper::{Group, Item, NoPictures, ObjectKind, Scene};
|
||||
use solidcraft_geom::{Aabb2, Loop2, Region2, Seg2, Vec2};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn p(x: f64, y: f64) -> Vec2 {
|
||||
Vec2::new(x, y)
|
||||
}
|
||||
|
||||
fn line(a: Vec2, b: Vec2) -> Seg2 {
|
||||
Seg2::Line { a, b }
|
||||
}
|
||||
|
||||
/// Anticlockwise from `min`.
|
||||
fn rectangle(min: Vec2, max: Vec2) -> Loop2 {
|
||||
Loop2::polygon(&[min, p(max.x, min.y), max, p(min.x, max.y)])
|
||||
}
|
||||
|
||||
fn scene(size: Vec2, items: Vec<Item>) -> Scene {
|
||||
Scene { size_mm: size, groups: vec![Group { object: 1, kind: ObjectKind::DrawingBorder, items }] }
|
||||
}
|
||||
|
||||
/// A 20 × 10 mm sheet: a 1 mm line along y = 5 from x = 2 to 18, and a 6 × 3 mm fill at (2, 1)
|
||||
/// with a 2 × 1 mm hole at (4, 2). At 254 dpi a millimetre is 10 pixels.
|
||||
fn small() -> Scene {
|
||||
scene(
|
||||
p(20.0, 10.0),
|
||||
vec![
|
||||
Item::Stroke { path: vec![line(p(2.0, 5.0), p(18.0, 5.0))], closed: false, width_mm: 1.0 },
|
||||
Item::Fill { region: Region2 { outer: rectangle(p(2.0, 1.0), p(8.0, 4.0)), holes: vec![rectangle(p(4.0, 2.0), p(6.0, 3.0))] } },
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::paper) struct Image {
|
||||
pub(in crate::paper) info: png::Info<'static>,
|
||||
/// One byte a sample, rows top down: 1-bit images unpacked to 0 or 255.
|
||||
pub(in crate::paper) samples: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
fn channels(&self) -> usize {
|
||||
self.info.color_type.samples()
|
||||
}
|
||||
|
||||
/// The samples of the pixel at column `x`, row `y` from the top.
|
||||
pub(in crate::paper) fn at(&self, x: usize, y: usize) -> &[u8] {
|
||||
let c = self.channels();
|
||||
let i = (y * self.info.width as usize + x) * c;
|
||||
&self.samples[i..i + c]
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(scene: &Scene, options: PngOptions) -> (Vec<u8>, PngReport) {
|
||||
let mut out = Vec::new();
|
||||
let report = paper_png(&scene.prepare().unwrap(), options, &NoPictures, &mut out).unwrap();
|
||||
(out, report)
|
||||
}
|
||||
|
||||
pub(in crate::paper) fn read(bytes: &[u8]) -> Image {
|
||||
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes.to_vec()));
|
||||
decoder.set_transformations(png::Transformations::EXPAND);
|
||||
let mut reader = decoder.read_info().unwrap();
|
||||
let mut samples = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut samples).unwrap();
|
||||
let info = reader.info().clone();
|
||||
if info.bit_depth == png::BitDepth::One {
|
||||
// EXPAND makes a 1-bit grey sample 0 or 255 a byte.
|
||||
assert!(samples.iter().all(|s| *s == 0 || *s == 255));
|
||||
}
|
||||
Image { info, samples }
|
||||
}
|
||||
|
||||
fn image(scene: &Scene, options: PngOptions) -> Image {
|
||||
read(&bytes(scene, options).0)
|
||||
}
|
||||
|
||||
const AT_254: PngOptions = PngOptions { dpi: 254.0, colour: PngColour::Grey };
|
||||
|
||||
/// A sheet is its size at the dpi, rounded outward as the sheet's pixel grid is (nothing is
|
||||
/// clipped), and says its dpi, so it prints at the sheet's size: 300 dpi greyscale unless asked,
|
||||
/// sRGB. A side over the grid's limit is refused with the limit named.
|
||||
#[test]
|
||||
fn a_sheet_is_its_size_at_the_dpi_and_records_it() {
|
||||
let a4 = scene(p(210.0, 297.0), vec![]);
|
||||
assert_eq!(PngOptions::default(), PngOptions { dpi: 300.0, colour: PngColour::Grey });
|
||||
let (data, report) = bytes(&a4, PngOptions::default());
|
||||
assert_eq!(report.pixels, [2481, 3508]);
|
||||
let image = read(&data);
|
||||
assert_eq!((image.info.width, image.info.height), (2481, 3508));
|
||||
assert_eq!((image.info.color_type, image.info.bit_depth), (png::ColorType::Grayscale, png::BitDepth::Eight));
|
||||
let dims = image.info.pixel_dims.unwrap();
|
||||
assert_eq!((dims.xppu, dims.yppu, dims.unit), (11811, 11811, png::Unit::Meter));
|
||||
assert!(image.info.srgb.is_some());
|
||||
assert!(image.samples.iter().all(|s| *s == 255), "blank paper is white");
|
||||
assert_eq!(bytes(&a4, PngOptions { dpi: 25.0, ..PngOptions::default() }).1.pixels, [207, 293]);
|
||||
assert_eq!(bytes(&scene(p(420.0, 297.0), vec![]), PngOptions::default()).1.pixels, [4961, 3508]);
|
||||
let a0 = scene(p(1189.0, 841.0), vec![]);
|
||||
let e = paper_png(&a0.prepare().unwrap(), PngOptions { dpi: 1500.0, colour: PngColour::Grey }, &NoPictures, Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("over the limit of 65536 px"), "{e}");
|
||||
}
|
||||
|
||||
/// The line and the fill land on their pixels: the line 10 rows deep round row 50 with butt ends,
|
||||
/// the fill's ring black and its hole white.
|
||||
#[test]
|
||||
fn lines_and_fills_land_on_their_pixels() {
|
||||
let image = image(&small(), AT_254);
|
||||
assert_eq!((image.info.width, image.info.height), (200, 100));
|
||||
let grey = |x, y| image.at(x, y)[0];
|
||||
for (x, y, value, what) in [
|
||||
(100, 45, 0, "the line's top row"),
|
||||
(100, 54, 0, "its bottom row"),
|
||||
(100, 44, 255, "above it"),
|
||||
(100, 55, 255, "below it"),
|
||||
(20, 50, 0, "its first column"),
|
||||
(19, 50, 255, "before its butt end"),
|
||||
(179, 50, 0, "its last column"),
|
||||
(180, 50, 255, "after it"),
|
||||
(30, 75, 0, "the fill's ring"),
|
||||
(50, 75, 255, "the fill's hole"),
|
||||
(90, 75, 255, "beside the fill"),
|
||||
] {
|
||||
assert_eq!(grey(x, y), value, "{what}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each colour: its PNG type, black ink and white (or no) paper.
|
||||
#[test]
|
||||
fn each_colour_has_its_type_ink_and_paper() {
|
||||
for (colour, kind, depth, ink, paper) in [
|
||||
(PngColour::Grey, png::ColorType::Grayscale, png::BitDepth::Eight, &[0][..], &[255][..]),
|
||||
(PngColour::BlackWhite, png::ColorType::Grayscale, png::BitDepth::One, &[0], &[255]),
|
||||
(PngColour::Rgb, png::ColorType::Rgb, png::BitDepth::Eight, &[0, 0, 0], &[255, 255, 255]),
|
||||
(PngColour::Transparent, png::ColorType::Rgba, png::BitDepth::Eight, &[0, 0, 0, 255], &[0, 0, 0, 0]),
|
||||
] {
|
||||
let image = image(&small(), PngOptions { dpi: 254.0, colour });
|
||||
assert_eq!((image.info.color_type, image.info.bit_depth), (kind, depth), "{colour:?}");
|
||||
assert_eq!(image.at(100, 50), ink, "{colour:?}: the line");
|
||||
// Either side of its butt end, bits 3 and 4 of a 1-bit row's third byte.
|
||||
assert_eq!((image.at(19, 50), image.at(20, 50)), (paper, ink), "{colour:?}: the line's start");
|
||||
assert_eq!(image.at(100, 20), paper, "{colour:?}: the paper");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line far thinner than a pixel is a light grey in greyscale, and a full black pixel in black
|
||||
/// and white, so it doesn't drop out, even between two rows' centres; edges are anti-aliased only
|
||||
/// where there is grey, and black and white inks a pixel when its centre is inside.
|
||||
#[test]
|
||||
fn a_hairline_stays_a_pixel_wide_in_black_and_white() {
|
||||
// 50.25 rows from the top: between the centres of rows 49 and 50.
|
||||
let hair = scene(p(20.0, 10.0), vec![Item::Stroke { path: vec![line(p(2.0, 4.975), p(18.0, 4.975))], closed: false, width_mm: 0.01 }]);
|
||||
let column = |colour| {
|
||||
let image = image(&hair, PngOptions { dpi: 254.0, colour });
|
||||
(40..60).map(|y| image.at(100, y)[0]).collect::<Vec<u8>>()
|
||||
};
|
||||
let grey = column(PngColour::Grey);
|
||||
assert!(grey.iter().all(|v| *v > 200) && grey.iter().any(|v| *v < 255), "a tenth of a pixel is light grey: {grey:?}");
|
||||
let bw = column(PngColour::BlackWhite);
|
||||
assert_eq!(bw.iter().filter(|v| **v == 0).count(), 1, "one black pixel across: {bw:?}");
|
||||
let edge = image(&small(), PngOptions { dpi: 100.0, colour: PngColour::Grey });
|
||||
assert!(edge.samples.iter().any(|v| *v != 0 && *v != 255), "greyscale edges are anti-aliased");
|
||||
// A bar a fifth of a pixel wide over column 100's centre: grey in greyscale, black in black and white.
|
||||
let bar = scene(p(20.0, 10.0), vec![Item::Fill { region: Region2 { outer: rectangle(p(10.045, 2.0), p(10.065, 8.0)), holes: vec![] } }]);
|
||||
let grey = image(&bar, AT_254).at(100, 50)[0];
|
||||
assert!(grey > 0 && grey < 255, "under half a pixel is grey: {grey}");
|
||||
assert_eq!(image(&bar, PngOptions { dpi: 254.0, colour: PngColour::BlackWhite }).at(100, 50), [0], "its centre is inside");
|
||||
}
|
||||
|
||||
/// A closed outline is joined where it starts, like its other corners, not left with two butt ends.
|
||||
#[test]
|
||||
fn a_closed_outline_joins_at_its_start() {
|
||||
let square = rectangle(p(2.0, 2.0), p(8.0, 8.0)).segs;
|
||||
let outline = scene(p(10.0, 10.0), vec![Item::Stroke { path: square, closed: true, width_mm: 1.0 }]);
|
||||
let image = image(&outline, AT_254);
|
||||
// A quarter of a millimetre outside each corner, inside the 1 mm line's mitred corner.
|
||||
for (x, y, what) in [(17, 82, "the start"), (82, 82, "the second corner"), (82, 17, "the third"), (17, 17, "the fourth")] {
|
||||
assert_eq!(image.at(x, y), [0], "{what}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Arcs are drawn from lines within 1/8 px: on a 40 mm circle at 600 dpi, every pixel the stroke's
|
||||
/// middle crosses is black and pixels a pixel outside its 0.5 mm width are white, at 64 angles.
|
||||
#[test]
|
||||
fn a_large_circle_is_round_to_the_pixel() {
|
||||
let c = p(50.0, 50.0);
|
||||
let circle = scene(
|
||||
p(100.0, 100.0),
|
||||
vec![Item::Stroke { path: vec![Seg2::Arc { center: c, radius: 40.0, start: 0.0, sweep: TAU }], closed: true, width_mm: 0.5 }],
|
||||
);
|
||||
let image = image(&circle, PngOptions { dpi: 600.0, colour: PngColour::Grey });
|
||||
let per_mm = 600.0 / 25.4;
|
||||
let pixel = |q: Vec2| image.at((q.x * per_mm) as usize, ((100.0 - q.y) * per_mm) as usize)[0];
|
||||
for k in 0..64 {
|
||||
let towards = Vec2::from_angle(TAU * f64::from(k) / 64.0);
|
||||
assert_eq!(pixel(c + towards * 40.0), 0, "on the circle at {k}/64");
|
||||
for r in [40.0 - 0.25 - 1.5 / per_mm, 40.0 + 0.25 + 1.5 / per_mm] {
|
||||
assert_eq!(pixel(c + towards * r), 255, "off the circle at {k}/64, r {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drawn a few rows at a time or all at once, the file is the same bytes, pictures and all, and
|
||||
/// each picture row is asked for once; and again the same bytes.
|
||||
#[test]
|
||||
fn bands_change_nothing_and_the_bytes_repeat() {
|
||||
let mut items = small().groups.remove(0).items;
|
||||
items.push(Item::Stroke {
|
||||
path: vec![Seg2::Arc { center: p(14.0, 3.0), radius: 2.5, start: 0.3, sweep: 1.5 * FRAC_PI_2 }],
|
||||
closed: false,
|
||||
width_mm: 0.35,
|
||||
});
|
||||
items.insert(0, picture(1, p(1.0, 1.0), p(3.0, 2.0), 1.0));
|
||||
items.push(picture(2, p(12.0, 5.0), p(16.0, 9.0), 0.7));
|
||||
items.push(picture(3, p(8.0, 0.5), p(10.03, 4.5), 1.0));
|
||||
let sheet = scene(p(20.0, 10.0), items);
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
// The rows asked for, by source: a band asks only for its own rows of a picture.
|
||||
let rows_asked = |provider: &Provider| {
|
||||
let mut rows = [0; 4];
|
||||
for (source, _, window) in provider.asked.borrow().iter() {
|
||||
rows[*source as usize] += window.y1 - window.y0;
|
||||
}
|
||||
rows
|
||||
};
|
||||
for colour in [PngColour::Grey, PngColour::BlackWhite, PngColour::Rgb, PngColour::Transparent] {
|
||||
let options = PngOptions { dpi: 300.0, colour };
|
||||
let (whole, once) = (&mut Vec::new(), Provider::default());
|
||||
write(&prepared, options, &once, &mut *whole, usize::MAX).unwrap();
|
||||
let width = read(whole).info.width as usize;
|
||||
for band_rows in [1, 3, 7] {
|
||||
let (rows, banded) = (&mut Vec::new(), Provider::default());
|
||||
write(&prepared, options, &banded, &mut *rows, band_rows * width * 4).unwrap();
|
||||
assert_eq!(whole, rows, "{colour:?}, {band_rows} rows a band");
|
||||
assert_eq!(rows_asked(&banded), rows_asked(&once), "{colour:?}, {band_rows} rows a band: each picture row once");
|
||||
}
|
||||
let again = &mut Vec::new();
|
||||
paper_png(&prepared, options, &Provider::default(), &mut *again).unwrap();
|
||||
assert_eq!(again, whole, "{colour:?}: the same bytes again");
|
||||
}
|
||||
}
|
||||
|
||||
/// Out of range resolutions, a curve the walk can't take yet, and more points than the cap are
|
||||
/// refused, never drawn some other way.
|
||||
#[test]
|
||||
fn what_cannot_be_drawn_is_refused() {
|
||||
let prepared_small = small();
|
||||
let prepared = prepared_small.prepare().unwrap();
|
||||
for dpi in [24.9, 2400.1, 0.0, -300.0, f64::NAN, f64::INFINITY] {
|
||||
let e = paper_png(&prepared, PngOptions { dpi, colour: PngColour::Grey }, &NoPictures, Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("25 to 2400 dpi"), "{dpi}: {e}");
|
||||
}
|
||||
for dpi in [25.0, 2400.0] {
|
||||
assert!(paper_png(&prepared, PngOptions { dpi, colour: PngColour::Grey }, &NoPictures, Vec::new()).is_ok(), "{dpi}");
|
||||
}
|
||||
let ellipse = scene(
|
||||
p(20.0, 10.0),
|
||||
vec![Item::Stroke { path: vec![Seg2::Conic { a: p(0.0, 0.0), apex: p(5.0, 5.0), b: p(10.0, 0.0), w: 0.5 }], closed: false, width_mm: 0.35 }],
|
||||
);
|
||||
let e = paper_png(&ellipse.prepare().unwrap(), PngOptions::default(), &NoPictures, Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("not supported yet"), "{e}");
|
||||
// 1,000 circles of 100 m at 2400 dpi, each about 19,000 points: over 2^24 in all. A small sheet,
|
||||
// so a cap that failed would cost seconds, not hours.
|
||||
let big = Loop2::circle(p(0.0, 0.0), 1e5);
|
||||
let circles = (0..1000).map(|_| Item::Fill { region: Region2 { outer: big.clone(), holes: vec![] } }).collect();
|
||||
let e =
|
||||
paper_png(&scene(p(20.0, 10.0), circles).prepare().unwrap(), PngOptions { dpi: 2400.0, colour: PngColour::Grey }, &NoPictures, Vec::new())
|
||||
.unwrap_err();
|
||||
assert!(e.to_string().contains("16777216 points"), "{e}");
|
||||
}
|
||||
|
||||
/// Pictures by source: 0 a checkerboard of the asked grid's own pixels, 1 red, 2 blue at half
|
||||
/// alpha, 3 mid grey, 4 noise that doesn't compress, 666 an error; every request is kept, and
|
||||
/// `short` drops a byte. The SVG tests use it too.
|
||||
#[derive(Default)]
|
||||
pub(in crate::paper) struct Provider {
|
||||
pub(in crate::paper) asked: RefCell<Vec<(u64, PixelGrid, GridWindow)>>,
|
||||
pub(in crate::paper) short: bool,
|
||||
}
|
||||
|
||||
impl Pictures for Provider {
|
||||
fn rows(&self, source: u64, grid: &PixelGrid, window: GridWindow) -> std::result::Result<Vec<u8>, String> {
|
||||
self.asked.borrow_mut().push((source, *grid, window));
|
||||
if source == 666 {
|
||||
return Err("boom".into());
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
for y in window.y0..window.y1 {
|
||||
for x in window.x0..window.x1 {
|
||||
rows.extend(match source {
|
||||
0 if (x + y) % 2 == 0 => [0, 0, 0, 255],
|
||||
0 => [255, 255, 255, 255],
|
||||
1 => [255, 0, 0, 255],
|
||||
2 => [0, 0, 255, 128],
|
||||
4 => (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).wrapping_mul(2_246_822_519).to_le_bytes(),
|
||||
_ => [128, 128, 128, 255],
|
||||
});
|
||||
}
|
||||
}
|
||||
if self.short {
|
||||
rows.pop();
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
fn picture(source: u64, min: Vec2, max: Vec2, opacity: f64) -> Item {
|
||||
Item::Picture(Picture { source, rect: Aabb2 { min, max }, opacity })
|
||||
}
|
||||
|
||||
fn pictured(scene: &Scene, options: PngOptions, pictures: &Provider) -> Image {
|
||||
let mut out = Vec::new();
|
||||
paper_png(&scene.prepare().unwrap(), options, pictures, &mut out).unwrap();
|
||||
read(&out)
|
||||
}
|
||||
|
||||
const RGB_254: PngOptions = PngOptions { dpi: 254.0, colour: PngColour::Rgb };
|
||||
|
||||
/// A picture fills exactly its window of the sheet's grid: a 2 × 1 mm picture 3 mm below the
|
||||
/// top, from x = 4, is columns 40 to 59 and rows 30 to 39 at 254 dpi, and a fill over the same
|
||||
/// rectangle covers every one of its pixels, so the two register. Also on a sheet 100.8 pixels
|
||||
/// high, whose grid is anchored at its top edge as the lines are, not at its bottom.
|
||||
#[test]
|
||||
fn a_picture_fills_exactly_its_window_and_registers_with_the_lines() {
|
||||
for height in [10.0, 10.08] {
|
||||
let rect = rectangle(p(4.0, height - 4.0), p(6.0, height - 3.0));
|
||||
let red = picture(1, p(4.0, height - 4.0), p(6.0, height - 3.0), 1.0);
|
||||
let image = pictured(&scene(p(20.0, height), vec![red.clone()]), RGB_254, &Provider::default());
|
||||
for (x, y, colour, what) in [
|
||||
(40, 30, [255, 0, 0], "its top-left pixel"),
|
||||
(59, 39, [255, 0, 0], "its bottom-right pixel"),
|
||||
(39, 35, [255, 255, 255], "left of it"),
|
||||
(60, 35, [255, 255, 255], "right of it"),
|
||||
(50, 29, [255, 255, 255], "above it"),
|
||||
(50, 40, [255, 255, 255], "below it"),
|
||||
] {
|
||||
assert_eq!(image.at(x, y), colour, "{height} mm high: {what}, ({x}, {y})");
|
||||
}
|
||||
let covered = Item::Fill { region: Region2 { outer: rect, holes: vec![] } };
|
||||
let image = pictured(&scene(p(20.0, height), vec![red, covered]), RGB_254, &Provider::default());
|
||||
assert!(image.samples.chunks(3).all(|c| c[1] == c[0]), "{height} mm high: no red left beside the fill's edges");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint goes on in the scene's order: a fill before a picture is under it, one after it is over it.
|
||||
#[test]
|
||||
fn pictures_keep_their_place_in_the_paint_order() {
|
||||
let red = || picture(1, p(4.0, 6.0), p(6.0, 7.0), 1.0);
|
||||
let fill = || Item::Fill { region: Region2 { outer: rectangle(p(3.0, 5.0), p(7.0, 8.0)), holes: vec![] } };
|
||||
let under = pictured(&scene(p(20.0, 10.0), vec![fill(), red()]), RGB_254, &Provider::default());
|
||||
assert_eq!(under.at(50, 35), [255, 0, 0], "the picture over the fill");
|
||||
assert_eq!(under.at(35, 35), [0, 0, 0], "the fill around it");
|
||||
let over = pictured(&scene(p(20.0, 10.0), vec![red(), fill()]), RGB_254, &Provider::default());
|
||||
assert_eq!(over.at(50, 35), [0, 0, 0], "the fill over the picture");
|
||||
}
|
||||
|
||||
/// Opacity scales a picture's alpha: red at half over white paper is pink; on transparent paper
|
||||
/// the pixel keeps the half alpha.
|
||||
#[test]
|
||||
fn opacity_scales_the_alpha() {
|
||||
let half = scene(p(20.0, 10.0), vec![picture(1, p(4.0, 6.0), p(6.0, 7.0), 0.5)]);
|
||||
assert_eq!(pictured(&half, RGB_254, &Provider::default()).at(50, 35), [255, 128, 128]);
|
||||
let clear = pictured(&half, PngOptions { dpi: 254.0, colour: PngColour::Transparent }, &Provider::default());
|
||||
assert_eq!(clear.at(50, 35), [255, 0, 0, 128]);
|
||||
let blue = scene(p(20.0, 10.0), vec![picture(2, p(4.0, 6.0), p(6.0, 7.0), 1.0)]);
|
||||
assert_eq!(pictured(&blue, RGB_254, &Provider::default()).at(50, 35), [127, 127, 255], "its own half alpha");
|
||||
}
|
||||
|
||||
/// Up to 1200 dpi a picture is asked for on the sheet's own grid. Above it, on the grid of half
|
||||
/// the dpi at 2400, each of whose pixels fills 2 × 2 of the sheet's.
|
||||
#[test]
|
||||
fn above_1200_dpi_a_coarser_pictures_pixels_are_copied() {
|
||||
let checks = scene(p(20.0, 10.0), vec![picture(0, p(4.0, 4.0), p(5.0, 5.0), 1.0)]);
|
||||
for (dpi, k) in [(1200.0, 1), (2400.0, 2)] {
|
||||
let provider = Provider::default();
|
||||
let image = pictured(&checks, PngOptions { dpi, colour: PngColour::Rgb }, &provider);
|
||||
let sheet = PixelGrid::sheet(p(20.0, 10.0), dpi).unwrap();
|
||||
let window = sheet.window(Aabb2 { min: p(4.0, 4.0), max: p(5.0, 5.0) }).unwrap();
|
||||
let asked = provider.asked.borrow();
|
||||
assert_eq!(asked.len(), 1, "one band, one request");
|
||||
assert!((asked[0].1.pitch - sheet.pitch * f64::from(k)).abs() < 1e-12, "{dpi}: asked at {} mm", asked[0].1.pitch);
|
||||
for y in window.y0..window.y1 {
|
||||
for x in window.x0..window.x1 {
|
||||
let black = (x / k + y / k) % 2 == 0;
|
||||
assert_eq!(image.at(x as usize, y as usize), if black { [0, 0, 0] } else { [255, 255, 255] }, "{dpi}: ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In black and white a picture is dithered at its place on the sheet: mid grey is half black,
|
||||
/// whatever the band; a line over it stays solid; the report says so.
|
||||
#[test]
|
||||
fn black_and_white_dithers_pictures_and_keeps_lines_solid() {
|
||||
// 16 × 16 pixels at 254 dpi, from column 8 and row 8.
|
||||
let grey = picture(3, p(0.8, 7.6), p(2.4, 9.2), 1.0);
|
||||
let line = Item::Stroke { path: vec![line(p(0.0, 8.0), p(20.0, 8.0))], closed: false, width_mm: 0.2 };
|
||||
let sheet = scene(p(20.0, 10.0), vec![grey, line]);
|
||||
let options = PngOptions { dpi: 254.0, colour: PngColour::BlackWhite };
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
let (whole, rows) = (&mut Vec::new(), &mut Vec::new());
|
||||
let report = write(&prepared, options, &Provider::default(), &mut *whole, usize::MAX).unwrap();
|
||||
write(&prepared, options, &Provider::default(), &mut *rows, 1).unwrap();
|
||||
assert_eq!(whole, rows, "bands change nothing");
|
||||
assert!(report.dithered);
|
||||
let image = read(whole);
|
||||
let black = (8..24).flat_map(|y| (8..24).map(move |x| (x, y))).filter(|&(x, y)| y != 19 && y != 20 && image.at(x, y)[0] == 0).count();
|
||||
assert_eq!(black, 14 * 16 / 2, "half of mid grey is black, away from the line");
|
||||
assert!((0..200).all(|x| image.at(x, 19)[0] == 0 && image.at(x, 20)[0] == 0), "the line is solid across the picture");
|
||||
assert!(!bytes(&small(), options).1.dithered, "nothing to dither");
|
||||
}
|
||||
|
||||
/// A provider's pixels are checked: too few bytes, or an error, refuse the PNG with the source
|
||||
/// named; no provider refuses any picture; a picture off the sheet asks for nothing.
|
||||
#[test]
|
||||
fn a_providers_pixels_are_checked() {
|
||||
let sheet = |source| scene(p(20.0, 10.0), vec![picture(source, p(4.0, 6.0), p(6.0, 7.0), 1.0)]);
|
||||
let refused = |s: &Scene, provider: &dyn Pictures| paper_png(&s.prepare().unwrap(), RGB_254, provider, Vec::new()).unwrap_err().to_string();
|
||||
let short = refused(&sheet(1), &Provider { short: true, ..Provider::default() });
|
||||
assert!(short.contains("picture 1: 799 bytes where 800 were asked for"), "{short}");
|
||||
assert!(refused(&sheet(666), &Provider::default()).contains("picture 666: boom"));
|
||||
assert!(refused(&sheet(1), &NoPictures).contains("no pixels for picture 1"));
|
||||
let provider = Provider::default();
|
||||
pictured(&scene(p(20.0, 10.0), vec![picture(1, p(30.0, 30.0), p(40.0, 40.0), 1.0)]), RGB_254, &provider);
|
||||
assert!(provider.asked.borrow().is_empty());
|
||||
}
|
||||
|
||||
/// One authored 100 mm length is already placed on paper at 1:2 and 1:4.
|
||||
/// These are consumer fixtures, not a model-view transform or a new view kind.
|
||||
fn mixed_scale_paper_pair() -> Scene {
|
||||
Scene {
|
||||
size_mm: p(100.0, 80.0),
|
||||
groups: [(101, p(10.0, 20.0), p(60.0, 20.0)), (202, p(10.0, 40.0), p(35.0, 40.0))]
|
||||
.into_iter()
|
||||
.map(|(object, a, b)| Group {
|
||||
object,
|
||||
kind: ObjectKind::DrawingBorder,
|
||||
items: vec![Item::Stroke { path: vec![line(a, b)], closed: false, width_mm: 0.2 }],
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Both real writers consume this same checked scene; no picture source is needed.
|
||||
fn svg_png_pair(scene: &Scene) -> (String, Image, PngReport) {
|
||||
let prepared = scene.prepare().unwrap();
|
||||
let (svg, svg_report) = crate::paper::paper_svg(&prepared, &NoPictures, 300.0).unwrap();
|
||||
let mut png = Vec::new();
|
||||
let png_report = paper_png(&prepared, AT_254, &NoPictures, &mut png).unwrap();
|
||||
assert_eq!(svg_report, png_report.grid, "both consumers use the same number-grid rules");
|
||||
let image = read(&png);
|
||||
assert_eq!((image.info.color_type, image.info.bit_depth), (png::ColorType::Grayscale, png::BitDepth::Eight));
|
||||
(String::from_utf8(svg).unwrap(), image, png_report)
|
||||
}
|
||||
|
||||
/// 254 dpi is 10 px/mm: 50/25 mm occupy 500/250 px while both 0.2 mm widths stay 2 px.
|
||||
/// All coordinates are hand-derived from the preplaced fixture, not recorded output.
|
||||
#[test]
|
||||
fn svg_and_png_keep_mixed_scale_paper_lengths_and_fixed_width() {
|
||||
let (svg, image, report) = svg_png_pair(&mixed_scale_paper_pair());
|
||||
assert!(svg.contains("width=\"100mm\" height=\"80mm\" viewBox=\"0 0 100 80\""));
|
||||
assert_eq!(svg.matches("<g data-object=").count(), 2);
|
||||
assert_eq!(svg.matches("<path ").count(), 2);
|
||||
for path in [
|
||||
"<path stroke-width=\"0.2\" d=\"M10 60L60 60\"/>",
|
||||
"<path stroke-width=\"0.2\" d=\"M10 40L35 40\"/>",
|
||||
] {
|
||||
assert_eq!(svg.matches(path).count(), 1, "{path}");
|
||||
}
|
||||
let first = svg.find("<g data-object=\"101\" data-kind=\"drawing_border\">").unwrap();
|
||||
let second = svg.find("<g data-object=\"202\" data-kind=\"drawing_border\">").unwrap();
|
||||
assert!(first < second, "group order is retained");
|
||||
assert_eq!(report.pixels, [1000, 800]);
|
||||
assert_eq!((image.info.width, image.info.height), (1000, 800));
|
||||
// Butt ends are [100,600) and [100,350). After the y flip, their two complete
|
||||
// black rows are 599/600 and 399/400. Every other pixel is white.
|
||||
for y in 0..800 {
|
||||
for x in 0..1000 {
|
||||
let ink = ((599..601).contains(&y) && (100..600).contains(&x)) || ((399..401).contains(&y) && (100..350).contains(&x));
|
||||
assert_eq!(image.at(x, y), if ink { &[0][..] } else { &[255][..] }, "pixel ({x},{y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The vector sheet is exactly 100.08 by 80.08 mm. At 254 dpi its 1000.8 by
|
||||
/// 800.8 pixel extent needs an outward 1001 by 801 image. Ink reaches both last
|
||||
/// partial pixels; rounding away that row/column or moving the origin loses it.
|
||||
#[test]
|
||||
fn svg_and_png_keep_fractional_sheet_edges_on_the_outward_grid() {
|
||||
let sheet = scene(
|
||||
p(100.08, 80.08),
|
||||
vec![Item::Fill { region: Region2 { outer: rectangle(p(99.0, 0.0), p(100.08, 1.0)), holes: vec![] } }],
|
||||
);
|
||||
let (svg, image, report) = svg_png_pair(&sheet);
|
||||
assert!(svg.contains("width=\"100.08mm\" height=\"80.08mm\" viewBox=\"0 0 100.08 80.08\""));
|
||||
assert_eq!(svg.matches("<path ").count(), 1);
|
||||
assert!(svg.contains("<path fill=\"#000\" stroke=\"none\" fill-rule=\"evenodd\" d=\"M99 80.08L100.08 80.08L100.08 79.08L99 79.08Z\"/>"));
|
||||
assert_eq!(report.pixels, [1001, 801]);
|
||||
assert_eq!((image.info.width, image.info.height), (1001, 801));
|
||||
assert_eq!(image.at(995, 795), [0], "inside the fill");
|
||||
assert_eq!(image.at(989, 795), [255], "left of the fill");
|
||||
assert_eq!(image.at(995, 789), [255], "above the fill");
|
||||
// The last column/row have 0.8 coverage and the corner 0.64. They are
|
||||
// partial dark pixels, not fully black and not white; no exact AA byte is
|
||||
// assumed. The existing PNG tests use the same mid-grey ink distinction.
|
||||
for (x, y) in [(1000, 795), (995, 800), (1000, 800)] {
|
||||
let grey = image.at(x, y)[0];
|
||||
assert!(grey > 0 && grey < 128, "ink in the last partial pixel ({x},{y}): {grey}");
|
||||
}
|
||||
let top = image.at(995, 790)[0];
|
||||
assert!(top > 128 && top < 255, "the first partial row has only 0.2 coverage: {top}");
|
||||
}
|
||||
|
||||
const PICTURE_ACCEPTANCE_DPI: f64 = 25.4;
|
||||
|
||||
/// Original pixels, top row first: each atlas corner and its middle differ.
|
||||
const PAPER_ATLAS_RGBA: [[u8; 4]; 6] = [
|
||||
[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255],
|
||||
[0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255],
|
||||
];
|
||||
const PAPER_ALPHA_RGBA: [[u8; 4]; 4] = [
|
||||
[255, 0, 0, 255], [0, 255, 0, 128],
|
||||
[0, 0, 255, 0], [255, 255, 255, 255],
|
||||
];
|
||||
const PAPER_BLUE_RGBA: [[u8; 4]; 4] = [[0, 0, 255, 255]; 4];
|
||||
|
||||
/// At 25.4 dpi one pixel is exactly one millimetre. No image resampling oracle.
|
||||
fn paper_picture_pixels(source: u64) -> (Aabb2, [usize; 2], &'static [[u8; 4]]) {
|
||||
let (min, max, size, rgba) = match source {
|
||||
901 => (p(3.0, 3.0), p(6.0, 5.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
902 => (p(-1.0, 7.0), p(2.0, 9.0), [3, 2], &PAPER_ATLAS_RGBA[..]),
|
||||
903 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_ALPHA_RGBA[..]),
|
||||
904 => (p(6.0, 2.0), p(8.0, 4.0), [2, 2], &PAPER_BLUE_RGBA[..]),
|
||||
_ => panic!("unknown original acceptance picture {source}"),
|
||||
};
|
||||
(Aabb2 { min, max }, size, rgba)
|
||||
}
|
||||
|
||||
fn paper_picture_item(source: u64, opacity: f64) -> Item {
|
||||
let (rect, _, _) = paper_picture_pixels(source);
|
||||
Item::Picture(Picture { source, rect, opacity })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PaperPicturePixels {
|
||||
asked: RefCell<Vec<(u64, PixelGrid, GridWindow)>>,
|
||||
}
|
||||
|
||||
impl Pictures for PaperPicturePixels {
|
||||
fn rows(&self, source: u64, grid: &PixelGrid, window: GridWindow) -> std::result::Result<Vec<u8>, String> {
|
||||
self.asked.borrow_mut().push((source, *grid, window));
|
||||
let (rect, size, rgba) = paper_picture_pixels(source);
|
||||
let mut out = Vec::new();
|
||||
// A provider reads the requested world grid: PNG asks on the sheet's
|
||||
// grid, SVG on the picture's own. Both sample the same original pixels.
|
||||
for y in window.y0..window.y1 {
|
||||
let (low, high) = grid.row(y);
|
||||
let row = (rect.max.y - (low + high) * 0.5).floor() as usize;
|
||||
for x in window.x0..window.x1 {
|
||||
let (low, high) = grid.column(x);
|
||||
let col = ((low + high) * 0.5 - rect.min.x).floor() as usize;
|
||||
if col >= size[0] || row >= size[1] {
|
||||
return Err(format!("outside original {source} at ({col},{row})"));
|
||||
}
|
||||
out.extend_from_slice(&rgba[row * size[0] + col]);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Both exports consume one Prepared, with the actual Pictures interface.
|
||||
fn paper_picture_exports(sheet: &Scene, pixels: &PaperPicturePixels, colour: PngColour) -> (String, Image) {
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
let (svg, svg_report) = crate::paper::paper_svg(&prepared, pixels, PICTURE_ACCEPTANCE_DPI).unwrap();
|
||||
let mut png = Vec::new();
|
||||
let report = paper_png(&prepared, PngOptions { dpi: PICTURE_ACCEPTANCE_DPI, colour }, pixels, &mut png).unwrap();
|
||||
assert_eq!(svg_report, report.grid);
|
||||
assert_eq!(report.pixels, [10, 8]);
|
||||
(String::from_utf8(svg).unwrap(), read(&png))
|
||||
}
|
||||
|
||||
/// Decode the actual embedded PNG, not a separately generated reference file.
|
||||
fn paper_embedded_images(svg: &str) -> Vec<(&str, Image)> {
|
||||
svg.split("<image ").skip(1).map(|rest| {
|
||||
let tag = rest.split_once("/>").unwrap().0;
|
||||
let encoded = tag.split_once("href=\"data:image/png;base64,").unwrap().1.split('"').next().unwrap();
|
||||
let bytes = solidcraft_doc::canvas::base64_decode(encoded).unwrap();
|
||||
(tag, read(&bytes))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// A non-square, asymmetric colour atlas distinguishes y reversal, reflection,
|
||||
/// transposition and placement. PNG starts at (3,3); SVG embeds exactly 3 by 2.
|
||||
#[test]
|
||||
fn svg_and_png_place_the_same_asymmetric_original_picture() {
|
||||
let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(901, 1.0)]);
|
||||
let pixels = PaperPicturePixels::default();
|
||||
let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
let embedded = paper_embedded_images(&svg);
|
||||
assert_eq!(embedded.len(), 1);
|
||||
let (tag, image) = &embedded[0];
|
||||
assert!(tag.starts_with("x=\"3\" y=\"3\" width=\"3\" height=\"2\" preserveAspectRatio=\"none\""));
|
||||
assert_eq!((image.info.width, image.info.height, image.info.color_type), (3, 2, png::ColorType::Rgba));
|
||||
for y in 0..8 {
|
||||
for x in 0..10 {
|
||||
let expected = if (3..6).contains(&x) && (3..5).contains(&y) {
|
||||
&PAPER_ATLAS_RGBA[(y - 3) * 3 + x - 3][..3]
|
||||
} else { &[255, 255, 255][..] };
|
||||
assert_eq!(png.at(x, y), expected, "sheet ({x},{y})");
|
||||
}
|
||||
}
|
||||
for y in 0..2 {
|
||||
for x in 0..3 {
|
||||
assert_eq!(image.at(x, y), PAPER_ATLAS_RGBA[y * 3 + x]);
|
||||
}
|
||||
}
|
||||
let asked = pixels.asked.borrow();
|
||||
assert_eq!(asked.len(), 2, "one small image request per export");
|
||||
assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (0, 0, 3, 2));
|
||||
assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (3, 3, 6, 5));
|
||||
}
|
||||
|
||||
/// Cropping left and above the sheet retains the atlas's bottom middle/right
|
||||
/// pixels (magenta/yellow), not its top-left pixels or a stretched whole image.
|
||||
#[test]
|
||||
fn svg_and_png_crop_an_original_picture_without_resetting_its_pixel_origin() {
|
||||
let sheet = scene(p(10.0, 8.0), vec![paper_picture_item(902, 1.0)]);
|
||||
let pixels = PaperPicturePixels::default();
|
||||
let (svg, png) = paper_picture_exports(&sheet, &pixels, PngColour::Rgb);
|
||||
let embedded = paper_embedded_images(&svg);
|
||||
assert_eq!(embedded.len(), 1);
|
||||
let (tag, image) = &embedded[0];
|
||||
assert!(tag.starts_with("x=\"0\" y=\"0\" width=\"2\" height=\"1\" preserveAspectRatio=\"none\""));
|
||||
assert_eq!((image.info.width, image.info.height), (2, 1));
|
||||
assert_eq!(image.at(0, 0), PAPER_ATLAS_RGBA[4]);
|
||||
assert_eq!(image.at(1, 0), PAPER_ATLAS_RGBA[5]);
|
||||
for y in 0..8 {
|
||||
for x in 0..10 {
|
||||
let expected = match (x, y) {
|
||||
(0, 0) => &[255, 0, 255][..],
|
||||
(1, 0) => &[255, 255, 0][..],
|
||||
_ => &[255, 255, 255][..],
|
||||
};
|
||||
assert_eq!(png.at(x, y), expected, "cropped sheet ({x},{y})");
|
||||
}
|
||||
}
|
||||
let asked = pixels.asked.borrow();
|
||||
assert_eq!(asked.len(), 2);
|
||||
assert_eq!((asked[0].2.x0, asked[0].2.y0, asked[0].2.x1, asked[0].2.y1), (1, 1, 3, 2));
|
||||
assert_eq!((asked[1].2.x0, asked[1].2.y0, asked[1].2.x1, asked[1].2.y1), (0, 0, 2, 1));
|
||||
}
|
||||
|
||||
/// Straight source alpha and item opacity multiply. Two Pictures in different
|
||||
/// groups use source-over in group order, independently of image colour order.
|
||||
#[test]
|
||||
fn original_picture_alpha_and_opacity_compose_across_groups_in_paint_order() {
|
||||
let alpha = paper_picture_item(903, 0.5);
|
||||
let (svg, clear) = paper_picture_exports(&scene(p(10.0, 8.0), vec![alpha.clone()]), &PaperPicturePixels::default(), PngColour::Transparent);
|
||||
let embedded = paper_embedded_images(&svg);
|
||||
assert_eq!(embedded.len(), 1);
|
||||
assert!(embedded[0].0.contains(" opacity=\"0.5\""));
|
||||
let expected_clear = [[255, 0, 0, 128], [0, 255, 0, 64], [0, 0, 0, 0], [255, 255, 255, 128]];
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
assert_eq!(clear.at(6 + x, 4 + y), expected_clear[y * 2 + x]);
|
||||
assert_eq!(embedded[0].1.at(x, y), PAPER_ALPHA_RGBA[y * 2 + x], "SVG keeps straight pixels; opacity stays on the image");
|
||||
}
|
||||
}
|
||||
assert_eq!(clear.at(0, 0), [0, 0, 0, 0]);
|
||||
let expected_over_blue = [[128, 0, 128], [0, 64, 191], [0, 0, 255], [128, 128, 255]];
|
||||
for reverse in [false, true] {
|
||||
let mut groups = vec![
|
||||
Group { object: 401, kind: ObjectKind::DrawingBorder, items: vec![paper_picture_item(904, 1.0)] },
|
||||
Group { object: 402, kind: ObjectKind::DrawingBorder, items: vec![alpha.clone()] },
|
||||
];
|
||||
if reverse { groups.reverse(); }
|
||||
let (svg, png) = paper_picture_exports(&Scene { size_mm: p(10.0, 8.0), groups }, &PaperPicturePixels::default(), PngColour::Rgb);
|
||||
let first = svg.find(if reverse { "<g data-object=\"402\"" } else { "<g data-object=\"401\"" }).unwrap();
|
||||
let last = svg.find(if reverse { "<g data-object=\"401\"" } else { "<g data-object=\"402\"" }).unwrap();
|
||||
assert!(first < last);
|
||||
let embedded = paper_embedded_images(&svg);
|
||||
assert_eq!(embedded.len(), 2);
|
||||
for (index, (_, image)) in embedded.iter().enumerate() {
|
||||
let expected = match (reverse, index) {
|
||||
(true, 0) | (false, 1) => &PAPER_ALPHA_RGBA,
|
||||
_ => &PAPER_BLUE_RGBA,
|
||||
};
|
||||
assert_eq!((image.info.width, image.info.height), (2, 2));
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
assert_eq!(image.at(x, y), expected[y * 2 + x], "embedded order, reverse={reverse}, image={index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
let expected = if reverse { [0, 0, 255] } else { expected_over_blue[y * 2 + x] };
|
||||
assert_eq!(png.at(6 + x, 4 + y), expected, "reverse={reverse}, ({x},{y})");
|
||||
}
|
||||
}
|
||||
assert_eq!(png.at(0, 0), [255, 255, 255]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
diff --git a/crates/io/src/paper/png_tests.rs b/crates/io/src/paper/png_tests.rs
|
||||
--- a/crates/io/src/paper/png_tests.rs
|
||||
+++ b/crates/io/src/paper/png_tests.rs
|
||||
@@ -426,3 +426,89 @@
|
||||
pictured(&scene(p(20.0, 10.0), vec![picture(1, p(30.0, 30.0), p(40.0, 40.0), 1.0)]), RGB_254, &provider);
|
||||
assert!(provider.asked.borrow().is_empty());
|
||||
}
|
||||
+
|
||||
+/// One authored 100 mm length is already placed on paper at 1:2 and 1:4.
|
||||
+/// These are consumer fixtures, not a model-view transform or a new view kind.
|
||||
+fn mixed_scale_paper_pair() -> Scene {
|
||||
+ Scene {
|
||||
+ size_mm: p(100.0, 80.0),
|
||||
+ groups: [(101, p(10.0, 20.0), p(60.0, 20.0)), (202, p(10.0, 40.0), p(35.0, 40.0))]
|
||||
+ .into_iter()
|
||||
+ .map(|(object, a, b)| Group {
|
||||
+ object,
|
||||
+ kind: ObjectKind::DrawingBorder,
|
||||
+ items: vec![Item::Stroke { path: vec![line(a, b)], closed: false, width_mm: 0.2 }],
|
||||
+ })
|
||||
+ .collect(),
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Both real writers consume this same checked scene; no picture source is needed.
|
||||
+fn svg_png_pair(scene: &Scene) -> (String, Image, PngReport) {
|
||||
+ let prepared = scene.prepare().unwrap();
|
||||
+ let (svg, svg_report) = crate::paper::paper_svg(&prepared, &NoPictures, 300.0).unwrap();
|
||||
+ let mut png = Vec::new();
|
||||
+ let png_report = paper_png(&prepared, AT_254, &NoPictures, &mut png).unwrap();
|
||||
+ assert_eq!(svg_report, png_report.grid, "both consumers use the same number-grid rules");
|
||||
+ let image = read(&png);
|
||||
+ assert_eq!((image.info.color_type, image.info.bit_depth), (png::ColorType::Grayscale, png::BitDepth::Eight));
|
||||
+ (String::from_utf8(svg).unwrap(), image, png_report)
|
||||
+}
|
||||
+
|
||||
+/// 254 dpi is 10 px/mm: 50/25 mm occupy 500/250 px while both 0.2 mm widths stay 2 px.
|
||||
+/// All coordinates are hand-derived from the preplaced fixture, not recorded output.
|
||||
+#[test]
|
||||
+fn svg_and_png_keep_mixed_scale_paper_lengths_and_fixed_width() {
|
||||
+ let (svg, image, report) = svg_png_pair(&mixed_scale_paper_pair());
|
||||
+ assert!(svg.contains("width=\"100mm\" height=\"80mm\" viewBox=\"0 0 100 80\""));
|
||||
+ assert_eq!(svg.matches("<g data-object=").count(), 2);
|
||||
+ assert_eq!(svg.matches("<path ").count(), 2);
|
||||
+ for path in [
|
||||
+ "<path stroke-width=\"0.2\" d=\"M10 60L60 60\"/>",
|
||||
+ "<path stroke-width=\"0.2\" d=\"M10 40L35 40\"/>",
|
||||
+ ] {
|
||||
+ assert_eq!(svg.matches(path).count(), 1, "{path}");
|
||||
+ }
|
||||
+ let first = svg.find("<g data-object=\"101\" data-kind=\"drawing_border\">").unwrap();
|
||||
+ let second = svg.find("<g data-object=\"202\" data-kind=\"drawing_border\">").unwrap();
|
||||
+ assert!(first < second, "group order is retained");
|
||||
+ assert_eq!(report.pixels, [1000, 800]);
|
||||
+ assert_eq!((image.info.width, image.info.height), (1000, 800));
|
||||
+ // Butt ends are [100,600) and [100,350). After the y flip, their two complete
|
||||
+ // black rows are 599/600 and 399/400. Every other pixel is white.
|
||||
+ for y in 0..800 {
|
||||
+ for x in 0..1000 {
|
||||
+ let ink = ((599..601).contains(&y) && (100..600).contains(&x)) || ((399..401).contains(&y) && (100..350).contains(&x));
|
||||
+ assert_eq!(image.at(x, y), if ink { &[0][..] } else { &[255][..] }, "pixel ({x},{y})");
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// The vector sheet is exactly 100.08 by 80.08 mm. At 254 dpi its 1000.8 by
|
||||
+/// 800.8 pixel extent needs an outward 1001 by 801 image. Ink reaches both last
|
||||
+/// partial pixels; rounding away that row/column or moving the origin loses it.
|
||||
+#[test]
|
||||
+fn svg_and_png_keep_fractional_sheet_edges_on_the_outward_grid() {
|
||||
+ let sheet = scene(
|
||||
+ p(100.08, 80.08),
|
||||
+ vec![Item::Fill { region: Region2 { outer: rectangle(p(99.0, 0.0), p(100.08, 1.0)), holes: vec![] } }],
|
||||
+ );
|
||||
+ let (svg, image, report) = svg_png_pair(&sheet);
|
||||
+ assert!(svg.contains("width=\"100.08mm\" height=\"80.08mm\" viewBox=\"0 0 100.08 80.08\""));
|
||||
+ assert_eq!(svg.matches("<path ").count(), 1);
|
||||
+ assert!(svg.contains("<path fill=\"#000\" stroke=\"none\" fill-rule=\"evenodd\" d=\"M99 80.08L100.08 80.08L100.08 79.08L99 79.08Z\"/>"));
|
||||
+ assert_eq!(report.pixels, [1001, 801]);
|
||||
+ assert_eq!((image.info.width, image.info.height), (1001, 801));
|
||||
+ assert_eq!(image.at(995, 795), [0], "inside the fill");
|
||||
+ assert_eq!(image.at(989, 795), [255], "left of the fill");
|
||||
+ assert_eq!(image.at(995, 789), [255], "above the fill");
|
||||
+ // The last column/row have 0.8 coverage and the corner 0.64. They are
|
||||
+ // partial dark pixels, not fully black and not white; no exact AA byte is
|
||||
+ // assumed. The existing PNG tests use the same mid-grey ink distinction.
|
||||
+ for (x, y) in [(1000, 795), (995, 800), (1000, 800)] {
|
||||
+ let grey = image.at(x, y)[0];
|
||||
+ assert!(grey > 0 && grey < 128, "ink in the last partial pixel ({x},{y}): {grey}");
|
||||
+ }
|
||||
+ let top = image.at(995, 790)[0];
|
||||
+ assert!(top > 128 && top < 255, "the first partial row has only 0.2 coverage: {top}");
|
||||
+}
|
||||
@@ -0,0 +1,7 @@
|
||||
# W38a five-file corrective source — preserved WIP
|
||||
|
||||
This patch is against PR #7608 head80e5bb347051f2e3972c4cc30ebb87d67fc0e7e2. It preserves our uncommitted corrective source at the user's explicit request. NOT APPLIED TO THE PUBLIC PR, NOT COMPILED, NOT RUN; no ready or merge claim. W38a is supporting preserved work, not an expansion of the current delivery priority.
|
||||
|
||||
It covers paper-aware creator parameters and compound redo isolation, including bounded scratch provenance/MAX_UNDO/checkpoint corrections. Independent source review covered the five files; it is not runtime qualification. Preserve the original failed/cancelled validation history in #7608. Rebind to the real receiver before applying; do not overwrite newer work or infer an exclusive file/build grant from this backup.
|
||||
|
||||
The source.patch is the payload; no private receipts, process logs, worktree metadata, credentials, assets or binaries are included. Patch SHA256: cb1041d896e635d1df12adb87b656abea6b64004f39a0cb98e9dd3483545b1b8.
|
||||
@@ -0,0 +1,633 @@
|
||||
diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs
|
||||
index df64e34c..622a96c6 100644
|
||||
--- a/crates/engine/src/cmd/drawing_tests.rs
|
||||
+++ b/crates/engine/src/cmd/drawing_tests.rs
|
||||
@@ -2419,3 +2419,281 @@ fn sheet_batch_command_capability_matrix_refuses_unsafe_record_families() {
|
||||
assert!(find_command(id).unwrap().allowed(&s).is_err(), "{id} is not admitted on a sheet");
|
||||
}
|
||||
}
|
||||
+
|
||||
+
|
||||
+/// Each newly admitted point parser keeps paper-mm literals under inch source units,
|
||||
+/// while its model path still interprets bare strings in the model's design unit.
|
||||
+#[test]
|
||||
+fn sheet_batch_typed_creator_points_use_paper_units_without_changing_model_units() {
|
||||
+ use solidcraft_geom::Vec2;
|
||||
+
|
||||
+ fn typed(value: &mut Value, source: bool) {
|
||||
+ match value {
|
||||
+ Value::Array(values) => {
|
||||
+ for value in values {
|
||||
+ typed(value, source);
|
||||
+ }
|
||||
+ }
|
||||
+ Value::Number(number) => {
|
||||
+ let number = number.as_f64().unwrap();
|
||||
+ *value = json!(if source { format!("Inset + {} mm", number - 25.4) } else { number.to_string() });
|
||||
+ }
|
||||
+ _ => {}
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ for (command, numeric, keys, points) in [
|
||||
+ ("sketch.line.midpoint", json!({"mid":[40,40],"end":[60,40]}), vec!["mid"], vec![[40.0,40.0],[20.0,40.0],[60.0,40.0]]),
|
||||
+ ("sketch.conic", json!({"start":[40,40],"end":[90,40],"apex":[65,65],"rho":0.5,"connect":false}),
|
||||
+ vec!["start","end","apex"], vec![[40.0,40.0],[90.0,40.0],[65.0,65.0]]),
|
||||
+ ("sketch.spline.fit_point", json!({"points":[[40,40],[50,60],[70,55],[85,40]],"connect":false}),
|
||||
+ vec!["points"], vec![[40.0,40.0],[50.0,60.0],[70.0,55.0],[85.0,40.0]]),
|
||||
+ ("sketch.spline.control_point", json!({"points":[[40,40],[50,60],[70,55],[85,40]],"connect":false}),
|
||||
+ vec!["points"], vec![[40.0,40.0],[50.0,60.0],[70.0,55.0],[85.0,40.0]]),
|
||||
+ ("sketch.spline.control_point_5", json!({"points":[[40,40],[50,60],[55,65],[70,65],[80,55],[85,40]],"connect":false}),
|
||||
+ vec!["points"], vec![[40.0,40.0],[50.0,60.0],[55.0,65.0],[70.0,65.0],[80.0,55.0],[85.0,40.0]]),
|
||||
+ ] {
|
||||
+ for mode in 0..3 {
|
||||
+ let (mut s, drawing, sketch, _) = sheet_editor();
|
||||
+ s.doc_mut().set_param("Inset", "1", Some("in"), None).unwrap();
|
||||
+ let source = s.doc.clone();
|
||||
+ let model = s.model.state();
|
||||
+ let history = s.undo.len();
|
||||
+ let evaluations = s.evaluations;
|
||||
+ let mut params = numeric.clone();
|
||||
+ if mode != 0 {
|
||||
+ for key in &keys {
|
||||
+ typed(params.get_mut(*key).unwrap(), mode == 2);
|
||||
+ }
|
||||
+ }
|
||||
+ run(&mut s, command, params);
|
||||
+ let record = s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch.clone();
|
||||
+ for point in &points {
|
||||
+ assert!(record.points.iter().any(|p| p.pos.dist(Vec2::new(point[0], point[1])) < 1e-6), "{command} mode {mode}: {point:?}");
|
||||
+ }
|
||||
+ assert_eq!((&s.doc.features, &s.doc.params, &s.doc.units), (&source.features, &source.params, &source.units), "{command}");
|
||||
+ assert_eq!((s.undo.len(), s.undo.last().unwrap().part), (history + 1, Some(drawing)), "{command}");
|
||||
+ assert_eq!(s.evaluations, evaluations);
|
||||
+ assert!(Arc::ptr_eq(&s.model.state(), &model), "{command}");
|
||||
+ let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
|
||||
+ assert_eq!(reopened.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch, record, "{command}");
|
||||
+ if mode == 2 {
|
||||
+ assert!(record.points.iter().any(|p| p.exprs.is_some()), "{command}: authored source expressions survive");
|
||||
+ s.doc_mut().set_param("Inset", "2", Some("in"), None).unwrap();
|
||||
+ let before_solve = s.doc.clone();
|
||||
+ let solved = s.doc.solve_sheet_sketch(drawing, sketch).unwrap();
|
||||
+ assert!(solved.sketch.points.iter().any(|p| p.pos.dist(Vec2::new(65.4, 65.4)) < 1e-6), "{command}: fresh source position");
|
||||
+ assert!(Arc::ptr_eq(&s.doc, &before_solve), "{command}: read-only resolution");
|
||||
+ assert_eq!(s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch, record, "{command}: stored expression not baked");
|
||||
+ }
|
||||
+ }
|
||||
+ for as_text in [false, true] {
|
||||
+ let mut s = Session::default();
|
||||
+ s.doc_mut().units = "in".into();
|
||||
+ run(&mut s, "sketch.create", json!({"plane":"XY"}));
|
||||
+ let mut params = numeric.clone();
|
||||
+ if as_text {
|
||||
+ for key in &keys {
|
||||
+ typed(params.get_mut(*key).unwrap(), false);
|
||||
+ }
|
||||
+ }
|
||||
+ run(&mut s, command, params);
|
||||
+ let sketch = s.doc.sketch(s.active_sketch.unwrap()).unwrap();
|
||||
+ let expected = if as_text { 1016.0 } else { 40.0 };
|
||||
+ assert!(sketch.points.iter().any(|p| p.pos.dist(Vec2::new(expected, expected)) < 1e-6), "{command}: original model units, text={as_text}");
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// A successful compound paper edit ends only its own redo branch. Failed compounds
|
||||
+/// retain every owner, including a dimension failure after its creator has run.
|
||||
+#[test]
|
||||
+fn sheet_batch_compound_edits_preserve_foreign_redo_and_refuse_atomically() {
|
||||
+ fn same_redo(s: &Session, before: &[crate::Snapshot]) {
|
||||
+ assert_eq!(s.redo.len(), before.len());
|
||||
+ for (after, before) in s.redo.iter().zip(before) {
|
||||
+ assert_eq!((&after.label, after.part), (&before.label, before.part));
|
||||
+ assert!(Arc::ptr_eq(&after.doc, &before.doc));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ for (command, params) in [
|
||||
+ ("sketch.rectangle.rounded", json!({"p0":[100,100],"p1":[160,140],"radius":5})),
|
||||
+ ("sketch.draw.dimensioned", json!({"command":"sketch.line","params":{"points":[[100,100],[150,100]],"connect":false},"dimensions":{"length":40}})),
|
||||
+ ] {
|
||||
+ let (mut s, drawing, sketch, made) = sheet_editor();
|
||||
+ run(&mut s, "sketch.finish", json!({}));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ let b = run(&mut s, "drawing.create", json!({"name":"Other"}));
|
||||
+ let other = ids::decode(b["id"].as_str().unwrap()).unwrap();
|
||||
+ run(&mut s, "drawing.set", json!({"name":"Other future"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ run(&mut s, "parameters.add", json!({"name":"ModelFuture","expression":"7 mm"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ run(&mut s, "drawing.open", the(drawing));
|
||||
+ run(&mut s, "drawing.sketch.edit", json!({"sketch":made["sketch"]}));
|
||||
+ run(&mut s, "sketch.point", json!({"point":[40,0],"id":"anchor"}));
|
||||
+ run(&mut s, "sketch.constraint.fix", json!({"entities":["anchor"]}));
|
||||
+ run(&mut s, "drawing.set", json!({"name":"Paper future"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ assert_eq!(s.redo.iter().map(|step| step.part).collect::<Vec<_>>(), vec![Some(other), None, Some(drawing)]);
|
||||
+ let redos = s.redo.clone();
|
||||
+ let before = s.doc.clone();
|
||||
+ let entry = s.active_sheet_sketch.clone();
|
||||
+ let model = s.model.state();
|
||||
+ let history = s.undo.len();
|
||||
+ let evaluations = s.evaluations;
|
||||
+ let failed = if command == "sketch.rectangle.rounded" {
|
||||
+ json!({"p0":[100,100],"p1":[160,140],"radius":25})
|
||||
+ } else {
|
||||
+ // Both endpoints are fixed. The nested line creator succeeds, but the
|
||||
+ // requested 5 mm driving dimension conflicts with their 40 mm distance.
|
||||
+ json!({"command":"sketch.line","params":{"points":["origin","anchor"],"connect":false,"infer":false},"dimensions":{"length":5}})
|
||||
+ };
|
||||
+ // Failure on a scratch must roll back its private owner provenance too:
|
||||
+ // adopting the unchanged failed attempt must preserve every old redo branch.
|
||||
+ let mut failed_attempt = s.scratch();
|
||||
+ refused(&mut failed_attempt, command, failed);
|
||||
+ s.accept_computed(failed_attempt);
|
||||
+ assert!(Arc::ptr_eq(&s.doc, &before), "{command}");
|
||||
+ assert!(Arc::ptr_eq(&s.model.state(), &model), "{command}");
|
||||
+ assert_eq!(s.active_sheet_sketch, entry, "{command}");
|
||||
+ assert_eq!((s.undo.len(), s.evaluations), (history, evaluations), "{command}");
|
||||
+ same_redo(&s, &redos);
|
||||
+
|
||||
+ run(&mut s, command, params);
|
||||
+ assert_eq!((s.undo.len(), s.undo.last().unwrap().part), (history + 1, Some(drawing)), "{command}: one own undo");
|
||||
+ same_redo(&s, &redos[..2]);
|
||||
+ assert_eq!(s.evaluations, evaluations);
|
||||
+ assert_eq!((&s.doc.features, &s.doc.params), (&before.features, &before.params), "{command}");
|
||||
+ assert!(Arc::ptr_eq(&s.model.state(), &model));
|
||||
+ let edited = s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().clone();
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch.curves.len(), 0);
|
||||
+ run(&mut s, "edit.redo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch, edited.sketch);
|
||||
+ same_redo(&s, &redos[..2]);
|
||||
+ run(&mut s, "sketch.finish", json!({}));
|
||||
+ run(&mut s, "drawing.open", the(other));
|
||||
+ run(&mut s, "edit.redo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(other).unwrap().name, "Other future");
|
||||
+ assert_eq!(s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch, edited.sketch);
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ run(&mut s, "edit.redo", json!({}));
|
||||
+ assert!(s.doc.params.iter().any(|p| p.name == "ModelFuture"));
|
||||
+ assert_eq!(s.doc.drawing(other).unwrap().name, "Other future");
|
||||
+ assert_eq!(s.doc.drawing(drawing).unwrap().sheet_sketch(sketch).unwrap().sketch, edited.sketch);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+
|
||||
+/// Provenance must outlive MAX_UNDO eviction, nested compound history clearing and
|
||||
+/// tab switches, while a checkpoint restores the matching branch provenance.
|
||||
+#[test]
|
||||
+fn sheet_batch_computed_history_replaces_each_touched_owner_only() {
|
||||
+ fn same_redo(s: &Session, redos: &[crate::Snapshot]) {
|
||||
+ assert_eq!(s.redo.len(), redos.len());
|
||||
+ for (after, before) in s.redo.iter().zip(redos) {
|
||||
+ assert_eq!((&after.label, after.part), (&before.label, before.part));
|
||||
+ assert!(Arc::ptr_eq(&after.doc, &before.doc));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ let mut s = design();
|
||||
+ let a = run(&mut s, "drawing.create", json!({"name":"A"}));
|
||||
+ let aid = ids::decode(a["id"].as_str().unwrap()).unwrap();
|
||||
+ run(&mut s, "drawing.set", json!({"name":"A old future"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ let b = run(&mut s, "drawing.create", json!({"name":"B"}));
|
||||
+ let bid = ids::decode(b["id"].as_str().unwrap()).unwrap();
|
||||
+ run(&mut s, "drawing.set", json!({"name":"B old future"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ let c = run(&mut s, "drawing.create", json!({"name":"C"}));
|
||||
+ let cid = ids::decode(c["id"].as_str().unwrap()).unwrap();
|
||||
+ let made = run(&mut s, "drawing.sketch.create", json!({"owner":c["sheets"][0]["id"]}));
|
||||
+ let sketch = ids::decode(made["sketch"].as_str().unwrap()).unwrap();
|
||||
+ run(&mut s, "sketch.finish", json!({}));
|
||||
+ run(&mut s, "drawing.set", json!({"name":"C old future"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ run(&mut s, "parameters.add", json!({"name":"ModelFuture","expression":"7 mm"}));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ let model_redo = s.redo.iter().find(|step| step.part.is_none()).unwrap().clone();
|
||||
+ let redos = s.redo.clone();
|
||||
+ run(&mut s, "drawing.open", the(aid));
|
||||
+ let before_read = s.doc.clone();
|
||||
+ let mut read_only = s.scratch();
|
||||
+ run(&mut read_only, "drawing.open", the(bid));
|
||||
+ run(&mut read_only, "drawing.inspect", json!({}));
|
||||
+ s.accept_computed(read_only);
|
||||
+ assert_eq!(s.open_drawing, Some(bid));
|
||||
+ assert!(Arc::ptr_eq(&s.doc, &before_read));
|
||||
+ same_redo(&s, &redos);
|
||||
+
|
||||
+ // A complete rollback, even across file.new, restores the old provenance just
|
||||
+ // as it restores the old document and undo/redo. The rolled-back edits must
|
||||
+ // not end the parent's legitimate redo branches at later adoption.
|
||||
+ run(&mut s, "drawing.open", the(aid));
|
||||
+ let mut rolled_back = s.scratch();
|
||||
+ let checkpoint = run(&mut rolled_back, "edit.checkpoint", json!({}))["checkpoint"].clone();
|
||||
+ run(&mut rolled_back, "drawing.set", json!({"name":"A discarded"}));
|
||||
+ run(&mut rolled_back, "drawing.open", the(bid));
|
||||
+ run(&mut rolled_back, "drawing.set", json!({"name":"B discarded"}));
|
||||
+ run(&mut rolled_back, "file.new", json!({}));
|
||||
+ assert!(rolled_back.doc.drawings.is_empty());
|
||||
+ run(&mut rolled_back, "edit.restore_checkpoint", json!({"checkpoint":checkpoint}));
|
||||
+ assert!(Arc::ptr_eq(&rolled_back.doc, &s.doc));
|
||||
+ s.accept_computed(rolled_back);
|
||||
+ same_redo(&s, &redos);
|
||||
+
|
||||
+ let mut computed = s.scratch();
|
||||
+ run(&mut computed, "drawing.set", json!({"name":"A new"}));
|
||||
+ run(&mut computed, "drawing.open", the(bid));
|
||||
+ for i in 0..=crate::MAX_UNDO {
|
||||
+ run(&mut computed, "drawing.set", json!({"name":format!("B new{i}")}));
|
||||
+ }
|
||||
+ assert_eq!(computed.undo.len(), crate::MAX_UNDO);
|
||||
+ assert!(computed.undo.iter().all(|step| step.part == Some(bid)), "A's edit really was evicted");
|
||||
+
|
||||
+ // The only edit of C happens in a nested scratch and a rounded compound.
|
||||
+ // Erasing its intermediate history and finishing on untouched B must not
|
||||
+ // erase C's owner evidence or mistake B for the compound's actual owner.
|
||||
+ let mut nested = computed.scratch();
|
||||
+ run(&mut nested, "drawing.open", the(cid));
|
||||
+ run(&mut nested, "drawing.sketch.edit", json!({"sketch":made["sketch"]}));
|
||||
+ run(&mut nested, "sketch.rectangle.rounded", json!({"p0":[20,20],"p1":[60,40],"radius":3}));
|
||||
+ nested.undo.clear();
|
||||
+ run(&mut nested, "sketch.finish", json!({}));
|
||||
+ run(&mut nested, "drawing.open", the(bid));
|
||||
+ assert!(nested.undo.is_empty() && nested.redo.is_empty());
|
||||
+ computed.accept_computed(nested);
|
||||
+ assert!(computed.undo.iter().all(|step| step.part == Some(bid)), "neither A nor C survives in retained history");
|
||||
+ s.accept_computed(computed);
|
||||
+ assert_eq!(s.open_drawing, Some(bid));
|
||||
+ assert_eq!(s.doc.drawing(aid).unwrap().name, "A new");
|
||||
+ assert_eq!(s.doc.drawing(bid).unwrap().name, format!("B new{}", crate::MAX_UNDO));
|
||||
+ assert_eq!(s.doc.drawing(cid).unwrap().sheet_sketch(sketch).unwrap().sketch.curves.len(), 8);
|
||||
+ assert_eq!(s.redo.len(), 1);
|
||||
+ assert!(s.redo[0].part.is_none());
|
||||
+ assert!(Arc::ptr_eq(&s.redo[0].doc, &model_redo.doc));
|
||||
+ run(&mut s, "drawing.open", the(aid));
|
||||
+ refused(&mut s, "edit.redo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(aid).unwrap().name, "A new", "old A future cannot overwrite the new edit");
|
||||
+ run(&mut s, "drawing.open", the(cid));
|
||||
+ refused(&mut s, "edit.redo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(cid).unwrap().sheet_sketch(sketch).unwrap().sketch.curves.len(), 8);
|
||||
+ run(&mut s, "drawing.open", the(bid));
|
||||
+ run(&mut s, "edit.undo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(bid).unwrap().name, format!("B new{}", crate::MAX_UNDO - 1));
|
||||
+ run(&mut s, "edit.redo", json!({}));
|
||||
+ assert_eq!(s.doc.drawing(bid).unwrap().name, format!("B new{}", crate::MAX_UNDO));
|
||||
+ run(&mut s, "drawing.close", json!({}));
|
||||
+ run(&mut s, "edit.redo", json!({}));
|
||||
+ assert!(s.doc.params.iter().any(|p| p.name == "ModelFuture"));
|
||||
+ assert_eq!(s.doc.drawing(aid).unwrap().name, "A new");
|
||||
+ assert_eq!(s.doc.drawing(bid).unwrap().name, format!("B new{}", crate::MAX_UNDO));
|
||||
+ assert_eq!(s.doc.drawing(cid).unwrap().sheet_sketch(sketch).unwrap().sketch.curves.len(), 8);
|
||||
+}
|
||||
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
|
||||
index a7f2a09e..d8391830 100644
|
||||
--- a/crates/engine/src/cmd/sketch.rs
|
||||
+++ b/crates/engine/src/cmd/sketch.rs
|
||||
@@ -458,11 +458,7 @@ impl PArg {
|
||||
}
|
||||
}
|
||||
|
||||
-pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result<PArg> {
|
||||
- parg_in(sk, doc, v, cmd, false)
|
||||
-}
|
||||
-
|
||||
-fn parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str, paper: bool) -> Result<PArg> {
|
||||
+pub(super) fn parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str, paper: bool) -> Result<PArg> {
|
||||
if let Some(p) = vec2(v) {
|
||||
return Ok(PArg::At(p));
|
||||
}
|
||||
@@ -487,11 +483,7 @@ fn parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str
|
||||
Err(bad(cmd, "a point must be [x, y], a point id like \"l1.end\", or {at, ref}"))
|
||||
}
|
||||
|
||||
-pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result<PArg> {
|
||||
- req_parg_in(sk, doc, p, k, cmd, false)
|
||||
-}
|
||||
-
|
||||
-fn req_parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str, paper: bool) -> Result<PArg> {
|
||||
+pub(super) fn req_parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str, paper: bool) -> Result<PArg> {
|
||||
parg_in(sk, doc, p.get(k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?, cmd, paper)
|
||||
}
|
||||
|
||||
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
|
||||
index 4e94b3ed..b6fe305d 100644
|
||||
--- a/crates/engine/src/cmd/sketch_create.rs
|
||||
+++ b/crates/engine/src/cmd/sketch_create.rs
|
||||
@@ -12,7 +12,7 @@ macro_rules! text_style_doc {
|
||||
};
|
||||
}
|
||||
|
||||
-use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, result, slot};
|
||||
+use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg_in, result, slot};
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, num, req_vec2, str_, string_list};
|
||||
@@ -498,12 +498,13 @@ fn joint_derivatives(sk: &Sketch, ci: usize, pi: usize, order: usize, leaving: b
|
||||
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.blend_curve";
|
||||
let order = blend_order(p, cmd)?;
|
||||
- if s.open_drawing.is_some() && order > 2 {
|
||||
+ let on_sheet = s.open_drawing.is_some();
|
||||
+ if on_sheet && order > 2 {
|
||||
return Err(bad(cmd, "sheet sketches support G1/G2 blends; higher-order splines need their own bounded record contract"));
|
||||
}
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
- let pa = req_parg(sk, doc, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?;
|
||||
- let pb = req_parg(sk, doc, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?;
|
||||
+ let pa = req_parg_in(sk, doc, p, "a", cmd, on_sheet)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?;
|
||||
+ let pb = req_parg_in(sk, doc, p, "b", cmd, on_sheet)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?;
|
||||
let (ca, ta) = end_of(sk, pa).ok_or_else(|| bad(cmd, "no curve ends at `a`"))?;
|
||||
let (cb, tb) = end_of(sk, pb).ok_or_else(|| bad(cmd, "no curve ends at `b`"))?;
|
||||
let (qa, qb) = (sk.point(pa).unwrap_or_default(), sk.point(pb).unwrap_or_default());
|
||||
@@ -627,14 +628,14 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
-fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
+fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str, paper: bool) -> Result<Vec<usize>> {
|
||||
let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list"))?;
|
||||
if list.len() < 2 || list.len() > solidcraft_sketch::MAX_SPLINE_POINTS {
|
||||
return Err(bad(cmd, "a spline needs 2 to 500 points"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list {
|
||||
- let a = super::sketch::parg(sk, doc, v, cmd)?;
|
||||
+ let a = super::sketch::parg_in(sk, doc, v, cmd, paper)?;
|
||||
let i = match a.idx() {
|
||||
Some(i) => i,
|
||||
None => sk.add_point(a.pos(), None)?,
|
||||
@@ -648,6 +649,7 @@ fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &
|
||||
}
|
||||
|
||||
fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> Result<Value> {
|
||||
+ let on_sheet = s.open_drawing.is_some();
|
||||
let periodic = match p.get("periodic") {
|
||||
None => false,
|
||||
Some(Value::Bool(v)) => *v,
|
||||
@@ -658,7 +660,7 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R
|
||||
}
|
||||
let p = &super::sketch_project::snap_points(s, p, cmd)?;
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
- let mut pts = point_list(sk, doc, p, cmd)?;
|
||||
+ let mut pts = point_list(sk, doc, p, cmd, on_sheet)?;
|
||||
if periodic
|
||||
&& sk.point(*pts.first().ok_or_else(|| bad(cmd, "missing first point"))?)
|
||||
!= sk.point(*pts.last().ok_or_else(|| bad(cmd, "missing last point"))?)
|
||||
@@ -684,6 +686,7 @@ fn spline_cv5(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn conic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.conic";
|
||||
+ let on_sheet = s.open_drawing.is_some();
|
||||
let rho = num(p, "rho").unwrap_or(0.5);
|
||||
if !(rho > 1e-6 && rho < 1.0 - 1e-6) {
|
||||
return Err(bad(cmd, "`rho` must be between 0 and 1"));
|
||||
@@ -692,7 +695,7 @@ fn conic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
let mut idx = Vec::new();
|
||||
for k in ["start", "end", "apex"] {
|
||||
- let a = req_parg(sk, doc, p, k, cmd)?;
|
||||
+ let a = req_parg_in(sk, doc, p, k, cmd, on_sheet)?;
|
||||
idx.push(match a.idx() {
|
||||
Some(i) => i,
|
||||
None => sk.add_point(a.pos(), None)?,
|
||||
@@ -711,9 +714,10 @@ fn conic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn midpoint_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.line.midpoint";
|
||||
+ let on_sheet = s.open_drawing.is_some();
|
||||
let end = req_vec2(cmd, p, "end")?;
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
- let m = req_parg(sk, doc, p, "mid", cmd)?;
|
||||
+ let m = req_parg_in(sk, doc, p, "mid", cmd, on_sheet)?;
|
||||
let start = m.pos() * 2.0 - end;
|
||||
if start.dist(end) < 1e-9 {
|
||||
return Err(bad(cmd, "the end must differ from the midpoint"));
|
||||
@@ -780,9 +784,10 @@ fn leaving_dir(sk: &Sketch, ci: usize, pi: usize) -> Option<Vec2> {
|
||||
|
||||
fn arc_tangent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.arc.tangent";
|
||||
+ let on_sheet = s.open_drawing.is_some();
|
||||
let end = req_vec2(cmd, p, "end")?;
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
|
||||
- let st = req_parg(sk, doc, p, "start", cmd)?;
|
||||
+ let st = req_parg_in(sk, doc, p, "start", cmd, on_sheet)?;
|
||||
let picked = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?;
|
||||
// The picked point, then any other point at the same place: a trimmed arc's end is its own
|
||||
// point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485).
|
||||
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
|
||||
index d640dc38..589b869b 100644
|
||||
--- a/crates/engine/src/lib.rs
|
||||
+++ b/crates/engine/src/lib.rs
|
||||
@@ -265,12 +265,19 @@ impl WorldCache {
|
||||
}
|
||||
}
|
||||
|
||||
+/// Only redo owners relevant to a scratch's parent. Keys are fixed when the scratch
|
||||
+/// is made; they do not grow as unrelated drawings are edited or history is evicted.
|
||||
+type RedoWatch = std::collections::BTreeMap<Option<u64>, bool>;
|
||||
+
|
||||
/// An editing session on one design.
|
||||
pub struct Session {
|
||||
pub doc: Arc<Document>,
|
||||
pub model: Model,
|
||||
pub undo: Vec<Snapshot>,
|
||||
pub redo: Vec<Snapshot>,
|
||||
+ /// Scratch-only owner provenance, independent of the bounded undo vector.
|
||||
+ /// Ordinary sessions keep None; adoption never installs a child's watch map.
|
||||
+ redo_watch: Option<RedoWatch>,
|
||||
/// Sketch feature being edited (sketch mode).
|
||||
pub active_sketch: Option<u64>,
|
||||
/// Explicitly owned sheet edit, independent of the model sketch being edited.
|
||||
@@ -368,6 +375,7 @@ pub(crate) struct Checkpoint {
|
||||
pub pending_moves: std::collections::BTreeMap<u64, solidcraft_doc::Mat>,
|
||||
pub undo: Vec<Snapshot>,
|
||||
pub redo: Vec<Snapshot>,
|
||||
+ redo_watch: Option<RedoWatch>,
|
||||
}
|
||||
|
||||
/// A way of shading the model's faces to judge their shape (view state, not part of the design).
|
||||
@@ -452,6 +460,7 @@ impl Session {
|
||||
model,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
+ redo_watch: None,
|
||||
active_sketch: None,
|
||||
active_sheet_sketch: None,
|
||||
open_drawing: None,
|
||||
@@ -502,6 +511,8 @@ impl Session {
|
||||
let render_jobs = self.render_jobs.scratch();
|
||||
let checkpoints = std::mem::take(&mut self.checkpoints);
|
||||
let next_checkpoint = self.next_checkpoint;
|
||||
+ let previous_doc = self.doc.clone();
|
||||
+ let redo_watch = self.redo_watch.take();
|
||||
*self = fresh;
|
||||
self.auto_project = auto_project;
|
||||
self.param_check = param_check;
|
||||
@@ -509,6 +520,8 @@ impl Session {
|
||||
self.render_jobs = render_jobs;
|
||||
self.checkpoints = checkpoints;
|
||||
self.next_checkpoint = next_checkpoint;
|
||||
+ self.redo_watch = redo_watch;
|
||||
+ self.note_redo_changes(&previous_doc);
|
||||
}
|
||||
|
||||
/// The design has changes not in its file: in the document, or in what is hidden.
|
||||
@@ -877,6 +890,7 @@ impl Session {
|
||||
}
|
||||
spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?;
|
||||
let open_drawing = self.open_drawing;
|
||||
+ let redo_watch_before = self.redo_watch.clone();
|
||||
let before =
|
||||
Snapshot { part: open_drawing.filter(|_| matches!(spec.part, cmd::Part::Drawing | cmd::Part::Sketch)), ..Snapshot::of(self, spec.label) };
|
||||
let null = Value::Object(Default::default());
|
||||
@@ -944,10 +958,16 @@ impl Session {
|
||||
None if render_only => self.refresh_render(&previous_doc),
|
||||
None => self.refresh_from(&previous_doc),
|
||||
}
|
||||
+ // Checkpoint restoration restores matching provenance with history;
|
||||
+ // its rollback delta must not re-mark the reverted owners.
|
||||
+ if spec.id != "edit.restore_checkpoint" {
|
||||
+ self.note_redo_changes(&previous_doc);
|
||||
+ }
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
+ self.redo_watch = redo_watch_before;
|
||||
self.open_drawing = open_drawing;
|
||||
self.active_sheet_sketch = before.active_sheet_sketch.clone();
|
||||
if changed || self.pending_moves != before.pending_moves {
|
||||
@@ -1009,6 +1029,7 @@ impl Session {
|
||||
undo: self.undo.clone(),
|
||||
pending_moves: self.pending_moves.clone(),
|
||||
redo: self.redo.clone(),
|
||||
+ redo_watch: self.redo_watch.clone(),
|
||||
});
|
||||
if self.checkpoints.len() > MAX_CHECKPOINTS {
|
||||
self.checkpoints.remove(0);
|
||||
@@ -1029,6 +1050,7 @@ impl Session {
|
||||
self.pending_moves = c.pending_moves;
|
||||
self.undo = c.undo;
|
||||
self.redo = c.redo;
|
||||
+ self.redo_watch = c.redo_watch;
|
||||
self.selection.clear();
|
||||
self.prune_sheet_sketch_edit();
|
||||
if self.render_only_change(&before) {
|
||||
@@ -1049,11 +1071,16 @@ impl Session {
|
||||
/// A scratch copy of the session (same design and model, no history or log) to try
|
||||
/// commands on without touching this one.
|
||||
pub fn scratch(&self) -> Session {
|
||||
+ let mut redo_watch: RedoWatch = self.redo_watch.as_ref().map(|watch| watch.keys().map(|part| (*part, false)).collect()).unwrap_or_default();
|
||||
+ for step in &self.redo {
|
||||
+ redo_watch.entry(step.part).or_insert(false);
|
||||
+ }
|
||||
Session {
|
||||
doc: self.doc.clone(),
|
||||
model: self.model.clone(),
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
+ redo_watch: Some(redo_watch),
|
||||
active_sketch: self.active_sketch,
|
||||
active_sheet_sketch: self.active_sheet_sketch.clone(),
|
||||
open_drawing: self.open_drawing,
|
||||
@@ -1112,18 +1139,59 @@ impl Session {
|
||||
self.model.unprime();
|
||||
}
|
||||
|
||||
+ /// Retain scratch provenance for relevant owners even after MAX_UNDO eviction.
|
||||
+ /// Drawing undo/redo and lifecycle commands cannot be classified by their
|
||||
+ /// generic CommandSpec part, so inspect the actual drawing/model delta.
|
||||
+ fn note_redo_changes(&mut self, previous: &Document) {
|
||||
+ let Some(watch) = &mut self.redo_watch else { return };
|
||||
+ let model_changed = watch.get(&None) == Some(&false)
|
||||
+ && (self.doc.drawings.len() != previous.drawings.len()
|
||||
+ || previous.drawings.iter().any(|drawing| self.doc.drawing(drawing.id).is_none())
|
||||
+ || (!self.doc.differs_only_in_drawings(previous) && *self.doc != *previous));
|
||||
+ for (part, touched) in watch {
|
||||
+ if !*touched {
|
||||
+ *touched = match part {
|
||||
+ None => model_changed,
|
||||
+ Some(id) => match (self.doc.drawing(*id), previous.drawing(*id)) {
|
||||
+ (Some(after), Some(before)) => !Arc::ptr_eq(after, before),
|
||||
+ (None, None) => false,
|
||||
+ _ => true,
|
||||
+ },
|
||||
+ };
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
/// Commit commands evaluated on a scratch copy without losing this session's file,
|
||||
/// saved state, view state, checkpoints or earlier undo steps.
|
||||
pub fn accept_computed(&mut self, mut computed: Session) {
|
||||
let previous_revision = self.revision;
|
||||
+ // Audited direct-mutation callers edit one current owner without commands.
|
||||
+ // Command provenance takes precedence if nested tools erased their history.
|
||||
+ let tracked = computed.redo_watch.as_ref().is_some_and(|watch| watch.values().any(|touched| *touched));
|
||||
+ let implicit_part = (computed.undo.is_empty() && computed.redo.is_empty() && !tracked && !Arc::ptr_eq(&self.doc, &computed.doc))
|
||||
+ .then_some(computed.open_drawing);
|
||||
self.doc = computed.doc;
|
||||
self.model = computed.model;
|
||||
self.world_cache = computed.world_cache;
|
||||
+ let replaces = |part| {
|
||||
+ Some(part) == implicit_part
|
||||
+ || computed.redo_watch.as_ref().and_then(|watch| watch.get(&part)).copied().unwrap_or(false)
|
||||
+ || computed.undo.iter().chain(&computed.redo).any(|edit| edit.part == part)
|
||||
+ };
|
||||
+ self.redo.retain(|step| !replaces(step.part));
|
||||
+ if let Some(watch) = &mut self.redo_watch {
|
||||
+ // Propagate only this parent's already-watched keys. Child-local redo
|
||||
+ // owners do not turn this into a growing, lifetime edit log.
|
||||
+ for (part, touched) in watch {
|
||||
+ *touched |= replaces(*part);
|
||||
+ }
|
||||
+ }
|
||||
+ self.redo.append(&mut computed.redo);
|
||||
self.undo.append(&mut computed.undo);
|
||||
if self.undo.len() > MAX_UNDO {
|
||||
self.undo.drain(..self.undo.len() - MAX_UNDO);
|
||||
}
|
||||
- self.redo = computed.redo;
|
||||
self.active_sketch = computed.active_sketch;
|
||||
self.active_sheet_sketch = computed.active_sheet_sketch;
|
||||
self.open_drawing = computed.open_drawing;
|
||||
diff --git a/docs/drawing-sheet-sketches.md b/docs/drawing-sheet-sketches.md
|
||||
index fe8e1630..de46e02f 100644
|
||||
--- a/docs/drawing-sheet-sketches.md
|
||||
+++ b/docs/drawing-sheet-sketches.md
|
||||
@@ -583,3 +583,30 @@ W19 view-attached annotation dimensions, W38b view sketches, W38c
|
||||
projection, W38d saved fills and W38e images retain their separate owners.
|
||||
This slice does **not** certify complete W38a, native/browser editing,
|
||||
canonical model+sheet Cancel composition, K/store imports or full CI.
|
||||
+
|
||||
+
|
||||
+R17 review corrections keep the shared point parser's unit context explicit for
|
||||
+midpoint lines, conics and all three spline creators, as well as endpoint
|
||||
+references used by tangent arcs and blends. Numeric paper positions and bare
|
||||
+coordinate strings therefore use the same paper-mm frame even when the source
|
||||
+design displays inches. Named source expressions retain their authored units
|
||||
+and resolve again without baking values into the stored drawing. The model
|
||||
+route still supplies its original design-unit context.
|
||||
+
|
||||
+Rounded rectangles and dimensioned creators use a scratch Session for atomic
|
||||
+publication. Adopting that changed, history-free scratch replaces only its
|
||||
+current owner's redo branch, leaving the model and other drawings' redo steps
|
||||
+available. Scratch-only owner provenance watches only redo owners relevant to
|
||||
+its parent, with fixed keys rather than an edit log that grows with each new
|
||||
+drawing. It survives bounded undo eviction and nested compound history clearing;
|
||||
+adoption replaces every touched owner's branch even if another tab is open.
|
||||
+An ordinary Session has no such watch map. A checkpoint restores matching
|
||||
+provenance with its document and history, including across file.new. Failed
|
||||
+commands restore precommand provenance; read-only resolution or tab switching
|
||||
+leaves every redo branch available. A new compound edit ends the current
|
||||
+drawing's redo branch, and failed creation or
|
||||
+driving constraints publish no geometry or history. Original regression cases
|
||||
+in the existing Drawing test module cover literal/expression unit context,
|
||||
+foreign redo branches, one-step compound history and refusal after a nested
|
||||
+line creator. Their execution status belongs to the exact-source validation
|
||||
+receipt; these cases alone do not establish the full CI or editor acceptance.
|
||||
@@ -0,0 +1,5 @@
|
||||
# W38d D7 original acceptance proposals — preservation only
|
||||
|
||||
Six source-bound whole-boundary identity fixtures and an additional paper-unit version of fixture5. These are original unexecuted requirements, NOT a saved-fill implementation or executed acceptance. Exact original documents are retained; references to a private report or historical locked checkout describe their authoring context, not current locks or authority.
|
||||
|
||||
R16 identity source d3b7cfcf6fc00107ce8d90c17a619a1f3901f38d and D6 hatch source5741c5d205f637ecdd09db09cacd6210492f2d7b are recorded inside the matrix. Later R17 80e5bb347051f2e3972c4cc30ebb87d67fc0e7e2 did not change these identity files. Reuse/factor the actual profile_refs strict matcher rather than duplicate it. Saved fill records, resolver/cache, persistence/undo and sheet scene receiver remain missing. No new implementation is authorized by this preservation branch.
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"schema": "solidcraft.private.acceptance-proposal.v1",
|
||||
"fixture": "W38d-D7-fixture5-paper-units-composed-seam",
|
||||
"status": "PROPOSED_NOT_RUN",
|
||||
"execution_performed": false,
|
||||
"dependency": "Agreed integration and actual sheet whole-boundary-to-region-to-hatch receiver; reuse doc/profile_refs.rs strict matcher, with no second matcher.",
|
||||
"scope": "Future composed acceptance; no assertion that the receiver or saved-fill records currently exist.",
|
||||
"owner": { "drawing": 100, "sheet": 110, "sketch": 120, "source": 140 },
|
||||
"units": {
|
||||
"source_document_display": "in",
|
||||
"drawing_display": "in",
|
||||
"sheet_coordinates": "mm",
|
||||
"hatch_lengths": "paper mm",
|
||||
"source_width_expression_unit": "mm",
|
||||
"bare_sheet_coordinate_strings_default": "mm"
|
||||
},
|
||||
"creation_variants": [
|
||||
{ "name": "numeric", "coordinate_encoding": "JSON numbers in paper mm" },
|
||||
{ "name": "bare_strings", "coordinate_encoding": "Bare decimal strings in paper mm; e.g. 40 and string 40 both mean 40 mm on the sheet" }
|
||||
],
|
||||
"geometry": {
|
||||
"outer_vertices": [[0, 0], ["Width", 0], ["Width", 20], [0, 20]],
|
||||
"hole1_vertices": [[8, 4], [12, 4], [12, 8], [8, 8]],
|
||||
"hole2_vertices": [[24, 10], [30, 10], [30, 14], [24, 14]],
|
||||
"curve_identity": {
|
||||
"outer": ["oa", "ob", "oc", "od"],
|
||||
"holes": [["h1a", "h1b", "h1c", "h1d"], ["h2a", "h2b", "h2c", "h2d"]]
|
||||
},
|
||||
"authored_right_vertex_x": "Retain the Width expression using the existing W38a expression representation; do not bake resolved values or invent a new payload field."
|
||||
},
|
||||
"pattern_family": {
|
||||
"angle_rad": 0,
|
||||
"origin_mm": [0, 0.5],
|
||||
"delta_x_mm": 0,
|
||||
"delta_y_mm": 2,
|
||||
"dashes_mm": []
|
||||
},
|
||||
"states": [
|
||||
{
|
||||
"source_width_expression": "40 mm",
|
||||
"resolved_width_mm": 40,
|
||||
"expected": { "identity": "unique_complete_outer_and_all_holes", "area_mm2": 760, "stroke_count": 14, "total_stroke_length_mm": 380 }
|
||||
},
|
||||
{
|
||||
"source_width_expression": "60 mm",
|
||||
"resolved_width_mm": 60,
|
||||
"expected": { "identity": "same_unique_complete_boundary", "area_mm2": 1160, "stroke_count": 14, "total_stroke_length_mm": 580 }
|
||||
}
|
||||
],
|
||||
"analytic_derivation": {
|
||||
"area_mm2": "20*Width - 4*4 - 6*4",
|
||||
"member_y_mm": [0.5, 2.5, 4.5, 6.5, 8.5, 10.5, 12.5, 14.5, 16.5, 18.5],
|
||||
"hole1_split_y_mm": [4.5, 6.5],
|
||||
"hole2_split_y_mm": [10.5, 12.5],
|
||||
"stroke_count": "10 base members + 2 hole1 splits + 2 hole2 splits = 14",
|
||||
"total_length_mm": "10*Width - 2*4 - 2*6",
|
||||
"endpoint_rule": "At each member y, begin with [0,Width]; remove [8,12] for 4<y<8 and [24,30] for 10<y<14. Compare every resulting endpoint and stroke, not just totals.",
|
||||
"oracle_origin": "Independent rectangle arithmetic; no implementation output or generated golden."
|
||||
},
|
||||
"read_only_resolution_checks": {
|
||||
"snapshot_timing": "For each creation variant and each width state, snapshot immediately after the intentional source edit and before resolving; compare immediately after resolution.",
|
||||
"source_document": "unchanged by resolution, including parameter expressions, units and model features",
|
||||
"source_history": "unchanged by resolution; the intentional Width edit is outside this comparison",
|
||||
"drawing_history": "unchanged by resolution",
|
||||
"authored_sheet_record": "unchanged by resolution, including point/curve IDs and Width expressions",
|
||||
"requested_boundary": "same canonical outer and all hole identities in both states",
|
||||
"owner_identity": "resolved drawing=100, sheet=110, sketch=120",
|
||||
"variant_equivalence": "Both creation variants produce the same analytic region and hatch in each state."
|
||||
},
|
||||
"unit_control": "Do not interpret explicitly authored Width=40 in as40 mm; this fixture deliberately uses40 mm and60 mm while display units are inches.",
|
||||
"excluded_claims": ["Executed acceptance", "Existing saved-fill API", "Persistence or undo qualification for future fill records", "Full CI or merge readiness"],
|
||||
"next_actor": "Engineer decides when the composed receiver is integrated and grants implementation/validation; Kernel Specialist remains quiet and available."
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
# W38d D7: original whole-boundary acceptance matrix
|
||||
|
||||
Private report to Engineer. Source review and proposed tests only: no product run,
|
||||
checkout edit, dependency adoption or executed acceptance is claimed.
|
||||
|
||||
## Exact source bindings
|
||||
|
||||
- R16 W38a: `0xlillith/solidcraft` commit
|
||||
`d3b7cfcf6fc00107ce8d90c17a619a1f3901f38d`.
|
||||
- D6 W38d: `0xlillith/solidcraft` commit
|
||||
`5741c5d205f637ecdd09db09cacd6210492f2d7b`.
|
||||
- The two branches have NOT been composed by this review. The live W38a checkout
|
||||
remains another execution's locked source. Public named blobs were inspected;
|
||||
the current uncommitted engine batch is outside this report.
|
||||
|
||||
Relevant blob identities:
|
||||
|
||||
| File | Git blob SHA |
|
||||
| --- | --- |
|
||||
| R16 `crates/doc/src/document.rs` | `9d87ee1c845b9ce02df4da1b696a85e3d40bfc17` |
|
||||
| R16 `crates/sketch/src/profiles.rs` | `553e9c04361f6234ee56ae5fbd21f87efd554fff` |
|
||||
| R16 `crates/doc/src/drawing/sketch.rs` | `86edcc7cf3b8b1b758dc1345365b29500be41d21` |
|
||||
| D6 `crates/geom/src/hatch.rs` | `8e753148c9322fac4db5c8492b8689b916a80fb6` |
|
||||
| D6 `crates/geom/src/hatch/generate.rs` | `114664cf732f06a64537cae2d3ee0586f153e108` |
|
||||
| D6 `crates/geom/src/hatch/budget.rs` | `243bed689af7f6f7c569790483e4e1389d004f60` |
|
||||
|
||||
## Existing APIs: reuse the strict matcher
|
||||
|
||||
`WholeProfileBoundary` already exists in `document.rs:100`: `outer: Vec<String>`
|
||||
and `holes: Vec<Vec<String>>`. `Profile::whole_curve_boundaries()` in
|
||||
`sketch/profiles.rs:42` returns certified complete-source identities. It is not
|
||||
equivalent to `outer_curves`/`hole_curves`: its private certificates are absent
|
||||
for partial/intersected/incomplete graph coverage.
|
||||
|
||||
There is ALREADY a strict matcher in `doc/profile_refs.rs`, not a missing
|
||||
algorithm to independently reimplement:
|
||||
|
||||
- `whole_boundary(Profile)` builds `WholeProfileBoundary` from the certificate.
|
||||
- `validate_whole` requires canonical sorted, unique, disjoint curve IDs. Limits
|
||||
are 128 selected profiles, 128 holes/profile, 512 IDs/boundary, 20,000 total
|
||||
IDs, and at most 512 bytes/ID.
|
||||
- `whole_profile_indices` compares outer AND all hole lists exactly, refusing a
|
||||
missing or ambiguous complete identity.
|
||||
- `profile_selection_indices(..., ProfileSel::WholeBoundaries { profiles })`
|
||||
uses it. Even the lenient feature wrapper routes this variant to that exact
|
||||
matcher; it does not use the ordinary curve-loop fallback.
|
||||
- `profile_by_curves` explicitly ignores holes (`profiles.rs:1076-1083`) and
|
||||
must NOT be the fill identity resolver.
|
||||
|
||||
Actual sheet entry is `Document::solve_sheet_sketch(drawing, sketch)` or
|
||||
`Drawing::solve_sheet_sketch(&Document, sketch)`. `SolvedSheetSketch` has
|
||||
`drawing`, `sheet`, `id`, `sketch`, `report`; it does NOT have `profiles`.
|
||||
Use `solidcraft_sketch::find_profiles(&solved.sketch)` and factor the strict
|
||||
whole-boundary matcher to accept `&[Profile]`. Do not manufacture a model
|
||||
feature/SolvedSketch merely to call the existing wrapper.
|
||||
|
||||
Missing APIs/data: no `SketchFill`, saved fill collection, fill resolver, last-good
|
||||
fill cache, fill command or sheet fill-scene adapter exists in the inspected
|
||||
R16 drawing record. Names/statuses below describe test requirements, not APIs
|
||||
that callers can use today. A later persisted record needs its own pending
|
||||
drawing-format change. Derived region/cache data must not accidentally become
|
||||
an authored saved field; its eventual ownership needs explicit design.
|
||||
|
||||
## Common original fixture
|
||||
|
||||
Use drawing D=100, sheet S=110, sheet-sketch K=120; source id=140 when expressions
|
||||
are used. These are distinct nonzero drawing-object ids. A future fill F=130
|
||||
would also be distinct; F is a proposed record id, not an existing field.
|
||||
|
||||
Build exact axis-aligned line loops, each with distinct point identities and
|
||||
the following curve identities. All coordinates are paper mm:
|
||||
|
||||
- Outer O: (0,0), (40,0), (40,20), (0,20), IDs `oa,ob,oc,od`.
|
||||
- Hole H1: rectangle (8,4)-(12,8), IDs `h1a,h1b,h1c,h1d`.
|
||||
- Hole H2: rectangle (24,10)-(30,14), IDs `h2a,h2b,h2c,h2d`.
|
||||
- Requested canonical boundary B: outer `[oa,ob,oc,od]`; holes
|
||||
`[[h1a,h1b,h1c,h1d],[h2a,h2b,h2c,h2d]]`.
|
||||
|
||||
Area oracle is `40*20 - 4*4 - 6*4 = 760 mm2`. Resolve the surrounding region,
|
||||
not either hole's own island. An optional independent D6 downstream oracle is
|
||||
one continuous horizontal family, angle=0, origin=(0,0.5), delta_x=0,
|
||||
delta_y=2, empty dashes. It has ten member lines y=0.5,2.5,...,18.5.
|
||||
H1 splits two members and H2 splits two others: exactly 14 output strokes,
|
||||
total length `10*40 - 2*4 - 2*6 = 380 mm`. No tangent/boundary coincidences
|
||||
are needed. These expectations come from integer arithmetic, not generator
|
||||
output or refreshed goldens.
|
||||
|
||||
## Six discriminating fixtures
|
||||
|
||||
### 1. Complete identity survives order changes, not noncanonical saved input
|
||||
|
||||
Initial B resolves uniquely to area760 and the 14/380 hatch oracle. Reorder
|
||||
the stored Sketch curve vector, reverse traversal of each original line loop,
|
||||
and swap the geometric discovery order of H1/H2 without changing IDs or point
|
||||
geometry. Recompute profiles: B still resolves uniquely; geometry/area and
|
||||
hatch remain equal. This catches reliance on profile index or traversal order.
|
||||
|
||||
By contrast, a request that stores B's outer or holes in noncanonical order
|
||||
is invalid input under the CURRENT `validate_whole`; it is not silently sorted
|
||||
on damaged-file read and is not a Lost attachment. Creation may use the
|
||||
certified canonical boundary returned by `whole_curve_boundaries()`.
|
||||
|
||||
### 2. Delete one hole: explicit Lost, never an outer-only refill
|
||||
|
||||
Delete H1's four curves and retain O/H2 exactly. The new surrounding area is
|
||||
776, but saved B must resolve as missing/Lost, not to this larger region.
|
||||
Adding an equal-area unrelated hole elsewhere also must not recover B.
|
||||
Keep the authored B unchanged and return no replacement region. If a later
|
||||
runtime last-good cache exists, it must retain the previous area760 region;
|
||||
the pure resolver must not invent persistence for that cache.
|
||||
|
||||
This fixture discriminates directly against `profile_by_curves`: that helper
|
||||
would still match O. It also rejects an area-only or point-inside fallback.
|
||||
|
||||
### 3. Replace equal geometry with different identities: still Lost
|
||||
|
||||
Replace H1 by an identical rectangle with new curve IDs `r1a,r1b,r1c,r1d`.
|
||||
Coordinates, area760 and visible hatch geometry remain equal to fixture1,
|
||||
but B is missing/Lost. Restore the ORIGINAL H1 IDs and remove the replacements:
|
||||
B resolves again. Never rewrite B to r1 IDs or treat coordinate equality as
|
||||
identity. Test both delete+recreate in a transaction and a later restoration.
|
||||
|
||||
### 4. Wrong owner, malformed identity and ambiguous certified candidates
|
||||
|
||||
Make drawing D=200, sheet S=210 with its own K=120 and local curve IDs equal to
|
||||
fixture1, but outer width60. A request owned by D=100 must use D100/K120 only;
|
||||
passing the other drawing as an owner must not redirect the original fill.
|
||||
Resolve each drawing explicitly with the real `solve_sheet_sketch(D,K)` seam
|
||||
and assert returned drawing/sheet/id before boundary matching. Missing owner
|
||||
is an owner error, not a geometric search across the document.
|
||||
|
||||
Within one sketch, repeating a curve ID is invalid at W38a payload validation.
|
||||
Within B, repeated outer IDs, an ID reused between outer and a hole, duplicate
|
||||
hole lists, or an empty boundary are invalid at `validate_whole`, not accepted
|
||||
as sets. Separately, a private matcher-level defensive test may clone one
|
||||
certified Profile in the candidate slice. Two exact matches are ambiguous;
|
||||
the resolver must report Lost/ambiguous or an explicit ambiguity error, never
|
||||
choose first or nearest. This synthetic slice is NOT a valid serialized Sketch.
|
||||
|
||||
### 5. Read-only source update changes geometry, preserves identity
|
||||
|
||||
Give the two right outer points an existing W38a paper-length expression based
|
||||
on source Width. Width40 yields fixture1. Change Width to60 by the model's own
|
||||
parameter edit, then resolve the drawing: exact B still resolves, outer area
|
||||
becomes1200 and filled area1160. The same family still gives14 strokes, total
|
||||
length `10*60-20 = 580 mm`. IDs/B stay unchanged. Resolution must not modify
|
||||
the source's parameter values/history or authored sketch expressions: compare
|
||||
the source snapshot immediately BEFORE versus AFTER resolution of each state.
|
||||
|
||||
Remove/rename Width: real `solve_sheet_sketch` must produce its unknown-source
|
||||
parameter error before profiles are adopted. This is a source/evaluation error,
|
||||
not permission to resolve stale points or select a different source. Preserve
|
||||
the previous authored B/expression and any runtime last-good region. Drawing
|
||||
display units and an unrelated view's scale must not rescale these paper values.
|
||||
|
||||
### 6. Explicit identity and generation budgets, no partial replacement
|
||||
|
||||
At the strict matcher boundary, construct a request with129 hole lists, and a
|
||||
separate boundary with513 IDs. Both must fail existing admission limits before
|
||||
candidate matching; keep original B and last-good state unchanged. An input
|
||||
with repeated IDs is invalid rather than a cheap way to fit a budget. The
|
||||
production default limits must not be raised for these tests.
|
||||
|
||||
Then use the VALID resolved fixture1 with one continuous family at angle0,
|
||||
origin(0,0), delta_y=0.000001, delta_x0. The 20mm span asks for about20 million
|
||||
candidate members, above D6's10,000 ceiling; the public `hatch::generate` must
|
||||
return `candidate line budget exhausted`, not a truncated Vec. Identity is
|
||||
still Resolved; this failure is a generation/resource error, not Lost. No
|
||||
new partial marks may replace the old display/cache. D6's other default caps
|
||||
remain input pieces8192, work2,000,000, events65,536, dash steps200,000,
|
||||
output marks40,000. Their existing tests remain intact.
|
||||
|
||||
## Minimal seam and implementation boundary
|
||||
|
||||
Factor the existing strict `profile_refs` matcher over `&[Profile]`, preserving
|
||||
the existing model selection wrapper's behavior and tests. Keep malformed
|
||||
selection admission separate from missing/ambiguous match classification so
|
||||
the new sheet caller need not parse DocError text. A private match result
|
||||
can distinguish Unique(index), Missing and Ambiguous; this is a proposal,
|
||||
not an existing API or a demand for a new public enum.
|
||||
|
||||
The sheet adapter resolves the exact drawing/sketch, computes current profiles,
|
||||
uses their complete-source certificates, and obtains the matched Region2.
|
||||
Save/restore of authored boundaries belongs to the later fill record/command
|
||||
transaction, through Session::edit_drawing. Retaining the last-good resolved
|
||||
region belongs to an explicitly owned runtime result. Those responsibilities
|
||||
must not be hidden inside a function that only compares IDs.
|
||||
|
||||
Keep general Curve/WholeProfileBoundary semantics unchanged, do not broaden
|
||||
profile_by_curves, and do not add another sketch store or solver. Reuse the
|
||||
same six fixtures for eventual saved records/undo/scene integration once those
|
||||
APIs actually exist; record-only tests cannot claim that later acceptance.
|
||||
@@ -0,0 +1,5 @@
|
||||
# X4 remaining text/number proposals — preservation only
|
||||
|
||||
Standalone full TEXT/MTEXT encoder f437cb7b1c11e463fbd62328267114d77a95117e88b71cb5ad823073a0e626bd (8 tests), raw-value decoder14003e07e96e0c74a5c71b0907bdfcf7f9971dfbfa98e172f2a3196ed7b16476 (11 tests), exact length decimal helper05671bbed70376f91e522db786bdb6a0ce449d779aeba978605ac374c4c13409 (5 tests), and historical cfg(test)-only Out bridge55ed9e266c45fb496c23eb5910bf9b0f3346cae5a2413040d0ed144b1a2345fb (6 tests). These are proposals, NOT wired or run.
|
||||
|
||||
The narrower nine-alignment TEXT adapter and text_value module are already included in D8 d8e7a8690a30e44a58255e5dd345881ef092a93a and are deliberately not duplicated here. Do not overlay this full codec onto D8 or assume its MTEXT contract is integrated. Full codec callers must supply untrimmed ordered values, once-only concatenation/decode and cumulative budgets. Source/new-file patches are alternatives; bridge registration is test-only, not production. Exact mathematical length-grid quantization versus current binary64 formatting remains an owner decision at issue5321 comment6479102559; no byte pins or default formatting change.
|
||||
@@ -0,0 +1,225 @@
|
||||
diff --git a/crates/io/src/dxf/text.rs b/crates/io/src/dxf/text.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/io/src/dxf/text.rs
|
||||
@@ -0,0 +1,220 @@
|
||||
+//! Private production-code proposal for dxf/text.rs. NOT APPLIED / NOT COMPILED / NOT RUN.
|
||||
+//! Decodes values only, not a second DXF parser. Caller supplies raw, untrimmed
|
||||
+//! text fields and finite byte/chunk budgets. No font-dependent styling fallback.
|
||||
+
|
||||
+use crate::{IoError, Result};
|
||||
+
|
||||
+fn invalid(reason: impl std::fmt::Display) -> IoError {
|
||||
+ IoError::Invalid(format!("DXF text value: {reason}"))
|
||||
+}
|
||||
+
|
||||
+fn push(out: &mut String, ch: char, max_bytes: usize) -> Result<()> {
|
||||
+ let needed = out.len().checked_add(ch.len_utf8()).ok_or_else(|| invalid("decoded size overflow"))?;
|
||||
+ if needed > max_bytes {
|
||||
+ return Err(invalid("decoded byte budget exceeded"));
|
||||
+ }
|
||||
+ out.try_reserve(ch.len_utf8()).map_err(|error| invalid(format!("cannot reserve decoded text: {error}")))?;
|
||||
+ out.push(ch);
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+fn cif(chars: &mut impl Iterator<Item = char>) -> Result<char> {
|
||||
+ if chars.next() != Some('+') {
|
||||
+ return Err(invalid("malformed CIF Unicode prefix"));
|
||||
+ }
|
||||
+ let mut code = 0_u32;
|
||||
+ for _ in 0..4 {
|
||||
+ let digit = chars.next().and_then(|ch| ch.to_digit(16)).ok_or_else(|| invalid("CIF Unicode escape requires four hexadecimal digits"))?;
|
||||
+ code = code * 16 + digit;
|
||||
+ }
|
||||
+ let ch = char::from_u32(code).ok_or_else(|| invalid("CIF Unicode escape is not a scalar value; surrogate pairs are unsupported"))?;
|
||||
+ if ch.is_control() {
|
||||
+ return Err(invalid("not supported yet: a control character encoded as CIF"));
|
||||
+ }
|
||||
+ Ok(ch)
|
||||
+}
|
||||
+
|
||||
+fn percent(chars: &mut impl Iterator<Item = char>, mtext: bool) -> Result<char> {
|
||||
+ match chars.next() {
|
||||
+ Some('%') if !mtext => Ok('%'),
|
||||
+ Some('d') => Ok('°'),
|
||||
+ Some('p') => Ok('±'),
|
||||
+ // Autodesk's published symbol mapping is U+2205, not U+2300/U+00D8.
|
||||
+ Some('c') => Ok('\u{2205}'),
|
||||
+ _ => Err(invalid("not supported yet: percent formatting code")),
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+fn decode(value: &str, mtext: bool, max_decoded_bytes: usize) -> Result<String> {
|
||||
+ let mut out = String::new();
|
||||
+ let mut chars = value.chars().peekable();
|
||||
+ while let Some(ch) = chars.next() {
|
||||
+ let decoded = match ch {
|
||||
+ // No hidden CR/LF/tab normalization or stripping. A paragraph is
|
||||
+ // admitted only through the explicit MTEXT escape below.
|
||||
+ c if c.is_control() => return Err(invalid("not supported yet: raw text control character")),
|
||||
+ '\\' => match chars.peek().copied() {
|
||||
+ Some('U') => {
|
||||
+ chars.next();
|
||||
+ cif(&mut chars)?
|
||||
+ }
|
||||
+ Some('\\' | '{' | '}') if mtext => chars.next().ok_or_else(|| invalid("incomplete MTEXT escape"))?,
|
||||
+ Some('P') if mtext => {
|
||||
+ chars.next();
|
||||
+ '\n'
|
||||
+ }
|
||||
+ _ if mtext => return Err(invalid("not supported yet: MTEXT formatting escape")),
|
||||
+ _ => '\\',
|
||||
+ },
|
||||
+ '%' if chars.peek() == Some(&'%') => {
|
||||
+ chars.next();
|
||||
+ percent(&mut chars, mtext)?
|
||||
+ }
|
||||
+ '{' | '}' if mtext => return Err(invalid("not supported yet: MTEXT formatting group")),
|
||||
+ c => c,
|
||||
+ };
|
||||
+ // Never feed decoded output back into the scanner. Decoded percent,
|
||||
+ // backslash, braces and 'P' remain literal rather than becoming syntax.
|
||||
+ push(&mut out, decoded, max_decoded_bytes)?;
|
||||
+ }
|
||||
+ Ok(out)
|
||||
+}
|
||||
+
|
||||
+/// TEXT's untrimmed group-1 value. Raw Unicode scalar text is preserved, including
|
||||
+/// non-BMP UTF8 in an imported newer-format file. That is distinct from the
|
||||
+/// AC1015 writer's no-non-BMP admission rule; this helper does not select a version.
|
||||
+pub(super) fn decode_text_value(value: &str, max_encoded_bytes: usize, max_decoded_bytes: usize) -> Result<String> {
|
||||
+ if value.len() > max_encoded_bytes {
|
||||
+ return Err(invalid("encoded byte budget exceeded"));
|
||||
+ }
|
||||
+ decode(value, false, max_decoded_bytes)
|
||||
+}
|
||||
+
|
||||
+/// Concatenate already-parsed MTEXT group-3 fields then its single group-1 tail,
|
||||
+/// preserving their stored order and spaces, and decode ONCE. Only pass codes1/3.
|
||||
+/// Chunk-length/empty-tail format policy remains the caller's responsibility:
|
||||
+/// this is a bounded value combiner, not a file/chunk-conformance validator.
|
||||
+pub(super) fn decode_mtext_values<'a>(
|
||||
+ values: impl IntoIterator<Item = (i32, &'a str)>, max_encoded_bytes: usize, max_decoded_bytes: usize, max_chunks: usize,
|
||||
+) -> Result<String> {
|
||||
+ let mut joined = String::new();
|
||||
+ let mut tail_seen = false;
|
||||
+ let mut count = 0_usize;
|
||||
+ for (code, value) in values {
|
||||
+ count = count.checked_add(1).ok_or_else(|| invalid("MTEXT chunk count overflow"))?;
|
||||
+ if count > max_chunks {
|
||||
+ return Err(invalid("MTEXT chunk budget exceeded"));
|
||||
+ }
|
||||
+ if tail_seen {
|
||||
+ return Err(invalid("MTEXT text field follows its group-1 tail"));
|
||||
+ }
|
||||
+ match code {
|
||||
+ 3 => {}
|
||||
+ 1 => tail_seen = true,
|
||||
+ _ => return Err(invalid("MTEXT value combiner accepts group1/3 only")),
|
||||
+ }
|
||||
+ let needed = joined.len().checked_add(value.len()).ok_or_else(|| invalid("MTEXT encoded size overflow"))?;
|
||||
+ if needed > max_encoded_bytes {
|
||||
+ return Err(invalid("MTEXT encoded byte budget exceeded"));
|
||||
+ }
|
||||
+ joined.try_reserve(value.len()).map_err(|error| invalid(format!("cannot reserve MTEXT text: {error}")))?;
|
||||
+ joined.push_str(value);
|
||||
+ }
|
||||
+ if !tail_seen {
|
||||
+ return Err(invalid("MTEXT is missing its group-1 tail"));
|
||||
+ }
|
||||
+ decode(&joined, true, max_decoded_bytes)
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::{decode_mtext_values, decode_text_value};
|
||||
+
|
||||
+ #[test]
|
||||
+ fn text_plain_percent_control_codes_and_cif_have_literal_expected_values() {
|
||||
+ assert_eq!(decode_text_value("%%% %%%%%%d %%d %%p %%c \\U+FFFF", 4096, 4096).unwrap(), "% %%d ° ± \u{2205} \u{ffff}");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn text_decodes_once_and_preserves_spaces_and_literal_backslash_syntax() {
|
||||
+ assert_eq!(decode_text_value(" \\U+005CU+0041 \\P \\{x\\} ", 4096, 4096).unwrap(), " \\U+0041 \\P \\{x\\} ");
|
||||
+ assert_eq!(decode_text_value("\\U+0025\\U+0025d", 4096, 4096).unwrap(), "%%d");
|
||||
+ assert_eq!(decode_text_value("trailing\\", 4096, 4096).unwrap(), "trailing\\");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_literals_and_paragraphs_decode_once_without_style_interpretation() {
|
||||
+ let fields = [(1, "\\U+0025 \\U+0025\\U+0025d \\U+00B0 \\\\P \\{x\\}\\Pnext")];
|
||||
+ assert_eq!(decode_mtext_values(fields, 4096, 4096, 1).unwrap(), "% %%d ° \\P {x}\nnext");
|
||||
+ assert_eq!(decode_mtext_values([(1, "\\\\U+0041")], 4096, 4096, 1).unwrap(), "\\U+0041");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_joins_cif_escape_across_real_250_byte_boundary_before_decoding() {
|
||||
+ let head = format!("{}\\U", "a".repeat(248));
|
||||
+ let fields = [(3, head.as_str()), (1, "+4E2Dz")];
|
||||
+ assert_eq!(head.len(), 250);
|
||||
+ assert_eq!(decode_mtext_values(fields, 256, 252, 2).unwrap(), format!("{}中z", "a".repeat(248)));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_joins_escaped_backslash_and_percent_without_second_decode() {
|
||||
+ let head = format!("{}\\", "a".repeat(249));
|
||||
+ assert_eq!(head.len(), 250);
|
||||
+ assert_eq!(decode_mtext_values([(3, head.as_str()), (1, "\\P")], 4096, 4096, 2).unwrap(), format!("{}\\P", "a".repeat(249)));
|
||||
+ assert_eq!(decode_mtext_values([(3, "\\U+002"), (1, "5\\U+0025d")], 4096, 4096, 2).unwrap(), "%%d");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn value_combiner_preserves_empty_tail_without_deciding_writer_chunk_policy() {
|
||||
+ let full = "x".repeat(250);
|
||||
+ assert_eq!(decode_mtext_values([(3, full.as_str()), (1, "")], 250, 250, 2).unwrap(), full);
|
||||
+ assert_eq!(decode_mtext_values([(1, "")], 0, 0, 1).unwrap(), "");
|
||||
+ assert_eq!(decode_mtext_values([(3, " one "), (1, " two ")], 4096, 4096, 2).unwrap(), " one two ");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn malformed_or_styled_escapes_are_explicit_errors_not_stripped_text() {
|
||||
+ for value in ["\\U+", "\\U+XYZ0", "\\U+123", "\\U0041", "\\U+D800", "\\U+DC00", "%%", "%%q", "%%u", "%%123"] {
|
||||
+ assert!(decode_text_value(value, 4096, 4096).is_err(), "{value}");
|
||||
+ }
|
||||
+ for value in ["\\", "\\H2x;Hi", "{styled}", "%%%", "\\~", "\\Lline"] {
|
||||
+ assert!(decode_mtext_values([(1, value)], 4096, 4096, 1).is_err(), "{value}");
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn raw_controls_and_cif_controls_do_not_silently_normalize() {
|
||||
+ for value in ["a\rb", "a\nb", "a\tb", "\\U+0000", "\\U+000A", "\\U+000D", "\\U+0085"] {
|
||||
+ assert!(decode_text_value(value, 4096, 4096).is_err());
|
||||
+ assert!(decode_mtext_values([(1, value)], 4096, 4096, 1).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn encoded_decoded_and_chunk_budgets_are_independently_inclusive() {
|
||||
+ assert_eq!(decode_text_value("\\U+FFFF", 7, 3).unwrap(), "\u{ffff}");
|
||||
+ assert!(decode_text_value("\\U+FFFF", 6, 3).is_err());
|
||||
+ assert!(decode_text_value("\\U+FFFF", 7, 2).is_err());
|
||||
+ assert_eq!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 3, 2).unwrap(), "\u{ffff}");
|
||||
+ assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 6, 3, 2).is_err());
|
||||
+ assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 2, 2).is_err());
|
||||
+ assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 3, 1).is_err());
|
||||
+ assert!(decode_mtext_values([(1, "")], 0, 0, 0).is_err());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_missing_duplicate_or_out_of_order_tail_refuses() {
|
||||
+ assert!(decode_mtext_values([], 4096, 4096, 8).is_err());
|
||||
+ assert!(decode_mtext_values([(3, "text")], 4096, 4096, 8).is_err());
|
||||
+ assert!(decode_mtext_values([(1, "a"), (1, "b")], 4096, 4096, 8).is_err());
|
||||
+ assert!(decode_mtext_values([(1, "a"), (3, "b")], 4096, 4096, 8).is_err());
|
||||
+ assert!(decode_mtext_values([(8, "LAYER"), (1, "a")], 4096, 4096, 8).is_err());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn direct_utf8_input_is_not_confused_with_ac1015_writer_admission() {
|
||||
+ assert_eq!(decode_text_value("中𠀋", 7, 7).unwrap(), "中𠀋");
|
||||
+ assert_eq!(decode_mtext_values([(1, "中𠀋")], 7, 7, 1).unwrap(), "中𠀋");
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Private production-code proposal for dxf/text.rs. NOT APPLIED / NOT COMPILED / NOT RUN.
|
||||
//! Decodes values only, not a second DXF parser. Caller supplies raw, untrimmed
|
||||
//! text fields and finite byte/chunk budgets. No font-dependent styling fallback.
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
fn invalid(reason: impl std::fmt::Display) -> IoError {
|
||||
IoError::Invalid(format!("DXF text value: {reason}"))
|
||||
}
|
||||
|
||||
fn push(out: &mut String, ch: char, max_bytes: usize) -> Result<()> {
|
||||
let needed = out.len().checked_add(ch.len_utf8()).ok_or_else(|| invalid("decoded size overflow"))?;
|
||||
if needed > max_bytes {
|
||||
return Err(invalid("decoded byte budget exceeded"));
|
||||
}
|
||||
out.try_reserve(ch.len_utf8()).map_err(|error| invalid(format!("cannot reserve decoded text: {error}")))?;
|
||||
out.push(ch);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cif(chars: &mut impl Iterator<Item = char>) -> Result<char> {
|
||||
if chars.next() != Some('+') {
|
||||
return Err(invalid("malformed CIF Unicode prefix"));
|
||||
}
|
||||
let mut code = 0_u32;
|
||||
for _ in 0..4 {
|
||||
let digit = chars.next().and_then(|ch| ch.to_digit(16)).ok_or_else(|| invalid("CIF Unicode escape requires four hexadecimal digits"))?;
|
||||
code = code * 16 + digit;
|
||||
}
|
||||
let ch = char::from_u32(code).ok_or_else(|| invalid("CIF Unicode escape is not a scalar value; surrogate pairs are unsupported"))?;
|
||||
if ch.is_control() {
|
||||
return Err(invalid("not supported yet: a control character encoded as CIF"));
|
||||
}
|
||||
Ok(ch)
|
||||
}
|
||||
|
||||
fn percent(chars: &mut impl Iterator<Item = char>, mtext: bool) -> Result<char> {
|
||||
match chars.next() {
|
||||
Some('%') if !mtext => Ok('%'),
|
||||
Some('d') => Ok('°'),
|
||||
Some('p') => Ok('±'),
|
||||
// Autodesk's published symbol mapping is U+2205, not U+2300/U+00D8.
|
||||
Some('c') => Ok('\u{2205}'),
|
||||
_ => Err(invalid("not supported yet: percent formatting code")),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(value: &str, mtext: bool, max_decoded_bytes: usize) -> Result<String> {
|
||||
let mut out = String::new();
|
||||
let mut chars = value.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
let decoded = match ch {
|
||||
// No hidden CR/LF/tab normalization or stripping. A paragraph is
|
||||
// admitted only through the explicit MTEXT escape below.
|
||||
c if c.is_control() => return Err(invalid("not supported yet: raw text control character")),
|
||||
'\\' => match chars.peek().copied() {
|
||||
Some('U') => {
|
||||
chars.next();
|
||||
cif(&mut chars)?
|
||||
}
|
||||
Some('\\' | '{' | '}') if mtext => chars.next().ok_or_else(|| invalid("incomplete MTEXT escape"))?,
|
||||
Some('P') if mtext => {
|
||||
chars.next();
|
||||
'\n'
|
||||
}
|
||||
_ if mtext => return Err(invalid("not supported yet: MTEXT formatting escape")),
|
||||
_ => '\\',
|
||||
},
|
||||
'%' if chars.peek() == Some(&'%') => {
|
||||
chars.next();
|
||||
percent(&mut chars, mtext)?
|
||||
}
|
||||
'{' | '}' if mtext => return Err(invalid("not supported yet: MTEXT formatting group")),
|
||||
c => c,
|
||||
};
|
||||
// Never feed decoded output back into the scanner. Decoded percent,
|
||||
// backslash, braces and 'P' remain literal rather than becoming syntax.
|
||||
push(&mut out, decoded, max_decoded_bytes)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// TEXT's untrimmed group-1 value. Raw Unicode scalar text is preserved, including
|
||||
/// non-BMP UTF8 in an imported newer-format file. That is distinct from the
|
||||
/// AC1015 writer's no-non-BMP admission rule; this helper does not select a version.
|
||||
pub(super) fn decode_text_value(value: &str, max_encoded_bytes: usize, max_decoded_bytes: usize) -> Result<String> {
|
||||
if value.len() > max_encoded_bytes {
|
||||
return Err(invalid("encoded byte budget exceeded"));
|
||||
}
|
||||
decode(value, false, max_decoded_bytes)
|
||||
}
|
||||
|
||||
/// Concatenate already-parsed MTEXT group-3 fields then its single group-1 tail,
|
||||
/// preserving their stored order and spaces, and decode ONCE. Only pass codes1/3.
|
||||
/// Chunk-length/empty-tail format policy remains the caller's responsibility:
|
||||
/// this is a bounded value combiner, not a file/chunk-conformance validator.
|
||||
pub(super) fn decode_mtext_values<'a>(
|
||||
values: impl IntoIterator<Item = (i32, &'a str)>, max_encoded_bytes: usize, max_decoded_bytes: usize, max_chunks: usize,
|
||||
) -> Result<String> {
|
||||
let mut joined = String::new();
|
||||
let mut tail_seen = false;
|
||||
let mut count = 0_usize;
|
||||
for (code, value) in values {
|
||||
count = count.checked_add(1).ok_or_else(|| invalid("MTEXT chunk count overflow"))?;
|
||||
if count > max_chunks {
|
||||
return Err(invalid("MTEXT chunk budget exceeded"));
|
||||
}
|
||||
if tail_seen {
|
||||
return Err(invalid("MTEXT text field follows its group-1 tail"));
|
||||
}
|
||||
match code {
|
||||
3 => {}
|
||||
1 => tail_seen = true,
|
||||
_ => return Err(invalid("MTEXT value combiner accepts group1/3 only")),
|
||||
}
|
||||
let needed = joined.len().checked_add(value.len()).ok_or_else(|| invalid("MTEXT encoded size overflow"))?;
|
||||
if needed > max_encoded_bytes {
|
||||
return Err(invalid("MTEXT encoded byte budget exceeded"));
|
||||
}
|
||||
joined.try_reserve(value.len()).map_err(|error| invalid(format!("cannot reserve MTEXT text: {error}")))?;
|
||||
joined.push_str(value);
|
||||
}
|
||||
if !tail_seen {
|
||||
return Err(invalid("MTEXT is missing its group-1 tail"));
|
||||
}
|
||||
decode(&joined, true, max_decoded_bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{decode_mtext_values, decode_text_value};
|
||||
|
||||
#[test]
|
||||
fn text_plain_percent_control_codes_and_cif_have_literal_expected_values() {
|
||||
assert_eq!(decode_text_value("%%% %%%%%%d %%d %%p %%c \\U+FFFF", 4096, 4096).unwrap(), "% %%d ° ± \u{2205} \u{ffff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_decodes_once_and_preserves_spaces_and_literal_backslash_syntax() {
|
||||
assert_eq!(decode_text_value(" \\U+005CU+0041 \\P \\{x\\} ", 4096, 4096).unwrap(), " \\U+0041 \\P \\{x\\} ");
|
||||
assert_eq!(decode_text_value("\\U+0025\\U+0025d", 4096, 4096).unwrap(), "%%d");
|
||||
assert_eq!(decode_text_value("trailing\\", 4096, 4096).unwrap(), "trailing\\");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_literals_and_paragraphs_decode_once_without_style_interpretation() {
|
||||
let fields = [(1, "\\U+0025 \\U+0025\\U+0025d \\U+00B0 \\\\P \\{x\\}\\Pnext")];
|
||||
assert_eq!(decode_mtext_values(fields, 4096, 4096, 1).unwrap(), "% %%d ° \\P {x}\nnext");
|
||||
assert_eq!(decode_mtext_values([(1, "\\\\U+0041")], 4096, 4096, 1).unwrap(), "\\U+0041");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_joins_cif_escape_across_real_250_byte_boundary_before_decoding() {
|
||||
let head = format!("{}\\U", "a".repeat(248));
|
||||
let fields = [(3, head.as_str()), (1, "+4E2Dz")];
|
||||
assert_eq!(head.len(), 250);
|
||||
assert_eq!(decode_mtext_values(fields, 256, 252, 2).unwrap(), format!("{}中z", "a".repeat(248)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_joins_escaped_backslash_and_percent_without_second_decode() {
|
||||
let head = format!("{}\\", "a".repeat(249));
|
||||
assert_eq!(head.len(), 250);
|
||||
assert_eq!(decode_mtext_values([(3, head.as_str()), (1, "\\P")], 4096, 4096, 2).unwrap(), format!("{}\\P", "a".repeat(249)));
|
||||
assert_eq!(decode_mtext_values([(3, "\\U+002"), (1, "5\\U+0025d")], 4096, 4096, 2).unwrap(), "%%d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_combiner_preserves_empty_tail_without_deciding_writer_chunk_policy() {
|
||||
let full = "x".repeat(250);
|
||||
assert_eq!(decode_mtext_values([(3, full.as_str()), (1, "")], 250, 250, 2).unwrap(), full);
|
||||
assert_eq!(decode_mtext_values([(1, "")], 0, 0, 1).unwrap(), "");
|
||||
assert_eq!(decode_mtext_values([(3, " one "), (1, " two ")], 4096, 4096, 2).unwrap(), " one two ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_styled_escapes_are_explicit_errors_not_stripped_text() {
|
||||
for value in ["\\U+", "\\U+XYZ0", "\\U+123", "\\U0041", "\\U+D800", "\\U+DC00", "%%", "%%q", "%%u", "%%123"] {
|
||||
assert!(decode_text_value(value, 4096, 4096).is_err(), "{value}");
|
||||
}
|
||||
for value in ["\\", "\\H2x;Hi", "{styled}", "%%%", "\\~", "\\Lline"] {
|
||||
assert!(decode_mtext_values([(1, value)], 4096, 4096, 1).is_err(), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_controls_and_cif_controls_do_not_silently_normalize() {
|
||||
for value in ["a\rb", "a\nb", "a\tb", "\\U+0000", "\\U+000A", "\\U+000D", "\\U+0085"] {
|
||||
assert!(decode_text_value(value, 4096, 4096).is_err());
|
||||
assert!(decode_mtext_values([(1, value)], 4096, 4096, 1).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_decoded_and_chunk_budgets_are_independently_inclusive() {
|
||||
assert_eq!(decode_text_value("\\U+FFFF", 7, 3).unwrap(), "\u{ffff}");
|
||||
assert!(decode_text_value("\\U+FFFF", 6, 3).is_err());
|
||||
assert!(decode_text_value("\\U+FFFF", 7, 2).is_err());
|
||||
assert_eq!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 3, 2).unwrap(), "\u{ffff}");
|
||||
assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 6, 3, 2).is_err());
|
||||
assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 2, 2).is_err());
|
||||
assert!(decode_mtext_values([(3, "\\U+"), (1, "FFFF")], 7, 3, 1).is_err());
|
||||
assert!(decode_mtext_values([(1, "")], 0, 0, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_missing_duplicate_or_out_of_order_tail_refuses() {
|
||||
assert!(decode_mtext_values([], 4096, 4096, 8).is_err());
|
||||
assert!(decode_mtext_values([(3, "text")], 4096, 4096, 8).is_err());
|
||||
assert!(decode_mtext_values([(1, "a"), (1, "b")], 4096, 4096, 8).is_err());
|
||||
assert!(decode_mtext_values([(1, "a"), (3, "b")], 4096, 4096, 8).is_err());
|
||||
assert!(decode_mtext_values([(8, "LAYER"), (1, "a")], 4096, 4096, 8).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_utf8_input_is_not_confused_with_ac1015_writer_admission() {
|
||||
assert_eq!(decode_text_value("中𠀋", 7, 7).unwrap(), "中𠀋");
|
||||
assert_eq!(decode_mtext_values([(1, "中𠀋")], 7, 7, 1).unwrap(), "中𠀋");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
diff --git a/crates/io/src/dxf_out/text.rs b/crates/io/src/dxf_out/text.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/io/src/dxf_out/text.rs
|
||||
@@ -0,0 +1,222 @@
|
||||
+//! Private X4 proposal: NOT APPLIED, NOT COMPILED, NOT RUN.
|
||||
+//! Intended as an internal dxf_out submodule after Engineer/W1 contract review.
|
||||
+//! No DxfFile, geometry, numeric formatter, reader or caller migration is defined here.
|
||||
+//! Controls other than line endings are refused pending explicit owner policy.
|
||||
+
|
||||
+use std::fmt::Write as _;
|
||||
+
|
||||
+use crate::{IoError, Result};
|
||||
+
|
||||
+const TEXT_CHAR_LIMIT: usize = 256;
|
||||
+const MTEXT_CHUNK_BYTES: usize = 250;
|
||||
+
|
||||
+fn invalid(reason: impl std::fmt::Display) -> IoError {
|
||||
+ IoError::Invalid(format!("DXF text: {reason}"))
|
||||
+}
|
||||
+
|
||||
+// Validate the WHOLE original string, including beyond the historical 250-character cap.
|
||||
+// The writer adapter adds entity/layer identity to this original character position.
|
||||
+fn validate(source: &str) -> Result<()> {
|
||||
+ for (index, ch) in source.chars().enumerate() {
|
||||
+ if u32::from(ch) > 0xffff {
|
||||
+ return Err(invalid(format!(
|
||||
+ "character {ch:?} (U+{:04X}) at position {} cannot be written as DXF AC1015 text; only characters through U+FFFF are supported",
|
||||
+ u32::from(ch),
|
||||
+ index + 1
|
||||
+ )));
|
||||
+ }
|
||||
+ }
|
||||
+ for (index, ch) in source.chars().enumerate() {
|
||||
+ if ch.is_control() && ch != '\n' && ch != '\r' {
|
||||
+ return Err(invalid(format!("control U+{:04X} at position {} is not supported", u32::from(ch), index + 1)));
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+fn unicode(out: &mut String, ch: char) -> Result<()> {
|
||||
+ write!(out, "\\U+{:04X}", u32::from(ch)).map_err(|error| invalid(format!("encoding failed: {error}")))
|
||||
+}
|
||||
+
|
||||
+fn encoded_len(source: &str, mtext: bool) -> Result<usize> {
|
||||
+ let mut bytes = 0_usize;
|
||||
+ let mut chars = source.chars().peekable();
|
||||
+ while let Some(ch) = chars.next() {
|
||||
+ let count = match ch {
|
||||
+ '\r' if mtext => {
|
||||
+ if chars.peek() == Some(&'\n') {
|
||||
+ chars.next();
|
||||
+ }
|
||||
+ 2
|
||||
+ }
|
||||
+ '\n' if mtext => 2,
|
||||
+ '%' if mtext => 7,
|
||||
+ '\\' | '{' | '}' if mtext => 2,
|
||||
+ '%' | '°' if !mtext => 3,
|
||||
+ '\\' if !mtext => 7,
|
||||
+ c if !c.is_ascii() => 7,
|
||||
+ _ => 1,
|
||||
+ };
|
||||
+ bytes = bytes.checked_add(count).ok_or_else(|| invalid("encoded size overflow"))?;
|
||||
+ }
|
||||
+ Ok(bytes)
|
||||
+}
|
||||
+
|
||||
+// The caller supplies the remaining encoded-text byte budget; no new global resource policy.
|
||||
+// This excludes DXF group/record overhead, which the file adapter must also account for.
|
||||
+fn encode(source: &str, mtext: bool, max_encoded_bytes: usize) -> Result<String> {
|
||||
+ let needed = encoded_len(source, mtext)?;
|
||||
+ if needed > max_encoded_bytes {
|
||||
+ return Err(invalid("encoded text exceeds the caller's byte budget"));
|
||||
+ }
|
||||
+ let mut out = String::new();
|
||||
+ out.try_reserve(needed).map_err(|error| invalid(format!("cannot reserve encoded text: {error}")))?;
|
||||
+ let mut chars = source.chars().peekable();
|
||||
+ while let Some(ch) = chars.next() {
|
||||
+ match ch {
|
||||
+ '\r' if mtext => {
|
||||
+ if chars.peek() == Some(&'\n') {
|
||||
+ chars.next();
|
||||
+ }
|
||||
+ out.push_str("\\P");
|
||||
+ }
|
||||
+ '\n' if mtext => out.push_str("\\P"),
|
||||
+ '%' if mtext => unicode(&mut out, ch)?,
|
||||
+ '\\' | '{' | '}' if mtext => {
|
||||
+ out.push('\\');
|
||||
+ out.push(ch);
|
||||
+ }
|
||||
+ '%' if !mtext => out.push_str("%%%"),
|
||||
+ '°' if !mtext => out.push_str("%%d"),
|
||||
+ '\\' if !mtext => unicode(&mut out, ch)?,
|
||||
+ c if !c.is_ascii() => unicode(&mut out, c)?,
|
||||
+ c => out.push(c),
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(out)
|
||||
+}
|
||||
+
|
||||
+/// One TEXT group-1 value from plain single-line text, never truncated.
|
||||
+pub(super) fn encode_text_value(source: &str, max_encoded_bytes: usize) -> Result<String> {
|
||||
+ validate(source)?;
|
||||
+ if source.contains(['\n', '\r']) || source.chars().count() > TEXT_CHAR_LIMIT {
|
||||
+ return Err(invalid("TEXT requires one line of at most 256 characters; use MTEXT"));
|
||||
+ }
|
||||
+ encode(source, false, max_encoded_bytes)
|
||||
+}
|
||||
+
|
||||
+/// MTEXT group-3 chunks and the final group-1 tail, from plain text.
|
||||
+/// All values are ASCII/CIF. Group-3 values have EXACTLY 250 bytes, the final group-1
|
||||
+/// fewer than 250 (possibly empty). Exact-multiple empty tails are a proposed policy:
|
||||
+/// owner/independent-reader acceptance is PENDING, not format conformance evidence.
|
||||
+/// A CIF escape may straddle a group boundary:
|
||||
+/// the reader must concatenate all group-3 values plus group-1 BEFORE decoding once.
|
||||
+pub(super) fn encode_mtext_groups(source: &str, max_encoded_bytes: usize) -> Result<Vec<(i32, String)>> {
|
||||
+ validate(source)?;
|
||||
+ let encoded = encode(source, true, max_encoded_bytes)?;
|
||||
+ let count = encoded.len() / MTEXT_CHUNK_BYTES + 1;
|
||||
+ let mut groups = Vec::new();
|
||||
+ groups.try_reserve(count).map_err(|error| invalid(format!("cannot reserve MTEXT chunks: {error}")))?;
|
||||
+ let mut start = 0;
|
||||
+ while encoded.len() - start >= MTEXT_CHUNK_BYTES {
|
||||
+ let end = start + MTEXT_CHUNK_BYTES;
|
||||
+ let chunk = encoded.get(start..end).ok_or_else(|| invalid("invalid ASCII chunk boundary"))?;
|
||||
+ let mut value = String::new();
|
||||
+ value.try_reserve(chunk.len()).map_err(|error| invalid(format!("cannot reserve MTEXT chunk: {error}")))?;
|
||||
+ value.push_str(chunk);
|
||||
+ groups.push((3, value));
|
||||
+ start = end;
|
||||
+ }
|
||||
+ let tail = encoded.get(start..).ok_or_else(|| invalid("invalid ASCII tail boundary"))?;
|
||||
+ let mut value = String::new();
|
||||
+ value.try_reserve(tail.len()).map_err(|error| invalid(format!("cannot reserve MTEXT tail: {error}")))?;
|
||||
+ value.push_str(tail);
|
||||
+ groups.push((1, value));
|
||||
+ Ok(groups)
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::{encode_mtext_groups, encode_text_value};
|
||||
+
|
||||
+ #[test]
|
||||
+ fn short_text_keeps_all_256_plain_characters_and_refuses_257() {
|
||||
+ for n in [0, 1, 255, 256] {
|
||||
+ let plain = "x".repeat(n);
|
||||
+ assert_eq!(encode_text_value(&plain, 4096).unwrap(), plain);
|
||||
+ }
|
||||
+ assert!(encode_text_value(&"x".repeat(257), 4096).is_err());
|
||||
+ assert!(encode_text_value("one\ntwo", 4096).is_err());
|
||||
+ assert!(encode_text_value("one\rtwo", 4096).is_err());
|
||||
+ assert_eq!(encode_text_value(&"中".repeat(256), 1792).unwrap(), "\\U+4E2D".repeat(256));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn plain_percent_degree_and_literal_unicode_escape_have_distinct_text_bytes() {
|
||||
+ assert_eq!(encode_text_value("% %%d ° \\U+0041 {}", 4096).unwrap(), "%%% %%%%%%d %%d \\U+005CU+0041 {}");
|
||||
+ assert_eq!(encode_text_value("\u{ffff}", 7).unwrap(), "\\U+FFFF");
|
||||
+ assert_eq!(encode_text_value("B1 UP 90° R1", 4096).unwrap(), "B1 UP 90%%d R1");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_plain_metacharacters_cannot_turn_into_formatting() {
|
||||
+ let groups = encode_mtext_groups("% %%d ° \\P {x}\nnext\r\nlast\rend", 4096).unwrap();
|
||||
+ assert_eq!(groups, vec![(1, "\\U+0025 \\U+0025\\U+0025d \\U+00B0 \\\\P \\{x\\}\\Pnext\\Plast\\Pend".into())]);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn mtext_chunk_boundaries_have_full_group_threes_and_one_terminal_tail() {
|
||||
+ for (n, expected) in [
|
||||
+ (0, vec![(1, 0)]),
|
||||
+ (249, vec![(1, 249)]),
|
||||
+ (250, vec![(3, 250), (1, 0)]),
|
||||
+ (251, vec![(3, 250), (1, 1)]),
|
||||
+ (500, vec![(3, 250), (3, 250), (1, 0)]),
|
||||
+ (501, vec![(3, 250), (3, 250), (1, 1)]),
|
||||
+ ] {
|
||||
+ let plain = "x".repeat(n);
|
||||
+ let groups = encode_mtext_groups(&plain, 4096).unwrap();
|
||||
+ assert_eq!(groups.iter().map(|(code, text)| (*code, text.len())).collect::<Vec<_>>(), expected);
|
||||
+ assert_eq!(groups.iter().map(|(_, text)| text.as_str()).collect::<String>(), plain);
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn cif_escape_across_group_boundary_is_reassembled_before_interpretation() {
|
||||
+ let plain = format!("{}中z", "a".repeat(248));
|
||||
+ let groups = encode_mtext_groups(&plain, 256).unwrap();
|
||||
+ assert_eq!(groups, vec![(3, format!("{}\\U", "a".repeat(248))), (1, "+4E2Dz".into())]);
|
||||
+ assert_eq!(groups.iter().map(|(_, text)| text.as_str()).collect::<String>(), format!("{}\\U+4E2Dz", "a".repeat(248)));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn non_bmp_is_never_substituted_even_beyond_old_cap_and_before_budget_error() {
|
||||
+ for plain in ["𠀋".into(), "𝑥".into(), format!("{}𠀋", "x".repeat(300))] {
|
||||
+ let text = encode_text_value(&plain, 0).unwrap_err().to_string();
|
||||
+ let mtext = encode_mtext_groups(&plain, 0).unwrap_err().to_string();
|
||||
+ assert!(text.contains("U+2000B") || text.contains("U+1D465"));
|
||||
+ assert_eq!(text, mtext);
|
||||
+ if plain.starts_with('x') {
|
||||
+ assert!(text.contains("position 301"));
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn encoded_budget_counts_expansion_and_is_inclusive() {
|
||||
+ assert_eq!(encode_text_value("°", 3).unwrap(), "%%d");
|
||||
+ assert!(encode_text_value("°", 2).is_err());
|
||||
+ assert_eq!(encode_mtext_groups("%", 7).unwrap(), vec![(1, "\\U+0025".into())]);
|
||||
+ assert!(encode_mtext_groups("%", 6).is_err());
|
||||
+ assert_eq!(encode_mtext_groups("", 0).unwrap(), vec![(1, String::new())]);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn unsupported_controls_refuse_instead_of_disappearing_pending_owner_policy() {
|
||||
+ for ch in ['\0', '\t', '\u{1f}', '\u{7f}', '\u{85}'] {
|
||||
+ let plain = format!("a{ch}b");
|
||||
+ assert!(encode_text_value(&plain, 4096).is_err());
|
||||
+ assert!(encode_mtext_groups(&plain, 4096).is_err());
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Private X4 proposal: NOT APPLIED, NOT COMPILED, NOT RUN.
|
||||
//! Intended as an internal dxf_out submodule after Engineer/W1 contract review.
|
||||
//! No DxfFile, geometry, numeric formatter, reader or caller migration is defined here.
|
||||
//! Controls other than line endings are refused pending explicit owner policy.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
const TEXT_CHAR_LIMIT: usize = 256;
|
||||
const MTEXT_CHUNK_BYTES: usize = 250;
|
||||
|
||||
fn invalid(reason: impl std::fmt::Display) -> IoError {
|
||||
IoError::Invalid(format!("DXF text: {reason}"))
|
||||
}
|
||||
|
||||
// Validate the WHOLE original string, including beyond the historical 250-character cap.
|
||||
// The writer adapter adds entity/layer identity to this original character position.
|
||||
fn validate(source: &str) -> Result<()> {
|
||||
for (index, ch) in source.chars().enumerate() {
|
||||
if u32::from(ch) > 0xffff {
|
||||
return Err(invalid(format!(
|
||||
"character {ch:?} (U+{:04X}) at position {} cannot be written as DXF AC1015 text; only characters through U+FFFF are supported",
|
||||
u32::from(ch),
|
||||
index + 1
|
||||
)));
|
||||
}
|
||||
}
|
||||
for (index, ch) in source.chars().enumerate() {
|
||||
if ch.is_control() && ch != '\n' && ch != '\r' {
|
||||
return Err(invalid(format!("control U+{:04X} at position {} is not supported", u32::from(ch), index + 1)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unicode(out: &mut String, ch: char) -> Result<()> {
|
||||
write!(out, "\\U+{:04X}", u32::from(ch)).map_err(|error| invalid(format!("encoding failed: {error}")))
|
||||
}
|
||||
|
||||
fn encoded_len(source: &str, mtext: bool) -> Result<usize> {
|
||||
let mut bytes = 0_usize;
|
||||
let mut chars = source.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
let count = match ch {
|
||||
'\r' if mtext => {
|
||||
if chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
2
|
||||
}
|
||||
'\n' if mtext => 2,
|
||||
'%' if mtext => 7,
|
||||
'\\' | '{' | '}' if mtext => 2,
|
||||
'%' | '°' if !mtext => 3,
|
||||
'\\' if !mtext => 7,
|
||||
c if !c.is_ascii() => 7,
|
||||
_ => 1,
|
||||
};
|
||||
bytes = bytes.checked_add(count).ok_or_else(|| invalid("encoded size overflow"))?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
// The caller supplies the remaining encoded-text byte budget; no new global resource policy.
|
||||
// This excludes DXF group/record overhead, which the file adapter must also account for.
|
||||
fn encode(source: &str, mtext: bool, max_encoded_bytes: usize) -> Result<String> {
|
||||
let needed = encoded_len(source, mtext)?;
|
||||
if needed > max_encoded_bytes {
|
||||
return Err(invalid("encoded text exceeds the caller's byte budget"));
|
||||
}
|
||||
let mut out = String::new();
|
||||
out.try_reserve(needed).map_err(|error| invalid(format!("cannot reserve encoded text: {error}")))?;
|
||||
let mut chars = source.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
match ch {
|
||||
'\r' if mtext => {
|
||||
if chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
out.push_str("\\P");
|
||||
}
|
||||
'\n' if mtext => out.push_str("\\P"),
|
||||
'%' if mtext => unicode(&mut out, ch)?,
|
||||
'\\' | '{' | '}' if mtext => {
|
||||
out.push('\\');
|
||||
out.push(ch);
|
||||
}
|
||||
'%' if !mtext => out.push_str("%%%"),
|
||||
'°' if !mtext => out.push_str("%%d"),
|
||||
'\\' if !mtext => unicode(&mut out, ch)?,
|
||||
c if !c.is_ascii() => unicode(&mut out, c)?,
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One TEXT group-1 value from plain single-line text, never truncated.
|
||||
pub(super) fn encode_text_value(source: &str, max_encoded_bytes: usize) -> Result<String> {
|
||||
validate(source)?;
|
||||
if source.contains(['\n', '\r']) || source.chars().count() > TEXT_CHAR_LIMIT {
|
||||
return Err(invalid("TEXT requires one line of at most 256 characters; use MTEXT"));
|
||||
}
|
||||
encode(source, false, max_encoded_bytes)
|
||||
}
|
||||
|
||||
/// MTEXT group-3 chunks and the final group-1 tail, from plain text.
|
||||
/// All values are ASCII/CIF. Group-3 values have EXACTLY 250 bytes, the final group-1
|
||||
/// fewer than 250 (possibly empty). Exact-multiple empty tails are a proposed policy:
|
||||
/// owner/independent-reader acceptance is PENDING, not format conformance evidence.
|
||||
/// A CIF escape may straddle a group boundary:
|
||||
/// the reader must concatenate all group-3 values plus group-1 BEFORE decoding once.
|
||||
pub(super) fn encode_mtext_groups(source: &str, max_encoded_bytes: usize) -> Result<Vec<(i32, String)>> {
|
||||
validate(source)?;
|
||||
let encoded = encode(source, true, max_encoded_bytes)?;
|
||||
let count = encoded.len() / MTEXT_CHUNK_BYTES + 1;
|
||||
let mut groups = Vec::new();
|
||||
groups.try_reserve(count).map_err(|error| invalid(format!("cannot reserve MTEXT chunks: {error}")))?;
|
||||
let mut start = 0;
|
||||
while encoded.len() - start >= MTEXT_CHUNK_BYTES {
|
||||
let end = start + MTEXT_CHUNK_BYTES;
|
||||
let chunk = encoded.get(start..end).ok_or_else(|| invalid("invalid ASCII chunk boundary"))?;
|
||||
let mut value = String::new();
|
||||
value.try_reserve(chunk.len()).map_err(|error| invalid(format!("cannot reserve MTEXT chunk: {error}")))?;
|
||||
value.push_str(chunk);
|
||||
groups.push((3, value));
|
||||
start = end;
|
||||
}
|
||||
let tail = encoded.get(start..).ok_or_else(|| invalid("invalid ASCII tail boundary"))?;
|
||||
let mut value = String::new();
|
||||
value.try_reserve(tail.len()).map_err(|error| invalid(format!("cannot reserve MTEXT tail: {error}")))?;
|
||||
value.push_str(tail);
|
||||
groups.push((1, value));
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{encode_mtext_groups, encode_text_value};
|
||||
|
||||
#[test]
|
||||
fn short_text_keeps_all_256_plain_characters_and_refuses_257() {
|
||||
for n in [0, 1, 255, 256] {
|
||||
let plain = "x".repeat(n);
|
||||
assert_eq!(encode_text_value(&plain, 4096).unwrap(), plain);
|
||||
}
|
||||
assert!(encode_text_value(&"x".repeat(257), 4096).is_err());
|
||||
assert!(encode_text_value("one\ntwo", 4096).is_err());
|
||||
assert!(encode_text_value("one\rtwo", 4096).is_err());
|
||||
assert_eq!(encode_text_value(&"中".repeat(256), 1792).unwrap(), "\\U+4E2D".repeat(256));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_percent_degree_and_literal_unicode_escape_have_distinct_text_bytes() {
|
||||
assert_eq!(encode_text_value("% %%d ° \\U+0041 {}", 4096).unwrap(), "%%% %%%%%%d %%d \\U+005CU+0041 {}");
|
||||
assert_eq!(encode_text_value("\u{ffff}", 7).unwrap(), "\\U+FFFF");
|
||||
assert_eq!(encode_text_value("B1 UP 90° R1", 4096).unwrap(), "B1 UP 90%%d R1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_plain_metacharacters_cannot_turn_into_formatting() {
|
||||
let groups = encode_mtext_groups("% %%d ° \\P {x}\nnext\r\nlast\rend", 4096).unwrap();
|
||||
assert_eq!(groups, vec![(1, "\\U+0025 \\U+0025\\U+0025d \\U+00B0 \\\\P \\{x\\}\\Pnext\\Plast\\Pend".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_chunk_boundaries_have_full_group_threes_and_one_terminal_tail() {
|
||||
for (n, expected) in [
|
||||
(0, vec![(1, 0)]),
|
||||
(249, vec![(1, 249)]),
|
||||
(250, vec![(3, 250), (1, 0)]),
|
||||
(251, vec![(3, 250), (1, 1)]),
|
||||
(500, vec![(3, 250), (3, 250), (1, 0)]),
|
||||
(501, vec![(3, 250), (3, 250), (1, 1)]),
|
||||
] {
|
||||
let plain = "x".repeat(n);
|
||||
let groups = encode_mtext_groups(&plain, 4096).unwrap();
|
||||
assert_eq!(groups.iter().map(|(code, text)| (*code, text.len())).collect::<Vec<_>>(), expected);
|
||||
assert_eq!(groups.iter().map(|(_, text)| text.as_str()).collect::<String>(), plain);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cif_escape_across_group_boundary_is_reassembled_before_interpretation() {
|
||||
let plain = format!("{}中z", "a".repeat(248));
|
||||
let groups = encode_mtext_groups(&plain, 256).unwrap();
|
||||
assert_eq!(groups, vec![(3, format!("{}\\U", "a".repeat(248))), (1, "+4E2Dz".into())]);
|
||||
assert_eq!(groups.iter().map(|(_, text)| text.as_str()).collect::<String>(), format!("{}\\U+4E2Dz", "a".repeat(248)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_bmp_is_never_substituted_even_beyond_old_cap_and_before_budget_error() {
|
||||
for plain in ["𠀋".into(), "𝑥".into(), format!("{}𠀋", "x".repeat(300))] {
|
||||
let text = encode_text_value(&plain, 0).unwrap_err().to_string();
|
||||
let mtext = encode_mtext_groups(&plain, 0).unwrap_err().to_string();
|
||||
assert!(text.contains("U+2000B") || text.contains("U+1D465"));
|
||||
assert_eq!(text, mtext);
|
||||
if plain.starts_with('x') {
|
||||
assert!(text.contains("position 301"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_budget_counts_expansion_and_is_inclusive() {
|
||||
assert_eq!(encode_text_value("°", 3).unwrap(), "%%d");
|
||||
assert!(encode_text_value("°", 2).is_err());
|
||||
assert_eq!(encode_mtext_groups("%", 7).unwrap(), vec![(1, "\\U+0025".into())]);
|
||||
assert!(encode_mtext_groups("%", 6).is_err());
|
||||
assert_eq!(encode_mtext_groups("", 0).unwrap(), vec![(1, String::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_controls_refuse_instead_of_disappearing_pending_owner_policy() {
|
||||
for ch in ['\0', '\t', '\u{1f}', '\u{7f}', '\u{85}'] {
|
||||
let plain = format!("a{ch}b");
|
||||
assert!(encode_text_value(&plain, 4096).is_err());
|
||||
assert!(encode_mtext_groups(&plain, 4096).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! PRIVATE production helper proposal for #5321; no application hook.
|
||||
//! NOT COMPILED / NOT RUN. Lengths only, in mm; never use for dimensionless
|
||||
//! angles, ratios, bulges, weights, knots or parameters (retain 12 decimals).
|
||||
//! Exact rounding of the stored binary64 value onto a 1e-9 mm integer grid.
|
||||
//! Tie-away-from-zero and at least one decimal are explicit review proposals.
|
||||
//! Constant work, 24 inline bytes, no heap allocation, no exponent or negative 0.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
const MAX_LENGTH_MM: f64 = 9_000_000.0;
|
||||
const MAX_TICKS: u128 = 9_000_000_000_000_000;
|
||||
const TICKS_PER_MM: u64 = 1_000_000_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum LengthFormatError {
|
||||
NonFinite,
|
||||
OutsideLengthRange,
|
||||
ArithmeticBounds,
|
||||
BufferInvariant,
|
||||
}
|
||||
|
||||
impl LengthFormatError {
|
||||
pub(crate) fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::NonFinite => "DXF length must be finite",
|
||||
Self::OutsideLengthRange => "DXF length magnitude exceeds 9000000 mm",
|
||||
Self::ArithmeticBounds => "DXF length integer-grid arithmetic bounds failed",
|
||||
Self::BufferInvariant => "DXF length decimal buffer bounds failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for LengthFormatError {
|
||||
fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
output.write_str(self.message())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LengthFormatError {}
|
||||
|
||||
/// Inline spelling, directly usable by the real Out::code Display argument.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LengthDecimal {
|
||||
bytes: [u8; 24],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl LengthDecimal {
|
||||
fn push(&mut self, byte: u8) -> Result<(), LengthFormatError> {
|
||||
let slot = self.bytes.get_mut(self.len).ok_or(LengthFormatError::BufferInvariant)?;
|
||||
*slot = byte;
|
||||
self.len += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(&self) -> Result<&str, LengthFormatError> {
|
||||
let bytes = self.bytes.get(..self.len).ok_or(LengthFormatError::BufferInvariant)?;
|
||||
std::str::from_utf8(bytes).map_err(|_| LengthFormatError::BufferInvariant)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for LengthDecimal {
|
||||
fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
output.write_str(self.as_str().map_err(|_| fmt::Error)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact grid magnitude for the binary64 input, without first rounding a
|
||||
/// floating-point multiplication. Does not make upstream trig platform-stable.
|
||||
fn grid_magnitude(value: f64) -> Result<u64, LengthFormatError> {
|
||||
if !value.is_finite() { return Err(LengthFormatError::NonFinite); }
|
||||
if value.abs() > MAX_LENGTH_MM { return Err(LengthFormatError::OutsideLengthRange); }
|
||||
let bits = value.to_bits();
|
||||
let exponent = ((bits >> 52) & 0x7ff) as u32;
|
||||
let fraction = bits & ((1u64 << 52) - 1);
|
||||
let (significand, shift) = if exponent == 0 {
|
||||
(fraction, 1074)
|
||||
} else {
|
||||
// value = significand * 2^(exponent-1075). Accepted magnitudes
|
||||
// ensure exponent <=1046, hence 29<=shift<=1074.
|
||||
(fraction | (1u64 << 52), 1075u32.checked_sub(exponent).ok_or(LengthFormatError::ArithmeticBounds)?)
|
||||
};
|
||||
// At most 53+30 bits: exact in u128, including subnormal significands.
|
||||
let scaled = u128::from(significand).checked_mul(u128::from(TICKS_PER_MM))
|
||||
.ok_or(LengthFormatError::ArithmeticBounds)?;
|
||||
let rounded = if shift >= 128 {
|
||||
// scaled <2^83, so such a value is strictly below half a grid tick.
|
||||
0
|
||||
} else {
|
||||
if shift == 0 { return Err(LengthFormatError::ArithmeticBounds); }
|
||||
let quotient = scaled >> shift;
|
||||
let remainder = scaled & ((1u128 << shift) - 1);
|
||||
let half = 1u128 << (shift - 1);
|
||||
quotient.checked_add(u128::from(remainder >= half)).ok_or(LengthFormatError::ArithmeticBounds)?
|
||||
};
|
||||
if rounded > MAX_TICKS { return Err(LengthFormatError::ArithmeticBounds); }
|
||||
u64::try_from(rounded).map_err(|_| LengthFormatError::ArithmeticBounds)
|
||||
}
|
||||
|
||||
/// Length in [-9000000,9000000] mm to shortest grid decimal with at least one
|
||||
/// fractional digit. Sign is emitted only for a nonzero rounded magnitude.
|
||||
pub(crate) fn length_decimal(value: f64) -> Result<LengthDecimal, LengthFormatError> {
|
||||
let ticks = grid_magnitude(value)?;
|
||||
let mut output = LengthDecimal { bytes: [0; 24], len: 0 };
|
||||
if ticks != 0 && value.is_sign_negative() { output.push(b'-')?; }
|
||||
let mut whole = ticks / TICKS_PER_MM;
|
||||
let fraction = ticks % TICKS_PER_MM;
|
||||
let mut reverse = [0u8; 7];
|
||||
let mut count = 0usize;
|
||||
loop {
|
||||
let digit = u8::try_from(whole % 10).map_err(|_| LengthFormatError::ArithmeticBounds)?;
|
||||
*reverse.get_mut(count).ok_or(LengthFormatError::BufferInvariant)? = b'0' + digit;
|
||||
count += 1;
|
||||
whole /= 10;
|
||||
if whole == 0 { break; }
|
||||
}
|
||||
for byte in reverse.iter().take(count).rev() { output.push(*byte)?; }
|
||||
output.push(b'.')?;
|
||||
let decimal_start = output.len;
|
||||
let mut divisor = 100_000_000u64;
|
||||
for _ in 0..9 {
|
||||
let digit = u8::try_from((fraction / divisor) % 10).map_err(|_| LengthFormatError::ArithmeticBounds)?;
|
||||
output.push(b'0' + digit)?;
|
||||
divisor /= 10;
|
||||
}
|
||||
while output.len > decimal_start + 1 && output.bytes.get(output.len - 1) == Some(&b'0') {
|
||||
output.len -= 1;
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zero_subnormals_signs_and_integral_values_have_explicit_spellings() {
|
||||
for value in [0.0, -0.0, f64::from_bits(1), -f64::from_bits(1), f64::MIN_POSITIVE, -f64::MIN_POSITIVE] {
|
||||
assert_eq!(length_decimal(value).unwrap().as_str().unwrap(), "0.0");
|
||||
}
|
||||
for (value, expected) in [(1.0, "1.0"), (-1.0, "-1.0"), (12.5, "12.5"), (-12.5, "-12.5")] {
|
||||
assert_eq!(length_decimal(value).unwrap().as_str().unwrap(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rational_binary_half_grid_ties_and_neighbors_have_independent_expectations() {
|
||||
// 1/1024 mm * 1e9 = 976562.5 ticks exactly, a binary rational tie.
|
||||
let half: f64 = 1.0 / 1024.0;
|
||||
for (value, expected) in [
|
||||
(half, "0.000976563"), (half.next_down(), "0.000976562"), (half.next_up(), "0.000976563"),
|
||||
(-half, "-0.000976563"), ((-half).next_up(), "-0.000976562"), ((-half).next_down(), "-0.000976563"),
|
||||
] { assert_eq!(length_decimal(value).unwrap().as_str().unwrap(), expected); }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_grid_rounding_does_not_lose_large_half_tick_to_f64_multiplication() {
|
||||
// Exact binary value; its scaled half tick is not representable at
|
||||
// this magnitude (the floating product has spacing 1 tick).
|
||||
let value: f64 = 8_000_000.0 + 1.0 / 1024.0;
|
||||
// The literal multiply-then-round policy rounds the intermediate
|
||||
// half tick to the even lower integer, demonstrating different bytes.
|
||||
assert_eq!((value * 1e9).round() as u64, 8_000_000_000_976_562);
|
||||
assert_eq!(grid_magnitude(value).unwrap(), 8_000_000_000_976_563);
|
||||
assert_eq!(length_decimal(value).unwrap().as_str().unwrap(), "8000000.000976563");
|
||||
assert_eq!(length_decimal(-value).unwrap().as_str().unwrap(), "-8000000.000976563");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inclusive_length_bounds_refuse_outside_values_and_all_nonfinite_values() {
|
||||
assert_eq!(length_decimal(9_000_000.0).unwrap().as_str().unwrap(), "9000000.0");
|
||||
assert_eq!(length_decimal(-9_000_000.0).unwrap().as_str().unwrap(), "-9000000.0");
|
||||
for value in [9_000_000.0f64.next_up(), (-9_000_000.0f64).next_down(), f64::MAX, -f64::MAX] {
|
||||
assert_eq!(length_decimal(value), Err(LengthFormatError::OutsideLengthRange));
|
||||
}
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert_eq!(length_decimal(value), Err(LengthFormatError::NonFinite));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_fraction_leading_and_trailing_zeroes_are_decimal_only() {
|
||||
for (value, expected) in [
|
||||
(1.0 / 512.0, "0.001953125"), (1.0 / 16.0, "0.0625"),
|
||||
(1e-9, "0.000000001"), (-1e-9, "-0.000000001"), (1e-12, "0.0"),
|
||||
] { assert_eq!(length_decimal(value).unwrap().as_str().unwrap(), expected); }
|
||||
for value in [-8_999_999.0, -0.001, 0.0, 0.001, 8_999_999.0] {
|
||||
let decimal = length_decimal(value).unwrap();
|
||||
let text = decimal.as_str().unwrap();
|
||||
assert!(text.len() <= 18);
|
||||
assert!(!text.chars().any(|c| matches!(c, 'e' | 'E' | '+')));
|
||||
assert_ne!(text, "-0.0");
|
||||
}
|
||||
assert_eq!(format!("{}", length_decimal(12.5).unwrap()), "12.5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs
|
||||
--- a/crates/io/src/dxf_out.rs
|
||||
+++ b/crates/io/src/dxf_out.rs
|
||||
@@ -18,1 +18,6 @@
|
||||
use crate::{IoError, Result};
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod text;
|
||||
+#[cfg(test)]
|
||||
+mod text_bridge;
|
||||
@@ -0,0 +1,127 @@
|
||||
diff --git a/crates/io/src/dxf_out/text_bridge.rs b/crates/io/src/dxf_out/text_bridge.rs
|
||||
new file mode 100644
|
||||
--- /dev/null
|
||||
+++ b/crates/io/src/dxf_out/text_bridge.rs
|
||||
@@ -0,0 +1,122 @@
|
||||
+//! Private cfg(test)-only X4/X2/Out bridge proposal. NOT APPLIED / NOT COMPILED / NOT RUN.
|
||||
+//! This writes one TEXT value field, not an entity or a DXF file. No production caller.
|
||||
+
|
||||
+use super::file_model::DxfFile;
|
||||
+use super::text::encode_text_value;
|
||||
+use super::{DxfShape, Out};
|
||||
+use crate::{IoError, Result};
|
||||
+
|
||||
+fn write_owned_text_value(out: &mut Out, file: &DxfFile<DxfShape>, index: usize, remaining_record_bytes: usize) -> Result<()> {
|
||||
+ let entity = file.entities().get(index).ok_or_else(|| IoError::Invalid("DXF private TEXT bridge: no such entity".into()))?;
|
||||
+ let layer = file.layer(entity.layer())?;
|
||||
+ let context = |error: IoError| IoError::Invalid(format!("DXF TEXT entity {} on layer {:?}: {error}", index + 1, layer.name()));
|
||||
+ let DxfShape::Text { text, .. } = entity.geometry() else {
|
||||
+ return Err(context(IoError::Invalid("not supported by private TEXT-only bridge: non-TEXT geometry".into())));
|
||||
+ };
|
||||
+ // Explicit partial bridge domain, NOT a product policy for control characters.
|
||||
+ // Neither MTEXT nor any disputed control/tail policy is invoked by this bridge.
|
||||
+ if text.chars().any(char::is_control) || text.chars().count() > 256 {
|
||||
+ return Err(context(IoError::Invalid("not supported by private TEXT-only bridge: controls, multiline or more than 256 characters".into())));
|
||||
+ }
|
||||
+ // The real Out::code(1, value) writes three code bytes plus two newlines.
|
||||
+ // Encode before the framing-floor check so the codec still validates the whole
|
||||
+ // supported-domain source for non-BMP when the remaining budget is zero.
|
||||
+ let encoded = encode_text_value(text, remaining_record_bytes.saturating_sub(5)).map_err(context)?;
|
||||
+ if remaining_record_bytes < 5 {
|
||||
+ return Err(context(IoError::Invalid("TEXT group1 framing exceeds remaining record bytes".into())));
|
||||
+ }
|
||||
+ out.code(1, encoded);
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::{DxfFile, DxfShape, Out, write_owned_text_value};
|
||||
+ use crate::DxfLinetype;
|
||||
+ use solidcraft_geom::Vec2;
|
||||
+
|
||||
+ fn file_with_text(text: &str) -> DxfFile<DxfShape> {
|
||||
+ let mut file = DxfFile::new().unwrap();
|
||||
+ let layer = file.declare_layer("NOTES", 7, DxfLinetype::Continuous, None).unwrap();
|
||||
+ let shape = DxfShape::Text { at: Vec2::new(3.0, 4.0), height: 5.0, angle_deg: 0.0, text: text.into() };
|
||||
+ file.push(layer, shape, None).unwrap();
|
||||
+ file
|
||||
+ }
|
||||
+
|
||||
+ fn sentinel() -> Out {
|
||||
+ Out { s: "sentinel\n".into(), next: 0x20 }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn owned_text_uses_actual_out_group1_framing_only() {
|
||||
+ let file = file_with_text("plain");
|
||||
+ let mut out = sentinel();
|
||||
+ write_owned_text_value(&mut out, &file, 0, 10).unwrap();
|
||||
+ assert_eq!(out.s, "sentinel\n 1\nplain\n");
|
||||
+ assert_eq!(out.next, 0x20, "a text-value field does not allocate entity handles");
|
||||
+ assert_eq!(file.layer(file.entities()[0].layer()).unwrap().name(), "NOTES");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn literal_percent_and_plain_degree_reach_real_out_without_preencoding() {
|
||||
+ let file = file_with_text("% %%d ° \\U+0041");
|
||||
+ let mut out = sentinel();
|
||||
+ write_owned_text_value(&mut out, &file, 0, 4096).unwrap();
|
||||
+ assert_eq!(out.s, "sentinel\n 1\n%%% %%%%%%d %%d \\U+005CU+0041\n");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn non_bmp_error_has_real_entity_layer_and_leaves_out_untouched() {
|
||||
+ let file = file_with_text("ab𠀋");
|
||||
+ let mut out = sentinel();
|
||||
+ let error = write_owned_text_value(&mut out, &file, 0, 0).unwrap_err().to_string();
|
||||
+ assert!(error.contains("entity 1 on layer \"NOTES\""), "{error}");
|
||||
+ assert!(error.contains("U+2000B") && error.contains("position 3"), "{error}");
|
||||
+ assert_eq!(out.s, "sentinel\n");
|
||||
+ assert_eq!(out.next, 0x20);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn unsupported_domain_refuses_before_writing_any_value() {
|
||||
+ for text in ["a\nb".into(), "a\rb".into(), "a\tb".into(), "x".repeat(257)] {
|
||||
+ let file = file_with_text(&text);
|
||||
+ let mut out = sentinel();
|
||||
+ let error = write_owned_text_value(&mut out, &file, 0, 4096).unwrap_err().to_string();
|
||||
+ assert!(error.contains("not supported by private TEXT-only bridge"), "{error}");
|
||||
+ assert_eq!(out.s, "sentinel\n");
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn inclusive_record_budget_counts_encoding_plus_five_framing_bytes() {
|
||||
+ let file = file_with_text("中");
|
||||
+ let mut out = sentinel();
|
||||
+ write_owned_text_value(&mut out, &file, 0, 12).unwrap();
|
||||
+ assert_eq!(out.s, "sentinel\n 1\n\\U+4E2D\n");
|
||||
+ let mut small = sentinel();
|
||||
+ assert!(write_owned_text_value(&mut small, &file, 0, 11).is_err());
|
||||
+ assert_eq!(small.s, "sentinel\n");
|
||||
+ let empty = file_with_text("");
|
||||
+ let mut out = sentinel();
|
||||
+ write_owned_text_value(&mut out, &empty, 0, 5).unwrap();
|
||||
+ assert_eq!(out.s, "sentinel\n 1\n\n");
|
||||
+ let mut small = sentinel();
|
||||
+ assert!(write_owned_text_value(&mut small, &empty, 0, 4).is_err());
|
||||
+ assert_eq!(small.s, "sentinel\n");
|
||||
+ let long = file_with_text(&"中".repeat(256));
|
||||
+ let mut out = sentinel();
|
||||
+ write_owned_text_value(&mut out, &long, 0, 1797).unwrap();
|
||||
+ assert_eq!(out.s, format!("sentinel\n 1\n{}\n", "\\U+4E2D".repeat(256)));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn wrong_geometry_and_missing_entity_cannot_write_a_partial_record() {
|
||||
+ let mut file = DxfFile::new().unwrap();
|
||||
+ file.push(file.default_layer(), DxfShape::Line(Vec2::ZERO, Vec2::new(1.0, 2.0)), None).unwrap();
|
||||
+ let mut out = sentinel();
|
||||
+ assert!(write_owned_text_value(&mut out, &file, 0, 4096).is_err());
|
||||
+ assert!(write_owned_text_value(&mut out, &file, usize::MAX, 4096).is_err());
|
||||
+ assert_eq!(out.s, "sentinel\n");
|
||||
+ assert_eq!(out.next, 0x20);
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Private cfg(test)-only X4/X2/Out bridge proposal. NOT APPLIED / NOT COMPILED / NOT RUN.
|
||||
//! This writes one TEXT value field, not an entity or a DXF file. No production caller.
|
||||
|
||||
use super::file_model::DxfFile;
|
||||
use super::text::encode_text_value;
|
||||
use super::{DxfShape, Out};
|
||||
use crate::{IoError, Result};
|
||||
|
||||
fn write_owned_text_value(out: &mut Out, file: &DxfFile<DxfShape>, index: usize, remaining_record_bytes: usize) -> Result<()> {
|
||||
let entity = file.entities().get(index).ok_or_else(|| IoError::Invalid("DXF private TEXT bridge: no such entity".into()))?;
|
||||
let layer = file.layer(entity.layer())?;
|
||||
let context = |error: IoError| IoError::Invalid(format!("DXF TEXT entity {} on layer {:?}: {error}", index + 1, layer.name()));
|
||||
let DxfShape::Text { text, .. } = entity.geometry() else {
|
||||
return Err(context(IoError::Invalid("not supported by private TEXT-only bridge: non-TEXT geometry".into())));
|
||||
};
|
||||
// Explicit partial bridge domain, NOT a product policy for control characters.
|
||||
// Neither MTEXT nor any disputed control/tail policy is invoked by this bridge.
|
||||
if text.chars().any(char::is_control) || text.chars().count() > 256 {
|
||||
return Err(context(IoError::Invalid("not supported by private TEXT-only bridge: controls, multiline or more than 256 characters".into())));
|
||||
}
|
||||
// The real Out::code(1, value) writes three code bytes plus two newlines.
|
||||
// Encode before the framing-floor check so the codec still validates the whole
|
||||
// supported-domain source for non-BMP when the remaining budget is zero.
|
||||
let encoded = encode_text_value(text, remaining_record_bytes.saturating_sub(5)).map_err(context)?;
|
||||
if remaining_record_bytes < 5 {
|
||||
return Err(context(IoError::Invalid("TEXT group1 framing exceeds remaining record bytes".into())));
|
||||
}
|
||||
out.code(1, encoded);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{DxfFile, DxfShape, Out, write_owned_text_value};
|
||||
use crate::DxfLinetype;
|
||||
use solidcraft_geom::Vec2;
|
||||
|
||||
fn file_with_text(text: &str) -> DxfFile<DxfShape> {
|
||||
let mut file = DxfFile::new().unwrap();
|
||||
let layer = file.declare_layer("NOTES", 7, DxfLinetype::Continuous, None).unwrap();
|
||||
let shape = DxfShape::Text { at: Vec2::new(3.0, 4.0), height: 5.0, angle_deg: 0.0, text: text.into() };
|
||||
file.push(layer, shape, None).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
fn sentinel() -> Out {
|
||||
Out { s: "sentinel\n".into(), next: 0x20 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_text_uses_actual_out_group1_framing_only() {
|
||||
let file = file_with_text("plain");
|
||||
let mut out = sentinel();
|
||||
write_owned_text_value(&mut out, &file, 0, 10).unwrap();
|
||||
assert_eq!(out.s, "sentinel\n 1\nplain\n");
|
||||
assert_eq!(out.next, 0x20, "a text-value field does not allocate entity handles");
|
||||
assert_eq!(file.layer(file.entities()[0].layer()).unwrap().name(), "NOTES");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_percent_and_plain_degree_reach_real_out_without_preencoding() {
|
||||
let file = file_with_text("% %%d ° \\U+0041");
|
||||
let mut out = sentinel();
|
||||
write_owned_text_value(&mut out, &file, 0, 4096).unwrap();
|
||||
assert_eq!(out.s, "sentinel\n 1\n%%% %%%%%%d %%d \\U+005CU+0041\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_bmp_error_has_real_entity_layer_and_leaves_out_untouched() {
|
||||
let file = file_with_text("ab𠀋");
|
||||
let mut out = sentinel();
|
||||
let error = write_owned_text_value(&mut out, &file, 0, 0).unwrap_err().to_string();
|
||||
assert!(error.contains("entity 1 on layer \"NOTES\""), "{error}");
|
||||
assert!(error.contains("U+2000B") && error.contains("position 3"), "{error}");
|
||||
assert_eq!(out.s, "sentinel\n");
|
||||
assert_eq!(out.next, 0x20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_domain_refuses_before_writing_any_value() {
|
||||
for text in ["a\nb".into(), "a\rb".into(), "a\tb".into(), "x".repeat(257)] {
|
||||
let file = file_with_text(&text);
|
||||
let mut out = sentinel();
|
||||
let error = write_owned_text_value(&mut out, &file, 0, 4096).unwrap_err().to_string();
|
||||
assert!(error.contains("not supported by private TEXT-only bridge"), "{error}");
|
||||
assert_eq!(out.s, "sentinel\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inclusive_record_budget_counts_encoding_plus_five_framing_bytes() {
|
||||
let file = file_with_text("中");
|
||||
let mut out = sentinel();
|
||||
write_owned_text_value(&mut out, &file, 0, 12).unwrap();
|
||||
assert_eq!(out.s, "sentinel\n 1\n\\U+4E2D\n");
|
||||
let mut small = sentinel();
|
||||
assert!(write_owned_text_value(&mut small, &file, 0, 11).is_err());
|
||||
assert_eq!(small.s, "sentinel\n");
|
||||
let empty = file_with_text("");
|
||||
let mut out = sentinel();
|
||||
write_owned_text_value(&mut out, &empty, 0, 5).unwrap();
|
||||
assert_eq!(out.s, "sentinel\n 1\n\n");
|
||||
let mut small = sentinel();
|
||||
assert!(write_owned_text_value(&mut small, &empty, 0, 4).is_err());
|
||||
assert_eq!(small.s, "sentinel\n");
|
||||
let long = file_with_text(&"中".repeat(256));
|
||||
let mut out = sentinel();
|
||||
write_owned_text_value(&mut out, &long, 0, 1797).unwrap();
|
||||
assert_eq!(out.s, format!("sentinel\n 1\n{}\n", "\\U+4E2D".repeat(256)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_geometry_and_missing_entity_cannot_write_a_partial_record() {
|
||||
let mut file = DxfFile::new().unwrap();
|
||||
file.push(file.default_layer(), DxfShape::Line(Vec2::ZERO, Vec2::new(1.0, 2.0)), None).unwrap();
|
||||
let mut out = sentinel();
|
||||
assert!(write_owned_text_value(&mut out, &file, 0, 4096).is_err());
|
||||
assert!(write_owned_text_value(&mut out, &file, usize::MAX, 4096).is_err());
|
||||
assert_eq!(out.s, "sentinel\n");
|
||||
assert_eq!(out.next, 0x20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"path": "proposals/drawings/W10/DERIVATION.md",
|
||||
"sha256": "5467c74a8162642dce5198c94467c5f8e870c02e6504cabd852c3d7ed31c695a",
|
||||
"bytes": 8617
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/cubics.rs",
|
||||
"sha256": "22e634fd8380f80fcdec09cccba52d45d309c44ab2f614bceab79f557da4e0e7",
|
||||
"bytes": 10047
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/grid-acceptance-source.patch",
|
||||
"sha256": "98fadea32952067d8bf0d9a61555b5fd081e266f5878ad685a55ba2b4547e808",
|
||||
"bytes": 7874
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/grid_endpoint_acceptance.rs",
|
||||
"sha256": "fa53fc03327c97a3e57a8447f9a5baf5dd52e9950a291f9c8a039eaec29ad582",
|
||||
"bytes": 7479
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/helper-and-11-tests.patch",
|
||||
"sha256": "ad6912aa3f89ed778737828d9a60d2d1cdb0054d7a59c1af0400c4ba7699b100",
|
||||
"bytes": 21615
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/pending-grid-test-include.patch",
|
||||
"sha256": "17b590f66f37a3b0f0ae39845f53e7e27d242c9190d8ebd177bbb1d084f554e4",
|
||||
"bytes": 251
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/pending-module-declaration.patch",
|
||||
"sha256": "fd3224e86279c83de88a0dd86883c04e614c665ac0ea0469e8633e992f0b1465",
|
||||
"bytes": 248
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/pending-segments-parent-hook.patch",
|
||||
"sha256": "714ddcaca5cc1fe7e31df882973908c547317d9049fdce1141e093be6b3859e5",
|
||||
"bytes": 411
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/segments-source.patch",
|
||||
"sha256": "6eba4e41eab68be344cf3e19c0dd8ad49c7ab309ed1f886aa34cde905fb1ded6",
|
||||
"bytes": 12332
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/segments.rs",
|
||||
"sha256": "895bc5af8b8eb907e27516e9516d20b3f2477bfdf26b4e130238e8285277f66d",
|
||||
"bytes": 11885
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W21/picture-five-tests.patch",
|
||||
"sha256": "39b999a824703f9907286c0d4f8b2203432e4718e07b9e0b915a16facb44d0cc",
|
||||
"bytes": 14250
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W21/picture-three-tests-increment.patch",
|
||||
"sha256": "7f6905378ecbd9b0a5d2ac7a2d85dd3e50c5c46466f563863fe9447505c10059",
|
||||
"bytes": 9615
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W21/png_tests-with-five-proposals.rs",
|
||||
"sha256": "f08f8f299cae24646c6046ac12387c7a362026cfbf16d23ed26ca2eb4fac9490",
|
||||
"bytes": 35407
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W21/w21-parity-tests.patch",
|
||||
"sha256": "10edeaee0b1ab40c5ad2ff77d2ab6958971c556540b2aff9ec722007ce43abbf",
|
||||
"bytes": 4948
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/decoder-new-module.patch",
|
||||
"sha256": "45a8bb6e7d4b343f2f87d8b339952da53743a37784506b8b00c32a505f080ba3",
|
||||
"bytes": 10533
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/decoder_text.rs",
|
||||
"sha256": "14003e07e96e0c74a5c71b0907bdfcf7f9971dfbfa98e172f2a3196ed7b16476",
|
||||
"bytes": 10161
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/encoder-new-module.patch",
|
||||
"sha256": "9c01d4cc7828f18cc80e22f4d82e0393871000ee192f57e9a09e1657a9327641",
|
||||
"bytes": 9897
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/encoder_text.rs",
|
||||
"sha256": "f437cb7b1c11e463fbd62328267114d77a95117e88b71cb5ad823073a0e626bd",
|
||||
"bytes": 9511
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/length_decimal.rs",
|
||||
"sha256": "05671bbed70376f91e522db786bdb6a0ce449d779aeba978605ac374c4c13409",
|
||||
"bytes": 8599
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/test-only-bridge-registration.patch",
|
||||
"sha256": "a9a7e11b4a35e4b72c9b9bb45bc80841c28f19f7b29f97189f2cc70396219413",
|
||||
"bytes": 235
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/test-only-bridge-source.patch",
|
||||
"sha256": "d4504fa54ac8940aaad05e9053c2d18a5bdf8d402de1d2f67450a09c469938c9",
|
||||
"bytes": 6108
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/test_only_text_bridge.rs",
|
||||
"sha256": "55ed9e266c45fb496c23eb5910bf9b0f3346cae5a2413040d0ed144b1a2345fb",
|
||||
"bytes": 5801
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W38a/source.patch",
|
||||
"sha256": "cb1041d896e635d1df12adb87b656abea6b64004f39a0cb98e9dd3483545b1b8",
|
||||
"bytes": 34236
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W38d/whole-boundary-acceptance-proposal.md",
|
||||
"sha256": "514dc67633abaeb46a7f11d50a4757501f782d528377ebd871556561b7208750",
|
||||
"bytes": 10853
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W38d/paper-unit-fixture-proposal.json",
|
||||
"sha256": "b5b36e4621d4453ba0f7819f9098c13f373804edfc7145c7499717db2e91f78b",
|
||||
"bytes": 4130
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W10/README.md",
|
||||
"sha256": "3150256a1eb79195b985a7ced64b4ec38b0c331d6e68137a1cce3ddf3a0cd89c",
|
||||
"bytes": 869
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W21/README.md",
|
||||
"sha256": "be96ea9bd550eadc557e4efd1dbf43b76f5f100cb27c1c59b7b1e2d6d8bd0ed9",
|
||||
"bytes": 758
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/X4/README.md",
|
||||
"sha256": "3210205ad34ad97532ac92686a3d96ec64b08f0bd80f6001da410c5a5d0e581f",
|
||||
"bytes": 1164
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W38a/README.md",
|
||||
"sha256": "20b503c4bddcf1cc6837b251460f46735d9349b3f78c4bb97ab85e7ceef5ef60",
|
||||
"bytes": 1010
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/W38d/README.md",
|
||||
"sha256": "758a8fc27b418224b89f71dac3f49b9677d4be2e4e43e7e2b43e64bf189881e6",
|
||||
"bytes": 908
|
||||
},
|
||||
{
|
||||
"path": "proposals/drawings/README.md",
|
||||
"sha256": "7a196825a47a38a484c4be11dd2fb3f33c181aa1c5fd50105ee47395d0e9581d",
|
||||
"bytes": 529
|
||||
}
|
||||
],
|
||||
"qualification": "SOURCE_PRESERVATION_ONLY_NO_RUNTIME"
|
||||
}
|
||||
Reference in new issue
Block a user