GLSLNodeBuilder.js 12 KB

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