GPUComputationRenderer.js 12 KB

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