CurveModifier.js 9.1 KB

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