Box3Helper.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { LineSegments } from '../objects/LineSegments.js';
  2. import { LineBasicMaterial } from '../materials/LineBasicMaterial.js';
  3. import { BufferAttribute, Float32BufferAttribute } from '../core/BufferAttribute.js';
  4. import { BufferGeometry } from '../core/BufferGeometry.js';
  5. /**
  6. * A helper object to visualize an instance of {@link Box3}.
  7. *
  8. * ```js
  9. * const box = new THREE.Box3();
  10. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  11. *
  12. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  13. * scene.add( helper )
  14. * ```
  15. *
  16. * @augments LineSegments
  17. */
  18. class Box3Helper extends LineSegments {
  19. /**
  20. * Constructs a new box3 helper.
  21. *
  22. * @param {Box3} box - The box to visualize.
  23. * @param {number|Color|string} [color=0xffff00] - The box's color.
  24. */
  25. constructor( box, color = 0xffff00 ) {
  26. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  27. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  28. const geometry = new BufferGeometry();
  29. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32. /**
  33. * The box being visualized.
  34. *
  35. * @type {Box3}
  36. */
  37. this.box = box;
  38. this.type = 'Box3Helper';
  39. this.geometry.computeBoundingSphere();
  40. }
  41. updateMatrixWorld( force ) {
  42. const box = this.box;
  43. if ( box.isEmpty() ) return;
  44. box.getCenter( this.position );
  45. box.getSize( this.scale );
  46. this.scale.multiplyScalar( 0.5 );
  47. super.updateMatrixWorld( force );
  48. }
  49. /**
  50. * Frees the GPU-related resources allocated by this instance. Call this
  51. * method whenever this instance is no longer used in your app.
  52. */
  53. dispose() {
  54. this.geometry.dispose();
  55. this.material.dispose();
  56. }
  57. }
  58. export { Box3Helper };
粤ICP备19079148号