GPUComputationRenderer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. ( function () {
  2. /**
  3. * GPUComputationRenderer, based on SimulationRenderer by zz85
  4. *
  5. * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
  6. * for each compute element (texel)
  7. *
  8. * Each variable has a fragment shader that defines the computation made to obtain the variable in question.
  9. * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
  10. * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
  11. *
  12. * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
  13. * as inputs to render the textures of the next frame.
  14. *
  15. * The render targets of the variables can be used as input textures for your visualization shaders.
  16. *
  17. * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
  18. * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
  19. *
  20. * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
  21. * #DEFINE resolution vec2( 1024.0, 1024.0 )
  22. *
  23. * -------------
  24. *
  25. * Basic use:
  26. *
  27. * // Initialization...
  28. *
  29. * // Create computation renderer
  30. * const gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
  31. *
  32. * // Create initial state float textures
  33. * const pos0 = gpuCompute.createTexture();
  34. * const vel0 = gpuCompute.createTexture();
  35. * // and fill in here the texture data...
  36. *
  37. * // Add texture variables
  38. * const velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
  39. * const posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
  40. *
  41. * // Add variable dependencies
  42. * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
  43. * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
  44. *
  45. * // Add custom uniforms
  46. * velVar.material.uniforms.time = { value: 0.0 };
  47. *
  48. * // Check for completeness
  49. * const error = gpuCompute.init();
  50. * if ( error !== null ) {
  51. * console.error( error );
  52. * }
  53. *
  54. *
  55. * // In each frame...
  56. *
  57. * // Compute!
  58. * gpuCompute.compute();
  59. *
  60. * // Update texture uniforms in your visualization materials with the gpu renderer output
  61. * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
  62. *
  63. * // Do your rendering
  64. * renderer.render( myScene, myCamera );
  65. *
  66. * -------------
  67. *
  68. * Also, you can use utility functions to create THREE.ShaderMaterial and perform computations (rendering between textures)
  69. * Note that the shaders can have multiple input textures.
  70. *
  71. * const myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
  72. * const myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
  73. *
  74. * const inputTexture = gpuCompute.createTexture();
  75. *
  76. * // Fill in here inputTexture...
  77. *
  78. * myFilter1.uniforms.theTexture.value = inputTexture;
  79. *
  80. * const myRenderTarget = gpuCompute.createRenderTarget();
  81. * myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
  82. *
  83. * const outputRenderTarget = gpuCompute.createRenderTarget();
  84. *
  85. * // Now use the output texture where you want:
  86. * myMaterial.uniforms.map.value = outputRenderTarget.texture;
  87. *
  88. * // And compute each frame, before rendering to screen:
  89. * gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
  90. * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
  91. *
  92. *
  93. *
  94. * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
  95. * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
  96. * @param {WebGLRenderer} renderer The renderer
  97. */
  98. class GPUComputationRenderer {
  99. constructor( sizeX, sizeY, renderer ) {
  100. this.variables = [];
  101. this.currentTextureIndex = 0;
  102. let dataType = THREE.FloatType;
  103. const scene = new THREE.Scene();
  104. const camera = new THREE.Camera();
  105. camera.position.z = 1;
  106. const passThruUniforms = {
  107. passThruTexture: {
  108. value: null
  109. }
  110. };
  111. const passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
  112. const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), passThruShader );
  113. scene.add( mesh );
  114. this.setDataType = function ( type ) {
  115. dataType = type;
  116. return this;
  117. };
  118. this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
  119. const material = this.createShaderMaterial( computeFragmentShader );
  120. const variable = {
  121. name: variableName,
  122. initialValueTexture: initialValueTexture,
  123. material: material,
  124. dependencies: null,
  125. renderTargets: [],
  126. wrapS: null,
  127. wrapT: null,
  128. minFilter: THREE.NearestFilter,
  129. magFilter: THREE.NearestFilter
  130. };
  131. this.variables.push( variable );
  132. return variable;
  133. };
  134. this.setVariableDependencies = function ( variable, dependencies ) {
  135. variable.dependencies = dependencies;
  136. };
  137. this.init = function () {
  138. if ( renderer.capabilities.isWebGL2 === false && renderer.extensions.has( 'OES_texture_float' ) === false ) {
  139. return 'No OES_texture_float support for float textures.';
  140. }
  141. if ( renderer.capabilities.maxVertexTextures === 0 ) {
  142. return 'No support for vertex shader textures.';
  143. }
  144. for ( let i = 0; i < this.variables.length; i ++ ) {
  145. const variable = this.variables[ i ]; // Creates rendertargets and initialize them with input texture
  146. variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
  147. variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
  148. this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
  149. this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] ); // Adds dependencies uniforms to the THREE.ShaderMaterial
  150. const material = variable.material;
  151. const uniforms = material.uniforms;
  152. if ( variable.dependencies !== null ) {
  153. for ( let d = 0; d < variable.dependencies.length; d ++ ) {
  154. const depVar = variable.dependencies[ d ];
  155. if ( depVar.name !== variable.name ) {
  156. // Checks if variable exists
  157. let found = false;
  158. for ( let j = 0; j < this.variables.length; j ++ ) {
  159. if ( depVar.name === this.variables[ j ].name ) {
  160. found = true;
  161. break;
  162. }
  163. }
  164. if ( ! found ) {
  165. return 'Variable dependency not found. Variable=' + variable.name + ', dependency=' + depVar.name;
  166. }
  167. }
  168. uniforms[ depVar.name ] = {
  169. value: null
  170. };
  171. material.fragmentShader = '\nuniform sampler2D ' + depVar.name + ';\n' + material.fragmentShader;
  172. }
  173. }
  174. }
  175. this.currentTextureIndex = 0;
  176. return null;
  177. };
  178. this.compute = function () {
  179. const currentTextureIndex = this.currentTextureIndex;
  180. const nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
  181. for ( let i = 0, il = this.variables.length; i < il; i ++ ) {
  182. const variable = this.variables[ i ]; // Sets texture dependencies uniforms
  183. if ( variable.dependencies !== null ) {
  184. const uniforms = variable.material.uniforms;
  185. for ( let d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
  186. const depVar = variable.dependencies[ d ];
  187. uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
  188. }
  189. } // Performs the computation for this variable
  190. this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
  191. }
  192. this.currentTextureIndex = nextTextureIndex;
  193. };
  194. this.getCurrentRenderTarget = function ( variable ) {
  195. return variable.renderTargets[ this.currentTextureIndex ];
  196. };
  197. this.getAlternateRenderTarget = function ( variable ) {
  198. return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
  199. };
  200. function addResolutionDefine( materialShader ) {
  201. materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + ' )';
  202. }
  203. this.addResolutionDefine = addResolutionDefine; // The following functions can be used to compute things manually
  204. function createShaderMaterial( computeFragmentShader, uniforms ) {
  205. uniforms = uniforms || {};
  206. const material = new THREE.ShaderMaterial( {
  207. uniforms: uniforms,
  208. vertexShader: getPassThroughVertexShader(),
  209. fragmentShader: computeFragmentShader
  210. } );
  211. addResolutionDefine( material );
  212. return material;
  213. }
  214. this.createShaderMaterial = createShaderMaterial;
  215. this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
  216. sizeXTexture = sizeXTexture || sizeX;
  217. sizeYTexture = sizeYTexture || sizeY;
  218. wrapS = wrapS || THREE.ClampToEdgeWrapping;
  219. wrapT = wrapT || THREE.ClampToEdgeWrapping;
  220. minFilter = minFilter || THREE.NearestFilter;
  221. magFilter = magFilter || THREE.NearestFilter;
  222. const renderTarget = new THREE.WebGLRenderTarget( sizeXTexture, sizeYTexture, {
  223. wrapS: wrapS,
  224. wrapT: wrapT,
  225. minFilter: minFilter,
  226. magFilter: magFilter,
  227. format: THREE.RGBAFormat,
  228. type: dataType,
  229. depthBuffer: false
  230. } );
  231. return renderTarget;
  232. };
  233. this.createTexture = function () {
  234. const data = new Float32Array( sizeX * sizeY * 4 );
  235. return new THREE.DataTexture( data, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
  236. };
  237. this.renderTexture = function ( input, output ) {
  238. // Takes a texture, and render out in rendertarget
  239. // input = Texture
  240. // output = RenderTarget
  241. passThruUniforms.passThruTexture.value = input;
  242. this.doRenderTarget( passThruShader, output );
  243. passThruUniforms.passThruTexture.value = null;
  244. };
  245. this.doRenderTarget = function ( material, output ) {
  246. const currentRenderTarget = renderer.getRenderTarget();
  247. mesh.material = material;
  248. renderer.setRenderTarget( output );
  249. renderer.render( scene, camera );
  250. mesh.material = passThruShader;
  251. renderer.setRenderTarget( currentRenderTarget );
  252. }; // Shaders
  253. function getPassThroughVertexShader() {
  254. return 'void main() {\n' + '\n' + ' gl_Position = vec4( position, 1.0 );\n' + '\n' + '}\n';
  255. }
  256. function getPassThroughFragmentShader() {
  257. return 'uniform sampler2D passThruTexture;\n' + '\n' + 'void main() {\n' + '\n' + ' vec2 uv = gl_FragCoord.xy / resolution.xy;\n' + '\n' + ' gl_FragColor = texture2D( passThruTexture, uv );\n' + '\n' + '}\n';
  258. }
  259. }
  260. }
  261. THREE.GPUComputationRenderer = GPUComputationRenderer;
  262. } )();