VertexTangentsHelper.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. LineSegments,
  5. LineBasicMaterial,
  6. Vector3
  7. } from 'three';
  8. const _v1 = new Vector3();
  9. const _v2 = new Vector3();
  10. class VertexTangentsHelper extends LineSegments {
  11. constructor( object, size = 1, color = 0x00ffff ) {
  12. const geometry = new BufferGeometry();
  13. const nTangents = object.geometry.attributes.tangent.count;
  14. const positions = new Float32BufferAttribute( nTangents * 2 * 3, 3 );
  15. geometry.setAttribute( 'position', positions );
  16. super( geometry, new LineBasicMaterial( { color, toneMapped: false } ) );
  17. this.object = object;
  18. this.size = size;
  19. this.type = 'VertexTangentsHelper';
  20. //
  21. this.matrixAutoUpdate = false;
  22. this.update();
  23. }
  24. update() {
  25. this.object.updateMatrixWorld( true );
  26. const matrixWorld = this.object.matrixWorld;
  27. const position = this.geometry.attributes.position;
  28. //
  29. const objGeometry = this.object.geometry;
  30. const objPos = objGeometry.attributes.position;
  31. const objTan = objGeometry.attributes.tangent;
  32. let idx = 0;
  33. // for simplicity, ignore index and drawcalls, and render every tangent
  34. for ( let j = 0, jl = objPos.count; j < jl; j ++ ) {
  35. _v1.fromBufferAttribute( objPos, j ).applyMatrix4( matrixWorld );
  36. _v2.fromBufferAttribute( objTan, j );
  37. _v2.transformDirection( matrixWorld ).multiplyScalar( this.size ).add( _v1 );
  38. position.setXYZ( idx, _v1.x, _v1.y, _v1.z );
  39. idx = idx + 1;
  40. position.setXYZ( idx, _v2.x, _v2.y, _v2.z );
  41. idx = idx + 1;
  42. }
  43. position.needsUpdate = true;
  44. }
  45. dispose() {
  46. this.geometry.dispose();
  47. this.material.dispose();
  48. }
  49. }
  50. export { VertexTangentsHelper };