Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): correct brush stroke geometry at large sizes

joshistoastc444dc5601d7
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts
index c9eff1ac48..f41ce9fb97 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts
@@ -1,7 +1,19 @@
import type { StrokeSamplePoint } from '@workbench/canvas-engine/freehand';
import type { Vec2 } from '@workbench/canvas-engine/types';
-import { polygonBounds, polygonToSvgPath, strokeOutlinePolygon, strokeToPath } from '@workbench/canvas-engine/freehand';
+import {
+ decimateSamples,
+ MAX_SAMPLE_SPACING,
+ outlineSmoothing,
+ PATH_ROUNDING_TOLERANCE,
+ polygonBounds,
+ polygonToSmoothSvgPath,
+ polygonToSvgPath,
+ sampleSpacing,
+ strokeOutlinePolygon,
+ strokeToPath,
+ TARGET_VERTEX_SPACING,
+} from '@workbench/canvas-engine/freehand';
import { describe, expect, it } from 'vitest';
/** Signed polygon area (shoelace); sign indicates winding, magnitude the area. */
@@ -18,6 +30,77 @@ const signedArea = (polygon: readonly Vec2[]): number => {
const horizontalLine = (pressure: number): StrokeSamplePoint[] =>
Array.from({ length: 9 }, (_, i) => ({ pressure, x: 10 + i * 10, y: 50 }));
+/** Deterministic LCG in [-0.5, 0.5), so jitter fixtures are reproducible. */
+const noise = (seed: number): (() => number) => {
+ let state = seed;
+ return () => {
+ state = (state * 1103515245 + 12345) & 0x7fffffff;
+ return state / 0x7fffffff - 0.5;
+ };
+};
+
+/**
+ * A slow, near-straight drag advancing `speed` document units per sample. Below
+ * ~0.5 units/sample the jitter dominates the direction vector — the regime that
+ * used to fill the outline with spurious full-radius corner caps.
+ */
+const slowDrag = (speed: number, jitter: number): StrokeSamplePoint[] => {
+ const rand = noise(7);
+ return Array.from({ length: 400 }, (_, i) => ({
+ pressure: 0.5,
+ x: i * speed + rand() * jitter,
+ y: rand() * jitter,
+ }));
+};
+
+/** An arc of `sweep` radians at `radius`, sampled every ~4 document units. */
+const arc = (radius: number, sweep: number): StrokeSamplePoint[] => {
+ const step = 4 / radius;
+ const points: StrokeSamplePoint[] = [];
+ for (let a = 0; a <= sweep; a += step) {
+ points.push({ pressure: 0.5, x: radius * Math.cos(a), y: radius * Math.sin(a) });
+ }
+ return points;
+};
+
+/**
+ * The edge lengths along the body of a stroke outline — how coarsely it
+ * approximates the offset curve, which under any serialization is the visible
+ * faceting. Edges within `size` of either end are excluded: the caps are drawn
+ * with a fixed segment count rather than by the vertex cull, so they say nothing
+ * about body density.
+ */
+const bodyEdgeLengths = (polygon: readonly Vec2[], points: readonly StrokeSamplePoint[], size: number): number[] => {
+ const ends = [points[0]!, points[points.length - 1]!];
+ const lengths: number[] = [];
+ for (let i = 0; i < polygon.length; i++) {
+ const a = polygon[i]!;
+ const b = polygon[(i + 1) % polygon.length]!;
+ const inCap = [a, b].some((q) => ends.some((e) => Math.hypot(q.x - e.x, q.y - e.y) < size));
+ if (!inCap) {
+ lengths.push(Math.hypot(b.x - a.x, b.y - a.y));
+ }
+ }
+ return lengths;
+};
+
+/** Total vertical extent of an outline where it crosses the vertical line at `x`. */
+const widthAt = (polygon: readonly Vec2[], x: number): number => {
+ let lo = Infinity;
+ let hi = -Infinity;
+ for (let i = 0; i < polygon.length; i++) {
+ const a = polygon[i]!;
+ const b = polygon[(i + 1) % polygon.length]!;
+ if ((a.x - x) * (b.x - x) > 0) {
+ continue;
+ }
+ const y = a.x === b.x ? a.y : a.y + ((x - a.x) / (b.x - a.x)) * (b.y - a.y);
+ lo = Math.min(lo, y);
+ hi = Math.max(hi, y);
+ }
+ return hi - lo;
+};
+
describe('strokeOutlinePolygon', () => {
it('returns an empty polygon for no points', () => {
expect(strokeOutlinePolygon([], { size: 20 })).toEqual([]);
@@ -51,6 +134,119 @@ describe('strokeOutlinePolygon', () => {
});
});
+describe('decimateSamples', () => {
+ const dense = (): StrokeSamplePoint[] => Array.from({ length: 50 }, (_, i) => ({ pressure: 0.5, x: i * 0.25, y: 0 }));
+
+ it('always keeps the first sample', () => {
+ expect(decimateSamples(dense(), 4, false)[0]).toEqual({ pressure: 0.5, x: 0, y: 0 });
+ expect(decimateSamples([], 4, true)).toEqual([]);
+ });
+
+ it('keeps retained samples at least `spacing` apart', () => {
+ const kept = decimateSamples(dense(), 4, false);
+ expect(kept.length).toBeGreaterThan(1);
+ expect(kept.length).toBeLessThan(50);
+ for (let i = 1; i < kept.length; i++) {
+ expect(Math.hypot(kept[i]!.x - kept[i - 1]!.x, kept[i]!.y - kept[i - 1]!.y)).toBeGreaterThanOrEqual(4);
+ }
+ });
+
+ it('lands on the final sample only once the stroke is complete', () => {
+ const points = dense();
+ const final = points[points.length - 1]!;
+ expect(decimateSamples(points, 4, false)).not.toContain(final);
+ expect(decimateSamples(points, 4, true)).toContain(final);
+ });
+
+ it('retains a prefix of the full result for any prefix of the input', () => {
+ // The greedy scan is what keeps already-drawn geometry from shifting as new
+ // samples arrive mid-gesture.
+ const points = dense();
+ const full = decimateSamples(points, 4, false);
+ for (const n of [5, 17, 33]) {
+ const partial = decimateSamples(points.slice(0, n), 4, false);
+ expect(full.slice(0, partial.length)).toEqual(partial);
+ }
+ });
+});
+
+describe('sampleSpacing', () => {
+ it('scales with the brush but stays within its floor and ceiling', () => {
+ expect(sampleSpacing(10)).toBe(1);
+ expect(sampleSpacing(100)).toBe(2);
+ expect(sampleSpacing(2000)).toBe(MAX_SAMPLE_SPACING);
+ });
+
+ it('never gates more coarsely than the outline it feeds', () => {
+ for (const size of [1, 20, 200, 2000]) {
+ expect(sampleSpacing(size)).toBeLessThan(TARGET_VERTEX_SPACING);
+ }
+ });
+});
+
+describe('outlineSmoothing', () => {
+ it('leaves small brushes on the library default', () => {
+ expect(outlineSmoothing(1)).toBe(0.5);
+ expect(outlineSmoothing(16)).toBe(0.5);
+ });
+
+ it('holds the size × smoothing product — the vertex cull — near the target', () => {
+ for (const size of [100, 400, 2000]) {
+ expect(size * outlineSmoothing(size)).toBeCloseTo(TARGET_VERTEX_SPACING);
+ }
+ });
+});
+
+describe('stroke quality at large brush sizes', () => {
+ it('does not let pointer jitter inflate the outline (spurious corner caps)', () => {
+ // Each >90° direction reversal splices a cap of the CURRENT radius into the
+ // outline, so jitter used to add hundreds of full-size lumps to a big brush.
+ const jittery = slowDrag(0.2, 1);
+ const clean = slowDrag(0.2, 0);
+ for (const size of [20, 100, 400, 1000, 2000]) {
+ const withJitter = strokeOutlinePolygon(jittery, { size, thinning: 0 }).length;
+ const without = strokeOutlinePolygon(clean, { size, thinning: 0 }).length;
+ expect(withJitter).toBeLessThanOrEqual(without * 2);
+ }
+ });
+
+ it('keeps outline vertex spacing bounded independently of brush size', () => {
+ // The library culls outline vertices closer than (size × smoothing), so a
+ // constant smoothing lets spacing — and with it the faceting — grow with the
+ // brush. On this arc a 400px brush used to reach 200-unit edges.
+ const curve = arc(1000, Math.PI / 2);
+ for (const size of [50, 200, 400]) {
+ const polygon = strokeOutlinePolygon(curve, { size, thinning: 0 });
+ const edges = bodyEdgeLengths(polygon, curve, size);
+ expect(edges.length).toBeGreaterThan(10);
+ expect(Math.max(...edges)).toBeLessThanOrEqual(TARGET_VERTEX_SPACING * 2);
+ }
+ });
+
+ it('tracks pressure from the start of a large-brush stroke', () => {
+ // The library's start-of-stroke noise gate drops every intermediate point —
+ // and so every pressure reading — until the running length reaches `size`.
+ // Sized in document units instead of brush diameters, it no longer flattens
+ // the pressure ramp across the first 1000 units of a 1000px brush.
+ const size = 1000;
+ const rampLength = 300;
+ const stroke: StrokeSamplePoint[] = [];
+ for (let x = 0; x <= 1200; x += 3) {
+ stroke.push({ pressure: Math.min(1, 0.05 + x / rampLength), x, y: 0 });
+ }
+ const polygon = strokeOutlinePolygon(stroke, { last: true, size, thinning: 0.5 });
+ // At full pressure `getStrokeRadius` gives size × 0.75, so width = 1.5 × size.
+ expect(widthAt(polygon, rampLength)).toBeGreaterThan(size * 1.5 * 0.95);
+ });
+
+ it('leaves small brushes on the library defaults', () => {
+ const line = horizontalLine(0.5);
+ expect(strokeOutlinePolygon(line, { size: 20, smoothing: 0.5, thinning: 0 })).toEqual(
+ strokeOutlinePolygon(line, { size: 20, thinning: 0 })
+ );
+ });
+});
+
describe('polygonToSvgPath', () => {
it('serializes a polygon to a closed move/line path', () => {
const path = polygonToSvgPath([
@@ -66,6 +262,50 @@ describe('polygonToSvgPath', () => {
});
});
+describe('polygonToSmoothSvgPath', () => {
+ it('runs a quadratic through each vertex, between its edge midpoints', () => {
+ const path = polygonToSmoothSvgPath([
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 10, y: 10 },
+ { x: 0, y: 10 },
+ ]);
+ // Starts on the seam midpoint (between the last and first vertices) so the
+ // ring closes as smoothly as it turns.
+ expect(path).toBe('M 0 5 Q 0 0 5 0 Q 10 0 10 5 Q 10 10 5 10 Q 0 10 0 5 Z');
+ });
+
+ it('falls back to straight segments when there is no curvature to describe', () => {
+ expect(polygonToSmoothSvgPath([])).toBe('');
+ expect(polygonToSmoothSvgPath([{ x: 1, y: 2 }])).toBe('M 1 2 Z');
+ expect(
+ polygonToSmoothSvgPath([
+ { x: 0, y: 0 },
+ { x: 4, y: 0 },
+ ])
+ ).toBe('M 0 0 L 4 0 Z');
+ });
+
+ it('stays within the polygon bounds, so the dirty rect still encloses it', () => {
+ // Every control point is a polygon vertex and every on-curve point an edge
+ // midpoint, so the curve cannot leave the polygon's convex hull — which is
+ // what lets `strokeToPath` keep reporting the polygon's bounds. Serializing
+ // rounds coordinates, which can move one half a step outside; the caller
+ // rounds the dirty rect outward to whole pixels, absorbing it.
+ const polygon = strokeOutlinePolygon(arc(1000, Math.PI / 2), { last: true, size: 400, thinning: 0 });
+ const bounds = polygonBounds(polygon);
+ const epsilon = PATH_ROUNDING_TOLERANCE;
+ for (const match of polygonToSmoothSvgPath(polygon).matchAll(/(-?[\d.]+) (-?[\d.]+)/g)) {
+ const x = Number(match[1]);
+ const y = Number(match[2]);
+ expect(x).toBeGreaterThanOrEqual(bounds.x - epsilon);
+ expect(x).toBeLessThanOrEqual(bounds.x + bounds.width + epsilon);
+ expect(y).toBeGreaterThanOrEqual(bounds.y - epsilon);
+ expect(y).toBeLessThanOrEqual(bounds.y + bounds.height + epsilon);
+ }
+ });
+});
+
describe('strokeToPath', () => {
it('builds the path via the injected factory and returns the polygon bounds', () => {
const seen: string[] = [];
@@ -79,6 +319,9 @@ describe('strokeToPath', () => {
expect(result.path).toBe(marker);
expect(seen).toHaveLength(1);
expect(seen[0]).toMatch(/^M /);
+ // The smooth serialization — straight joins would show as facets at size.
+ expect(seen[0]).toContain(' Q ');
+ expect(seen[0]).toBe(polygonToSmoothSvgPath(result.polygon));
expect(result.polygon.length).toBeGreaterThan(2);
expect(result.bounds).toEqual(polygonBounds(result.polygon));
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
index 83e57cd3d4..e8ddc23da8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts
@@ -8,12 +8,45 @@
* `createPath2D` factory (the engine passes `(d) => new Path2D(d)`; tests pass a
* stub). This keeps the interesting geometry testable without a DOM.
*
+ * ## Why this isn't a bare `getStroke` call
+ *
+ * `perfect-freehand` is tuned for pen-sized strokes; driven naively it degrades
+ * badly as the brush diameter grows, in three independent ways. Each is
+ * corrected here, and each correction is a no-op at small sizes:
+ *
+ * 1. **Input decimation** ({@link decimateSamples}). The library flags any turn
+ * sharper than 90° between consecutive point vectors as a corner and splices
+ * a cap of the CURRENT RADIUS into the outline. Nothing upstream decimates
+ * pointer input, so once the pointer advances less than ~0.5 document units
+ * per sample — a slow drag, a high-rate pen, or any zoom above ~2×, since
+ * document units per screen pixel shrink with zoom — sub-pixel jitter
+ * dominates the direction vector and fires those reversals constantly. At a
+ * 10px brush the spurious caps are invisible; at a 1000px brush each one is a
+ * 500px-radius lump. Distance-gating the samples removes them outright.
+ *
+ * 2. **Size-relative smoothing** ({@link outlineSmoothing}). `smoothing` feeds
+ * exactly one thing in the library: the `(size * smoothing)²` outline-vertex
+ * cull. Left at a constant, vertex spacing scales with the brush, so a large
+ * brush traces a smooth arc with edges hundreds of units long. Pinning the
+ * PRODUCT instead holds spacing near {@link TARGET_VERTEX_SPACING}.
+ *
+ * 3. **A decoupled start gate** ({@link START_GATE_SIZE}). `getStrokePoints`
+ * drops every intermediate point until the running length reaches `size`, to
+ * suppress start-of-stroke noise. Since `size` is the brush diameter, a 400px
+ * brush renders the first 400 document units as one straight capsule. Running
+ * the two library stages separately lets that gate keep its small absolute
+ * value while the outline stage gets the real diameter.
+ *
+ * Finally, the outline is serialized with quadratic curves
+ * ({@link polygonToSmoothSvgPath}) rather than the straight segments the lasso
+ * wants, so whatever facets remain read as curves.
+ *
* Zero React, zero import-time side effects.
*/
import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
-import { getStroke } from 'perfect-freehand';
+import { getStrokeOutlinePoints, getStrokePoints } from 'perfect-freehand';
/** A single pressure-sampled input point for a stroke. */
export interface StrokeSamplePoint {
@@ -29,7 +62,10 @@ export interface FreehandOptions {
size: number;
/** Effect of pressure on width, [0, 1]. 0 disables pressure sensitivity. */
thinning?: number;
- /** Edge softening, [0, 1]. */
+ /**
+ * Outline vertex density, [0, 1]. Defaults to {@link outlineSmoothing} of
+ * `size`; only set this to override the size-relative default.
+ */
smoothing?: number;
/** Input smoothing / lag, [0, 1]. */
streamline?: number;
@@ -44,25 +80,147 @@ const DEFAULT_SMOOTHING = 0.5;
const DEFAULT_STREAMLINE = 0.5;
const DEFAULT_THINNING = 0.5;
+/**
+ * Target spacing (document units) between adjacent outline vertices, held
+ * roughly constant across brush sizes by {@link outlineSmoothing}.
+ *
+ * Chosen against the QUADRATIC serialization, not straight segments: at this
+ * spacing the rendered curve strays from the true offset curve by under 0.2
+ * document pixels even where the stroke turns on a 60px radius. Going finer
+ * only multiplies vertices — the outline is re-tessellated, re-serialized and
+ * re-filled on every pointer batch, so vertex count is squarely on the hot path.
+ */
+export const TARGET_VERTEX_SPACING = 24;
+
+/** Smallest spacing (document units) the input decimator will gate on. */
+export const MIN_SAMPLE_SPACING = 1;
+
+/**
+ * Largest spacing (document units) the input decimator will gate on. Kept well
+ * under {@link TARGET_VERTEX_SPACING} so decimation can never drop detail the
+ * outline it feeds could have represented.
+ */
+export const MAX_SAMPLE_SPACING = 8;
+
+/** Fraction of the brush diameter used as the input decimation spacing. */
+const SAMPLE_SPACING_RATIO = 0.02;
+
+/**
+ * Diameter (document units) handed to `getStrokePoints` purely to size its
+ * start-of-stroke noise gate — see the module docs. Never the real brush size.
+ */
+export const START_GATE_SIZE = 24;
+
+/**
+ * Coordinate precision (decimal places) used when serializing a stroke path.
+ *
+ * Layer caches are 1:1 with document pixels, so a hundredth of a unit is two
+ * orders of magnitude below anything the rasterizer can resolve — while full
+ * float precision costs ~25 characters per vertex in a string that is rebuilt
+ * and re-parsed into a `Path2D` on every pointer batch.
+ */
+const PATH_PRECISION = 100;
+
+/**
+ * The most a serialized coordinate can move from its exact value — half a
+ * precision step. A serialized path can therefore sit this far outside
+ * {@link polygonBounds}, which callers absorb by rounding the rect outward
+ * (`roundOut`) before using it as a dirty region.
+ */
+export const PATH_ROUNDING_TOLERANCE = 0.5 / PATH_PRECISION;
+
+/** Rounds a coordinate to {@link PATH_PRECISION} for path serialization. */
+const round = (value: number): number => Math.round(value * PATH_PRECISION) / PATH_PRECISION;
+
+/** Squared distance between two sample points. */
+const dist2 = (a: StrokeSamplePoint, b: StrokeSamplePoint): number => {
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ return dx * dx + dy * dy;
+};
+
+/** Minimum spacing (document units) between retained input samples for `size`. */
+export const sampleSpacing = (size: number): number =>
+ Math.min(MAX_SAMPLE_SPACING, Math.max(MIN_SAMPLE_SPACING, size * SAMPLE_SPACING_RATIO));
+
+/**
+ * The `smoothing` value that holds outline vertex spacing near
+ * {@link TARGET_VERTEX_SPACING} for a stroke of diameter `size`. Falls back to
+ * the library's own {@link DEFAULT_SMOOTHING} for brushes small enough that it
+ * already yields tight enough spacing.
+ */
+export const outlineSmoothing = (size: number): number =>
+ Math.min(DEFAULT_SMOOTHING, TARGET_VERTEX_SPACING / Math.max(size, 1));
+
+/**
+ * Drops input samples closer together than `spacing` (document units) so
+ * sub-pixel pointer jitter can't masquerade as a direction reversal — see the
+ * module docs.
+ *
+ * The scan is greedy left-to-right, so the samples retained for a prefix of
+ * `points` are themselves a prefix of those retained for the whole array: as new
+ * samples arrive mid-gesture, already-drawn geometry never shifts. The one
+ * exception is the final sample, which is retained only once `last` is set, so
+ * the completed stroke ends exactly under the pointer. Mid-gesture the head
+ * therefore trails by at most `spacing` (≤ {@link MAX_SAMPLE_SPACING}).
+ */
+export const decimateSamples = (
+ points: readonly StrokeSamplePoint[],
+ spacing: number,
+ last: boolean
+): StrokeSamplePoint[] => {
+ const first = points[0];
+ if (!first) {
+ return [];
+ }
+ const minDistance = spacing * spacing;
+ const kept: StrokeSamplePoint[] = [first];
+ let anchor = first;
+ for (let i = 1; i < points.length; i++) {
+ const p = points[i]!;
+ if (dist2(anchor, p) >= minDistance) {
+ kept.push(p);
+ anchor = p;
+ }
+ }
+ // Land the completed stroke exactly on the last sample the pointer produced.
+ const final = points[points.length - 1]!;
+ if (last && anchor !== final) {
+ kept.push(final);
+ }
+ return kept;
+};
+
/**
* Computes the filled outline polygon (a closed ring of document-space points)
* of a variable-width stroke through `points`. Pure and DOM-free.
+ *
+ * The two `perfect-freehand` stages are driven separately so the start-of-stroke
+ * noise gate (which `getStrokePoints` derives from `size`) can keep a small
+ * absolute value while the outline is built at the real brush diameter. Passing
+ * the same `size` to both is exactly equivalent to calling `getStroke`.
*/
export const strokeOutlinePolygon = (points: readonly StrokeSamplePoint[], opts: FreehandOptions): Vec2[] => {
if (points.length === 0) {
return [];
}
- const outline = getStroke(
- points.map((p) => [p.x, p.y, p.pressure]),
+ const last = opts.last ?? false;
+ const samples = decimateSamples(points, sampleSpacing(opts.size), last);
+ const strokePoints = getStrokePoints(
+ samples.map((p) => [p.x, p.y, p.pressure]),
{
- last: opts.last ?? false,
- simulatePressure: false,
- size: opts.size,
- smoothing: opts.smoothing ?? DEFAULT_SMOOTHING,
+ last,
+ size: Math.min(opts.size, START_GATE_SIZE),
streamline: opts.streamline ?? DEFAULT_STREAMLINE,
- thinning: opts.thinning ?? DEFAULT_THINNING,
}
);
+ const outline = getStrokeOutlinePoints(strokePoints, {
+ last,
+ simulatePressure: false,
+ size: opts.size,
+ smoothing: opts.smoothing ?? outlineSmoothing(opts.size),
+ thinning: opts.thinning ?? DEFAULT_THINNING,
+ });
return outline.map(([x, y]) => ({ x, y }));
};
@@ -79,6 +237,40 @@ export const polygonToSvgPath = (polygon: readonly Vec2[]): string => {
return `${d} Z`;
};
+/**
+ * Serializes an outline polygon to a smooth closed SVG path, treating each
+ * vertex as the control point of a quadratic segment running between the
+ * midpoints of its two edges.
+ *
+ * The curve stays inside the convex hull of the polygon, so
+ * {@link polygonBounds} of the polygon bounds the rendered shape to within
+ * {@link PATH_ROUNDING_TOLERANCE} — which is what the dirty-rect accounting in
+ * the stroke session relies on, and why it rounds that rect outward. Collinear
+ * runs are reproduced exactly, so this only differs from
+ * {@link polygonToSvgPath} where the outline actually turns.
+ *
+ * Polygons with fewer than three vertices have no meaningful curvature and fall
+ * back to the straight-segment form.
+ */
+export const polygonToSmoothSvgPath = (polygon: readonly Vec2[]): string => {
+ const n = polygon.length;
+ if (n < 3) {
+ return polygonToSvgPath(polygon);
+ }
+ const midX = (a: Vec2, b: Vec2): number => round((a.x + b.x) / 2);
+ const midY = (a: Vec2, b: Vec2): number => round((a.y + b.y) / 2);
+ // Start on the seam midpoint so the ring closes as smoothly as it turns.
+ const seamA = polygon[n - 1]!;
+ const seamB = polygon[0]!;
+ let d = `M ${midX(seamA, seamB)} ${midY(seamA, seamB)}`;
+ for (let i = 0; i < n; i++) {
+ const control = polygon[i]!;
+ const next = polygon[(i + 1) % n]!;
+ d += ` Q ${round(control.x)} ${round(control.y)} ${midX(control, next)} ${midY(control, next)}`;
+ }
+ return `${d} Z`;
+};
+
/** Axis-aligned bounds of an outline polygon; an empty polygon yields a zero-size rect. */
export const polygonBounds = (polygon: readonly Vec2[]): Rect => {
if (polygon.length === 0) {
@@ -110,6 +302,11 @@ export const polygonBounds = (polygon: readonly Vec2[]): Rect => {
* `createPath2D` factory (so callers in node can stub it). Returns the built
* path and the polygon's document-space {@link Rect} bounds so the caller can
* derive the dirty region without recomputing the outline.
+ *
+ * The path is the smooth ({@link polygonToSmoothSvgPath}) serialization — the
+ * outline is a coarse sampling of a curve, so joining its vertices with straight
+ * lines would show as facets at large brush sizes. The returned bounds still
+ * come from the polygon, which encloses the curve.
*/
export const strokeToPath = (
points: readonly StrokeSamplePoint[],
@@ -117,6 +314,6 @@ export const strokeToPath = (
createPath2D: CreatePath2D
): { path: Path2D; polygon: Vec2[]; bounds: Rect } => {
const polygon = strokeOutlinePolygon(points, opts);
- const path = createPath2D(polygonToSvgPath(polygon));
+ const path = createPath2D(polygonToSmoothSvgPath(polygon));
return { bounds: polygonBounds(polygon), path, polygon };
};