collision.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import { distanceBetweenPointAndSegment } from "../math";
  2. import { ExcalidrawElement } from "./types";
  3. import {
  4. getDiamondPoints,
  5. getElementAbsoluteCoords,
  6. getLinearElementAbsoluteBounds,
  7. } from "./bounds";
  8. import { Point } from "roughjs/bin/geometry";
  9. import { Drawable, OpSet } from "roughjs/bin/core";
  10. import { AppState } from "../types";
  11. import { getShapeForElement } from "../renderer/renderElement";
  12. function isElementDraggableFromInside(
  13. element: ExcalidrawElement,
  14. appState: AppState,
  15. ): boolean {
  16. return (
  17. element.backgroundColor !== "transparent" ||
  18. appState.selectedElementIds[element.id]
  19. );
  20. }
  21. export function hitTest(
  22. element: ExcalidrawElement,
  23. appState: AppState,
  24. x: number,
  25. y: number,
  26. zoom: number,
  27. ): boolean {
  28. // For shapes that are composed of lines, we only enable point-selection when the distance
  29. // of the click is less than x pixels of any of the lines that the shape is composed of
  30. const lineThreshold = 10 / zoom;
  31. if (element.type === "ellipse") {
  32. // https://stackoverflow.com/a/46007540/232122
  33. const px = Math.abs(x - element.x - element.width / 2);
  34. const py = Math.abs(y - element.y - element.height / 2);
  35. let tx = 0.707;
  36. let ty = 0.707;
  37. const a = Math.abs(element.width) / 2;
  38. const b = Math.abs(element.height) / 2;
  39. [0, 1, 2, 3].forEach(x => {
  40. const xx = a * tx;
  41. const yy = b * ty;
  42. const ex = ((a * a - b * b) * tx ** 3) / a;
  43. const ey = ((b * b - a * a) * ty ** 3) / b;
  44. const rx = xx - ex;
  45. const ry = yy - ey;
  46. const qx = px - ex;
  47. const qy = py - ey;
  48. const r = Math.hypot(ry, rx);
  49. const q = Math.hypot(qy, qx);
  50. tx = Math.min(1, Math.max(0, ((qx * r) / q + ex) / a));
  51. ty = Math.min(1, Math.max(0, ((qy * r) / q + ey) / b));
  52. const t = Math.hypot(ty, tx);
  53. tx /= t;
  54. ty /= t;
  55. });
  56. if (isElementDraggableFromInside(element, appState)) {
  57. return (
  58. a * tx - (px - lineThreshold) >= 0 && b * ty - (py - lineThreshold) >= 0
  59. );
  60. }
  61. return Math.hypot(a * tx - px, b * ty - py) < lineThreshold;
  62. } else if (element.type === "rectangle") {
  63. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  64. if (isElementDraggableFromInside(element, appState)) {
  65. return (
  66. x > x1 - lineThreshold &&
  67. x < x2 + lineThreshold &&
  68. y > y1 - lineThreshold &&
  69. y < y2 + lineThreshold
  70. );
  71. }
  72. // (x1, y1) --A-- (x2, y1)
  73. // |D |B
  74. // (x1, y2) --C-- (x2, y2)
  75. return (
  76. distanceBetweenPointAndSegment(x, y, x1, y1, x2, y1) < lineThreshold || // A
  77. distanceBetweenPointAndSegment(x, y, x2, y1, x2, y2) < lineThreshold || // B
  78. distanceBetweenPointAndSegment(x, y, x2, y2, x1, y2) < lineThreshold || // C
  79. distanceBetweenPointAndSegment(x, y, x1, y2, x1, y1) < lineThreshold // D
  80. );
  81. } else if (element.type === "diamond") {
  82. x -= element.x;
  83. y -= element.y;
  84. let [
  85. topX,
  86. topY,
  87. rightX,
  88. rightY,
  89. bottomX,
  90. bottomY,
  91. leftX,
  92. leftY,
  93. ] = getDiamondPoints(element);
  94. if (isElementDraggableFromInside(element, appState)) {
  95. // TODO: remove this when we normalize coordinates globally
  96. if (topY > bottomY) {
  97. [bottomY, topY] = [topY, bottomY];
  98. }
  99. if (rightX < leftX) {
  100. [leftX, rightX] = [rightX, leftX];
  101. }
  102. topY -= lineThreshold;
  103. bottomY += lineThreshold;
  104. leftX -= lineThreshold;
  105. rightX += lineThreshold;
  106. // all deltas should be < 0. Delta > 0 indicates it's on the outside side
  107. // of the line.
  108. //
  109. // (topX, topY)
  110. // D / \ A
  111. // / \
  112. // (leftX, leftY) (rightX, rightY)
  113. // C \ / B
  114. // \ /
  115. // (bottomX, bottomY)
  116. //
  117. // https://stackoverflow.com/a/2752753/927631
  118. return (
  119. // delta from line D
  120. (leftX - topX) * (y - leftY) - (leftX - x) * (topY - leftY) <= 0 &&
  121. // delta from line A
  122. (topX - rightX) * (y - rightY) - (x - rightX) * (topY - rightY) <= 0 &&
  123. // delta from line B
  124. (rightX - bottomX) * (y - bottomY) -
  125. (x - bottomX) * (rightY - bottomY) <=
  126. 0 &&
  127. // delta from line C
  128. (bottomX - leftX) * (y - leftY) - (x - leftX) * (bottomY - leftY) <= 0
  129. );
  130. }
  131. return (
  132. distanceBetweenPointAndSegment(x, y, topX, topY, rightX, rightY) <
  133. lineThreshold ||
  134. distanceBetweenPointAndSegment(x, y, rightX, rightY, bottomX, bottomY) <
  135. lineThreshold ||
  136. distanceBetweenPointAndSegment(x, y, bottomX, bottomY, leftX, leftY) <
  137. lineThreshold ||
  138. distanceBetweenPointAndSegment(x, y, leftX, leftY, topX, topY) <
  139. lineThreshold
  140. );
  141. } else if (element.type === "arrow" || element.type === "line") {
  142. if (!getShapeForElement(element)) {
  143. return false;
  144. }
  145. const shape = getShapeForElement(element) as Drawable[];
  146. const [x1, y1, x2, y2] = getLinearElementAbsoluteBounds(element);
  147. if (x < x1 || y < y1 - 10 || x > x2 || y > y2 + 10) {
  148. return false;
  149. }
  150. const relX = x - element.x;
  151. const relY = y - element.y;
  152. // hit thest all "subshapes" of the linear element
  153. return shape.some(subshape => hitTestRoughShape(subshape.sets, relX, relY));
  154. } else if (element.type === "text") {
  155. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  156. return x >= x1 && x <= x2 && y >= y1 && y <= y2;
  157. } else if (element.type === "selection") {
  158. console.warn("This should not happen, we need to investigate why it does.");
  159. return false;
  160. }
  161. throw new Error(`Unimplemented type ${element.type}`);
  162. }
  163. const pointInBezierEquation = (
  164. p0: Point,
  165. p1: Point,
  166. p2: Point,
  167. p3: Point,
  168. [mx, my]: Point,
  169. ) => {
  170. // B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
  171. const equation = (t: number, idx: number) =>
  172. Math.pow(1 - t, 3) * p3[idx] +
  173. 3 * t * Math.pow(1 - t, 2) * p2[idx] +
  174. 3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
  175. p0[idx] * Math.pow(t, 3);
  176. const epsilon = 20;
  177. // go through t in increments of 0.01
  178. let t = 0;
  179. while (t <= 1.0) {
  180. const tx = equation(t, 0);
  181. const ty = equation(t, 1);
  182. const diff = Math.sqrt(Math.pow(tx - mx, 2) + Math.pow(ty - my, 2));
  183. if (diff < epsilon) {
  184. return true;
  185. }
  186. t += 0.01;
  187. }
  188. return false;
  189. };
  190. const hitTestRoughShape = (opSet: OpSet[], x: number, y: number) => {
  191. // read operations from first opSet
  192. const ops = opSet[0].ops;
  193. // set start position as (0,0) just in case
  194. // move operation does not exist (unlikely but it is worth safekeeping it)
  195. let currentP: Point = [0, 0];
  196. return ops.some(({ op, data }, idx) => {
  197. // There are only four operation types:
  198. // move, bcurveTo, lineTo, and curveTo
  199. if (op === "move") {
  200. // change starting point
  201. currentP = data as Point;
  202. // move operation does not draw anything; so, it always
  203. // returns false
  204. } else if (op === "bcurveTo") {
  205. // create points from bezier curve
  206. // bezier curve stores data as a flattened array of three positions
  207. // [x1, y1, x2, y2, x3, y3]
  208. const p1 = [data[0], data[1]] as Point;
  209. const p2 = [data[2], data[3]] as Point;
  210. const p3 = [data[4], data[5]] as Point;
  211. const p0 = currentP;
  212. currentP = p3;
  213. // check if points are on the curve
  214. // cubic bezier curves require four parameters
  215. // the first parameter is the last stored position (p0)
  216. const retVal = pointInBezierEquation(p0, p1, p2, p3, [x, y]);
  217. // set end point of bezier curve as the new starting point for
  218. // upcoming operations as each operation is based on the last drawn
  219. // position of the previous operation
  220. return retVal;
  221. } else if (op === "lineTo") {
  222. // TODO: Implement this
  223. } else if (op === "qcurveTo") {
  224. // TODO: Implement this
  225. }
  226. return false;
  227. });
  228. };