GLSLNodeBuilder.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import { MathNode, GLSLNodeParser, NodeBuilder, NodeMaterial, FunctionNode } from '../../../nodes/Nodes.js';
  2. import UniformBuffer from '../../common/UniformBuffer.js';
  3. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. const glslMethods = {
  6. [ MathNode.ATAN2 ]: 'atan',
  7. textureDimensions: 'textureSize'
  8. };
  9. const precisionLib = {
  10. low: 'lowp',
  11. medium: 'mediump',
  12. high: 'highp'
  13. };
  14. const supports = {
  15. instance: true
  16. };
  17. class GLSLNodeBuilder extends NodeBuilder {
  18. constructor( object, renderer, scene = null ) {
  19. super( object, renderer, new GLSLNodeParser(), scene );
  20. this.uniformGroups = {};
  21. }
  22. getMethod( method ) {
  23. return glslMethods[ method ] || method;
  24. }
  25. getPropertyName( node, shaderStage ) {
  26. if ( node.isOutputStructVar ) return '';
  27. return super.getPropertyName( node, shaderStage );
  28. }
  29. buildFunctionNode( shaderNode ) {
  30. const layout = shaderNode.layout;
  31. const flowData = this.flowShaderNode( shaderNode );
  32. const parameters = [];
  33. for ( const input of layout.inputs ) {
  34. parameters.push( this.getType( input.type ) + ' ' + input.name );
  35. }
  36. //
  37. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38. ${ flowData.vars }
  39. ${ flowData.code }
  40. return ${ flowData.result };
  41. }`;
  42. //
  43. return new FunctionNode( code );
  44. }
  45. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  46. if ( texture.isTextureCube ) {
  47. return `textureCube( ${ textureProperty }, ${ uvSnippet } )`;
  48. } else if ( texture.isDepthTexture ) {
  49. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  50. } else {
  51. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  52. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  53. }
  54. }
  55. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  56. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  57. }
  58. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  59. if ( shaderStage === 'fragment' ) {
  60. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  61. } else {
  62. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  63. }
  64. }
  65. getVars( shaderStage ) {
  66. const snippets = [];
  67. const vars = this.vars[ shaderStage ];
  68. if ( vars !== undefined ) {
  69. for ( const variable of vars ) {
  70. if ( variable.isOutputStructVar ) continue;
  71. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  72. }
  73. }
  74. return snippets.join( '\n\t' );
  75. }
  76. getUniforms( shaderStage ) {
  77. const uniforms = this.uniforms[ shaderStage ];
  78. const bindingSnippets = [];
  79. const uniformGroups = {};
  80. for ( const uniform of uniforms ) {
  81. let snippet = null;
  82. let group = false;
  83. if ( uniform.type === 'texture' ) {
  84. const texture = uniform.node.value;
  85. if ( texture.compareFunction ) {
  86. snippet = `sampler2DShadow ${ uniform.name };`;
  87. } else if ( texture.isDataArrayTexture === true ) {
  88. snippet = `sampler2DArray ${ uniform.name };`;
  89. } else {
  90. snippet = `sampler2D ${ uniform.name };`;
  91. }
  92. } else if ( uniform.type === 'cubeTexture' ) {
  93. snippet = `samplerCube ${ uniform.name };`;
  94. } else if ( uniform.type === 'buffer' ) {
  95. const bufferNode = uniform.node;
  96. const bufferType = this.getType( bufferNode.bufferType );
  97. const bufferCount = bufferNode.bufferCount;
  98. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  99. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  100. } else {
  101. const vectorType = this.getVectorType( uniform.type );
  102. snippet = `${vectorType} ${uniform.name};`;
  103. group = true;
  104. }
  105. const precision = uniform.node.precision;
  106. if ( precision !== null ) {
  107. snippet = precisionLib[ precision ] + ' ' + snippet;
  108. }
  109. if ( group ) {
  110. snippet = '\t' + snippet;
  111. const groupName = uniform.groupNode.name;
  112. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  113. groupSnippets.push( snippet );
  114. } else {
  115. snippet = 'uniform ' + snippet;
  116. bindingSnippets.push( snippet );
  117. }
  118. }
  119. let output = '';
  120. for ( const name in uniformGroups ) {
  121. const groupSnippets = uniformGroups[ name ];
  122. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  123. }
  124. output += bindingSnippets.join( '\n' );
  125. return output;
  126. }
  127. getAttributes( shaderStage ) {
  128. let snippet = '';
  129. if ( shaderStage === 'vertex' ) {
  130. const attributes = this.getAttributesArray();
  131. let location = 0;
  132. for ( const attribute of attributes ) {
  133. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  134. }
  135. }
  136. return snippet;
  137. }
  138. getStructMembers( struct ) {
  139. const snippets = [];
  140. const members = struct.getMemberTypes();
  141. for ( let i = 0; i < members.length; i ++ ) {
  142. const member = members[ i ];
  143. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  144. }
  145. return snippets.join( '\n' );
  146. }
  147. getStructs( shaderStage ) {
  148. const snippets = [];
  149. const structs = this.structs[ shaderStage ];
  150. if ( structs.length === 0 ) {
  151. return 'layout( location = 0 ) out vec4 fragColor;\n';
  152. }
  153. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  154. const struct = structs[ index ];
  155. let snippet = '\n';
  156. snippet += this.getStructMembers( struct );
  157. snippet += '\n';
  158. snippets.push( snippet );
  159. }
  160. return snippets.join( '\n\n' );
  161. }
  162. getVaryings( shaderStage ) {
  163. let snippet = '';
  164. const varyings = this.varyings;
  165. if ( shaderStage === 'vertex' ) {
  166. for ( const varying of varyings ) {
  167. const type = varying.type;
  168. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  169. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  170. }
  171. } else if ( shaderStage === 'fragment' ) {
  172. for ( const varying of varyings ) {
  173. if ( varying.needsInterpolation ) {
  174. const type = varying.type;
  175. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  176. snippet += `${flat}in ${type} ${varying.name};\n`;
  177. }
  178. }
  179. }
  180. return snippet;
  181. }
  182. getVertexIndex() {
  183. return 'gl_VertexID';
  184. }
  185. getInstanceIndex() {
  186. return 'uint( gl_InstanceID )';
  187. }
  188. getFrontFacing() {
  189. return 'gl_FrontFacing';
  190. }
  191. getFragCoord() {
  192. return 'gl_FragCoord';
  193. }
  194. isAvailable( name ) {
  195. return supports[ name ] === true;
  196. }
  197. isFlipY() {
  198. return true;
  199. }
  200. _getGLSLUniformStruct( name, vars ) {
  201. return `
  202. layout( std140 ) uniform ${name} {
  203. ${vars}
  204. };`;
  205. }
  206. _getGLSLVertexCode( shaderData ) {
  207. return `#version 300 es
  208. ${ this.getSignature() }
  209. // precision
  210. precision highp float;
  211. precision highp int;
  212. // uniforms
  213. ${shaderData.uniforms}
  214. // varyings
  215. ${shaderData.varyings}
  216. // attributes
  217. ${shaderData.attributes}
  218. // codes
  219. ${shaderData.codes}
  220. void main() {
  221. // vars
  222. ${shaderData.vars}
  223. // flow
  224. ${shaderData.flow}
  225. gl_PointSize = 1.0;
  226. }
  227. `;
  228. }
  229. _getGLSLFragmentCode( shaderData ) {
  230. return `#version 300 es
  231. ${ this.getSignature() }
  232. // precision
  233. precision highp float;
  234. precision highp int;
  235. precision highp sampler2DArray;
  236. precision lowp sampler2DShadow;
  237. // uniforms
  238. ${shaderData.uniforms}
  239. // varyings
  240. ${shaderData.varyings}
  241. // codes
  242. ${shaderData.codes}
  243. ${shaderData.structs}
  244. void main() {
  245. // vars
  246. ${shaderData.vars}
  247. // flow
  248. ${shaderData.flow}
  249. }
  250. `;
  251. }
  252. buildCode() {
  253. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  254. for ( const shaderStage in shadersData ) {
  255. let flow = '// code\n\n';
  256. flow += this.flowCode[ shaderStage ];
  257. const flowNodes = this.flowNodes[ shaderStage ];
  258. const mainNode = flowNodes[ flowNodes.length - 1 ];
  259. for ( const node of flowNodes ) {
  260. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  261. const slotName = node.name;
  262. if ( slotName ) {
  263. if ( flow.length > 0 ) flow += '\n';
  264. flow += `\t// flow -> ${ slotName }\n\t`;
  265. }
  266. flow += `${ flowSlotData.code }\n\t`;
  267. if ( node === mainNode && shaderStage !== 'compute' ) {
  268. flow += '// result\n\t';
  269. if ( shaderStage === 'vertex' ) {
  270. flow += 'gl_Position = ';
  271. flow += `${ flowSlotData.result };`;
  272. } else if ( shaderStage === 'fragment' ) {
  273. if ( ! node.outputNode.isOutputStructNode ) {
  274. flow += 'fragColor = ';
  275. flow += `${ flowSlotData.result };`;
  276. }
  277. }
  278. }
  279. }
  280. const stageData = shadersData[ shaderStage ];
  281. stageData.uniforms = this.getUniforms( shaderStage );
  282. stageData.attributes = this.getAttributes( shaderStage );
  283. stageData.varyings = this.getVaryings( shaderStage );
  284. stageData.vars = this.getVars( shaderStage );
  285. stageData.structs = this.getStructs( shaderStage );
  286. stageData.codes = this.getCodes( shaderStage );
  287. stageData.flow = flow;
  288. }
  289. if ( this.material !== null ) {
  290. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  291. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  292. } else {
  293. console.warn( 'GLSLNodeBuilder: compute shaders are not supported.' );
  294. //this.computeShader = this._getGLSLComputeCode( shadersData.compute );
  295. }
  296. }
  297. getUniformFromNode( node, type, shaderStage, name = null ) {
  298. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  299. const nodeData = this.getDataFromNode( node, shaderStage );
  300. let uniformGPU = nodeData.uniformGPU;
  301. if ( uniformGPU === undefined ) {
  302. if ( type === 'texture' ) {
  303. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  304. this.bindings[ shaderStage ].push( uniformGPU );
  305. } else if ( type === 'cubeTexture' ) {
  306. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  307. this.bindings[ shaderStage ].push( uniformGPU );
  308. } else if ( type === 'buffer' ) {
  309. node.name = `NodeBuffer_${node.id}`;
  310. const buffer = new UniformBuffer( node.name, node.value );
  311. uniformNode.name = `buffer${node.id}`;
  312. this.bindings[ shaderStage ].push( buffer );
  313. uniformGPU = buffer;
  314. } else {
  315. const group = node.groupNode;
  316. const groupName = group.name;
  317. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  318. let uniformsGroup = uniformsStage[ groupName ];
  319. if ( uniformsGroup === undefined ) {
  320. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  321. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  322. uniformsStage[ groupName ] = uniformsGroup;
  323. this.bindings[ shaderStage ].push( uniformsGroup );
  324. }
  325. uniformGPU = this.getNodeUniform( uniformNode, type );
  326. uniformsGroup.addUniform( uniformGPU );
  327. }
  328. nodeData.uniformGPU = uniformGPU;
  329. }
  330. return uniformNode;
  331. }
  332. build() {
  333. // @TODO: Move this code to super.build()
  334. const { object, material } = this;
  335. if ( material !== null ) {
  336. NodeMaterial.fromMaterial( material ).build( this );
  337. } else {
  338. this.addFlow( 'compute', object );
  339. }
  340. return super.build();
  341. }
  342. }
  343. export default GLSLNodeBuilder;