Sphere.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * @author bhouston / http://exocortex.com
  3. */
  4. THREE.Sphere = function ( center, radius ) {
  5. if ( center === undefined && radius === undefined ) {
  6. this.center = new THREE.Vector3();
  7. this.radius = 0;
  8. } else {
  9. this.center = center.clone();
  10. this.radius = radius || 0;
  11. }
  12. };
  13. THREE.Sphere.prototype = {
  14. constructor: THREE.Sphere,
  15. set: function ( center, radius ) {
  16. this.center.copy( center );
  17. this.radius = radius;
  18. return this;
  19. },
  20. setFromCenterAndPoints: function ( center, points ) {
  21. var maxRadiusSq = 0;
  22. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23. var radiusSq = center.distanceToSquared( points[ i ] );
  24. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  25. }
  26. this.center = center;
  27. this.radius = Math.sqrt( maxRadiusSq );
  28. return this;
  29. },
  30. copy: function ( sphere ) {
  31. this.center.copy( sphere.center );
  32. this.radius = sphere.radius;
  33. return this;
  34. },
  35. empty: function () {
  36. return ( this.radius <= 0 );
  37. },
  38. containsPoint: function ( point ) {
  39. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  40. },
  41. distanceToPoint: function ( point ) {
  42. return ( point.distanceTo( this.center ) - this.radius );
  43. },
  44. clampPoint: function ( point ) {
  45. var deltaLengthSq = this.center.distanceToSquared( point );
  46. var result = new THREE.Vector3().copy( point );
  47. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  48. result.subSelf( this.center ).normalize();
  49. result.multiplyScalar( this.radius ).addSelf( this.center );
  50. }
  51. return result;
  52. },
  53. bounds: function () {
  54. var box = new THREE.Box3( this.center, this.center );
  55. box.expandByScalar( this.radius );
  56. return box;
  57. },
  58. translate: function ( offset ) {
  59. this.center.addSelf( this.offset );
  60. return this;
  61. },
  62. scale: function ( factor ) {
  63. this.radius *= factor;
  64. return this;
  65. },
  66. equals: function ( sphere ) {
  67. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  68. },
  69. clone: function () {
  70. return new THREE.Sphere3().copy( this );
  71. }
  72. };