VertexNormalsHelper.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. LineSegments,
  5. LineBasicMaterial,
  6. Matrix3,
  7. Vector3
  8. } from '../../../build/three.module.js';
  9. const _v1 = new Vector3();
  10. const _v2 = new Vector3();
  11. const _normalMatrix = new Matrix3();
  12. class VertexNormalsHelper extends LineSegments {
  13. constructor( object, size = 1, color = 0xff0000 ) {
  14. let nNormals = 0;
  15. const objGeometry = object.geometry;
  16. if ( objGeometry && objGeometry.isGeometry ) {
  17. console.error( 'THREE.VertexNormalsHelper no longer supports Geometry. Use BufferGeometry instead.' );
  18. return;
  19. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  20. nNormals = objGeometry.attributes.normal.count;
  21. }
  22. //
  23. const geometry = new BufferGeometry();
  24. const positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  25. geometry.setAttribute( 'position', positions );
  26. super( geometry, new LineBasicMaterial( { color, toneMapped: false } ) );
  27. this.object = object;
  28. this.size = size;
  29. this.type = 'VertexNormalsHelper';
  30. //
  31. this.matrixAutoUpdate = false;
  32. this.update();
  33. }
  34. update() {
  35. this.object.updateMatrixWorld( true );
  36. _normalMatrix.getNormalMatrix( this.object.matrixWorld );
  37. const matrixWorld = this.object.matrixWorld;
  38. const position = this.geometry.attributes.position;
  39. //
  40. const objGeometry = this.object.geometry;
  41. if ( objGeometry && objGeometry.isGeometry ) {
  42. console.error( 'THREE.VertexNormalsHelper no longer supports Geometry. Use BufferGeometry instead.' );
  43. return;
  44. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  45. const objPos = objGeometry.attributes.position;
  46. const objNorm = objGeometry.attributes.normal;
  47. let idx = 0;
  48. // for simplicity, ignore index and drawcalls, and render every normal
  49. for ( let j = 0, jl = objPos.count; j < jl; j ++ ) {
  50. _v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  51. _v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  52. _v2.applyMatrix3( _normalMatrix ).normalize().multiplyScalar( this.size ).add( _v1 );
  53. position.setXYZ( idx, _v1.x, _v1.y, _v1.z );
  54. idx = idx + 1;
  55. position.setXYZ( idx, _v2.x, _v2.y, _v2.z );
  56. idx = idx + 1;
  57. }
  58. }
  59. position.needsUpdate = true;
  60. }
  61. }
  62. export { VertexNormalsHelper };