galines.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import * as GA from "./ga";
  2. import { Line, Point } from "./ga";
  3. /**
  4. * A line is stored as an array `[0, c, a, b, 0, 0, 0, 0]` representing:
  5. * c * e0 + a * e1 + b*e2
  6. *
  7. * This maps to a standard formula `a * x + b * y + c`.
  8. *
  9. * `(-b, a)` correponds to a 2D vector parallel to the line. The lines
  10. * have a natural orientation, corresponding to that vector.
  11. *
  12. * The magnitude ("norm") of the line is `sqrt(a ^ 2 + b ^ 2)`.
  13. * `c / norm(line)` is the oriented distance from line to origin.
  14. */
  15. // Returns line with direction (x, y) through origin
  16. export const vector = (x: number, y: number): Line =>
  17. GA.normalized([0, 0, -y, x, 0, 0, 0, 0]);
  18. // For equation ax + by + c = 0.
  19. export const equation = (a: number, b: number, c: number): Line =>
  20. GA.normalized([0, c, a, b, 0, 0, 0, 0]);
  21. export const through = (from: Point, to: Point): Line =>
  22. GA.normalized(GA.join(to, from));
  23. export const orthogonal = (line: Line, point: Point): Line =>
  24. GA.dot(line, point);
  25. // Returns a line perpendicular to the line through `against` and `intersection`
  26. // going through `intersection`.
  27. export const orthogonalThrough = (against: Point, intersection: Point): Line =>
  28. orthogonal(through(against, intersection), intersection);
  29. export const parallel = (line: Line, distance: number): Line => {
  30. const result = line.slice();
  31. result[1] -= distance;
  32. return (result as unknown) as Line;
  33. };
  34. export const parallelThrough = (line: Line, point: Point): Line =>
  35. orthogonal(orthogonal(point, line), point);
  36. export const distance = (line1: Line, line2: Line): number =>
  37. GA.inorm(GA.meet(line1, line2));
  38. export const angle = (line1: Line, line2: Line): number =>
  39. Math.acos(GA.dot(line1, line2)[0]);
  40. // The orientation of the line
  41. export const sign = (line: Line): number => Math.sign(line[1]);