collision.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. import * as GA from "../ga";
  2. import * as GAPoint from "../gapoints";
  3. import * as GADirection from "../gadirections";
  4. import * as GALine from "../galines";
  5. import * as GATransform from "../gatransforms";
  6. import {
  7. distance2d,
  8. rotatePoint,
  9. isPathALoop,
  10. isPointInPolygon,
  11. rotate,
  12. } from "../math";
  13. import { pointsOnBezierCurves } from "points-on-curve";
  14. import {
  15. NonDeletedExcalidrawElement,
  16. ExcalidrawBindableElement,
  17. ExcalidrawElement,
  18. ExcalidrawRectangleElement,
  19. ExcalidrawDiamondElement,
  20. ExcalidrawTextElement,
  21. ExcalidrawEllipseElement,
  22. NonDeleted,
  23. ExcalidrawFreeDrawElement,
  24. ExcalidrawImageElement,
  25. } from "./types";
  26. import { getElementAbsoluteCoords, getCurvePathOps, Bounds } from "./bounds";
  27. import { Point } from "../types";
  28. import { Drawable } from "roughjs/bin/core";
  29. import { AppState } from "../types";
  30. import { getShapeForElement } from "../renderer/renderElement";
  31. import { isImageElement } from "./typeChecks";
  32. const isElementDraggableFromInside = (
  33. element: NonDeletedExcalidrawElement,
  34. ): boolean => {
  35. if (element.type === "arrow") {
  36. return false;
  37. }
  38. if (element.type === "freedraw") {
  39. return true;
  40. }
  41. const isDraggableFromInside = element.backgroundColor !== "transparent";
  42. if (element.type === "line") {
  43. return isDraggableFromInside && isPathALoop(element.points);
  44. }
  45. return isDraggableFromInside || isImageElement(element);
  46. };
  47. export const hitTest = (
  48. element: NonDeletedExcalidrawElement,
  49. appState: AppState,
  50. x: number,
  51. y: number,
  52. ): boolean => {
  53. // How many pixels off the shape boundary we still consider a hit
  54. const threshold = 10 / appState.zoom.value;
  55. const point: Point = [x, y];
  56. if (isElementSelected(appState, element)) {
  57. return isPointHittingElementBoundingBox(element, point, threshold);
  58. }
  59. return isHittingElementNotConsideringBoundingBox(element, appState, point);
  60. };
  61. export const isHittingElementBoundingBoxWithoutHittingElement = (
  62. element: NonDeletedExcalidrawElement,
  63. appState: AppState,
  64. x: number,
  65. y: number,
  66. ): boolean => {
  67. const threshold = 10 / appState.zoom.value;
  68. return (
  69. !isHittingElementNotConsideringBoundingBox(element, appState, [x, y]) &&
  70. isPointHittingElementBoundingBox(element, [x, y], threshold)
  71. );
  72. };
  73. export const isHittingElementNotConsideringBoundingBox = (
  74. element: NonDeletedExcalidrawElement,
  75. appState: AppState,
  76. point: Point,
  77. ): boolean => {
  78. const threshold = 10 / appState.zoom.value;
  79. const check =
  80. element.type === "text"
  81. ? isStrictlyInside
  82. : isElementDraggableFromInside(element)
  83. ? isInsideCheck
  84. : isNearCheck;
  85. return hitTestPointAgainstElement({ element, point, threshold, check });
  86. };
  87. const isElementSelected = (
  88. appState: AppState,
  89. element: NonDeleted<ExcalidrawElement>,
  90. ) => appState.selectedElementIds[element.id];
  91. const isPointHittingElementBoundingBox = (
  92. element: NonDeleted<ExcalidrawElement>,
  93. [x, y]: Point,
  94. threshold: number,
  95. ) => {
  96. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  97. const elementCenterX = (x1 + x2) / 2;
  98. const elementCenterY = (y1 + y2) / 2;
  99. // reverse rotate to take element's angle into account.
  100. const [rotatedX, rotatedY] = rotate(
  101. x,
  102. y,
  103. elementCenterX,
  104. elementCenterY,
  105. -element.angle,
  106. );
  107. return (
  108. rotatedX > x1 - threshold &&
  109. rotatedX < x2 + threshold &&
  110. rotatedY > y1 - threshold &&
  111. rotatedY < y2 + threshold
  112. );
  113. };
  114. export const bindingBorderTest = (
  115. element: NonDeleted<ExcalidrawBindableElement>,
  116. { x, y }: { x: number; y: number },
  117. ): boolean => {
  118. const threshold = maxBindingGap(element, element.width, element.height);
  119. const check = isOutsideCheck;
  120. const point: Point = [x, y];
  121. return hitTestPointAgainstElement({ element, point, threshold, check });
  122. };
  123. export const maxBindingGap = (
  124. element: ExcalidrawElement,
  125. elementWidth: number,
  126. elementHeight: number,
  127. ): number => {
  128. // Aligns diamonds with rectangles
  129. const shapeRatio = element.type === "diamond" ? 1 / Math.sqrt(2) : 1;
  130. const smallerDimension = shapeRatio * Math.min(elementWidth, elementHeight);
  131. // We make the bindable boundary bigger for bigger elements
  132. return Math.max(16, Math.min(0.25 * smallerDimension, 32));
  133. };
  134. type HitTestArgs = {
  135. element: NonDeletedExcalidrawElement;
  136. point: Point;
  137. threshold: number;
  138. check: (distance: number, threshold: number) => boolean;
  139. };
  140. const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
  141. switch (args.element.type) {
  142. case "rectangle":
  143. case "image":
  144. case "text":
  145. case "diamond":
  146. case "ellipse":
  147. const distance = distanceToBindableElement(args.element, args.point);
  148. return args.check(distance, args.threshold);
  149. case "freedraw": {
  150. if (
  151. !args.check(
  152. distanceToRectangle(args.element, args.point),
  153. args.threshold,
  154. )
  155. ) {
  156. return false;
  157. }
  158. return hitTestFreeDrawElement(args.element, args.point, args.threshold);
  159. }
  160. case "arrow":
  161. case "line":
  162. return hitTestLinear(args);
  163. case "selection":
  164. console.warn(
  165. "This should not happen, we need to investigate why it does.",
  166. );
  167. return false;
  168. }
  169. };
  170. export const distanceToBindableElement = (
  171. element: ExcalidrawBindableElement,
  172. point: Point,
  173. ): number => {
  174. switch (element.type) {
  175. case "rectangle":
  176. case "image":
  177. case "text":
  178. return distanceToRectangle(element, point);
  179. case "diamond":
  180. return distanceToDiamond(element, point);
  181. case "ellipse":
  182. return distanceToEllipse(element, point);
  183. }
  184. };
  185. const isStrictlyInside = (distance: number, threshold: number): boolean => {
  186. return distance < 0;
  187. };
  188. const isInsideCheck = (distance: number, threshold: number): boolean => {
  189. return distance < threshold;
  190. };
  191. const isNearCheck = (distance: number, threshold: number): boolean => {
  192. return Math.abs(distance) < threshold;
  193. };
  194. const isOutsideCheck = (distance: number, threshold: number): boolean => {
  195. return 0 <= distance && distance < threshold;
  196. };
  197. const distanceToRectangle = (
  198. element:
  199. | ExcalidrawRectangleElement
  200. | ExcalidrawTextElement
  201. | ExcalidrawFreeDrawElement
  202. | ExcalidrawImageElement,
  203. point: Point,
  204. ): number => {
  205. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  206. return Math.max(
  207. GAPoint.distanceToLine(pointRel, GALine.equation(0, 1, -hheight)),
  208. GAPoint.distanceToLine(pointRel, GALine.equation(1, 0, -hwidth)),
  209. );
  210. };
  211. const distanceToDiamond = (
  212. element: ExcalidrawDiamondElement,
  213. point: Point,
  214. ): number => {
  215. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  216. const side = GALine.equation(hheight, hwidth, -hheight * hwidth);
  217. return GAPoint.distanceToLine(pointRel, side);
  218. };
  219. const distanceToEllipse = (
  220. element: ExcalidrawEllipseElement,
  221. point: Point,
  222. ): number => {
  223. const [pointRel, tangent] = ellipseParamsForTest(element, point);
  224. return -GALine.sign(tangent) * GAPoint.distanceToLine(pointRel, tangent);
  225. };
  226. const ellipseParamsForTest = (
  227. element: ExcalidrawEllipseElement,
  228. point: Point,
  229. ): [GA.Point, GA.Line] => {
  230. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  231. const [px, py] = GAPoint.toTuple(pointRel);
  232. // We're working in positive quadrant, so start with `t = 45deg`, `tx=cos(t)`
  233. let tx = 0.707;
  234. let ty = 0.707;
  235. const a = hwidth;
  236. const b = hheight;
  237. // This is a numerical method to find the params tx, ty at which
  238. // the ellipse has the closest point to the given point
  239. [0, 1, 2, 3].forEach((_) => {
  240. const xx = a * tx;
  241. const yy = b * ty;
  242. const ex = ((a * a - b * b) * tx ** 3) / a;
  243. const ey = ((b * b - a * a) * ty ** 3) / b;
  244. const rx = xx - ex;
  245. const ry = yy - ey;
  246. const qx = px - ex;
  247. const qy = py - ey;
  248. const r = Math.hypot(ry, rx);
  249. const q = Math.hypot(qy, qx);
  250. tx = Math.min(1, Math.max(0, ((qx * r) / q + ex) / a));
  251. ty = Math.min(1, Math.max(0, ((qy * r) / q + ey) / b));
  252. const t = Math.hypot(ty, tx);
  253. tx /= t;
  254. ty /= t;
  255. });
  256. const closestPoint = GA.point(a * tx, b * ty);
  257. const tangent = GALine.orthogonalThrough(pointRel, closestPoint);
  258. return [pointRel, tangent];
  259. };
  260. const hitTestFreeDrawElement = (
  261. element: ExcalidrawFreeDrawElement,
  262. point: Point,
  263. threshold: number,
  264. ): boolean => {
  265. // Check point-distance-to-line-segment for every segment in the
  266. // element's points (its input points, not its outline points).
  267. // This is... okay? It's plenty fast, but the GA library may
  268. // have a faster option.
  269. let x: number;
  270. let y: number;
  271. if (element.angle === 0) {
  272. x = point[0] - element.x;
  273. y = point[1] - element.y;
  274. } else {
  275. // Counter-rotate the point around center before testing
  276. const [minX, minY, maxX, maxY] = getElementAbsoluteCoords(element);
  277. const rotatedPoint = rotatePoint(
  278. point,
  279. [minX + (maxX - minX) / 2, minY + (maxY - minY) / 2],
  280. -element.angle,
  281. );
  282. x = rotatedPoint[0] - element.x;
  283. y = rotatedPoint[1] - element.y;
  284. }
  285. let [A, B] = element.points;
  286. let P: readonly [number, number];
  287. // For freedraw dots
  288. if (
  289. distance2d(A[0], A[1], x, y) < threshold ||
  290. distance2d(B[0], B[1], x, y) < threshold
  291. ) {
  292. return true;
  293. }
  294. // For freedraw lines
  295. for (let i = 0; i < element.points.length; i++) {
  296. const delta = [B[0] - A[0], B[1] - A[1]];
  297. const length = Math.hypot(delta[1], delta[0]);
  298. const U = [delta[0] / length, delta[1] / length];
  299. const C = [x - A[0], y - A[1]];
  300. const d = (C[0] * U[0] + C[1] * U[1]) / Math.hypot(U[1], U[0]);
  301. P = [A[0] + U[0] * d, A[1] + U[1] * d];
  302. const da = distance2d(P[0], P[1], A[0], A[1]);
  303. const db = distance2d(P[0], P[1], B[0], B[1]);
  304. P = db < da && da > length ? B : da < db && db > length ? A : P;
  305. if (Math.hypot(y - P[1], x - P[0]) < threshold) {
  306. return true;
  307. }
  308. A = B;
  309. B = element.points[i + 1];
  310. }
  311. return false;
  312. };
  313. const hitTestLinear = (args: HitTestArgs): boolean => {
  314. const { element, threshold } = args;
  315. if (!getShapeForElement(element)) {
  316. return false;
  317. }
  318. const [point, pointAbs, hwidth, hheight] = pointRelativeToElement(
  319. args.element,
  320. args.point,
  321. );
  322. const side1 = GALine.equation(0, 1, -hheight);
  323. const side2 = GALine.equation(1, 0, -hwidth);
  324. if (
  325. !isInsideCheck(GAPoint.distanceToLine(pointAbs, side1), threshold) ||
  326. !isInsideCheck(GAPoint.distanceToLine(pointAbs, side2), threshold)
  327. ) {
  328. return false;
  329. }
  330. const [relX, relY] = GAPoint.toTuple(point);
  331. const shape = getShapeForElement(element) as Drawable[];
  332. if (args.check === isInsideCheck) {
  333. const hit = shape.some((subshape) =>
  334. hitTestCurveInside(subshape, relX, relY, element.strokeSharpness),
  335. );
  336. if (hit) {
  337. return true;
  338. }
  339. }
  340. // hit test all "subshapes" of the linear element
  341. return shape.some((subshape) =>
  342. hitTestRoughShape(subshape, relX, relY, threshold),
  343. );
  344. };
  345. // Returns:
  346. // 1. the point relative to the elements (x, y) position
  347. // 2. the point relative to the element's center with positive (x, y)
  348. // 3. half element width
  349. // 4. half element height
  350. //
  351. // Note that for linear elements the (x, y) position is not at the
  352. // top right corner of their boundary.
  353. //
  354. // Rectangles, diamonds and ellipses are symmetrical over axes,
  355. // and other elements have a rectangular boundary,
  356. // so we only need to perform hit tests for the positive quadrant.
  357. const pointRelativeToElement = (
  358. element: ExcalidrawElement,
  359. pointTuple: Point,
  360. ): [GA.Point, GA.Point, number, number] => {
  361. const point = GAPoint.from(pointTuple);
  362. const elementCoords = getElementAbsoluteCoords(element);
  363. const center = coordsCenter(elementCoords);
  364. // GA has angle orientation opposite to `rotate`
  365. const rotate = GATransform.rotation(center, element.angle);
  366. const pointRotated = GATransform.apply(rotate, point);
  367. const pointRelToCenter = GA.sub(pointRotated, GADirection.from(center));
  368. const pointRelToCenterAbs = GAPoint.abs(pointRelToCenter);
  369. const elementPos = GA.offset(element.x, element.y);
  370. const pointRelToPos = GA.sub(pointRotated, elementPos);
  371. const [ax, ay, bx, by] = elementCoords;
  372. const halfWidth = (bx - ax) / 2;
  373. const halfHeight = (by - ay) / 2;
  374. return [pointRelToPos, pointRelToCenterAbs, halfWidth, halfHeight];
  375. };
  376. // Returns point in absolute coordinates
  377. export const pointInAbsoluteCoords = (
  378. element: ExcalidrawElement,
  379. // Point relative to the element position
  380. point: Point,
  381. ): Point => {
  382. const [x, y] = point;
  383. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  384. const cx = (x2 - x1) / 2;
  385. const cy = (y2 - y1) / 2;
  386. const [rotatedX, rotatedY] = rotate(x, y, cx, cy, element.angle);
  387. return [element.x + rotatedX, element.y + rotatedY];
  388. };
  389. const relativizationToElementCenter = (
  390. element: ExcalidrawElement,
  391. ): GA.Transform => {
  392. const elementCoords = getElementAbsoluteCoords(element);
  393. const center = coordsCenter(elementCoords);
  394. // GA has angle orientation opposite to `rotate`
  395. const rotate = GATransform.rotation(center, element.angle);
  396. const translate = GA.reverse(
  397. GATransform.translation(GADirection.from(center)),
  398. );
  399. return GATransform.compose(rotate, translate);
  400. };
  401. const coordsCenter = ([ax, ay, bx, by]: Bounds): GA.Point => {
  402. return GA.point((ax + bx) / 2, (ay + by) / 2);
  403. };
  404. // The focus distance is the oriented ratio between the size of
  405. // the `element` and the "focus image" of the element on which
  406. // all focus points lie, so it's a number between -1 and 1.
  407. // The line going through `a` and `b` is a tangent to the "focus image"
  408. // of the element.
  409. export const determineFocusDistance = (
  410. element: ExcalidrawBindableElement,
  411. // Point on the line, in absolute coordinates
  412. a: Point,
  413. // Another point on the line, in absolute coordinates (closer to element)
  414. b: Point,
  415. ): number => {
  416. const relateToCenter = relativizationToElementCenter(element);
  417. const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
  418. const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
  419. const line = GALine.through(aRel, bRel);
  420. const q = element.height / element.width;
  421. const hwidth = element.width / 2;
  422. const hheight = element.height / 2;
  423. const n = line[2];
  424. const m = line[3];
  425. const c = line[1];
  426. const mabs = Math.abs(m);
  427. const nabs = Math.abs(n);
  428. switch (element.type) {
  429. case "rectangle":
  430. case "image":
  431. case "text":
  432. return c / (hwidth * (nabs + q * mabs));
  433. case "diamond":
  434. return mabs < nabs ? c / (nabs * hwidth) : c / (mabs * hheight);
  435. case "ellipse":
  436. return c / (hwidth * Math.sqrt(n ** 2 + q ** 2 * m ** 2));
  437. }
  438. };
  439. export const determineFocusPoint = (
  440. element: ExcalidrawBindableElement,
  441. // The oriented, relative distance from the center of `element` of the
  442. // returned focusPoint
  443. focus: number,
  444. adjecentPoint: Point,
  445. ): Point => {
  446. if (focus === 0) {
  447. const elementCoords = getElementAbsoluteCoords(element);
  448. const center = coordsCenter(elementCoords);
  449. return GAPoint.toTuple(center);
  450. }
  451. const relateToCenter = relativizationToElementCenter(element);
  452. const adjecentPointRel = GATransform.apply(
  453. relateToCenter,
  454. GAPoint.from(adjecentPoint),
  455. );
  456. const reverseRelateToCenter = GA.reverse(relateToCenter);
  457. let point;
  458. switch (element.type) {
  459. case "rectangle":
  460. case "image":
  461. case "text":
  462. case "diamond":
  463. point = findFocusPointForRectangulars(element, focus, adjecentPointRel);
  464. break;
  465. case "ellipse":
  466. point = findFocusPointForEllipse(element, focus, adjecentPointRel);
  467. break;
  468. }
  469. return GAPoint.toTuple(GATransform.apply(reverseRelateToCenter, point));
  470. };
  471. // Returns 2 or 0 intersection points between line going through `a` and `b`
  472. // and the `element`, in ascending order of distance from `a`.
  473. export const intersectElementWithLine = (
  474. element: ExcalidrawBindableElement,
  475. // Point on the line, in absolute coordinates
  476. a: Point,
  477. // Another point on the line, in absolute coordinates
  478. b: Point,
  479. // If given, the element is inflated by this value
  480. gap: number = 0,
  481. ): Point[] => {
  482. const relateToCenter = relativizationToElementCenter(element);
  483. const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
  484. const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
  485. const line = GALine.through(aRel, bRel);
  486. const reverseRelateToCenter = GA.reverse(relateToCenter);
  487. const intersections = getSortedElementLineIntersections(
  488. element,
  489. line,
  490. aRel,
  491. gap,
  492. );
  493. return intersections.map((point) =>
  494. GAPoint.toTuple(GATransform.apply(reverseRelateToCenter, point)),
  495. );
  496. };
  497. const getSortedElementLineIntersections = (
  498. element: ExcalidrawBindableElement,
  499. // Relative to element center
  500. line: GA.Line,
  501. // Relative to element center
  502. nearPoint: GA.Point,
  503. gap: number = 0,
  504. ): GA.Point[] => {
  505. let intersections: GA.Point[];
  506. switch (element.type) {
  507. case "rectangle":
  508. case "image":
  509. case "text":
  510. case "diamond":
  511. const corners = getCorners(element);
  512. intersections = corners
  513. .flatMap((point, i) => {
  514. const edge: [GA.Point, GA.Point] = [point, corners[(i + 1) % 4]];
  515. return intersectSegment(line, offsetSegment(edge, gap));
  516. })
  517. .concat(
  518. corners.flatMap((point) => getCircleIntersections(point, gap, line)),
  519. );
  520. break;
  521. case "ellipse":
  522. intersections = getEllipseIntersections(element, gap, line);
  523. break;
  524. }
  525. if (intersections.length < 2) {
  526. // Ignore the "edge" case of only intersecting with a single corner
  527. return [];
  528. }
  529. const sortedIntersections = intersections.sort(
  530. (i1, i2) =>
  531. GAPoint.distance(i1, nearPoint) - GAPoint.distance(i2, nearPoint),
  532. );
  533. return [
  534. sortedIntersections[0],
  535. sortedIntersections[sortedIntersections.length - 1],
  536. ];
  537. };
  538. const getCorners = (
  539. element:
  540. | ExcalidrawRectangleElement
  541. | ExcalidrawImageElement
  542. | ExcalidrawDiamondElement
  543. | ExcalidrawTextElement,
  544. scale: number = 1,
  545. ): GA.Point[] => {
  546. const hx = (scale * element.width) / 2;
  547. const hy = (scale * element.height) / 2;
  548. switch (element.type) {
  549. case "rectangle":
  550. case "image":
  551. case "text":
  552. return [
  553. GA.point(hx, hy),
  554. GA.point(hx, -hy),
  555. GA.point(-hx, -hy),
  556. GA.point(-hx, hy),
  557. ];
  558. case "diamond":
  559. return [
  560. GA.point(0, hy),
  561. GA.point(hx, 0),
  562. GA.point(0, -hy),
  563. GA.point(-hx, 0),
  564. ];
  565. }
  566. };
  567. // Returns intersection of `line` with `segment`, with `segment` moved by
  568. // `gap` in its polar direction.
  569. // If intersection conincides with second segment point returns empty array.
  570. const intersectSegment = (
  571. line: GA.Line,
  572. segment: [GA.Point, GA.Point],
  573. ): GA.Point[] => {
  574. const [a, b] = segment;
  575. const aDist = GAPoint.distanceToLine(a, line);
  576. const bDist = GAPoint.distanceToLine(b, line);
  577. if (aDist * bDist >= 0) {
  578. // The intersection is outside segment `(a, b)`
  579. return [];
  580. }
  581. return [GAPoint.intersect(line, GALine.through(a, b))];
  582. };
  583. const offsetSegment = (
  584. segment: [GA.Point, GA.Point],
  585. distance: number,
  586. ): [GA.Point, GA.Point] => {
  587. const [a, b] = segment;
  588. const offset = GATransform.translationOrthogonal(
  589. GADirection.fromTo(a, b),
  590. distance,
  591. );
  592. return [GATransform.apply(offset, a), GATransform.apply(offset, b)];
  593. };
  594. const getEllipseIntersections = (
  595. element: ExcalidrawEllipseElement,
  596. gap: number,
  597. line: GA.Line,
  598. ): GA.Point[] => {
  599. const a = element.width / 2 + gap;
  600. const b = element.height / 2 + gap;
  601. const m = line[2];
  602. const n = line[3];
  603. const c = line[1];
  604. const squares = a * a * m * m + b * b * n * n;
  605. const discr = squares - c * c;
  606. if (squares === 0 || discr <= 0) {
  607. return [];
  608. }
  609. const discrRoot = Math.sqrt(discr);
  610. const xn = -a * a * m * c;
  611. const yn = -b * b * n * c;
  612. return [
  613. GA.point(
  614. (xn + a * b * n * discrRoot) / squares,
  615. (yn - a * b * m * discrRoot) / squares,
  616. ),
  617. GA.point(
  618. (xn - a * b * n * discrRoot) / squares,
  619. (yn + a * b * m * discrRoot) / squares,
  620. ),
  621. ];
  622. };
  623. export const getCircleIntersections = (
  624. center: GA.Point,
  625. radius: number,
  626. line: GA.Line,
  627. ): GA.Point[] => {
  628. if (radius === 0) {
  629. return GAPoint.distanceToLine(line, center) === 0 ? [center] : [];
  630. }
  631. const m = line[2];
  632. const n = line[3];
  633. const c = line[1];
  634. const [a, b] = GAPoint.toTuple(center);
  635. const r = radius;
  636. const squares = m * m + n * n;
  637. const discr = r * r * squares - (m * a + n * b + c) ** 2;
  638. if (squares === 0 || discr <= 0) {
  639. return [];
  640. }
  641. const discrRoot = Math.sqrt(discr);
  642. const xn = a * n * n - b * m * n - m * c;
  643. const yn = b * m * m - a * m * n - n * c;
  644. return [
  645. GA.point((xn + n * discrRoot) / squares, (yn - m * discrRoot) / squares),
  646. GA.point((xn - n * discrRoot) / squares, (yn + m * discrRoot) / squares),
  647. ];
  648. };
  649. // The focus point is the tangent point of the "focus image" of the
  650. // `element`, where the tangent goes through `point`.
  651. export const findFocusPointForEllipse = (
  652. ellipse: ExcalidrawEllipseElement,
  653. // Between -1 and 1 (not 0) the relative size of the "focus image" of
  654. // the element on which the focus point lies
  655. relativeDistance: number,
  656. // The point for which we're trying to find the focus point, relative
  657. // to the ellipse center.
  658. point: GA.Point,
  659. ): GA.Point => {
  660. const relativeDistanceAbs = Math.abs(relativeDistance);
  661. const a = (ellipse.width * relativeDistanceAbs) / 2;
  662. const b = (ellipse.height * relativeDistanceAbs) / 2;
  663. const orientation = Math.sign(relativeDistance);
  664. const [px, pyo] = GAPoint.toTuple(point);
  665. // The calculation below can't handle py = 0
  666. const py = pyo === 0 ? 0.0001 : pyo;
  667. const squares = px ** 2 * b ** 2 + py ** 2 * a ** 2;
  668. // Tangent mx + ny + 1 = 0
  669. const m =
  670. (-px * b ** 2 +
  671. orientation * py * Math.sqrt(Math.max(0, squares - a ** 2 * b ** 2))) /
  672. squares;
  673. const n = (-m * px - 1) / py;
  674. const x = -(a ** 2 * m) / (n ** 2 * b ** 2 + m ** 2 * a ** 2);
  675. return GA.point(x, (-m * x - 1) / n);
  676. };
  677. export const findFocusPointForRectangulars = (
  678. element:
  679. | ExcalidrawRectangleElement
  680. | ExcalidrawImageElement
  681. | ExcalidrawDiamondElement
  682. | ExcalidrawTextElement,
  683. // Between -1 and 1 for how far away should the focus point be relative
  684. // to the size of the element. Sign determines orientation.
  685. relativeDistance: number,
  686. // The point for which we're trying to find the focus point, relative
  687. // to the element center.
  688. point: GA.Point,
  689. ): GA.Point => {
  690. const relativeDistanceAbs = Math.abs(relativeDistance);
  691. const orientation = Math.sign(relativeDistance);
  692. const corners = getCorners(element, relativeDistanceAbs);
  693. let maxDistance = 0;
  694. let tangentPoint: null | GA.Point = null;
  695. corners.forEach((corner) => {
  696. const distance = orientation * GALine.through(point, corner)[1];
  697. if (distance > maxDistance) {
  698. maxDistance = distance;
  699. tangentPoint = corner;
  700. }
  701. });
  702. return tangentPoint!;
  703. };
  704. const pointInBezierEquation = (
  705. p0: Point,
  706. p1: Point,
  707. p2: Point,
  708. p3: Point,
  709. [mx, my]: Point,
  710. lineThreshold: number,
  711. ) => {
  712. // B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
  713. const equation = (t: number, idx: number) =>
  714. Math.pow(1 - t, 3) * p3[idx] +
  715. 3 * t * Math.pow(1 - t, 2) * p2[idx] +
  716. 3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
  717. p0[idx] * Math.pow(t, 3);
  718. // go through t in increments of 0.01
  719. let t = 0;
  720. while (t <= 1.0) {
  721. const tx = equation(t, 0);
  722. const ty = equation(t, 1);
  723. const diff = Math.sqrt(Math.pow(tx - mx, 2) + Math.pow(ty - my, 2));
  724. if (diff < lineThreshold) {
  725. return true;
  726. }
  727. t += 0.01;
  728. }
  729. return false;
  730. };
  731. const hitTestCurveInside = (
  732. drawable: Drawable,
  733. x: number,
  734. y: number,
  735. sharpness: ExcalidrawElement["strokeSharpness"],
  736. ) => {
  737. const ops = getCurvePathOps(drawable);
  738. const points: Point[] = [];
  739. let odd = false; // select one line out of double lines
  740. for (const operation of ops) {
  741. if (operation.op === "move") {
  742. odd = !odd;
  743. if (odd) {
  744. points.push([operation.data[0], operation.data[1]]);
  745. }
  746. } else if (operation.op === "bcurveTo") {
  747. if (odd) {
  748. points.push([operation.data[0], operation.data[1]]);
  749. points.push([operation.data[2], operation.data[3]]);
  750. points.push([operation.data[4], operation.data[5]]);
  751. }
  752. }
  753. }
  754. if (points.length >= 4) {
  755. if (sharpness === "sharp") {
  756. return isPointInPolygon(points, x, y);
  757. }
  758. const polygonPoints = pointsOnBezierCurves(points as any, 10, 5);
  759. return isPointInPolygon(polygonPoints, x, y);
  760. }
  761. return false;
  762. };
  763. const hitTestRoughShape = (
  764. drawable: Drawable,
  765. x: number,
  766. y: number,
  767. lineThreshold: number,
  768. ) => {
  769. // read operations from first opSet
  770. const ops = getCurvePathOps(drawable);
  771. // set start position as (0,0) just in case
  772. // move operation does not exist (unlikely but it is worth safekeeping it)
  773. let currentP: Point = [0, 0];
  774. return ops.some(({ op, data }, idx) => {
  775. // There are only four operation types:
  776. // move, bcurveTo, lineTo, and curveTo
  777. if (op === "move") {
  778. // change starting point
  779. currentP = data as unknown as Point;
  780. // move operation does not draw anything; so, it always
  781. // returns false
  782. } else if (op === "bcurveTo") {
  783. // create points from bezier curve
  784. // bezier curve stores data as a flattened array of three positions
  785. // [x1, y1, x2, y2, x3, y3]
  786. const p1 = [data[0], data[1]] as Point;
  787. const p2 = [data[2], data[3]] as Point;
  788. const p3 = [data[4], data[5]] as Point;
  789. const p0 = currentP;
  790. currentP = p3;
  791. // check if points are on the curve
  792. // cubic bezier curves require four parameters
  793. // the first parameter is the last stored position (p0)
  794. const retVal = pointInBezierEquation(
  795. p0,
  796. p1,
  797. p2,
  798. p3,
  799. [x, y],
  800. lineThreshold,
  801. );
  802. // set end point of bezier curve as the new starting point for
  803. // upcoming operations as each operation is based on the last drawn
  804. // position of the previous operation
  805. return retVal;
  806. } else if (op === "lineTo") {
  807. // TODO: Implement this
  808. } else if (op === "qcurveTo") {
  809. // TODO: Implement this
  810. }
  811. return false;
  812. });
  813. };