diff --git a/packages/element/src/collision.ts b/packages/element/src/collision.ts index 68ff96a08e..7fe6e1f9df 100644 --- a/packages/element/src/collision.ts +++ b/packages/element/src/collision.ts @@ -8,6 +8,7 @@ import { pointFromVector, pointRotateRads, pointsEqual, + polygonIncludesPoint, vectorFromPoint, vectorNormalize, vectorScale, @@ -22,6 +23,7 @@ import type { Curve, GlobalPoint, LineSegment, + LocalPoint, Radians, } from "@excalidraw/math"; @@ -63,6 +65,8 @@ import { getBindingGap } from "./binding"; import { hasBackground } from "./comparisons"; +import { getFreedrawFillPolygon, getFreedrawMaxStrokeRadius } from "./shape"; + import type { ElementsMap, ExcalidrawArrowElement, @@ -177,7 +181,10 @@ export const hitElementItself = ({ point, bounds, element.angle, - threshold, + // Freedraw bounds follow the centerline points, but the ink extends past them + isFreeDrawElement(element) + ? threshold + getFreedrawMaxStrokeRadius(element) + : threshold, ); // PERF: Bail out early if the point is not even in the @@ -785,6 +792,26 @@ export const isPointInElement = ( return false; } + if (isFreeDrawElement(element)) { + // Test before the rotated-bounds check below: the smoothed fill can bulge + // past the recorded points, and how much of it those bounds would clip + // depends on the angle. An asymmetric loop's rotated bounds center is also + // not its rotation pivot. + const [x1, y1, x2, y2] = getElementBounds(element, elementsMap, true); + const [px, py] = pointRotateRads( + point, + pointFrom((x1 + x2) / 2, (y1 + y2) / 2), + -element.angle as Radians, + ); + + // The fill follows the centerline rather than the stroke outline, and uses + // the same even-odd rule as RoughJS's filled curves. + return polygonIncludesPoint( + pointFrom(px - element.x, py - element.y), + getFreedrawFillPolygon(element), + ); + } + const [x1, y1, x2, y2] = getElementBounds(element, elementsMap); if (!isPointWithinBounds(pointFrom(x1, y1), point, pointFrom(x2, y2))) { diff --git a/packages/element/src/distance.ts b/packages/element/src/distance.ts index b7fc11e953..1206569c3e 100644 --- a/packages/element/src/distance.ts +++ b/packages/element/src/distance.ts @@ -2,6 +2,7 @@ import { curvePointDistance, distanceToLineSegment, pointRotateRads, + polygonIncludesPointNonZero, } from "@excalidraw/math"; import { ellipse, ellipseDistanceFromPoint } from "@excalidraw/math/ellipse"; @@ -48,8 +49,9 @@ export const distanceToElement = ( return distanceToEllipseElement(element, elementsMap, p); case "line": case "arrow": - case "freedraw": return distanceToLinearOrFreeDraElement(element, elementsMap, p); + case "freedraw": + return distanceToFreeDrawElement(element, elementsMap, p); } }; @@ -142,3 +144,30 @@ const distanceToLinearOrFreeDraElement = ( ...curves.map((a) => curvePointDistance(a, p)), ); }; + +/** + * Returns the distance of a point to a freedraw element. + * + * @param element The freedraw element + * @param p The point to consider + * @returns 0 if the point is within the inked area, otherwise the euclidean + * distance to the stroke outline + */ +const distanceToFreeDrawElement = ( + element: ExcalidrawFreeDrawElement, + elementsMap: ElementsMap, + p: GlobalPoint, +) => { + const [lines] = deconstructLinearOrFreeDrawElement(element, elementsMap); + + if (lines.length === 0) { + return Infinity; + } + + const polygon = lines.map((line) => line[0]); + if (polygonIncludesPointNonZero(p, polygon)) { + return 0; + } + + return Math.min(...lines.map((s) => distanceToLineSegment(p, s))); +}; diff --git a/packages/element/src/shape.ts b/packages/element/src/shape.ts index 7b905b4e07..bf699b5b3c 100644 --- a/packages/element/src/shape.ts +++ b/packages/element/src/shape.ts @@ -1,4 +1,4 @@ -import { simplify } from "points-on-curve"; +import { pointsOnBezierCurves, simplify } from "points-on-curve"; import { getStroke, getStrokePoints } from "perfect-freehand"; import { LaserPointer } from "@excalidraw/laser-pointer"; @@ -16,6 +16,7 @@ import { pointDistance, type LocalPoint, pointRotateRads, + polygonFromPoints, } from "@excalidraw/math"; import { ROUGHNESS, @@ -30,7 +31,7 @@ import { import { RoughGenerator } from "roughjs/bin/generator"; -import type { GlobalPoint } from "@excalidraw/math"; +import type { GlobalPoint, Polygon } from "@excalidraw/math"; import type { Mutable } from "@excalidraw/common/utility-types"; @@ -575,6 +576,48 @@ const getArrowheadShapes = ( } }; +/** The simplified centerline the freedraw fill is drawn along. */ +const getFreedrawFillCurvePoints = (element: ExcalidrawFreeDrawElement) => + simplify(element.points as Mutable, 0.75) as [number, number][]; + +const freedrawFillPolygonCache = new WeakMap< + ExcalidrawFreeDrawElement, + { version: number; polygon: Polygon } +>(); + +/** + * Returns the flattened fill contour of a freedraw loop in local, unrotated + * coordinates, following the rendered fill rather than the stroke outline. + */ +export const getFreedrawFillPolygon = (element: ExcalidrawFreeDrawElement) => { + const cached = freedrawFillPolygonCache.get(element); + if (cached?.version === element.version) { + return cached.polygon; + } + + // Same curve as the rendered fill, without roughness jitter. RoughJS also + // handles inputs simplified to two points. + const ops = new RoughGenerator().curve(getFreedrawFillCurvePoints(element), { + roughness: 0, + disableMultiStroke: true, + }).sets[0].ops; + const bezierPoints: LocalPoint[] = []; + // A single curve pass consists of a move followed by cubic control points. + for (const { data } of ops) { + for (let i = 0; i < data.length; i += 2) { + bezierPoints.push(pointFrom(data[i], data[i + 1])); + } + } + + // Omit the optional distance argument to avoid simplifying the boundary again. + const polygon = polygonFromPoints( + pointsOnBezierCurves(bezierPoints, 0.5) as LocalPoint[], + ); + freedrawFillPolygonCache.set(element, { version: element.version, polygon }); + + return polygon; +}; + export const generateLinearCollisionShape = ( element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement, elementsMap: ElementsMap, @@ -675,69 +718,44 @@ export const generateLinearCollisionShape = ( }); } case "freedraw": { - if (element.points.length < 2) { + const outlinePoints = getFreedrawOutlinePoints(element); + + if (outlinePoints.length < 2) { return []; } - const simplifiedPoints = simplify( - element.points as Mutable, - 0.75, - ); + const collisionOutline = + element.strokeOptions?.variability === "constant" + ? (simplify( + outlinePoints as Mutable, + CONSTANT_WIDTH_FREEDRAW.COLLISION_SIMPLIFY_TOLERANCE, + ) as [number, number][]) + : outlinePoints; - return generator - .curve(simplifiedPoints as [number, number][], options) - .sets[0].ops.slice(0, element.points.length) - .map((op, i) => { - if (i === 0) { - const p = pointRotateRads( - pointFrom( - element.x + op.data[0], - element.y + op.data[1], - ), - center, - element.angle, - ); + if (collisionOutline.length < 2) { + return []; + } - return { - op: "move", - data: pointFrom(p[0] - element.x, p[1] - element.y), - }; - } + // Close the outline polygon so its boundary never has a gap at the seam. + const [firstX, firstY] = collisionOutline[0]; + const [lastX, lastY] = collisionOutline[collisionOutline.length - 1]; + const closedOutline = + firstX === lastX && firstY === lastY + ? collisionOutline + : [...collisionOutline, collisionOutline[0]]; - return { - op: "bcurveTo", - data: [ - pointRotateRads( - pointFrom( - element.x + op.data[0], - element.y + op.data[1], - ), - center, - element.angle, - ), - pointRotateRads( - pointFrom( - element.x + op.data[2], - element.y + op.data[3], - ), - center, - element.angle, - ), - pointRotateRads( - pointFrom( - element.x + op.data[4], - element.y + op.data[5], - ), - center, - element.angle, - ), - ] - .map((p) => - pointFrom(p[0] - element.x, p[1] - element.y), - ) - .flat(), - }; - }); + return closedOutline.map((point, idx) => { + const p = pointRotateRads( + pointFrom(element.x + point[0], element.y + point[1]), + center, + element.angle, + ); + + return { + op: idx === 0 ? "move" : "lineTo", + data: pointFrom(p[0] - element.x, p[1] - element.y), + }; + }); } } }; @@ -962,12 +980,8 @@ const _generateElementShape = ( // (1) background fill (rc shape), optional if (isPathALoop(element.points)) { // generate rough polygon to fill freedraw shape - const simplifiedPoints = simplify( - element.points as Mutable, - 0.75, - ); shapes.push( - generator.curve(simplifiedPoints as [number, number][], { + generator.curve(getFreedrawFillCurvePoints(element), { ...generateRoughOptions(element, false, isDarkMode), stroke: "none", }), @@ -1193,6 +1207,11 @@ const VARIABLE_WIDTH_FREEDRAW = { const CONSTANT_WIDTH_FREEDRAW = { /** Stroke size relative to `strokeWidth` for uniform (laser) strokes. */ SIZE_FACTOR: 1.4, + /** + * Max deviation (px) when dropping vertices of the dense laser outline for + * collision. Perfect-freehand outlines are already thinned by `smoothing`. + */ + COLLISION_SIMPLIFY_TOLERANCE: 0.2, } as const; const getFreedrawStreamline = (element: ExcalidrawFreeDrawElement) => @@ -1257,6 +1276,21 @@ export const getFreedrawOutlinePoints = ( : getVariableWidthFreedrawOutline(element); }; +/** + * Upper bound on how far a freedraw stroke's ink reaches past its centerline + * points. Both stroke generators scale the stroke size by at most 1 (easing + * or pressure), so the size itself bounds the radius, except for + * perfect-freehand's short strokes: under 3px long, the start cap is drawn + * around the first point from an outline point of the last one (reaching + * sqrt(size² + 3²)), and a single point gets a synthetic neighbor 1px away. + */ +export const getFreedrawMaxStrokeRadius = ( + element: ExcalidrawFreeDrawElement, +) => + element.strokeOptions?.variability === "constant" + ? element.strokeWidth * CONSTANT_WIDTH_FREEDRAW.SIZE_FACTOR + : element.strokeWidth * VARIABLE_WIDTH_FREEDRAW.SIZE_FACTOR + 3; + /** * The streamline-smoothed centerline the freedraw stroke is rendered * around, in element-local coordinates. Boundary-sensitive consumers (e.g. diff --git a/packages/element/tests/collision.test.tsx b/packages/element/tests/collision.test.tsx index a44f1f7bb0..d2f303ef1e 100644 --- a/packages/element/tests/collision.test.tsx +++ b/packages/element/tests/collision.test.tsx @@ -1,5 +1,10 @@ -import { arrayToMap, reseed } from "@excalidraw/common"; -import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math"; +import { arrayToMap, getSizeFromPoints, reseed } from "@excalidraw/common"; +import { + type GlobalPoint, + type LocalPoint, + pointFrom, + pointRotateRads, +} from "@excalidraw/math"; import { Excalidraw } from "@excalidraw/excalidraw"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { UI } from "@excalidraw/excalidraw/tests/helpers/ui"; @@ -7,7 +12,10 @@ import "@excalidraw/utils/test-utils"; import { render } from "@excalidraw/excalidraw/tests/test-utils"; import * as distance from "../src/distance"; -import { hitElementItself } from "../src/collision"; +import { getElementBounds } from "../src/bounds"; +import { hitElementItself, isPointInElement } from "../src/collision"; +import { mutateElement } from "../src/mutateElement"; +import { newFreeDrawElement } from "../src/newElement"; describe("check rotated elements can be hit:", () => { beforeEach(async () => { @@ -218,3 +226,397 @@ describe("hitElementItself cache", () => { ).toBe(true); }); }); + +describe("freedraw collision matches the rendered stroke width", () => { + // A straight, horizontal stroke centered on y === 0. + const points = Array.from({ length: 21 }, (_, i) => + pointFrom(i * 5, 0), + ); + + const createFreeDraw = (variability: "variable" | "constant") => + API.createElement({ + type: "freedraw", + x: 0, + y: 0, + strokeWidth: 10, + points, + strokeOptions: { variability, streamline: 0.5 }, + }); + + const distanceAt = ( + element: ReturnType, + x: number, + y: number, + ) => + distance.distanceToElement( + element, + arrayToMap([element]), + pointFrom(x, y), + ); + + it("treats a point on the centerline as a direct hit for both modes", () => { + expect(distanceAt(createFreeDraw("variable"), 50, 0)).toBe(0); + expect(distanceAt(createFreeDraw("constant"), 50, 0)).toBe(0); + }); + + it("hits across the body of a thick stroke, not just near the centerline", () => { + expect(distanceAt(createFreeDraw("variable"), 50, 20)).toBe(0); + }); + + it("uses a wider hit area for variable-width than for constant-width strokes", () => { + const offset = 20; + const variableDistance = distanceAt(createFreeDraw("variable"), 50, offset); + const constantDistance = distanceAt(createFreeDraw("constant"), 50, offset); + + expect(variableDistance).toBe(0); + expect(constantDistance).toBeGreaterThan(0); + expect(variableDistance).toBeLessThan(constantDistance); + }); + + it("does not hit points clearly outside even the widest stroke", () => { + expect(distanceAt(createFreeDraw("variable"), 50, 45)).toBeGreaterThan(0); + }); + + it("hits thick ink outside the centerline bounds", () => { + const hitAt = ( + element: ReturnType, + x: number, + y: number, + ) => + hitElementItself({ + element, + elementsMap: arrayToMap([element]), + point: pointFrom(x, y), + threshold: 1, + }); + + // The centerline bounds have zero height, far below the ink's reach. + expect(hitAt(createFreeDraw("variable"), 50, 20)).toBe(true); + expect(hitAt(createFreeDraw("variable"), 50, -20)).toBe(true); + expect(hitAt(createFreeDraw("constant"), 50, 10)).toBe(true); + expect(hitAt(createFreeDraw("constant"), 50, 20)).toBe(false); + expect(hitAt(createFreeDraw("variable"), 50, 45)).toBe(false); + }); + + it("hits the start cap of a short stroke reaching past its stroke size", () => { + // Under 3px long, perfect-freehand draws the start cap around the first + // point from the last point's outline, reaching past the stroke size. + const element = newFreeDrawElement({ + type: "freedraw", + x: 0, + y: 0, + strokeWidth: 1, + simulatePressure: false, + pressures: [1, 1, 1], + points: [ + pointFrom(0, 0), + pointFrom(0.01, 0), + pointFrom(2.9, 0), + ], + strokeOptions: { variability: "variable", streamline: 0.5 }, + }); + const elementsMap = arrayToMap([element]); + const point = pointFrom(0.1, 4.9); + + expect(distance.distanceToElement(element, elementsMap, point)).toBe(0); + // The hit threshold at 30x zoom. + expect( + hitElementItself({ element, elementsMap, point, threshold: 0.6 }), + ).toBe(true); + }); +}); + +const createLoop = ({ + angle = 0, + backgroundColor = "#ffc9c9", + variability = "variable", + points = Array.from({ length: 81 }, (_, i) => + pointFrom( + 80 + 80 * Math.cos((i / 80) * 2 * Math.PI), + 40 + 40 * Math.sin((i / 80) * 2 * Math.PI), + ), + ), +}: { + angle?: number; + backgroundColor?: string; + variability?: "variable" | "constant"; + points?: LocalPoint[]; +} = {}) => + API.createElement({ + type: "freedraw", + x: 300, + y: 200, + ...getSizeFromPoints(points), + angle, + strokeWidth: 2, + backgroundColor, + fillStyle: "solid", + points, + strokeOptions: { variability, streamline: 0.5 }, + }); + +// The fill contour does not depend on the stroke; only its interplay with the +// stroke geometry is tested per stroke variability. +describe.each(["variable", "constant"] as const)( + "%s freedraw loop containment", + (variability) => { + it.each([0, Math.PI / 4])( + "hits the fill independently of the stroke at angle %s", + (angle) => { + const element = createLoop({ angle, variability }); + const elementsMap = arrayToMap([element]); + const point = pointRotateRads( + pointFrom(400, 250), + pointFrom(380, 240), + element.angle, + ); + + // Checking the fill must not replace the cached stroke geometry. + expect( + distance.distanceToElement(element, elementsMap, point), + ).toBeGreaterThan(10); + expect(isPointInElement(point, element, elementsMap)).toBe(true); + expect( + hitElementItself({ element, elementsMap, point, threshold: 1 }), + ).toBe(true); + expect( + distance.distanceToElement(element, elementsMap, point), + ).toBeGreaterThan(10); + }, + ); + + it.each([0, Math.PI / 4])( + "does not hit the interior of a transparent loop at angle %s", + (angle) => { + const element = createLoop({ + angle, + backgroundColor: "transparent", + variability, + }); + const elementsMap = arrayToMap([element]); + const point = pointRotateRads( + pointFrom(400, 250), + pointFrom(380, 240), + element.angle, + ); + + // Warm the fill cache first; it must not replace the stroke geometry. + isPointInElement(point, element, elementsMap); + expect( + hitElementItself({ element, elementsMap, point, threshold: 1 }), + ).toBe(false); + }, + ); + + it("does not treat the empty corners of the loop bounds as fill", () => { + const element = createLoop({ variability }); + const elementsMap = arrayToMap([element]); + const point = pointFrom(310, 210); + + expect(isPointInElement(point, element, elementsMap)).toBe(false); + expect( + hitElementItself({ element, elementsMap, point, threshold: 1 }), + ).toBe(false); + }); + }, +); + +describe("freedraw loop fill containment", () => { + it.each([0, Math.PI / 4])( + "hits the center and axes of a loop with curve junctions at angle %s", + (angle) => { + const element = createLoop({ angle }); + const elementsMap = arrayToMap([element]); + const center = pointFrom(380, 240); + + for (const point of [ + center, + pointFrom(400, 240), + pointFrom(380, 250), + ]) { + expect( + isPointInElement( + pointRotateRads(point, center, element.angle), + element, + elementsMap, + ), + ).toBe(true); + } + }, + ); + + it.each([0, Math.PI / 4])( + "implicitly closes the fill of an unsnapped loop at angle %s", + (angle) => { + const element = createLoop({ angle }); + const elementsMap = arrayToMap([element]); + mutateElement(element, elementsMap, { + points: [ + ...element.points.slice(0, -1), + pointFrom(160, 36), + ], + }); + const point = pointRotateRads( + pointFrom(440, 239.5), + pointFrom(380, 240), + element.angle, + ); + + expect(isPointInElement(point, element, elementsMap)).toBe(true); + }, + ); + + it("rotates around the unrotated bounds center of an asymmetric loop", () => { + const element = createLoop({ + angle: Math.PI / 4, + points: [ + pointFrom(0, 0), + pointFrom(200, 0), + pointFrom(0, 100), + pointFrom(0, 0), + ], + }); + const point = pointRotateRads( + pointFrom(330, 205), + pointFrom(400, 250), + element.angle, + ); + + expect(isPointInElement(point, element, arrayToMap([element]))).toBe(true); + }); + + it("hits smoothed fill outside the rotated bounds of the points", () => { + const element = createLoop({ + angle: (2 * Math.PI) / 3, + points: [ + pointFrom(0, 0), + pointFrom(200, 0), + pointFrom(0, 100), + pointFrom(0, 0), + ], + }); + const elementsMap = arrayToMap([element]); + // Outside the raw triangle, inside the curve bulging past its hypotenuse. + const point = pointRotateRads( + pointFrom(436, 240), + pointFrom(400, 250), + element.angle, + ); + const [x1, y1, x2, y2] = getElementBounds(element, elementsMap); + + expect( + point[0] < x1 || point[0] > x2 || point[1] < y1 || point[1] > y2, + ).toBe(true); + expect(isPointInElement(point, element, elementsMap)).toBe(true); + expect( + hitElementItself({ element, elementsMap, point, threshold: 1 }), + ).toBe(true); + }); + + it.each([ + { + name: "a three-point retraced path", + points: [ + pointFrom(0, 0), + pointFrom(100, 100), + pointFrom(0, 0), + ], + point: pointFrom(350, 250), + }, + { + name: "a loop that simplifies to two identical points", + points: [ + pointFrom(0, 0), + pointFrom(0.3, 0), + pointFrom(0.3, 0.3), + pointFrom(0, 0.3), + pointFrom(0, 0), + ], + point: pointFrom(300.15, 200.15), + }, + ])("contains nothing for $name", ({ points, point }) => { + const element = createLoop({ points }); + + expect(isPointInElement(point, element, arrayToMap([element]))).toBe(false); + }); + + it("preserves the curved fill of a nearly closed three-point path", () => { + const element = createLoop({ + points: [ + pointFrom(0, 0), + pointFrom(100, 100), + pointFrom(3, 0), + ], + }); + + expect( + isPointInElement( + pointFrom(350, 250), + element, + arrayToMap([element]), + ), + ).toBe(true); + }); + + it("includes the smoothed fill beyond the raw-point polygon", () => { + const element = createLoop({ + points: [ + pointFrom(200, 100), + pointFrom(100, 200), + pointFrom(0, 100), + pointFrom(100, 0), + pointFrom(200, 100), + ], + }); + + expect( + isPointInElement( + pointFrom(305, 285), + element, + arrayToMap([element]), + ), + ).toBe(true); + }); + + it("uses even-odd fill for a self-intersecting loop", () => { + const element = createLoop({ + points: Array.from({ length: 6 }, (_, i) => { + const angle = -Math.PI / 2 + (((i * 2) % 5) / 5) * 2 * Math.PI; + return pointFrom( + 100 + 95 * Math.cos(angle), + 100 + 95 * Math.sin(angle), + ); + }), + }); + + expect( + isPointInElement( + pointFrom(400, 300), + element, + arrayToMap([element]), + ), + ).toBe(false); + }); + + it("invalidates the fill contour when points change on the same element", () => { + const element = createLoop(); + const elementsMap = arrayToMap([element]); + const point = pointFrom(415, 255); + const version = element.version; + + expect(isPointInElement(point, element, elementsMap)).toBe(true); + + // Preserve the bounds so a stale contour cannot hide behind that pre-check. + mutateElement(element, elementsMap, { + points: [ + pointFrom(0, 0), + pointFrom(160, 0), + pointFrom(0, 80), + pointFrom(0, 0), + ], + }); + + expect(element.version).toBeGreaterThan(version); + expect(isPointInElement(point, element, elementsMap)).toBe(false); + }); +}); diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsx index 64ec933d90..a016a2eb98 100644 --- a/packages/excalidraw/tests/selection.test.tsx +++ b/packages/excalidraw/tests/selection.test.tsx @@ -712,6 +712,41 @@ describe("box-selection overlap mode", () => { assertSelectedElements([]); }); + it.each(["variable", "constant"] as const)( + "should select and drag a filled %s freedraw loop from its interior", + (variability) => { + const freedraw = API.createElement({ + type: "freedraw", + x: 100, + y: 100, + width: 200, + height: 100, + backgroundColor: "#ffc9c9", + fillStyle: "solid", + strokeOptions: { variability, streamline: 0.5 }, + points: [ + pointFrom(0, 0), + pointFrom(200, 0), + pointFrom(200, 100), + pointFrom(0, 100), + pointFrom(0, 0), + ], + }); + + API.setElements([freedraw]); + + mouse.clickAt(203, 152); + assertSelectedElements([freedraw.id]); + + mouse.downAt(203, 152); + mouse.moveTo(233, 172); + mouse.up(); + + expect(API.getElement(freedraw)).toMatchObject({ x: 130, y: 120 }); + assertSelectedElements([freedraw.id]); + }, + ); + it("should not select a freedraw when the selection box only overlaps its bounds", () => { const freedraw = API.createElement({ type: "freedraw",