smoothSpline.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { distance as v2Distance } from '../../core/vector.js';
  2. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  3. var v0 = (p2 - p0) * 0.5;
  4. var v1 = (p3 - p1) * 0.5;
  5. return (2 * (p1 - p2) + v0 + v1) * t3
  6. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  7. + v0 * t + p1;
  8. }
  9. export default function smoothSpline(points, isLoop) {
  10. var len = points.length;
  11. var ret = [];
  12. var distance = 0;
  13. for (var i = 1; i < len; i++) {
  14. distance += v2Distance(points[i - 1], points[i]);
  15. }
  16. var segs = distance / 2;
  17. segs = segs < len ? len : segs;
  18. for (var i = 0; i < segs; i++) {
  19. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  20. var idx = Math.floor(pos);
  21. var w = pos - idx;
  22. var p0 = void 0;
  23. var p1 = points[idx % len];
  24. var p2 = void 0;
  25. var p3 = void 0;
  26. if (!isLoop) {
  27. p0 = points[idx === 0 ? idx : idx - 1];
  28. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  29. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  30. }
  31. else {
  32. p0 = points[(idx - 1 + len) % len];
  33. p2 = points[(idx + 1) % len];
  34. p3 = points[(idx + 2) % len];
  35. }
  36. var w2 = w * w;
  37. var w3 = w * w2;
  38. ret.push([
  39. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  40. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  41. ]);
  42. }
  43. return ret;
  44. }