CurveModifier.js 10 KB

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