collision.ts 24 KB

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