NURBSCurve.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {
  2. Curve,
  3. Vector3,
  4. Vector4
  5. } from 'three';
  6. import * as NURBSUtils from '../curves/NURBSUtils.js';
  7. /**
  8. * NURBS curve object
  9. *
  10. * Derives from Curve, overriding getPoint and getTangent.
  11. *
  12. * Implementation is based on (x, y [, z=0 [, w=1]]) control points with w=weight.
  13. *
  14. **/
  15. class NURBSCurve extends Curve {
  16. constructor(
  17. degree,
  18. knots /* array of reals */,
  19. controlPoints /* array of Vector(2|3|4) */,
  20. startKnot /* index in knots */,
  21. endKnot /* index in knots */
  22. ) {
  23. super();
  24. this.degree = degree;
  25. this.knots = knots;
  26. this.controlPoints = [];
  27. // Used by periodic NURBS to remove hidden spans
  28. this.startKnot = startKnot || 0;
  29. this.endKnot = endKnot || ( this.knots.length - 1 );
  30. for ( let i = 0; i < controlPoints.length; ++ i ) {
  31. // ensure Vector4 for control points
  32. const point = controlPoints[ i ];
  33. this.controlPoints[ i ] = new Vector4( point.x, point.y, point.z, point.w );
  34. }
  35. }
  36. getPoint( t, optionalTarget = new Vector3() ) {
  37. const point = optionalTarget;
  38. const u = this.knots[ this.startKnot ] + t * ( this.knots[ this.endKnot ] - this.knots[ this.startKnot ] ); // linear mapping t->u
  39. // following results in (wx, wy, wz, w) homogeneous point
  40. const hpoint = NURBSUtils.calcBSplinePoint( this.degree, this.knots, this.controlPoints, u );
  41. if ( hpoint.w !== 1.0 ) {
  42. // project to 3D space: (wx, wy, wz, w) -> (x, y, z, 1)
  43. hpoint.divideScalar( hpoint.w );
  44. }
  45. return point.set( hpoint.x, hpoint.y, hpoint.z );
  46. }
  47. getTangent( t, optionalTarget = new Vector3() ) {
  48. const tangent = optionalTarget;
  49. const u = this.knots[ 0 ] + t * ( this.knots[ this.knots.length - 1 ] - this.knots[ 0 ] );
  50. const ders = NURBSUtils.calcNURBSDerivatives( this.degree, this.knots, this.controlPoints, u, 1 );
  51. tangent.copy( ders[ 1 ] ).normalize();
  52. return tangent;
  53. }
  54. }
  55. export { NURBSCurve };