Wireframe.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {
  2. InstancedInterleavedBuffer,
  3. InterleavedBufferAttribute,
  4. Mesh,
  5. Vector3,
  6. Vector4
  7. } from 'three';
  8. import { LineSegmentsGeometry } from '../lines/LineSegmentsGeometry.js';
  9. import { LineMaterial } from '../lines/LineMaterial.js';
  10. const _start = new Vector3();
  11. const _end = new Vector3();
  12. const _viewport = new Vector4();
  13. class Wireframe extends Mesh {
  14. constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  15. super( geometry, material );
  16. this.isWireframe = true;
  17. this.type = 'Wireframe';
  18. }
  19. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  20. computeLineDistances() {
  21. const geometry = this.geometry;
  22. const instanceStart = geometry.attributes.instanceStart;
  23. const instanceEnd = geometry.attributes.instanceEnd;
  24. const lineDistances = new Float32Array( 2 * instanceStart.count );
  25. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  26. _start.fromBufferAttribute( instanceStart, i );
  27. _end.fromBufferAttribute( instanceEnd, i );
  28. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  29. lineDistances[ j + 1 ] = lineDistances[ j ] + _start.distanceTo( _end );
  30. }
  31. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  32. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  33. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  34. return this;
  35. }
  36. onBeforeRender( renderer ) {
  37. const uniforms = this.material.uniforms;
  38. if ( uniforms && uniforms.resolution ) {
  39. renderer.getViewport( _viewport );
  40. this.material.uniforms.resolution.value.set( _viewport.z, _viewport.w );
  41. }
  42. }
  43. }
  44. export { Wireframe };