collision.ts 7.6 KB

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