FaceNormalsHelper.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. LineSegments,
  5. LineBasicMaterial,
  6. Matrix3,
  7. Vector3
  8. } from '../../../build/three.module.js';
  9. var _v1 = new Vector3();
  10. var _v2 = new Vector3();
  11. var _normalMatrix = new Matrix3();
  12. function FaceNormalsHelper( object, size, hex, linewidth ) {
  13. // FaceNormalsHelper only supports THREE.Geometry
  14. this.object = object;
  15. this.size = ( size !== undefined ) ? size : 1;
  16. var color = ( hex !== undefined ) ? hex : 0xffff00;
  17. var width = ( linewidth !== undefined ) ? linewidth : 1;
  18. //
  19. var nNormals = 0;
  20. var objGeometry = this.object.geometry;
  21. if ( objGeometry && objGeometry.isGeometry ) {
  22. nNormals = objGeometry.faces.length;
  23. } else {
  24. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  25. }
  26. //
  27. var geometry = new BufferGeometry();
  28. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  29. geometry.setAttribute( 'position', positions );
  30. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  31. this.type = 'FaceNormalsHelper';
  32. //
  33. this.matrixAutoUpdate = false;
  34. this.update();
  35. }
  36. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  37. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  38. FaceNormalsHelper.prototype.update = function () {
  39. this.object.updateMatrixWorld( true );
  40. _normalMatrix.getNormalMatrix( this.object.matrixWorld );
  41. var matrixWorld = this.object.matrixWorld;
  42. var position = this.geometry.attributes.position;
  43. //
  44. var objGeometry = this.object.geometry;
  45. var vertices = objGeometry.vertices;
  46. var faces = objGeometry.faces;
  47. var idx = 0;
  48. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  49. var face = faces[ i ];
  50. var normal = face.normal;
  51. _v1.copy( vertices[ face.a ] )
  52. .add( vertices[ face.b ] )
  53. .add( vertices[ face.c ] )
  54. .divideScalar( 3 )
  55. .applyMatrix4( matrixWorld );
  56. _v2.copy( normal ).applyMatrix3( _normalMatrix ).normalize().multiplyScalar( this.size ).add( _v1 );
  57. position.setXYZ( idx, _v1.x, _v1.y, _v1.z );
  58. idx = idx + 1;
  59. position.setXYZ( idx, _v2.x, _v2.y, _v2.z );
  60. idx = idx + 1;
  61. }
  62. position.needsUpdate = true;
  63. };
  64. export { FaceNormalsHelper };