Plane.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @author Ben Houston / [email protected] / http://github.com/bhouston
  3. */
  4. ( function ( THREE ) {
  5. THREE.Plane = function ( normal, constant ) {
  6. // TODO: ensure that normal is of length 1 and if it isn't readjust both normal and constant?
  7. this.normal = normal || new THREE.Vector3();
  8. this.constant = constant || 0;
  9. };
  10. THREE.Plane.prototype.set = function ( normal, constant ) {
  11. // TODO: ensure that normal is of length 1 and if it isn't readjust both normal and constant?
  12. this.normal = normal;
  13. this.constant = constant;
  14. return this;
  15. };
  16. THREE.Plane.prototype.setComponents = function ( x, y, z, w ) {
  17. // TODO: ensure that normal is of length 1 and if it isn't readjust both normal and constant?
  18. this.normal.x = x;
  19. this.normal.y = y;
  20. this.normal.z = z;
  21. this.constant = w;
  22. return this;
  23. };
  24. THREE.Plane.prototype.copy = function ( plane ) {
  25. this.normal = plane.normal;
  26. this.constant = plane.constant;
  27. return this;
  28. };
  29. THREE.Plane.prototype.flip = function () {
  30. // Note: can also be flipped by inverting constant, but I like constant to stay positive generally.
  31. this.normal.negate();
  32. return this;
  33. };
  34. THREE.Plane.prototype.normalize = function () {
  35. // Note: will lead to a divide by zero if the plane is invalid.
  36. var inverseNormalLength = 1.0 / this.normal.length()
  37. this.normal.multipleByScalar( inverseNormalLength );
  38. this.constant *= inverseNormalLength;
  39. return this;
  40. };
  41. THREE.Plane.prototype.distanceToPoint = function ( point ) {
  42. return this.normal.dot( point ) + this.constant;
  43. };
  44. THREE.Plane.prototype.projectPoint = function ( point ) {
  45. return new THREE.Vector3().copy( point ).sub( this.orthoPoint( point ) );
  46. };
  47. THREE.Plane.prototype.orthoPoint = function ( point ) {
  48. var perpendicularMagnitude = this.distanceToPoint( point );
  49. return new THREE.Vector3().copy( this.normal ).multipleByScalar( perpendicularMagnitude );
  50. };
  51. THREE.Plane.prototype.intersectsLine = function ( startPoint, endPoint ) {
  52. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  53. var startSign = this.distanceToPoint( startPoint );
  54. var endSign = this.distanceToPoint( endPoint );
  55. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  56. };
  57. THREE.Plane.prototype.coplanarPoint = function () {
  58. return this.projectPoint( new THREE.Vector3() );
  59. };
  60. }( THREE ) );