fix(anatomy): V1-2.2 refuse zones without a usable interior

A polygon or path zone or trigger must fill a disc of 4 CSS px on the
320 x 568 preview under the layer's nonzero rule, stroke left out:
conservative widest-disc search on the flattened outline, caps and a
per-sheet budget, closed codes interior_too_small and
marker_interior_too_small. Browser probe on six projects.
This commit is contained in:
bchanot committed 2026-11-01 12:19:08 +01:00
1 parent de2dfb392e
commit 8dd2d78d38
18 files changed
+1852 -38

No files matched your search

+51 -10
View File
@@ -16,7 +16,11 @@
//! about `|v| × 2⁻²⁴` and, measured against the frame, grows with the ratio of the frame's
//! farthest edge to its span. And each annotation must show at least `MIN_VISIBLE_PX` on the
//! smallest preview the product supports, measured on the shape the layer paints.
//!
//! Owner brief 2026-11-01 (the last MEDIUM, zone without interior): a polygon or a path must
//! also fill a disc of `MIN_VISIBLE_PX` on that preview (`interior`), its stroke left out.
use super::interior::{Budget, LAYER_FILL_RULE, Search, geometry_outline, widest_disc};
use super::layer::{find_view, twin_radius};
use super::path::{Bounds, number_list, path_bounds};
use super::svg::Element;
@@ -61,6 +65,9 @@ pub const DETAIL_PREVIEW_PX: (f64, f64) = (254.0, 191.0);
/// The smallest visible size of an annotation on that preview (owner decision 2026-11-01): a
/// point's visible disc, a filled shape's smaller side. The equine junctions show 4.97 px.
pub const MIN_VISIBLE_PX: f64 = 4.0;
/// How far a chord may depart from its curve, and the step below which the interior search
/// cuts no cell, on that preview: far below a device pixel, taken off the measure.
pub const INTERIOR_TOLERANCE_PX: f64 = 0.05;
impl Frame {
fn from_numbers(min_x: f64, min_y: f64, width: f64, height: f64) -> Option<Self> {
@@ -138,6 +145,12 @@ pub enum Placement {
Unreadable,
/// In frame, but smaller than `MIN_VISIBLE_PX` on the smallest preview.
TooSmall,
/// A polygon or a path in frame whose fill holds no disc of `MIN_VISIBLE_PX` on the smallest
/// preview.
InteriorTooSmall,
/// A polygon or a path the interior measure cannot afford: past
/// `interior::MAX_OUTLINE_VERTICES`, or the sheet's `interior::MAX_INTERIOR_WORK` spent.
InteriorUnmeasured,
}
/// The size an annotation shows, in frame units: what the layer paints. A point's (or a circle
@@ -190,26 +203,52 @@ fn placement_with_bounds(geometry: &Geometry, frame: &Frame) -> (Placement, Opti
}
}
/// The placement of `annotation` on its view's frame, its visible size on the smallest preview
/// included.
pub fn annotation_placement(annotation: &Annotation, frame: &Frame, main_view: bool) -> Placement {
/// The placement of `annotation` on its view's frame, its visible size and its interior on the
/// smallest preview included, the interior measured within the sheet's `budget`.
pub fn annotation_placement(
annotation: &Annotation,
frame: &Frame,
main_view: bool,
budget: &mut Budget,
) -> Placement {
let Some(geometry) = geometry_of(annotation) else {
return Placement::InFrame;
};
match placement_with_bounds(geometry, frame) {
(Placement::InFrame, Some(bounds)) => {
let shown =
visible_size(annotation, geometry, &bounds) * frame.preview_scale(main_view);
if shown >= MIN_VISIBLE_PX {
Placement::InFrame
} else {
let scale = frame.preview_scale(main_view);
if visible_size(annotation, geometry, &bounds) * scale < MIN_VISIBLE_PX {
Placement::TooSmall
} else {
interior_placement(geometry, scale, budget)
}
}
(placement, _) => placement,
}
}
/// Whether the fill of a polygon or a path holds a disc of `MIN_VISIBLE_PX` at `scale` CSS px
/// per unit; a circle's disc is its own (path data the bounds read whole always has an outline).
fn interior_placement(geometry: &Geometry, scale: f64, budget: &mut Budget) -> Placement {
let tolerance = INTERIOR_TOLERANCE_PX / scale;
let Some(outline) = geometry_outline(geometry, tolerance) else {
return Placement::InFrame;
};
if !budget.affords(&outline) {
return Placement::InteriorUnmeasured;
}
let radius = MIN_VISIBLE_PX / 2.0 / scale;
let search = Search {
floor: radius,
enough: radius,
precision: tolerance,
};
match widest_disc(&outline, LAYER_FILL_RULE, &search, budget) {
Some(disc) if disc.radius >= radius => Placement::InFrame,
_ => Placement::InteriorTooSmall,
}
}
/// What the frame check found on one view.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameFault {
@@ -229,6 +268,7 @@ pub fn frame_faults<'a>(
drawing_of: impl Fn(&str) -> Option<&'a Element>,
) -> Vec<FrameFault> {
let mut faults = Vec::new();
let mut budget = Budget::default();
for (view_index, view) in document.views.iter().enumerate() {
// A repeated view id draws the first view of that id, as the composers find it.
if !find_view(document, view.id()).is_some_and(|first| std::ptr::eq(first, view)) {
@@ -242,7 +282,7 @@ pub fn frame_faults<'a>(
faults.push(FrameFault::NoFrame { view_index });
continue;
};
faults.extend(annotation_faults(document, view, &frame));
faults.extend(annotation_faults(document, view, &frame, &mut budget));
}
faults
}
@@ -251,6 +291,7 @@ fn annotation_faults(
document: &AnatomicalSheetDocument,
view: &SheetView,
frame: &Frame,
budget: &mut Budget,
) -> Vec<FrameFault> {
document
.annotations
@@ -258,7 +299,7 @@ fn annotation_faults(
.enumerate()
.filter(|(_, a)| a.view_id() == view.id())
.filter_map(|(annotation_index, annotation)| {
let placement = annotation_placement(annotation, frame, view.is_main());
let placement = annotation_placement(annotation, frame, view.is_main(), budget);
(placement != Placement::InFrame).then_some(FrameFault::Annotation {
annotation_index,
placement,
+450
View File
@@ -0,0 +1,450 @@
//! The interior a tap can reach in a filled shape (owner brief « V1-2.2 : fermeture du dernier
//! MEDIUM », 2026-11-01). A zone or a trigger drawn as a polygon or a path passes the bounds rule
//! of `frame` with a large box and still selects nothing: a path drawn forth and back fills no
//! point (winding 0), a near-flat polygon fills a sliver. The layer's shapes take taps on their
//! fill and their 2-unit stroke; the stroke never counts here.
//!
//! The measure is the widest disc the fill holds, under the fill rule the layer paints with
//! (`LAYER_FILL_RULE`: the layer writes none, the composition root carries none, so `nonzero`).
//! It is conservative. A centre counts only when the fill rule puts it inside and every edge of
//! the outline, the closing edges included, is at least the radius away: the disc then crosses
//! no edge, so every point of it has the centre's winding number. Curves and arcs are cut into
//! chords (`path::path_outline`) and the chord deviation is taken off the radius. The search is
//! the polylabel subdivision (square cells, a cell's best possible centre is its centre's
//! distance plus its half diagonal, the most promising cell cut first), at most
//! `MAX_INTERIOR_CELLS` cells: deterministic, and what it has not shown counts as absent. One
//! budget (`Budget`, edge distances) bounds the work on a whole sheet: a shape it can no longer
//! afford is refused, never accepted.
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::f64::consts::SQRT_2;
use super::path::{Outline, path_outline};
use crate::domain::sheet::Geometry;
/// How a point is inside a fill (SVG `fill-rule`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FillRule {
NonZero,
EvenOdd,
}
/// The fill rule of the layer's shapes: the SVG initial value, as no `fill-rule` reaches them.
pub const LAYER_FILL_RULE: FillRule = FillRule::NonZero;
/// The largest number of outline vertices measured: past it the shape is refused (a hand-drawn
/// zone holds tens; the equine at most 17).
pub const MAX_OUTLINE_VERTICES: usize = 4096;
/// The largest number of cells the search evaluates.
pub const MAX_INTERIOR_CELLS: usize = 4096;
/// The edge distances the measure may compute on one sheet: `2²⁵`, about 0.35 s natively
/// (measured 2026-11-01: 8 192 edges × 4 096 cells), where the equine draft takes about 10⁵.
pub const MAX_INTERIOR_WORK: usize = 1 << 25;
/// The work left to the measure on one sheet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Budget {
pub work: usize,
}
impl Default for Budget {
fn default() -> Self {
Self {
work: MAX_INTERIOR_WORK,
}
}
}
impl Budget {
/// The cells left for an outline of `edges` edges.
fn cells(&self, edges: usize) -> usize {
MAX_INTERIOR_CELLS.min(self.work / edges.max(1))
}
/// Whether the outline can still be measured: within the vertex cap, one cell affordable.
pub fn affords(&self, outline: &Outline) -> bool {
!outline.overflow && self.cells(edge_count(outline)) > 0
}
}
fn edge_count(outline: &Outline) -> usize {
outline.subpaths.iter().map(Vec::len).sum()
}
/// A disc inside the fill.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Disc {
pub centre: (f64, f64),
pub radius: f64,
}
/// What the search looks for, in user units: cells that cannot reach `floor` are dropped, the
/// search stops at a disc of `enough`, and no cell is cut below `precision`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Search {
pub floor: f64,
pub enough: f64,
pub precision: f64,
}
/// The fill outline of a polygon or a path, chords at most `tolerance` from the curves; `None`
/// for a circle (its disc is exact) and for path data a browser would not read whole.
pub fn geometry_outline(geometry: &Geometry, tolerance: f64) -> Option<Outline> {
match geometry {
Geometry::Circle(_) => None,
Geometry::Polygon(p) => Some(Outline {
subpaths: vec![p.points.iter().map(|p| (p.0, p.1)).collect()],
deviation: 0.0,
overflow: p.points.len() > MAX_OUTLINE_VERTICES,
}),
Geometry::Path(path) => path_outline(&path.d, tolerance, MAX_OUTLINE_VERTICES),
}
}
/// The widest disc found inside the outline's fill under `rule`, its radius net of the chord
/// deviation, the work taken from `budget`; `None` when the search shows none.
pub fn widest_disc(
outline: &Outline,
rule: FillRule,
search: &Search,
budget: &mut Budget,
) -> Option<Disc> {
let edges = edge_count(outline);
let affordable = budget.cells(edges);
if affordable == 0 {
return None;
}
let mut points = outline.subpaths.iter().flatten();
let first = *points.next()?;
let (min, max) = points.fold((first, first), |(min, max), &(x, y)| {
((min.0.min(x), min.1.min(y)), (max.0.max(x), max.1.max(y)))
});
let half = (max.0 - min.0).max(max.1 - min.1) / 2.0;
let root = Cell::new(outline, rule, (min.0 + half, min.1 + half), half);
let mut best = root.disc();
let mut cells = BinaryHeap::from([root]);
let mut evaluated = 1;
while let Some(cell) = cells.pop() {
let widest = best.map_or(0.0, |disc| disc.radius);
// The heap gives the cell of greatest reach: when it cannot do better, none can.
if widest >= search.enough
|| cell.reach() < search.floor
|| cell.reach() <= widest + search.precision
|| evaluated + 4 > affordable
{
break;
}
if cell.half * SQRT_2 <= search.precision {
continue;
}
let quarter = cell.half / 2.0;
for (dx, dy) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] {
let centre = (cell.centre.0 + dx * quarter, cell.centre.1 + dy * quarter);
let child = Cell::new(outline, rule, centre, quarter);
if child.radius > best.map_or(0.0, |disc| disc.radius) {
best = child.disc();
}
cells.push(child);
}
evaluated += 4;
}
budget.work -= evaluated * edges;
best
}
/// A square cell of the search: its centre's radius and its half side.
struct Cell {
centre: (f64, f64),
half: f64,
radius: f64,
}
impl Cell {
fn new(outline: &Outline, rule: FillRule, centre: (f64, f64), half: f64) -> Self {
let radius = clearance(outline, rule, centre) - outline.deviation;
Self {
centre,
half,
radius,
}
}
/// The widest radius a centre inside the cell could have.
fn reach(&self) -> f64 {
self.radius + self.half * SQRT_2
}
fn disc(&self) -> Option<Disc> {
(self.radius > 0.0).then_some(Disc {
centre: self.centre,
radius: self.radius,
})
}
}
impl Ord for Cell {
fn cmp(&self, other: &Self) -> Ordering {
self.reach().total_cmp(&other.reach())
}
}
impl PartialOrd for Cell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Cell {}
/// The distance from `point` to the nearest edge, negative when the fill leaves it out.
fn clearance(outline: &Outline, rule: FillRule, point: (f64, f64)) -> f64 {
let mut nearest = f64::INFINITY;
let mut winding = 0_i64;
for subpath in &outline.subpaths {
let closing = subpath.last().into_iter().chain(subpath.iter());
for (&a, &b) in closing.zip(subpath.iter()) {
nearest = nearest.min(segment_distance(point, a, b));
winding += crossing(point, a, b);
}
}
let inside = match rule {
FillRule::NonZero => winding != 0,
FillRule::EvenOdd => winding % 2 != 0,
};
if inside { nearest } else { -nearest }
}
/// +1 or −1 when the edge crosses the horizontal ray to the right of `point` upwards or
/// downwards, else 0.
fn crossing(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> i64 {
let side = (b.0 - a.0) * (point.1 - a.1) - (point.0 - a.0) * (b.1 - a.1);
if a.1 <= point.1 && point.1 < b.1 && side > 0.0 {
1
} else if b.1 <= point.1 && point.1 < a.1 && side < 0.0 {
-1
} else {
0
}
}
fn segment_distance(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let length = dx * dx + dy * dy;
let t = if length > 0.0 {
(((p.0 - a.0) * dx + (p.1 - a.1) * dy) / length).clamp(0.0, 1.0)
} else {
0.0
};
(p.0 - a.0 - t * dx).hypot(p.1 - a.1 - t * dy)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
const MEASURE: Search = Search {
floor: 0.0,
enough: f64::INFINITY,
precision: 1e-3,
};
fn polygon(points: &[(f64, f64)]) -> Outline {
Outline {
subpaths: vec![points.to_vec()],
..Outline::default()
}
}
fn widest(outline: &Outline, rule: FillRule) -> f64 {
measure(outline, rule).map_or(0.0, |d| d.radius)
}
fn measure(outline: &Outline, rule: FillRule) -> Option<Disc> {
widest_disc(outline, rule, &MEASURE, &mut Budget::default())
}
#[test]
fn a_square_holds_its_inscribed_disc() {
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let r = widest(&square, FillRule::NonZero);
assert!((r - 5.0).abs() < 2e-3, "{r}");
}
/// A pentagram: its centre has winding 2, filled under nonzero, a hole under evenodd.
#[test]
fn the_fill_rule_decides_a_self_intersection() {
let star: Vec<(f64, f64)> = (0..5)
.map(|i| {
let angle =
std::f64::consts::FRAC_PI_2 + f64::from(i * 2) * std::f64::consts::TAU / 5.0;
(100.0 * angle.cos(), 100.0 * angle.sin())
})
.collect();
let star = polygon(&star);
let nonzero = widest(&star, FillRule::NonZero);
let evenodd = widest(&star, FillRule::EvenOdd);
// Conservative: the disc crosses no edge, so it stops at the inner pentagon's inscribed
// radius, 100 × cos 72° ≈ 30.9, where the fill itself reaches the concave corners at
// 38.2; under evenodd the centre is a hole and only a tip's disc remains.
assert!(
(nonzero - 100.0 * 72_f64.to_radians().cos()).abs() < 0.01,
"{nonzero}"
);
// A tip, an isosceles triangle of apex 36°: inscribed radius 16.31.
assert!((evenodd - 16.31).abs() < 0.01, "{evenodd}");
let centre = clearance(&star, FillRule::EvenOdd, (0.0, 0.0));
assert!(centre < 0.0, "the centre is a hole under evenodd");
}
#[test]
fn an_outline_drawn_forth_and_back_fills_nothing() {
let there_and_back = polygon(&[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0), (50.0, 0.0)]);
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
assert!(measure(&there_and_back, rule).is_none());
}
// Two opposite loops over the same square: winding 0 under nonzero, 2 even.
let square = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
let mut reversed = square;
reversed.reverse();
let both = Outline {
subpaths: vec![square.to_vec(), reversed.to_vec()],
..Outline::default()
};
assert!(measure(&both, FillRule::NonZero).is_none());
assert!(measure(&both, FillRule::EvenOdd).is_none());
}
#[test]
fn the_deviation_is_taken_off() {
let mut square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
square.deviation = 1.0;
let r = widest(&square, FillRule::NonZero);
assert!((r - 4.0).abs() < 2e-3, "{r}");
}
#[test]
fn the_search_stops_at_enough_and_drops_cells_below_the_floor() {
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let enough = Search {
floor: 2.0,
enough: 2.0,
precision: 1e-3,
};
let disc =
widest_disc(&square, FillRule::NonZero, &enough, &mut Budget::default()).unwrap();
assert!(disc.radius >= 2.0);
let out_of_reach = Search {
floor: 5.1,
enough: 5.1,
precision: 1e-3,
};
let disc = widest_disc(
&square,
FillRule::NonZero,
&out_of_reach,
&mut Budget::default(),
);
assert!(disc.is_none_or(|d| d.radius < 5.1));
}
/// The budget counts edge distances across shapes; a shape it cannot afford is not measured.
#[test]
fn the_budget_is_shared_and_spent() {
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let mut budget = Budget { work: 4 * 9 };
assert!(budget.affords(&square));
let small = widest_disc(&square, FillRule::NonZero, &MEASURE, &mut budget);
assert!(small.is_some(), "the root cell finds the centre");
assert_eq!(budget.work, 0, "nine cells: the root and two cuts of four");
let mut spent = Budget { work: 3 };
assert!(!spent.affords(&square));
assert!(widest_disc(&square, FillRule::NonZero, &MEASURE, &mut spent).is_none());
let mut too_many = square.clone();
too_many.overflow = true;
assert!(!Budget::default().affords(&too_many));
}
#[test]
fn every_centre_found_holds_its_disc() {
let comb = polygon(&[
(0.0, 0.0),
(30.0, 0.0),
(30.0, 10.0),
(20.0, 10.0),
(20.0, 2.0),
(10.0, 2.0),
(10.0, 10.0),
(0.0, 10.0),
]);
let disc = measure(&comb, FillRule::NonZero).unwrap();
for i in 0..64 {
let angle = f64::from(i) * std::f64::consts::TAU / 64.0;
let at = (
disc.centre.0 + 0.999 * disc.radius * angle.cos(),
disc.centre.1 + 0.999 * disc.radius * angle.sin(),
);
assert!(clearance(&comb, FillRule::NonZero, at) > 0.0, "{at:?}");
}
assert!((disc.radius - 5.0).abs() < 2e-3, "{disc:?}");
}
/// A deterministic generator for the sampled comparisons.
struct Lcg(u64);
impl Lcg {
fn next(&mut self, low: f64, high: f64) -> f64 {
self.0 = self
.0
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
low + (high - low) * ((self.0 >> 11) as f64 / (1_u64 << 53) as f64)
}
}
/// Random polygons, self-intersecting ones included, under both rules: the disc found never
/// beats a dense grid of centres by more than the grid's half diagonal, and every point of
/// its rim is filled.
#[test]
fn the_disc_found_is_never_wider_than_the_fill() {
let mut rng = Lcg(5);
for case in 0..60 {
let count = 3 + (case % 7);
let points: Vec<(f64, f64)> = (0..count)
.map(|_| (rng.next(0.0, 40.0), rng.next(0.0, 40.0)))
.collect();
let shape = polygon(&points);
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let Some(disc) = measure(&shape, rule) else {
continue;
};
let mut grid = 0.0_f64;
for i in 0..=200 {
for j in 0..=200 {
let at = (0.2 * f64::from(i), 0.2 * f64::from(j));
grid = grid.max(clearance(&shape, rule, at));
}
}
assert!(
disc.radius <= grid + 0.15,
"case {case}: {disc:?} vs {grid}"
);
for k in 0..90 {
let angle = f64::from(k) * std::f64::consts::TAU / 90.0;
let rim = (
disc.centre.0 + 0.999 * disc.radius * angle.cos(),
disc.centre.1 + 0.999 * disc.radius * angle.sin(),
);
assert!(clearance(&shape, rule, rim) > 0.0, "case {case}: {rim:?}");
}
}
}
}
}
+1
View File
@@ -5,6 +5,7 @@
pub mod compose;
pub mod frame;
pub mod interior;
pub mod layer;
pub mod path;
pub mod svg;
+257 -7
View File
@@ -10,6 +10,10 @@
//! `f32::MAX` (Chromium, WebKit; WebKit already for an arc radius of `1e30`), while a radius or a
//! rotation that big leaves the bounds unchanged. A coordinate past the bound is outside every
//! usable frame, a radius past it draws a straight segment on one.
//!
//! The same reading gives a path's fill outline (`path_outline`, owner brief 2026-11-01, zone
//! without interior): each subpath as a polyline, curves and arcs cut into chords, with the
//! largest distance between a chord and its curve (`Outline::deviation`).
/// The smallest box holding a set of points.
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -55,8 +59,45 @@ pub fn number_list(value: &str) -> Option<Vec<f64>> {
/// The bounds of every point `d` draws; `None` when a browser would not read all of it.
pub fn path_bounds(d: &str) -> Option<Bounds> {
let mut cursor = Cursor::new(d);
let mut pen = Pen::default();
read_path(d, &mut pen)?;
pen.bounds
}
/// The largest number of chords a curve or an arc is cut into: past it the deviation grows
/// instead (the measure stays conservative).
pub const MAX_CURVE_CHORDS: usize = 64;
/// A fill outline: its subpaths as polylines (each closed by the fill), the largest distance
/// between a chord and the curve it stands for, and whether more than the asked number of
/// vertices was needed (the outline is then incomplete).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Outline {
pub subpaths: Vec<Vec<(f64, f64)>>,
pub deviation: f64,
pub overflow: bool,
}
/// The outline `d` fills, curves and arcs cut into chords at most `tolerance` away from them
/// (`MAX_CURVE_CHORDS` aside), at most `max_vertices` vertices; `None` when a browser would not
/// read all of it.
pub fn path_outline(d: &str, tolerance: f64, max_vertices: usize) -> Option<Outline> {
let mut pen = Pen {
flat: Some(Flattening {
tolerance,
max_vertices,
vertices: 0,
start: None,
outline: Outline::default(),
}),
..Pen::default()
};
read_path(d, &mut pen)?;
Some(pen.flat?.outline)
}
fn read_path(d: &str, pen: &mut Pen) -> Option<()> {
let mut cursor = Cursor::new(d);
cursor.skip_space();
if !matches!(cursor.peek(), Some(b'M' | b'm')) {
return None;
@@ -74,10 +115,7 @@ pub fn path_bounds(d: &str) -> Option<Bounds> {
}
}
}
if !cursor.done() {
return None;
}
pen.bounds
cursor.done().then_some(())
}
/// A position in the text being read.
@@ -245,8 +283,8 @@ struct Arc {
to: (f64, f64),
}
/// The current point, the subpath start, the previous control point (for `S` and `T`), and
/// the bounds so far.
/// The current point, the subpath start, the previous control point (for `S` and `T`), the
/// bounds so far, and the outline when one is asked.
#[derive(Default)]
struct Pen {
at: (f64, f64),
@@ -254,6 +292,44 @@ struct Pen {
cubic_control: Option<(f64, f64)>,
quadratic_control: Option<(f64, f64)>,
bounds: Option<Bounds>,
flat: Option<Flattening>,
}
/// The outline being drawn: a subpath starts with the first point drawn after its moveto or
/// closepath, so a lone moveto adds nothing.
struct Flattening {
tolerance: f64,
max_vertices: usize,
vertices: usize,
start: Option<(f64, f64)>,
outline: Outline,
}
impl Flattening {
fn push(&mut self, point: (f64, f64)) {
if let Some(start) = self.start.take() {
self.outline.subpaths.push(Vec::new());
self.push(start);
}
if self.vertices == self.max_vertices {
self.outline.overflow = true;
return;
}
self.vertices += 1;
if let Some(subpath) = self.outline.subpaths.last_mut() {
subpath.push(point);
}
}
/// The chords for a curve whose second derivative stays within `bend`: a chord over a
/// parameter step `h` departs from the curve by at most `bend × h² / 8`.
fn chords(&mut self, bend: f64) -> usize {
let wanted = (bend / (8.0 * self.tolerance)).sqrt().ceil();
let count = wanted.clamp(1.0, MAX_CURVE_CHORDS as f64) as usize;
let step = 1.0 / count as f64;
self.outline.deviation = self.outline.deviation.max(bend * step * step / 8.0);
count
}
}
impl Pen {
@@ -264,10 +340,32 @@ impl Pen {
}
}
/// Starts a subpath of the outline at the current point, once something is drawn from it.
fn open_subpath(&mut self) {
if let Some(flat) = &mut self.flat {
flat.start = Some(self.at);
}
}
/// The points of a curve between its ends, `count` chords over `t` in (0, 1).
fn trace(&mut self, count: usize, at: impl Fn(f64) -> (f64, f64)) {
if let Some(flat) = &mut self.flat {
for i in 1..count {
flat.push(at(i as f64 / count as f64));
}
}
}
fn chords(&mut self, bend: f64) -> usize {
self.flat.as_mut().map_or(1, |flat| flat.chords(bend))
}
/// A drawing command after a closepath starts a new subpath at the closed one's start.
fn close(&mut self) {
self.at = self.start;
self.cubic_control = None;
self.quadratic_control = None;
self.open_subpath();
}
/// One parameter group of `command`; a moveto's later pairs are linetos.
@@ -282,6 +380,7 @@ impl Pen {
self.at = point(x, y);
self.start = self.at;
self.add(self.at);
self.open_subpath();
self.cubic_control = None;
self.quadratic_control = None;
return self.linetos(relative, cursor);
@@ -343,6 +442,9 @@ impl Pen {
fn line(&mut self, to: (f64, f64)) {
self.add(to);
if let Some(flat) = &mut self.flat {
flat.push(to);
}
self.at = to;
}
@@ -359,6 +461,16 @@ impl Pen {
cubic_at(from.1, c1.1, c2.1, to.1, t),
));
}
let bend = 6.0
* distance(second_difference(from, c1, c2))
.max(distance(second_difference(c1, c2, to)));
let count = self.chords(bend);
self.trace(count, |t| {
(
cubic_at(from.0, c1.0, c2.0, to.0, t),
cubic_at(from.1, c1.1, c2.1, to.1, t),
)
});
self.line(to);
c2
}
@@ -378,6 +490,13 @@ impl Pen {
quadratic_at(from.1, control.1, to.1, t),
));
}
let count = self.chords(2.0 * distance(second_difference(from, control, to)));
self.trace(count, |t| {
(
quadratic_at(from.0, control.0, to.0, t),
quadratic_at(from.1, control.1, to.1, t),
)
});
self.line(to);
control
}
@@ -398,10 +517,23 @@ impl Pen {
self.add(ellipse.at(angle));
}
}
// Over the sweep as `t` goes from 0 to 1 the second derivative stays within the larger
// radius times the sweep squared.
let count = self.chords(ellipse.rx.max(ellipse.ry) * ellipse.sweep * ellipse.sweep);
self.trace(count, |t| ellipse.at(ellipse.start + ellipse.sweep * t));
self.line(arc.to);
}
}
/// `a − 2b + c`, the curve's second difference over three control points.
fn second_difference(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> (f64, f64) {
(a.0 - 2.0 * b.0 + c.0, a.1 - 2.0 * b.1 + c.1)
}
fn distance((x, y): (f64, f64)) -> f64 {
x.hypot(y)
}
/// The reflection of the previous control point about the current point, or the current point.
fn reflect(control: Option<(f64, f64)>, at: (f64, f64)) -> (f64, f64) {
control.map_or(at, |(x, y)| (2.0 * at.0 - x, 2.0 * at.1 - y))
@@ -637,6 +769,124 @@ mod tests {
}
}
/// A curve by its parameter in [0, 1].
type Curve<'a> = Box<dyn Fn(f64) -> (f64, f64) + 'a>;
fn polyline_distance(point: (f64, f64), line: &[(f64, f64)]) -> f64 {
line.windows(2)
.map(|pair| {
let (a, b) = (pair[0], pair[1]);
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let length = dx * dx + dy * dy;
let t = if length > 0.0 {
(((point.0 - a.0) * dx + (point.1 - a.1) * dy) / length).clamp(0.0, 1.0)
} else {
0.0
};
(point.0 - a.0 - t * dx).hypot(point.1 - a.1 - t * dy)
})
.fold(f64::INFINITY, f64::min)
}
/// Every point of the curve lies within the declared deviation of its chords, and the
/// deviation within the tolerance asked unless the curve took `MAX_CURVE_CHORDS` (an arc
/// whose radii the endpoints scale up).
#[test]
fn outline_chords_stay_within_the_deviation() {
let mut rng = Lcg(13);
let tolerance = 0.05;
for case in 0..300 {
let p: Vec<f64> = (0..8).map(|_| rng.next(-50.0, 50.0)).collect();
let arc = Arc {
rx: rng.next(0.5, 30.0),
ry: rng.next(0.5, 30.0),
rotation: rng.next(-360.0, 360.0),
large: rng.next(0.0, 1.0) < 0.5,
sweep: rng.next(0.0, 1.0) < 0.5,
to: (p[6], p[7]),
};
let curves: [(String, Curve<'_>); 3] = [
(
format!(
"M{} {}C{} {} {} {} {} {}",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]
),
Box::new(|t| {
(
cubic_at(p[0], p[2], p[4], p[6], t),
cubic_at(p[1], p[3], p[5], p[7], t),
)
}),
),
(
format!("M{} {}Q{} {} {} {}", p[0], p[1], p[2], p[3], p[6], p[7]),
Box::new(|t| {
(
quadratic_at(p[0], p[2], p[6], t),
quadratic_at(p[1], p[3], p[7], t),
)
}),
),
(
format!(
"M{} {}A{} {} {} {} {} {} {}",
p[0],
p[1],
arc.rx,
arc.ry,
arc.rotation,
u8::from(arc.large),
u8::from(arc.sweep),
p[6],
p[7]
),
{
let ellipse = Ellipse::through((p[0], p[1]), &arc);
Box::new(move |t| ellipse.at(ellipse.start + ellipse.sweep * t))
},
),
];
for (d, at) in &curves {
let outline = path_outline(d, tolerance, 4096).unwrap();
assert_eq!(outline.subpaths.len(), 1, "{d}");
let line = &outline.subpaths[0];
let capped = line.len() == MAX_CURVE_CHORDS + 1;
assert!(
outline.deviation <= tolerance || capped,
"case {case} {d}: {}",
outline.deviation
);
for i in 0..=2000 {
let point = at(f64::from(i) / 2000.0);
let gap = polyline_distance(point, line);
assert!(gap <= outline.deviation + 1e-9, "case {case} {d}: {gap}");
}
}
}
}
#[test]
fn a_closepath_starts_the_next_subpath_at_its_start() {
let outline = path_outline("M0 0h10v10h-10zh-10v10h10z", 0.05, 4096).unwrap();
assert_eq!(
outline.subpaths,
[
vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)],
vec![(0.0, 0.0), (-10.0, 0.0), (-10.0, 10.0), (0.0, 10.0)],
]
);
assert_eq!(outline.deviation, 0.0);
let lone = path_outline("M5 5M0 0h1v1z", 0.05, 4096).unwrap();
assert_eq!(lone.subpaths.len(), 1, "a lone moveto fills nothing");
}
#[test]
fn the_outline_stops_at_its_vertex_cap() {
let d = format!("M0 0{}", "l1 1".repeat(9));
assert!(!path_outline(&d, 0.05, 10).unwrap().overflow);
assert!(path_outline(&d, 0.05, 9).unwrap().overflow);
}
#[test]
fn the_grammar_is_read_as_a_browser_reads_it() {
let read = |d: &str| path_bounds(d).map(|b| (b.min_x, b.min_y, b.max_x, b.max_y));
+11
View File
@@ -28,6 +28,9 @@ pub const NO_FRAME: &str = "view.frame.unknown";
/// An annotation in frame that shows below `anatomy::frame::MIN_VISIBLE_PX` on the smallest
/// preview (owner brief 2026-11-01, the scale bypass).
pub const TOO_SMALL: &str = "annotation.geometry.too_small";
/// A polygon or a path in frame whose fill holds no disc of `anatomy::frame::MIN_VISIBLE_PX` on
/// the smallest preview (owner brief 2026-11-01, zone without interior; `anatomy::interior`).
pub const INTERIOR_TOO_SMALL: &str = "annotation.geometry.interior_too_small";
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
@@ -123,6 +126,14 @@ fn frame_issue(document: &AnatomicalSheetDocument, fault: &FrameFault) -> SheetI
let (code, what) = match placement {
Placement::Unreadable => (OUT_OF_FRAME, "has path data that cannot be read whole"),
Placement::TooSmall => (TOO_SMALL, "shows too small on the phone preview"),
Placement::InteriorTooSmall => (
INTERIOR_TOO_SMALL,
"fills no interior wide enough to tap on the phone preview",
),
Placement::InteriorUnmeasured => (
INTERIOR_TOO_SMALL,
"is too complex for the interior measure on the phone preview",
),
Placement::InFrame | Placement::OutOfFrame => {
(OUT_OF_FRAME, "is not entirely inside the frame")
}
+9 -2
View File
@@ -21,8 +21,8 @@ use ts_rs::TS;
use super::caps::CapsReport;
use super::fingerprint::{FingerprintError, document_fingerprint};
use super::report::{
NO_FRAME, OUT_OF_FRAME, SheetReport, TOO_SMALL, frame_issues, referenced_asset_ids,
sheet_report,
INTERIOR_TOO_SMALL, NO_FRAME, OUT_OF_FRAME, SheetReport, TOO_SMALL, frame_issues,
referenced_asset_ids, sheet_report,
};
use super::review::{Completeness, ElementChange, ReviewGroup, change_list};
use super::schema::AnatomicalSheetDocument;
@@ -58,6 +58,9 @@ pub mod codes {
/// An annotation in frame that shows below 4 CSS px on the smallest preview (owner brief
/// 2026-11-01): measured on the same views.
pub const MARKER_TOO_SMALL: &str = "verification.validation.marker_too_small";
/// A polygon or a path in frame whose fill holds no disc of 4 CSS px on that preview, its
/// stroke left out (owner brief 2026-11-01, zone without interior).
pub const MARKER_INTERIOR_TOO_SMALL: &str = "verification.validation.marker_interior_too_small";
pub const FINGERPRINT: &str = "verification.integrity.fingerprint";
}
@@ -285,6 +288,7 @@ fn rule_failures(report: &SheetReport) -> Vec<&'static str> {
OUT_OF_FRAME,
NO_FRAME,
TOO_SMALL,
INTERIOR_TOO_SMALL,
]
.contains(&code)
};
@@ -316,6 +320,9 @@ fn frame_failures(report: &SheetReport) -> Vec<&'static str> {
if found(&[TOO_SMALL]) {
out.push(codes::MARKER_TOO_SMALL);
}
if found(&[INTERIOR_TOO_SMALL]) {
out.push(codes::MARKER_INTERIOR_TOO_SMALL);
}
out
}