diff --git a/.prettierignore b/.prettierignore index aaeef54a..53340eff 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,6 +3,7 @@ crates/core/tests/oracles/ crates/core/tests/conformance/ crates/core/tests/fixtures/ apps/app/tests/fixtures/goldens/ +apps/app/e2e/fixtures/interior-probe.json packages/core-wasm/types/ packages/core-wasm/pkg/ packages/core-wasm/pkg-proofs/ diff --git a/apps/app/e2e/fixtures/interior-probe.json b/apps/app/e2e/fixtures/interior-probe.json new file mode 100644 index 00000000..dbf0c42e --- /dev/null +++ b/apps/app/e2e/fixtures/interior-probe.json @@ -0,0 +1,219 @@ +{ + "generatedBy": "crates/core/tests/interior_probe.rs", + "frame": { + "width": 286, + "height": 310 + }, + "cases": [ + { + "name": "square-6", + "accepted": true, + "codes": [], + "widest": { + "x": 43.0, + "y": 43.0, + "r": 3.0 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "flat-triangle", + "accepted": true, + "codes": [], + "widest": { + "x": 70.0, + "y": 42.287, + "r": 2.287 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "arc-disc-6", + "accepted": true, + "codes": [], + "widest": { + "x": 43.0, + "y": 50.0, + "r": 2.998 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "cubic-lens", + "accepted": true, + "codes": [], + "widest": { + "x": 59.999, + "y": 50.0, + "r": 4.498 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "ell-3.6", + "accepted": true, + "codes": [], + "widest": { + "x": 42.109, + "y": 42.109, + "r": 2.109 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "pentagram-evenodd-root", + "accepted": true, + "codes": [], + "widest": { + "x": 59.999, + "y": 60.0, + "r": 3.09 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "forth-and-back", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": null, + "svg": "Jarret / Jarret" + }, + { + "name": "square-twice-opposite", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": null, + "svg": "Jarret / Jarret" + }, + { + "name": "diagonal-sliver", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": { + "x": 89.507, + "y": 88.809, + "r": 0.493 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "cubic-there-and-back", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": null, + "svg": "Jarret / Jarret" + }, + { + "name": "arc-there-and-back", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": null, + "svg": "Jarret / Jarret" + }, + { + "name": "flat-ellipse-45", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": { + "x": 65.0, + "y": 65.0, + "r": 1.0 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "ell-3.3", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": { + "x": 41.933, + "y": 41.933, + "r": 1.933 + }, + "svg": "Jarret / Jarret" + }, + { + "name": "triangle-6.6", + "accepted": false, + "codes": [ + "annotation.geometry.interior_too_small" + ], + "widest": { + "x": 43.3, + "y": 43.811, + "r": 1.905 + }, + "svg": "Jarret / Jarret" + } + ], + "equine": [ + { + "id": "caudal", + "view": "main", + "widest": { + "x": 1692.151, + "y": 554.007, + "r": 17.95 + } + }, + { + "id": "sacral", + "view": "main", + "widest": { + "x": 1470.781, + "y": 505.112, + "r": 40.963 + } + }, + { + "id": "lumbar", + "view": "main", + "widest": { + "x": 1341.641, + "y": 510.702, + "r": 51.297 + } + }, + { + "id": "thoracic", + "view": "main", + "widest": { + "x": 872.953, + "y": 484.677, + "r": 41.579 + } + }, + { + "id": "cervical", + "view": "main", + "widest": { + "x": 521.605, + "y": 279.763, + "r": 44.126 + } + }, + { + "id": "head-trigger", + "view": "main", + "widest": { + "x": 341.041, + "y": 303.749, + "r": 105.59 + } + } + ] +} diff --git a/apps/app/e2e/harness/interior.html b/apps/app/e2e/harness/interior.html new file mode 100644 index 00000000..2f5eaec2 --- /dev/null +++ b/apps/app/e2e/harness/interior.html @@ -0,0 +1,12 @@ + + + + + + Interior harness + + +
+ + + diff --git a/apps/app/e2e/harness/interior.ts b/apps/app/e2e/harness/interior.ts new file mode 100644 index 00000000..27a1bdd6 --- /dev/null +++ b/apps/app/e2e/harness/interior.ts @@ -0,0 +1,33 @@ +/** + * Test page for the interior rule in a real browser (e2e/ui/interior-clicks.spec.ts): the + * canvas the core composes for one probe case (e2e/fixtures/interior-probe.json, generated by + * crates/core/tests/interior_probe.rs) in the phone preview's 286 × 310 box, inserted as the + * editor inserts it (DOMParser, importNode), every click on a marker recorded. Served by the + * Vite dev server only (`/e2e/harness/interior.html?case=`); the build never ships it. + */ +import probe from '../fixtures/interior-probe.json' + +const name = new URLSearchParams(location.search).get('case') +const found = probe.cases.find((c) => c.name === name) +if (!found) throw new Error(`no probe case ${String(name)}`) + +const root = document.getElementById('root') as HTMLElement +const clicks = document.createElement('output') +clicks.dataset.testid = 'clicks' +clicks.style.cssText = 'display:block;height:24px;overflow:hidden' +const box = document.createElement('div') +box.dataset.testid = 'preview' +box.style.cssText = `width:${probe.frame.width}px;height:${probe.frame.height}px` +const parsed = new DOMParser().parseFromString(found.svg, 'image/svg+xml') +const svg = document.importNode( + parsed.documentElement, + true, +) as unknown as SVGSVGElement +svg.style.cssText = 'display:block;width:100%;height:100%' +box.append(svg) +root.append(clicks, box) +box.addEventListener('click', (event) => { + const marker = (event.target as Element).closest('[data-anno-id]') + const id = marker?.getAttribute('data-anno-id') + if (id) clicks.textContent = `${clicks.textContent ?? ''} ${id}`.trim() +}) diff --git a/apps/app/e2e/support/browser.ts b/apps/app/e2e/support/browser.ts index b1080878..00820f13 100644 --- a/apps/app/e2e/support/browser.ts +++ b/apps/app/e2e/support/browser.ts @@ -41,13 +41,14 @@ export const PROJECTS: Project[] = [ ] /** - * The canvas click proof (V1-2.2, e2e/ui/canvas-clicks.spec.ts) also runs on Firefox and + * The canvas click proofs (V1-2.2, e2e/ui/canvas-clicks.spec.ts and interior-clicks.spec.ts) + * also run on Firefox and * WebKit, desktop, and on the WebKit phone, when the pinned engine is installed, and on a * 320 px Chromium phone * (`playwright install firefox webkit`, no sudo, never `--with-deps`). A missing engine is * named in the run's output, never passed silently. */ -const CANVAS_CLICKS = /canvas-clicks\.spec\.ts$/ +const CANVAS_CLICKS = /(canvas|interior)-clicks\.spec\.ts$/ function installed(name: string, executable: string): boolean { const present = existsSync(executable) diff --git a/apps/app/e2e/ui/interior-clicks.spec.ts b/apps/app/e2e/ui/interior-clicks.spec.ts new file mode 100644 index 00000000..caceb7df --- /dev/null +++ b/apps/app/e2e/ui/interior-clicks.spec.ts @@ -0,0 +1,295 @@ +import { expect, test } from '../support/browser' +import type { Page } from '@playwright/test' +import probe from '../fixtures/interior-probe.json' + +// Owner brief « V1-2.2 : fermeture du dernier MEDIUM » (2026-11-01): a zone or a trigger drawn +// as a polygon or a path must fill a disc of 4 CSS px on the phone preview, its stroke left +// out. The core's verdict (e2e/fixtures/interior-probe.json, crates/core/tests/interior_probe.rs) +// against the browser's own hit test, in the preview's 286 × 310 box (one unit per CSS px): +// an accepted shape takes real presses in the disc the core found and its fill alone holds a +// 4 px disc; a refused one fills none. Then the equine draft's zones, in the editor canvas. +// Run on Chromium, Firefox and WebKit when installed. + +type Point = { x: number; y: number } +type Disc = { x: number; y: number; r: number } + +/** The threshold: a disc of 4 CSS px across. */ +const MIN_RADIUS_PX = 2 +/** The browser's mask is sampled every quarter pixel: its radius is within that of the fill. */ +const MASK_STEP_PX = 0.25 + +async function press(page: Page, at: Point, touch: boolean) { + if (touch) await page.touchscreen.tap(at.x, at.y) + else await page.mouse.click(at.x, at.y) +} + +async function recorded(page: Page): Promise { + const text = (await page.getByTestId('clicks').textContent()) ?? '' + return text.split(' ').filter(Boolean) +} + +async function clickRecords(page: Page, at: Point, touch: boolean) { + const before = (await recorded(page)).length + await press(page, at, touch) + await page.waitForTimeout(50) + return (await recorded(page)).slice(before) +} + +test.describe('interior clicks', () => { + for (const c of probe.cases) { + test(`${c.accepted ? 'accepted' : 'refused'}: ${c.name}`, async ({ + page, + }, info) => { + await page.goto(`/e2e/harness/interior.html?case=${c.name}`) + await expect(page.locator('[data-anno-id="shape"]')).toBeAttached() + const browser = await page.evaluate(widestFill, MASK_STEP_PX) + if (c.widest) { + // The core never claims more than the browser fills (it may claim less: its disc + // crosses no edge, where a nonzero fill may run on past one). + expect(browser.r, JSON.stringify(browser)).toBeGreaterThan( + c.widest.r - 0.5, + ) + } + if (!c.accepted) { + expect(browser.r, JSON.stringify(browser)).toBeLessThan(MIN_RADIUS_PX) + return + } + if (!c.widest) throw new Error(`${c.name} accepted without a disc`) + expect(browser.r).toBeGreaterThanOrEqual(MIN_RADIUS_PX) + const disc = c.widest + for (const fillOnly of [true, false]) { + const ring = await page.evaluate(ringHits, { disc, fillOnly }) + expect(ring, `fillOnly ${String(fillOnly)}`).toEqual({ + missed: [], + covered: 0, + }) + } + const centre = await page.evaluate(toScreen, { x: disc.x, y: disc.y }) + const touch = info.project.use.hasTouch === true + expect(await clickRecords(page, centre, touch)).toEqual(['shape']) + }) + } + + test('every equine zone holds the disc the core found and takes a real press', async ({ + page, + }, info) => { + await page.goto('/e2e/harness/canvas.html') + await expect( + page.locator('[data-testid="anatomy-canvas"] [data-anno-id="caudal"]'), + ).toBeAttached() + const touch = info.project.use.hasTouch === true + for (const zone of probe.equine) { + if (!zone.widest) throw new Error(`${zone.id} without a disc`) + const disc = zone.widest + // A point painted over the zone takes its taps (« the visible wins »): the samples under + // a visible disc are left out, at most a quarter of them. + const { missed, covered } = await page.evaluate(ringHits, { + disc, + fillOnly: false, + id: zone.id, + clearOfDiscs: true, + }) + expect(missed, zone.id).toEqual([]) + expect(covered, zone.id).toBeLessThanOrEqual(8) + // Chromium's touch adjustment gives a point the taps up to about 10 px around its disc + // (measured 2026-11-01): the real press goes where the zone's fill lies farthest from + // every disc, inside its edges. + const at = await page.evaluate(clearestFill, { id: zone.id, disc }) + expect(await clickRecords(page, at, touch), zone.id).toEqual([zone.id]) + } + }) +}) + +/** + * In the page: the point of the shape's fill, on a half CSS px grid, its own on the hit test and + * inside its edges by 2 px or 60 % of the core's disc radius if less (the caudal zone's disc is + * 4.95 px across at 320), farthest from every visible disc. + */ +function clearestFill(args: { id: string; disc: Disc }): Point { + const { id, disc } = args + const svg = document.querySelector( + '[data-testid="anatomy-canvas"] svg', + ) as SVGSVGElement + const ctm = svg.getScreenCTM() + if (!ctm) throw new Error('no CTM') + const shape = svg.querySelector( + `[data-anno-id="${id}"]`, + ) as SVGGeometryElement + const twins = ( + Array.from( + svg.querySelectorAll('circle[pointer-events="visiblePainted"]'), + ) as SVGCircleElement[] + ).map((t) => ({ + centre: new DOMPoint( + t.cx.baseVal.value, + t.cy.baseVal.value, + ).matrixTransform(ctm), + r: t.r.baseVal.value * ctm.a, + })) + const inverse = ctm.inverse() + const filled = (x: number, y: number) => + shape.isPointInFill(new DOMPoint(x, y).matrixTransform(inverse)) + const margin = Math.min(2, 0.6 * disc.r * ctm.a) + const box = shape.getBoundingClientRect() + let best = { x: 0, y: 0, d: -1 } + for (let x = Math.ceil(box.left); x <= box.right; x += 0.5) { + for (let y = Math.ceil(box.top); y <= box.bottom; y += 0.5) { + const steps = [-margin, 0, margin] + const inside = steps.every((dx) => + steps.every((dy) => filled(x + dx, y + dy)), + ) + if (!inside) continue + const hit = document.elementFromPoint(x, y)?.closest('[data-anno-id]') + if (hit?.getAttribute('data-anno-id') !== id) continue + const d = Math.min( + ...twins.map((t) => Math.hypot(x - t.centre.x, y - t.centre.y) - t.r), + ) + if (d > best.d) best = { x, y, d } + } + } + if (best.d < 0) throw new Error(`${id}: no fill clear of the discs`) + return { x: best.x, y: best.y } +} + +/** In the page: a point of the layer's user space on screen. */ +function toScreen(at: Point): Point { + const svg = document.querySelector('svg') as SVGSVGElement + const ctm = svg.getScreenCTM() + if (!ctm) throw new Error('no CTM') + const p = new DOMPoint(at.x, at.y).matrixTransform(ctm) + return { x: p.x, y: p.y } +} + +/** + * In the page: the browser's hit test at the disc's centre and 32 points at 90 % of its radius. + * With `fillOnly` the shape takes `pointer-events="fill"` meanwhile, its stroke out of the test; + * with `clearOfDiscs` the points within a visible disc (its stroke and half a pixel included) + * are counted apart. Answers the points that hit another element, and the points left out. + */ +function ringHits(args: { + disc: Disc + fillOnly: boolean + id?: string + clearOfDiscs?: boolean +}): { missed: string[]; covered: number } { + const { disc, fillOnly } = args + const id = args.id ?? 'shape' + const svg = document.querySelector('svg') as SVGSVGElement + const ctm = svg.getScreenCTM() + if (!ctm) throw new Error('no CTM') + const shapes = Array.from(svg.querySelectorAll(`[data-anno-id="${id}"]`)) + const kept = shapes.map((s) => s.getAttribute('pointer-events')) + if (fillOnly) shapes.forEach((s) => s.setAttribute('pointer-events', 'fill')) + const reach = disc.r * 0.9 + const points: Point[] = [{ x: disc.x, y: disc.y }] + for (let k = 0; k < 32; k++) { + const a = (k * 2 * Math.PI) / 32 + points.push({ + x: disc.x + reach * Math.cos(a), + y: disc.y + reach * Math.sin(a), + }) + } + const twins = Array.from( + svg.querySelectorAll('circle[pointer-events="visiblePainted"]'), + ) as SVGCircleElement[] + const underDisc = (at: Point) => + twins.some( + (t) => + Math.hypot(at.x - t.cx.baseVal.value, at.y - t.cy.baseVal.value) <= + t.r.baseVal.value + 0.75 + 0.5 / ctm.a, + ) + const missed: string[] = [] + let covered = 0 + for (const at of points) { + if (args.clearOfDiscs && underDisc(at)) { + covered++ + continue + } + const p = new DOMPoint(at.x, at.y).matrixTransform(ctm) + const hit = document + .elementFromPoint(p.x, p.y) + ?.closest('[data-anno-id]') + ?.getAttribute('data-anno-id') + if (hit !== id) + missed.push(`${at.x.toFixed(2)},${at.y.toFixed(2)}: ${String(hit)}`) + } + shapes.forEach((s, i) => { + const value = kept[i] + if (value === null || value === undefined) + s.removeAttribute('pointer-events') + else s.setAttribute('pointer-events', value) + }) + return { missed, covered } +} + +/** + * In the page: the widest disc of the shape's fill as the browser hits it (`pointer-events` + * `fill`, the stroke out), from a mask sampled every `step` CSS px over its box and 3 px around + * it, by an exact Euclidean distance transform (Felzenszwalb and Huttenlocher). The radius is + * the distance to the nearest sample outside the fill, less half a step. + */ +function widestFill(step: number): Disc { + const svg = document.querySelector('svg') as SVGSVGElement + const shape = svg.querySelector( + '[data-anno-id="shape"]', + ) as SVGGraphicsElement + const kept = shape.getAttribute('pointer-events') + shape.setAttribute('pointer-events', 'fill') + const box = shape.getBoundingClientRect() + const x0 = box.left - 3 + const y0 = box.top - 3 + const w = Math.ceil((box.width + 6) / step) + 1 + const h = Math.ceil((box.height + 6) / step) + 1 + const far = 1e20 + const grid = new Float64Array(w * h) + for (let j = 0; j < h; j++) { + for (let i = 0; i < w; i++) { + const hit = document.elementFromPoint(x0 + i * step, y0 + j * step) + grid[j * w + i] = hit === shape ? far : 0 + } + } + if (kept === null) shape.removeAttribute('pointer-events') + else shape.setAttribute('pointer-events', kept) + const line = (f: Float64Array): Float64Array => { + const n = f.length + const d = new Float64Array(n) + const v = new Int32Array(n) + const z = new Float64Array(n + 1) + let k = 0 + v[0] = 0 + z[0] = -Infinity + z[1] = Infinity + for (let q = 1; q < n; q++) { + let s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) + while (s <= z[k]) { + k-- + s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) + } + k++ + v[k] = q + z[k] = s + z[k + 1] = Infinity + } + k = 0 + for (let q = 0; q < n; q++) { + while (z[k + 1] < q) k++ + d[q] = (q - v[k]) ** 2 + f[v[k]] + } + return d + } + for (let i = 0; i < w; i++) { + const column = new Float64Array(h) + for (let j = 0; j < h; j++) column[j] = grid[j * w + i] + const done = line(column) + for (let j = 0; j < h; j++) grid[j * w + i] = done[j] + } + let best = { x: 0, y: 0, r: 0 } + for (let j = 0; j < h; j++) { + const done = line(grid.subarray(j * w, (j + 1) * w).slice()) + for (let i = 0; i < w; i++) { + const r = Math.sqrt(done[i]) * step - step / 2 + if (r > best.r) best = { x: x0 + i * step, y: y0 + j * step, r } + } + } + return best +} diff --git a/crates/core/src/anatomy/frame.rs b/crates/core/src/anatomy/frame.rs index d83cedc4..bc37701d 100644 --- a/crates/core/src/anatomy/frame.rs +++ b/crates/core/src/anatomy/frame.rs @@ -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 { @@ -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 { 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 { 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, diff --git a/crates/core/src/anatomy/interior.rs b/crates/core/src/anatomy/interior.rs new file mode 100644 index 00000000..d83141d2 --- /dev/null +++ b/crates/core/src/anatomy/interior.rs @@ -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 { + 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 { + 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 { + (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 { + 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 { + 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:?}"); + } + } + } + } +} diff --git a/crates/core/src/anatomy/mod.rs b/crates/core/src/anatomy/mod.rs index c368b9a4..a3136534 100644 --- a/crates/core/src/anatomy/mod.rs +++ b/crates/core/src/anatomy/mod.rs @@ -5,6 +5,7 @@ pub mod compose; pub mod frame; +pub mod interior; pub mod layer; pub mod path; pub mod svg; diff --git a/crates/core/src/anatomy/path.rs b/crates/core/src/anatomy/path.rs index 0c8f81ca..a50dfb6c 100644 --- a/crates/core/src/anatomy/path.rs +++ b/crates/core/src/anatomy/path.rs @@ -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> { /// The bounds of every point `d` draws; `None` when a browser would not read all of it. pub fn path_bounds(d: &str) -> Option { - 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>, + 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 { + 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 { } } } - 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, + flat: Option, +} + +/// 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 (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 = (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)); diff --git a/crates/core/src/domain/sheet/report.rs b/crates/core/src/domain/sheet/report.rs index a84a2485..29ec3ec5 100644 --- a/crates/core/src/domain/sheet/report.rs +++ b/crates/core/src/domain/sheet/report.rs @@ -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") } diff --git a/crates/core/src/domain/sheet/verdict.rs b/crates/core/src/domain/sheet/verdict.rs index c35ffc4c..9cc23a07 100644 --- a/crates/core/src/domain/sheet/verdict.rs +++ b/crates/core/src/domain/sheet/verdict.rs @@ -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 } diff --git a/crates/core/tests/interior_probe.rs b/crates/core/tests/interior_probe.rs new file mode 100644 index 00000000..0af1f045 --- /dev/null +++ b/crates/core/tests/interior_probe.rs @@ -0,0 +1,232 @@ +//! The browser proof of the interior rule (owner brief « V1-2.2 : fermeture du dernier MEDIUM », +//! 2026-11-01): `apps/app/e2e/fixtures/interior-probe.json`, read by +//! `apps/app/e2e/ui/interior-clicks.spec.ts` in Chromium, Firefox and WebKit. Each case is a +//! sheet whose main view, framed `0 0 286 310` (one unit per CSS px on the phone preview), holds +//! one shape: the canvas the editor gets (`view.canvas`), the verdict's code, and the widest disc +//! the core measures. The equine draft's shapes give their discs too. The file is generated +//! here and compared byte for byte; `MAKE_INTERIOR_PROBE=1` writes it. +#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::sheet_readers::{DETAIL_ASSET, MAIN_ASSET, OPEN, document, drawing}; +use faunosteo_core::anatomy::interior::{ + Budget, LAYER_FILL_RULE, Search, geometry_outline, widest_disc, +}; +use faunosteo_core::domain::sheet::preview::{PreviewInput, PreviewSheet, PreviewStatus}; +use faunosteo_core::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry}; +use faunosteo_core::facade::call_with_preview; +use serde_json::{Value, json}; + +const FIXTURE: &str = "apps/app/e2e/fixtures/interior-probe.json"; +const THIN: &str = "annotation.geometry.interior_too_small"; +const PHONE: &str = "0 0 286 310"; + +/// The widest disc of a shape, measured to a thousandth of a unit: centre and radius. +fn widest(geometry: &Geometry) -> Value { + let outline = geometry_outline(geometry, 0.001).unwrap(); + let search = Search { + floor: 0.0, + enough: f64::INFINITY, + precision: 0.001, + }; + match widest_disc(&outline, LAYER_FILL_RULE, &search, &mut Budget::default()) { + Some(disc) => json!({ + "x": round(disc.centre.0), + "y": round(disc.centre.1), + "r": round(disc.radius), + }), + None => Value::Null, + } +} + +fn round(value: f64) -> f64 { + (value * 1000.0).round() / 1000.0 +} + +/// One case: the canvas, the frame codes, the widest disc. +fn case(name: &str, geometry: Value, root: &str) -> Value { + let mut doc: Value = serde_json::from_str(&document()).unwrap(); + doc["annotations"][0]["id"] = json!("shape"); + doc["annotations"][0]["kind"] = json!("zone"); + doc["annotations"][0]["geometry"] = geometry.clone(); + let main = OPEN.replace( + "viewBox=\"0 0 10 10\"", + &format!("{root}viewBox=\"{PHONE}\""), + ) + ""; + let detail = OPEN.to_owned() + ""; + let input = PreviewInput { + status: PreviewStatus::Draft, + document: doc.to_string(), + fingerprint: None, + }; + let preview = PreviewSheet::load( + input, + vec![drawing(MAIN_ASSET, &main), drawing(DETAIL_ASSET, &detail)], + ) + .unwrap(); + let codes: Vec = preview + .state() + .unwrap() + .report + .issues + .iter() + .filter(|i| i.code.starts_with("annotation.geometry.")) + .map(|i| i.code.clone()) + .collect(); + let canvas: Value = serde_json::from_str(&call_with_preview( + &preview, + "view.canvas", + &json!({ "viewId": "main" }).to_string(), + )) + .unwrap(); + assert_eq!(canvas["ok"], json!(true), "{name}: {canvas}"); + let typed: Geometry = serde_json::from_value(geometry).unwrap(); + json!({ + "name": name, + "accepted": codes.is_empty(), + "codes": codes, + "widest": widest(&typed), + "svg": canvas["value"]["svg"], + }) +} + +fn polygon(points: &[[f64; 2]]) -> Value { + json!({ "type": "polygon", "points": points }) +} + +fn path(d: &str) -> Value { + json!({ "type": "path", "d": d }) +} + +fn ell(x: f64, y: f64, w: f64) -> Value { + polygon(&[ + [x, y], + [x + 40.0, y], + [x + 40.0, y + w], + [x + w, y + w], + [x + w, y + 40.0], + [x, y + 40.0], + ]) +} + +fn star(cx: f64, cy: f64, r: f64) -> Value { + let points: Vec<[f64; 2]> = (0..5) + .map(|i| { + let angle = + -std::f64::consts::FRAC_PI_2 + f64::from(i * 2) * std::f64::consts::TAU / 5.0; + [cx + r * angle.cos(), cy + r * angle.sin()] + }) + .collect(); + polygon(&points) +} + +fn cases() -> Vec { + let plain = ""; + vec![ + // Accepted: small shapes that fill. + case( + "square-6", + polygon(&[[40.0, 40.0], [46.0, 40.0], [46.0, 46.0], [40.0, 46.0]]), + plain, + ), + case( + "flat-triangle", + polygon(&[[40.0, 40.0], [100.0, 40.0], [70.0, 44.6]]), + plain, + ), + case( + "arc-disc-6", + path("M40 50a3 3 0 1 0 6 0a3 3 0 1 0 -6 0Z"), + plain, + ), + case( + "cubic-lens", + path("M40 50C50 44 70 44 80 50C70 56 50 56 40 50Z"), + plain, + ), + case("ell-3.6", ell(40.0, 40.0, 3.6), plain), + // Winding 2 at the centre: filled by the layer's nonzero rule, whatever the drawing says. + case( + "pentagram-evenodd-root", + star(60.0, 60.0, 10.0), + "fill-rule=\"evenodd\" ", + ), + // Refused: no interior a tap reaches on the phone. + case("forth-and-back", path("M40 40L90 90L40 40"), plain), + case( + "square-twice-opposite", + path("M40 40h40v40h-40zM40 40v40h40v-40z"), + plain, + ), + case( + "diagonal-sliver", + polygon(&[[40.0, 40.0], [90.0, 90.0], [90.0, 88.6]]), + plain, + ), + case( + "cubic-there-and-back", + path("M40 80C50 40 80 40 90 80C80 40 50 40 40 80Z"), + plain, + ), + case( + "arc-there-and-back", + path("M40 80A25 25 0 0 1 90 80A25 25 0 0 0 40 80Z"), + plain, + ), + case( + "flat-ellipse-45", + path("M40 40A35 1 45 0 1 90 90A35 1 45 0 1 40 40Z"), + plain, + ), + case("ell-3.3", ell(40.0, 40.0, 3.3), plain), + case( + "triangle-6.6", + polygon(&[[40.0, 45.716], [46.6, 45.716], [43.3, 40.0]]), + plain, + ), + ] +} + +/// The equine draft's polygons and paths: their widest disc, in the frame's units. +fn equine() -> Vec { + let text = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/document.json"); + let doc: AnatomicalSheetDocument = serde_json::from_str(&text).unwrap(); + doc.annotations + .iter() + .filter_map(|a| { + let geometry = match a { + Annotation::Observable(o) => o.geometry.as_ref(), + Annotation::DetailTrigger(t) => t.geometry.as_ref(), + }?; + if matches!(geometry, Geometry::Circle(_)) { + return None; + } + Some(json!({ "id": a.id(), "view": a.view_id(), "widest": widest(geometry) })) + }) + .collect() +} + +#[test] +fn the_interior_probe_is_current() { + let cases = cases(); + for c in &cases { + let refused = c["codes"] == json!([THIN]); + assert!(c["accepted"] == json!(true) || refused, "{}", c["name"]); + } + let probe = json!({ + "generatedBy": "crates/core/tests/interior_probe.rs", + "frame": { "width": 286, "height": 310 }, + "cases": cases, + "equine": equine(), + }); + let text = serde_json::to_string_pretty(&probe).unwrap() + "\n"; + let path = format!("{}/../../{FIXTURE}", env!("CARGO_MANIFEST_DIR")); + if std::env::var("MAKE_INTERIOR_PROBE").is_ok_and(|v| v == "1") { + std::fs::write(&path, &text).unwrap(); + } + assert!( + common::repo_file(FIXTURE) == text, + "{FIXTURE} is stale: MAKE_INTERIOR_PROBE=1 cargo test --test interior_probe" + ); +} diff --git a/crates/core/tests/sheet_marker_visibility.rs b/crates/core/tests/sheet_marker_visibility.rs index a53931ca..5817fb5b 100644 --- a/crates/core/tests/sheet_marker_visibility.rs +++ b/crates/core/tests/sheet_marker_visibility.rs @@ -24,10 +24,12 @@ use serde_json::{Value, json}; const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft"; const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a"; const TOO_SMALL: &str = "annotation.geometry.too_small"; +const THIN: &str = "annotation.geometry.interior_too_small"; const NO_FRAME: &str = "view.frame.unknown"; const OUT_OF_FRAME: &str = "annotation.geometry.out_of_frame"; /// The verdict's closed codes, as the SQL stores them. const SMALL_FAILURE: &str = "verification.validation.marker_too_small"; +const THIN_FAILURE: &str = "verification.validation.marker_interior_too_small"; const FRAME_FAILURE: &str = "verification.validation.out_of_frame"; /// The frame and size issues `(code, path)`, the verdict and the preview agreeing, and the @@ -68,7 +70,7 @@ fn judged( let state = PreviewSheet::load(input, given).unwrap().state().unwrap(); let issues = |all: &[faunosteo_core::domain::sheet::SheetIssue]| -> Vec<(String, String)> { all.iter() - .filter(|i| [TOO_SMALL, NO_FRAME, OUT_OF_FRAME].contains(&i.code.as_str())) + .filter(|i| [TOO_SMALL, THIN, NO_FRAME, OUT_OF_FRAME].contains(&i.code.as_str())) .map(|i| (i.code.clone(), i.path.clone())) .collect() }; @@ -179,28 +181,50 @@ fn the_blown_up_horse_is_refused() { assert_eq!(text, equine(), "the document is never rewritten"); } -/// The threshold on the real sheet: the junctions fall below 4 px once the horse is scaled by -/// more than 4.966 / 4 ≈ 1.2414; the other points (disc r 22) hold until ≈ 1.517. +/// The threshold on the real sheet. The caudal zone's widest disc (4.951 px) falls below 4 px +/// first, once the horse is scaled by more than 4.951 / 4 ≈ 1.2378; then the junctions, past +/// 4.966 / 4 ≈ 1.2414; the other points (disc r 22) hold until ≈ 1.517, the other zones (at +/// least 11.30 px) until ≈ 2.8. In doubt the measure refuses: at 1.236 (4.006 px) the search, +/// which cuts no cell below 0.05 px, has not shown the disc. #[test] -fn the_equine_threshold_falls_on_the_junctions_first() { +fn the_equine_threshold_falls_on_the_caudal_zone_then_the_junctions() { let text = equine(); - let small = |factor: f64| -> Vec { + let small = |factor: f64| -> Vec<(String, String)> { let (issues, _) = judged(&text, &[(HORSE_ID, &scaled_horse(factor))]); let doc: Value = serde_json::from_str(&text).unwrap(); - issues + let mut found: Vec<(String, String)> = issues .iter() - .map(|(_, path)| { + .map(|(code, path)| { let index: usize = path[12..path.len() - 10].parse().unwrap(); - doc["annotations"][index]["id"].as_str().unwrap().to_owned() + let id = doc["annotations"][index]["id"].as_str().unwrap(); + (id.to_owned(), code.clone()) }) - .collect() + .collect(); + found.sort(); + found }; - assert!(small(1.24).is_empty()); - let mut junctions = small(1.25); - junctions.sort(); - assert_eq!(junctions, ["c7-t1", "l6-s1", "t18-l1"]); - assert_eq!(small(1.51).len(), 3); - assert_eq!(small(1.52).len(), 13, "every point, the zones still shown"); + let pair = |id: &str, code: &str| (id.to_owned(), code.to_owned()); + assert!(small(1.23).is_empty()); + assert_eq!(small(1.24), [pair("caudal", THIN)]); + let (_, failures) = judged(&text, &[(HORSE_ID, &scaled_horse(1.24))]); + assert_eq!( + failures, + [THIN_FAILURE], + "the interior alone, never a rules failure" + ); + assert_eq!( + small(1.25), + [ + pair("c7-t1", TOO_SMALL), + pair("caudal", THIN), + pair("l6-s1", TOO_SMALL), + pair("t18-l1", TOO_SMALL), + ] + ); + assert_eq!(small(1.51).len(), 4); + let past = small(1.52); + assert_eq!(past.len(), 14, "every point and the caudal zone"); + assert_eq!(past.iter().filter(|(_, code)| code == THIN).count(), 1); } /// A point shows its visible disc, `2 × max(2, r − 12)`, never its transparent hitbox; at @@ -381,3 +405,152 @@ fn path_numbers_past_the_frame_magnitude_are_refused() { assert_eq!(main(d), [OUT_OF_FRAME], "{d}"); } } + +/// The last MEDIUM (owner brief 2026-11-01, zone without interior): a polygon or a path must fill +/// a disc of 4 px on the smallest preview, its stroke left out. A frame of 286 × 310 units shows +/// one unit per CSS px on the main view. Each shape passes the bounds rule (it was accepted +/// before this rule) and is now refused. +#[test] +fn shapes_without_a_usable_interior_are_refused() { + let phone = "0 0 286 310"; + let hostile = [ + // A path drawn forth and back: winding 0 everywhere. + path("M20 20L200 200L20 20"), + path("M20 20L200 20L200 200L200 20Z"), + // The same square twice, in opposite directions: winding 0 under nonzero. + path("M20 20h100v100h-100zM20 20v100h100v-100z"), + // A near-flat polygon on the diagonal, 1 px thick, 180 px of bounds. + json!({ "type": "polygon", "points": [[20, 20], [200, 200], [200, 198.6]] }), + // A cubic and an arc travelled there and back. + path("M20 150C60 20 160 20 200 150C160 20 60 20 20 150Z"), + path("M20 150A90 90 0 0 1 200 150A90 90 0 0 0 20 150Z"), + // A flat ellipse turned 45°: 2 px thick, 127 px of bounds. + path("M50 50A127 1 45 0 1 230 230A127 1 45 0 1 50 50Z"), + // An L whose arms are 3.3 px wide: its widest disc, at the elbow, is 3.87 px. + json!({ "type": "polygon", "points": [[20, 20], [80, 20], [80, 23.3], [23.3, 23.3], [23.3, 80], [20, 80]] }), + ]; + for geometry in hostile { + let found = on_main(geometry.clone(), phone); + assert_eq!(codes(&found), [THIN], "{geometry}"); + assert!(found.1.iter().any(|f| f == THIN_FAILURE), "{:?}", found.1); + } +} + +/// Small shapes that fill: a 4.5 px tall triangle, a disc of 6 px drawn with two arcs, a cubic +/// lens, the L with 3.6 px arms (4.22 px at the elbow), a pentagram whose centre has winding 2 +/// (the layer fills nonzero: 6.18 px; under evenodd only a tip would hold 3.26 px). +#[test] +fn small_shapes_that_fill_are_accepted() { + let phone = "0 0 286 310"; + let legitimate = [ + json!({ "type": "polygon", "points": [[20, 20], [200, 20], [110, 24.5]] }), + path("M100 100a3 3 0 1 0 6 0a3 3 0 1 0 -6 0Z"), + path("M20 100C40 90 60 90 80 100C60 110 40 110 20 100Z"), + json!({ "type": "polygon", "points": [[20, 20], [80, 20], [80, 23.6], [23.6, 23.6], [23.6, 80], [20, 80]] }), + json!({ "type": "polygon", "points": star(100.0, 100.0, 10.0) }), + ]; + for geometry in legitimate { + assert!( + codes(&on_main(geometry.clone(), phone)).is_empty(), + "{geometry}" + ); + } +} + +fn star(cx: f64, cy: f64, r: f64) -> Vec<[f64; 2]> { + (0..5) + .map(|i| { + let angle = + -std::f64::consts::FRAC_PI_2 + f64::from(i * 2) * std::f64::consts::TAU / 5.0; + [cx + r * angle.cos(), cy + r * angle.sin()] + }) + .collect() +} + +/// The threshold, on a shape whose widest disc is off its bounds' centre: an L with arms `w` +/// wide holds a disc of `2√2 w / (1 + √2)` at its elbow, a sharp peak the search approaches +/// from below. In doubt it refuses: measured, the first L accepted holds 4.026 px. +#[test] +fn the_interior_threshold_holds_at_its_edge() { + let elbow = |w: f64| { + let shape = json!({ "type": "polygon", "points": [[20, 20], [80, 20], [80, 20.0 + w], [20.0 + w, 20.0 + w], [20.0 + w, 80], [20, 80]] }); + codes(&on_main(shape, "0 0 286 310")) + }; + let diameter = |w: f64| 2.0 * std::f64::consts::SQRT_2 * w / (1.0 + std::f64::consts::SQRT_2); + assert!((diameter(3.44) - 4.030).abs() < 1e-3); + assert!(elbow(3.44).is_empty(), "4.030 px"); + assert_eq!(elbow(3.43), [THIN], "4.019 px, in the doubt band"); + assert_eq!(elbow(3.41), [THIN], "3.995 px"); +} + +/// Extreme frames and scales: the measure follows the projection, not the units. The same L at +/// a tenth of the scale, near the offset limit, and in a one-unit frame. +#[test] +fn the_interior_follows_the_projection() { + let l = |x: f64, y: f64, unit: f64, w: f64| { + let p = |a: f64, b: f64| [x + a * unit, y + b * unit]; + json!({ "type": "polygon", "points": [p(0.0, 0.0), p(60.0, 0.0), p(60.0, w), p(w, w), p(w, 60.0), p(0.0, 60.0)] }) + }; + // Ten units per px. + assert!(codes(&on_main(l(200.0, 200.0, 10.0, 3.6), "0 0 2860 3100")).is_empty()); + assert_eq!( + codes(&on_main(l(200.0, 200.0, 10.0, 3.3), "0 0 2860 3100")), + [THIN] + ); + // The far edge at 256 spans (`MAX_FRAME_OFFSET_RATIO`): 2 860 units across, 0.1 px each. + let near = MAX_FRAME_OFFSET_RATIO * 2860.0 - 2860.0; + let frame = format!("{near} 0 2860 3100"); + assert!(codes(&on_main(l(near + 200.0, 200.0, 10.0, 3.6), &frame)).is_empty()); + assert_eq!( + codes(&on_main(l(near + 200.0, 200.0, 10.0, 3.3), &frame)), + [THIN] + ); + // A one-unit frame: 286 px per unit. + let unit = 1.0 / 286.0; + assert!(codes(&on_main(l(0.1, 0.1, unit, 3.6), "0 0 1 1.0839")).is_empty()); + assert_eq!( + codes(&on_main(l(0.1, 0.1, unit, 3.3), "0 0 1 1.0839")), + [THIN] + ); +} + +/// A drawing scaled inside never changes the interior: the markers are drawn in the frame. +#[test] +fn drawing_transforms_never_change_the_interior() { + let mut doc: Value = serde_json::from_str(&document()).unwrap(); + doc["annotations"][0]["geometry"] = path("M20 20L200 200L20 20"); + let scaled = OPEN.replace("0 0 10 10", "0 0 286 310") + + ""; + let plain = OPEN.to_owned() + ""; + let (issues, _) = judged( + &doc.to_string(), + &[(MAIN_ASSET, &scaled), (DETAIL_ASSET, &plain)], + ); + assert_eq!( + issues, + [(THIN.to_owned(), "annotations[0].geometry".to_owned())] + ); +} + +/// Over the measure's caps the shape is refused, never accepted: a disc drawn with 5 000 vertices. +#[test] +fn a_shape_too_complex_to_measure_is_refused() { + let ring = |count: u32| { + let points: Vec<[f64; 2]> = (0..count) + .map(|i| { + let angle = f64::from(i) * std::f64::consts::TAU / f64::from(count); + [143.0 + 100.0 * angle.cos(), 155.0 + 100.0 * angle.sin()] + }) + .collect(); + json!({ "type": "polygon", "points": points }) + }; + assert!(codes(&on_main(ring(4096), "0 0 286 310")).is_empty()); + assert_eq!(codes(&on_main(ring(4097), "0 0 286 310")), [THIN]); + // The same cap on a path's outline, its curves' chords counted. + let square = |sides: usize| format!("M40 40{}h100v100h-100Z", "h0.001".repeat(sides)); + assert_eq!( + codes(&on_main(path(&square(4092)), "0 0 286 310")), + Vec::::new() + ); + assert_eq!(codes(&on_main(path(&square(4093)), "0 0 286 310")), [THIN]); +} diff --git a/docs/ANNOTATION-RENDERING.md b/docs/ANNOTATION-RENDERING.md index 797055fe..ed706231 100644 --- a/docs/ANNOTATION-RENDERING.md +++ b/docs/ANNOTATION-RENDERING.md @@ -96,7 +96,16 @@ draw faithfully (edges within 2²⁰, spans from 1 unit, aspect at most every annotation must show at least 4 CSS px on the smallest preview, the editor at 320 × 568 (`verification.validation.marker_too_small`): a frame blown up with its drawing scaled back keeps the drawing and shrinks every -marker, refused. +marker, refused. A zone or a trigger drawn as a polygon or a path must also +fill a disc of 4 CSS px on that preview, under the `nonzero` rule the layer +fills with (it writes no `fill-rule`, and none reaches it), its stroke left out +(`verification.validation.marker_interior_too_small`, owner brief 2026-11-01): +an outline drawn forth and back, the same loop twice in opposite directions, or +a near-flat shape on a diagonal fills no point a tap can reach, refused. The +measure is conservative (a disc crossing no edge, curves cut into chords whose +deviation is taken off) and refuses in doubt; a point painted over a zone takes +the taps on its disc, which the measure does not count (known limitation, +RUST.md §12.14). The editor canvas is inlined in the page, where `#id` resolves against the whole document. Since V1-2.2 (owner decision 2026-10-29) the core writes diff --git a/docs/development/BROWSER_TESTS.md b/docs/development/BROWSER_TESTS.md index 440109a3..b2297129 100644 --- a/docs/development/BROWSER_TESTS.md +++ b/docs/development/BROWSER_TESTS.md @@ -123,7 +123,16 @@ suite needs Docker in the runner for the sandbox. 100.9 left of it; Chromium keeps the fraction on a click, rounds a tap), so a real press keeps 1.5 px of margin from any edge it tests; below that margin the spec asks the browser's own hit test (`elementFromPoint`) at the exact - point. Firefox, WebKit + point. `e2e/ui/interior-clicks.spec.ts` runs on the same six projects + (V1-2.2, the interior rule): the core's probe cases + (`e2e/fixtures/interior-probe.json`, generated and drift-checked by + `crates/core/tests/interior_probe.rs`, `MAKE_INTERIOR_PROBE=1` rewrites it) in + the phone preview's 286 × 310 box (harness `e2e/harness/interior.{html,ts}`, + dev server only), then the equine zones in the canvas harness. Chromium's touch + adjustment gives a point the taps up to about 10 px around its disc + (measured 2026-11-01, `chromium-320` and `chromium-375`; WebKit 375 does + not), so the real press on an equine zone goes where its fill lies farthest + from every disc. Firefox, WebKit and the 412 × 915 viewport join every suite at V1-5 (contract §12.5). WebKit's system libraries may need `sudo` (owner action). Desktop WebKit is not iOS Safari: the owner's manual check on a real iPhone diff --git a/docs/development/RUST.md b/docs/development/RUST.md index 97ab67da..5d599b2e 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -4342,3 +4342,72 @@ security review measured its consequence (MEDIUM, open, owner decision): a zone (an outline traced twice in opposite directions) or a near-collinear polygon passes the 4 px rule, paints no interior and is hit only on its 2-unit stroke (0.28 CSS px on the equine phone scale), in the three engines. Closing it needs a filled-area measure (nonzero rule) or a « zone without interior » issue. + +### 12.14 The last MEDIUM: zone without interior (owner, 2026-11-01) + +Brief « V1-2.2 : fermeture du dernier MEDIUM » on `de2dfb3`: the decisions of §12.13 confirmed (threshold, frame rule, +bounds, codes `too_small` / `marker_too_small`, isolation, canvas passes, PDF order and bytes, R3 transforms, R4.1 +manifest, the five former `fixme`); a zone without a usable filled interior refused by the verifier, in the core. + +**Rule** (`anatomy::interior`, called by `frame::annotation_placement` after the bounds rule, so by the verdict and the +preview): a polygon or a path annotation (zone or trigger) must fill a disc of `MIN_VISIBLE_PX` 4 CSS px across on the +smallest preview (§12.13: main 286 × 310, detail 254 × 191, `xMidYMid meet`). Circles keep their exact disc measure. + +| Part | What and why | Where | +|---|---|---| +| Fill rule | `nonzero` (`LAYER_FILL_RULE`): the layer writes no `fill-rule`, the composition root carries none, the drawing's sits in its own group (§12.12). The measure takes either rule; `evenodd` is tested, never used by the layer | `interior::FillRule` | +| Stroke | never counted: the measure reads the fill alone, whatever the shape's `pointer-events` (`all` on zones and triggers, its 2-unit stroke taken by the browser too) | | +| Outline | a polygon's points; a path read by the one SVG path reader (`path::path_outline`, same grammar and `±2²⁰` bound as `path_bounds`), each subpath closed by the fill, a lone moveto adding nothing; cubics, quadratics and arcs cut into chords: over a parameter step `h` a chord departs from its curve by at most `K h² / 8`, `K` bounding the second derivative (cubic `6 max‖Δ²‖`, quadratic `2‖Δ²‖`, arc `max(rx, ry) × sweep²`, the radii as scaled to reach the endpoint); chords asked within 0.05 px (`INTERIOR_TOLERANCE_PX`), at most `MAX_CURVE_CHORDS` 64 per curve, the largest deviation recorded | `path::Outline` | +| Measure | the widest disc whose centre the rule puts inside and every edge (closing edges included) at least the radius away: the disc crosses no edge, so all of it has the centre's winding number; the deviation taken off the radius. Conservative: a nonzero fill running on past an inner edge is not counted (pentagram: 3.09 measured, 3.82 filled) | `interior::widest_disc` | +| Search | polylabel's subdivision: square cells from one covering the outline, a cell's best centre at most its centre's radius plus its half diagonal, the most promising cell cut first (a max-heap ordered by `total_cmp`), cells below 0.05 px never cut; deterministic. Refuses in doubt: measured, the first L accepted at its elbow holds 4.026 px | | +| Caps | 4 096 outline vertices (`MAX_OUTLINE_VERTICES`), 4 096 cells per shape, one budget of `2²⁵` edge distances per sheet (`MAX_INTERIOR_WORK`, 0.35 s natively at 8 192 edges × 4 096 cells; the equine takes about 10⁵): a shape over them is refused, never accepted | `interior::Budget` | +| Refusal | issue `annotation.geometry.interior_too_small` (« fills no interior wide enough to tap », or « too complex for the interior measure »), verdict `verification.validation.marker_interior_too_small` after `marker_too_small`, never a rules failure; the document never rewritten | `report.rs`, `verdict.rs` | + +Threshold, measured before freezing (equine draft, 320 × 568, widest disc across): caudal 4.951 px, sacral 11.30, +thoracic 11.47, cervical 12.17, lumbar 14.15, head trigger 29.13. 4 px keeps the approved threshold of the points (a point +shows a 4 px disc, a zone must hold one) and refuses no equine shape; the caudal zone now falls first when the horse is +scaled, past × 1.2378 (4.951 / 4), before the junctions (× 1.2414). Above 4.95 px the threshold would refuse the +validated equine; below, a tap target smaller than the points'. + +| Proof | Result | +|---|---| +| `sheet_marker_visibility::shapes_without_a_usable_interior_are_refused` | each accepted before this rule (bounds pass): a path forth and back, a triangle traced back on itself, the same square twice in opposite directions, a 1 px diagonal sliver, a cubic and an arc travelled there and back, a 2 px ellipse turned 45°, an L of 3.3 px arms (3.87 px): `interior_too_small`, `marker_interior_too_small` | +| `small_shapes_that_fill_are_accepted` | a 4.5 px tall triangle, a 6 px disc of two arcs, a cubic lens, an L of 3.6 px arms (4.22 px), a pentagram of winding 2 (6.18 px; 3.26 under evenodd) | +| `the_interior_threshold_holds_at_its_edge` | L at 4.030 px accepted, 4.019 (doubt band) and 3.995 refused | +| `the_interior_follows_the_projection` | the same L at ten units per px, at the offset limit (256 spans), in a one-unit frame (286 px per unit) | +| `drawing_transforms_never_change_the_interior`, `a_shape_too_complex_to_measure_is_refused` | a drawing scaled × 1 000 changes nothing; 4 096 vertices measured, 4 097 refused (polygon and path) | +| equine | `the_equine_draft_shows_every_marker_on_the_phone_preview` passes; `the_equine_threshold_falls_on_the_caudal_zone_then_the_junctions`: × 1.235 accepted, × 1.24 the caudal zone alone (failures `[marker_interior_too_small]`), × 1.25 with the three junctions | +| `interior` unit tests | square, pentagram under both rules, forth and back, two opposite loops, deviation taken off, stop and floor, budget shared and spent, 60 random polygons (self-intersecting included) under both rules: never wider than a dense grid, every rim point filled | +| `path` unit tests | 300 random cubics, quadratics and arcs: every curve point within the recorded deviation of its chords, the deviation within 0.05 unless capped (arcs whose radii the endpoints scale up); closepath restarts at the subpath start; vertex cap | + +Browsers (`apps/app/e2e/ui/interior-clicks.spec.ts`, the six click projects: Chromium 1280, 375 and 320 touch, Firefox +1280, WebKit 1280 and 375 touch; 90 passed, and `canvas-clicks.spec.ts` 99 unchanged). The probe +(`e2e/fixtures/interior-probe.json`, written and drift-checked by `tests/interior_probe.rs`) gives 14 shapes in the +preview's 286 × 310 box (one unit per CSS px) with the core's verdict and widest disc. For each, the browser's own fill +(`pointer-events="fill"`, stroke out) is sampled every 0.25 px and its widest disc taken by an exact distance transform: +the core never claims more than the browser fills (at most 0.5 px under it); the 8 refused fill no 4 px disc in any +engine; the 6 accepted take a real click or tap at the core's centre and the hit test at 32 points of 90 % of its radius, +fill only and as shipped. A drawing root `fill-rule="evenodd"` leaves the pentagram filled at its centre (isolation). +Then the equine shapes in the canvas: the core's disc hit test-clear (samples under a point's disc aside, at most a +quarter), and a real press where the fill lies farthest from every disc records the zone. + +Chromium's touch adjustment, measured (tool `.claude/audits/2026-11-01-v1-2-2-interior-tools/`, taps every 2 px of each +equine zone's own hit area, 400 ms apart): a tap up to about 10 px around a point's disc goes to the point on +`chromium-320` and `chromium-375`, not on `webkit-375`. Taps recorded as the zone at 320 px: caudal 18/21, sacral 51/67, +lumbar 87/104, thoracic 72/97, cervical 195/195, trigger 278/284 (the rest to the neighbouring junctions and points, or to +nothing at the edges); WebKit 375: 91 to 99 %. Every equine zone keeps a tappable interior; near a point, Chromium's +targeting goes to the point, a browser behaviour the measure does not model (no selection redesign in V1-2.2). + +Known limitation (owner, 2026-11-01, LOW accepted): a visible disc covering another marker entirely, or the only +interior of a zone, takes its taps; no rule refuses it. The human review identifies overlapping markers before a sheet +is published; no proof here claims that every marker is individually selectable when two overlap entirely. The arc +rotation reduced in `f32` by browsers (sub-pixel, §12.13) stays bounded by the `2²⁰` number bound, its tests kept. + +Mutations (`.claude/audits/2026-11-01-v1-2-2-mutations-interior.py`): 24 killed, Z22 (the floor prune removed) survives +as equivalent, a cell that cannot reach the floor never holding an accepted disc; S1, S8 and F16 of the previous scripts, +whose anchors moved, re-anchored and killed. Module 579 180 B gzip -9 (+4 946 B, budget 600 000, margin 20 820 B). + +Ignored cargo tests: the three are one test, `pdf_serialize::l_report_with_real_rasters_costs_what_it_costs`, counted +once per cargo run whose features build `pdf_serialize` (workspace, `cli`, `ts,pdf-read,pdf-write`). A timing print for +§10.7, 40 s in debug; run on request in release (2026-11-01: passed, 120 views, 46.5 MB, 5.2 s). The L report's export +itself is covered unignored (`pdf_budget`); it masks no required scenario. diff --git a/docs/development/V1-2_ANATOMICAL_SHEETS.md b/docs/development/V1-2_ANATOMICAL_SHEETS.md index 3cd655cc..3d279b29 100644 --- a/docs/development/V1-2_ANATOMICAL_SHEETS.md +++ b/docs/development/V1-2_ANATOMICAL_SHEETS.md @@ -1048,6 +1048,7 @@ Four stages, each a superset of the previous: | Every reachable drawing present, size and sha256 equal to its row, read without removal, in the stored form of §9.2 | yes | | | `verification.integrity.*` | | Every annotation entirely inside the frame of its view, edges included: the view's `view_box`, else the `viewBox` of the drawing it draws, read as a browser reads it (four numbers, positive width and height) and usable within the range rules browsers draw faithfully (owner brief 2026-11-01: edges within 2²⁰, spans from 1 unit, aspect at most 100, farthest edge at most 256 smaller spans); curves and arcs measured on their shape; path data a browser would not read whole refused; a view drawn on a clean drawing without either has no frame. Measured on the views whose drawing reads clean; the document is never rewritten (owner brief 2026-10-30, RUST.md §12.11) | yes | | | `verification.validation.out_of_frame` (issues `annotation.geometry.out_of_frame`, `view.frame.unknown`) | | Every annotation in frame shows at least 4 CSS px on the smallest preview, the editor at 320 × 568 (main view box 286 × 310, detail view box 254 × 191, `xMidYMid meet`): a point's visible disc (`2 × max(2, r − 12)`), a trigger circle's diameter, a polygon's or a path's smaller side (curves and arcs on their shape). Same views, same frame; the document is never rewritten (owner brief 2026-11-01, RUST.md §12.13) | yes | | | `verification.validation.marker_too_small` (issue `annotation.geometry.too_small`) | +| Every polygon or path annotation in frame fills a disc of 4 CSS px on the same preview: under the `nonzero` rule the layer fills with, its stroke left out, a centre inside the fill at least the radius from every edge (closing edges included), curves and arcs cut into chords whose deviation is taken off; measured within `interior::MAX_OUTLINE_VERTICES` 4 096 vertices and one budget of `2²⁵` edge distances per sheet, refused past them; refused in doubt (owner brief « fermeture du dernier MEDIUM » 2026-11-01, RUST.md §12.14) | yes | | | `verification.validation.marker_interior_too_small` (issue `annotation.geometry.interior_too_small`) | | Fingerprint computed | yes | | | `verification.integrity.fingerprint` | | Verdict passed, on the current revision | | yes | yes | `verdict.missing`, `verdict.failed`, `verdict.stale` | | No `to_confirm` element (D2) | | yes | yes | `publish.to_confirm.open` |