0
0

CurveModifier.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. ( function () {
  2. // Original src: https://github.com/zz85/threejs-path-flow
  3. const BITS = 3;
  4. const TEXTURE_WIDTH = 1024;
  5. const TEXTURE_HEIGHT = 4;
  6. /**
  7. * Make a new THREE.DataTexture to store the descriptions of the curves.
  8. *
  9. * @param { number } numberOfCurves the number of curves needed to be described by this texture.
  10. */
  11. function initSplineTexture( numberOfCurves = 1 ) {
  12. const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * BITS );
  13. const dataTexture = new THREE.DataTexture( dataArray, TEXTURE_WIDTH, TEXTURE_HEIGHT * numberOfCurves, THREE.RGBFormat, THREE.FloatType );
  14. dataTexture.wrapS = THREE.RepeatWrapping;
  15. dataTexture.wrapY = THREE.RepeatWrapping;
  16. dataTexture.magFilter = THREE.NearestFilter;
  17. dataTexture.needsUpdate = true;
  18. return dataTexture;
  19. }
  20. /**
  21. * Write the curve description to the data texture
  22. *
  23. * @param { THREE.DataTexture } texture The THREE.DataTexture to write to
  24. * @param { Curve } splineCurve The curve to describe
  25. * @param { number } offset Which curve slot to write to
  26. */
  27. function updateSplineTexture( texture, splineCurve, offset = 0 ) {
  28. const numberOfPoints = Math.floor( TEXTURE_WIDTH * ( TEXTURE_HEIGHT / 4 ) );
  29. splineCurve.arcLengthDivisions = numberOfPoints / 2;
  30. splineCurve.updateArcLengths();
  31. const points = splineCurve.getSpacedPoints( numberOfPoints );
  32. const frenetFrames = splineCurve.computeFrenetFrames( numberOfPoints, true );
  33. for ( let i = 0; i < numberOfPoints; i ++ ) {
  34. const rowOffset = Math.floor( i / TEXTURE_WIDTH );
  35. const rowIndex = i % TEXTURE_WIDTH;
  36. let pt = points[ i ];
  37. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + TEXTURE_HEIGHT * offset );
  38. pt = frenetFrames.tangents[ i ];
  39. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + TEXTURE_HEIGHT * offset );
  40. pt = frenetFrames.normals[ i ];
  41. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + TEXTURE_HEIGHT * offset );
  42. pt = frenetFrames.binormals[ i ];
  43. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + TEXTURE_HEIGHT * offset );
  44. }
  45. texture.needsUpdate = true;
  46. }
  47. function setTextureValue( texture, index, x, y, z, o ) {
  48. const image = texture.image;
  49. const {
  50. data
  51. } = image;
  52. const i = BITS * TEXTURE_WIDTH * o; // Row Offset
  53. data[ index * BITS + i + 0 ] = x;
  54. data[ index * BITS + i + 1 ] = y;
  55. data[ index * BITS + i + 2 ] = z;
  56. }
  57. /**
  58. * Create a new set of uniforms for describing the curve modifier
  59. *
  60. * @param { THREE.DataTexture } Texture which holds the curve description
  61. */
  62. function getUniforms( splineTexture ) {
  63. const uniforms = {
  64. spineTexture: {
  65. value: splineTexture
  66. },
  67. pathOffset: {
  68. type: 'f',
  69. value: 0
  70. },
  71. // time of path curve
  72. pathSegment: {
  73. type: 'f',
  74. value: 1
  75. },
  76. // fractional length of path
  77. spineOffset: {
  78. type: 'f',
  79. value: 161
  80. },
  81. spineLength: {
  82. type: 'f',
  83. value: 400
  84. },
  85. flow: {
  86. type: 'i',
  87. value: 1
  88. }
  89. };
  90. return uniforms;
  91. }
  92. function modifyShader( material, uniforms, numberOfCurves = 1 ) {
  93. if ( material.__ok ) return;
  94. material.__ok = true;
  95. material.onBeforeCompile = shader => {
  96. if ( shader.__modified ) return;
  97. shader.__modified = true;
  98. Object.assign( shader.uniforms, uniforms );
  99. const vertexShader = `
  100. uniform sampler2D spineTexture;
  101. uniform float pathOffset;
  102. uniform float pathSegment;
  103. uniform float spineOffset;
  104. uniform float spineLength;
  105. uniform int flow;
  106. float textureLayers = ${TEXTURE_HEIGHT * numberOfCurves}.;
  107. float textureStacks = ${TEXTURE_HEIGHT / 4}.;
  108. ${shader.vertexShader}
  109. ` // chunk import moved in front of modified shader below
  110. .replace( '#include <beginnormal_vertex>', '' ) // vec3 transformedNormal declaration overriden below
  111. .replace( '#include <defaultnormal_vertex>', '' ) // vec3 transformed declaration overriden below
  112. .replace( '#include <begin_vertex>', '' ) // shader override
  113. .replace( /void\s*main\s*\(\)\s*\{/, `
  114. void main() {
  115. #include <beginnormal_vertex>
  116. vec4 worldPos = modelMatrix * vec4(position, 1.);
  117. bool bend = flow > 0;
  118. float xWeight = bend ? 0. : 1.;
  119. #ifdef USE_INSTANCING
  120. float pathOffsetFromInstanceMatrix = instanceMatrix[3][2];
  121. float spineLengthFromInstanceMatrix = instanceMatrix[3][0];
  122. float spinePortion = bend ? (worldPos.x + spineOffset) / spineLengthFromInstanceMatrix : 0.;
  123. float mt = (spinePortion * pathSegment + pathOffset + pathOffsetFromInstanceMatrix)*textureStacks;
  124. #else
  125. float spinePortion = bend ? (worldPos.x + spineOffset) / spineLength : 0.;
  126. float mt = (spinePortion * pathSegment + pathOffset)*textureStacks;
  127. #endif
  128. mt = mod(mt, textureStacks);
  129. float rowOffset = floor(mt);
  130. #ifdef USE_INSTANCING
  131. rowOffset += instanceMatrix[3][1] * ${TEXTURE_HEIGHT}.;
  132. #endif
  133. vec3 spinePos = texture2D(spineTexture, vec2(mt, (0. + rowOffset + 0.5) / textureLayers)).xyz;
  134. vec3 a = texture2D(spineTexture, vec2(mt, (1. + rowOffset + 0.5) / textureLayers)).xyz;
  135. vec3 b = texture2D(spineTexture, vec2(mt, (2. + rowOffset + 0.5) / textureLayers)).xyz;
  136. vec3 c = texture2D(spineTexture, vec2(mt, (3. + rowOffset + 0.5) / textureLayers)).xyz;
  137. mat3 basis = mat3(a, b, c);
  138. vec3 transformed = basis
  139. * vec3(worldPos.x * xWeight, worldPos.y * 1., worldPos.z * 1.)
  140. + spinePos;
  141. vec3 transformedNormal = normalMatrix * (basis * objectNormal);
  142. ` ).replace( '#include <project_vertex>', `vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
  143. gl_Position = projectionMatrix * mvPosition;` );
  144. shader.vertexShader = vertexShader;
  145. };
  146. }
  147. /**
  148. * A helper class for making meshes bend aroudn curves
  149. */
  150. class Flow {
  151. /**
  152. * @param {Mesh} mesh The mesh to clone and modify to bend around the curve
  153. * @param {number} numberOfCurves The amount of space that should preallocated for additional curves
  154. */
  155. constructor( mesh, numberOfCurves = 1 ) {
  156. const obj3D = mesh.clone();
  157. const splineTexure = initSplineTexture( numberOfCurves );
  158. const uniforms = getUniforms( splineTexure );
  159. obj3D.traverse( function ( child ) {
  160. if ( child instanceof THREE.Mesh || child instanceof THREE.InstancedMesh ) {
  161. child.material = child.material.clone();
  162. modifyShader( child.material, uniforms, numberOfCurves );
  163. }
  164. } );
  165. this.curveArray = new Array( numberOfCurves );
  166. this.curveLengthArray = new Array( numberOfCurves );
  167. this.object3D = obj3D;
  168. this.splineTexure = splineTexure;
  169. this.uniforms = uniforms;
  170. }
  171. updateCurve( index, curve ) {
  172. if ( index >= this.curveArray.length ) throw Error( 'Index out of range for Flow' );
  173. const curveLength = curve.getLength();
  174. this.uniforms.spineLength.value = curveLength;
  175. this.curveLengthArray[ index ] = curveLength;
  176. this.curveArray[ index ] = curve;
  177. updateSplineTexture( this.splineTexure, curve, index );
  178. }
  179. moveAlongCurve( amount ) {
  180. this.uniforms.pathOffset.value += amount;
  181. }
  182. }
  183. const matrix = new THREE.Matrix4();
  184. /**
  185. * A helper class for creating instanced versions of flow, where the instances are placed on the curve.
  186. */
  187. class InstancedFlow extends Flow {
  188. /**
  189. *
  190. * @param {number} count The number of instanced elements
  191. * @param {number} curveCount The number of curves to preallocate for
  192. * @param {Geometry} geometry The geometry to use for the instanced mesh
  193. * @param {Material} material The material to use for the instanced mesh
  194. */
  195. constructor( count, curveCount, geometry, material ) {
  196. const mesh = new THREE.InstancedMesh( geometry, material, count );
  197. mesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  198. super( mesh, curveCount );
  199. this.offsets = new Array( count ).fill( 0 );
  200. this.whichCurve = new Array( count ).fill( 0 );
  201. }
  202. /**
  203. * The extra information about which curve and curve position is stored in the translation components of the matrix for the instanced objects
  204. * This writes that information to the matrix and marks it as needing update.
  205. *
  206. * @param {number} index of the instanced element to update
  207. */
  208. writeChanges( index ) {
  209. matrix.makeTranslation( this.curveLengthArray[ this.whichCurve[ index ] ], this.whichCurve[ index ], this.offsets[ index ] );
  210. this.object3D.setMatrixAt( index, matrix );
  211. this.object3D.instanceMatrix.needsUpdate = true;
  212. }
  213. /**
  214. * Move an individual element along the curve by a specific amount
  215. *
  216. * @param {number} index Which element to update
  217. * @param {number} offset Move by how much
  218. */
  219. moveIndividualAlongCurve( index, offset ) {
  220. this.offsets[ index ] += offset;
  221. this.writeChanges( index );
  222. }
  223. /**
  224. * Select which curve to use for an element
  225. *
  226. * @param {number} index the index of the instanced element to update
  227. * @param {number} curveNo the index of the curve it should use
  228. */
  229. setCurve( index, curveNo ) {
  230. if ( isNaN( curveNo ) ) throw Error( 'curve index being set is Not a Number (NaN)' );
  231. this.whichCurve[ index ] = curveNo;
  232. this.writeChanges( index );
  233. }
  234. }
  235. THREE.Flow = Flow;
  236. THREE.InstancedFlow = InstancedFlow;
  237. THREE.getUniforms = getUniforms;
  238. THREE.initSplineTexture = initSplineTexture;
  239. THREE.modifyShader = modifyShader;
  240. THREE.updateSplineTexture = updateSplineTexture;
  241. } )();