GPUComputationRenderer.js 10 KB

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