collision.ts 27 KB

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