GLSLNodeBuilder.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import { MathNode, GLSLNodeParser, NodeBuilder, UniformNode, vectorComponents } from '../../../nodes/Nodes.js';
  2. import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
  3. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture, NodeSampledTexture3D } from '../../common/nodes/NodeSampledTexture.js';
  5. import { RedFormat, RGFormat, IntType, DataTexture, RGBFormat, RGBAFormat, FloatType } from 'three';
  6. const glslMethods = {
  7. [ MathNode.ATAN2 ]: 'atan',
  8. textureDimensions: 'textureSize',
  9. equals: 'equal'
  10. };
  11. const precisionLib = {
  12. low: 'lowp',
  13. medium: 'mediump',
  14. high: 'highp'
  15. };
  16. const supports = {
  17. instance: true,
  18. swizzleAssign: true
  19. };
  20. const defaultPrecisions = `
  21. precision highp float;
  22. precision highp int;
  23. precision highp sampler3D;
  24. precision mediump sampler2DArray;
  25. precision lowp sampler2DShadow;
  26. `;
  27. class GLSLNodeBuilder extends NodeBuilder {
  28. constructor( object, renderer, scene = null ) {
  29. super( object, renderer, new GLSLNodeParser(), scene );
  30. this.uniformGroups = {};
  31. this.transforms = [];
  32. }
  33. getMethod( method ) {
  34. return glslMethods[ method ] || method;
  35. }
  36. getPropertyName( node, shaderStage ) {
  37. return super.getPropertyName( node, shaderStage );
  38. }
  39. getOutputStructName() {
  40. return '';
  41. }
  42. buildFunctionCode( shaderNode ) {
  43. const layout = shaderNode.layout;
  44. const flowData = this.flowShaderNode( shaderNode );
  45. const parameters = [];
  46. for ( const input of layout.inputs ) {
  47. parameters.push( this.getType( input.type ) + ' ' + input.name );
  48. }
  49. //
  50. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  51. ${ flowData.vars }
  52. ${ flowData.code }
  53. return ${ flowData.result };
  54. }`;
  55. //
  56. return code;
  57. }
  58. setupPBO( storageBufferNode ) {
  59. const attribute = storageBufferNode.value;
  60. if ( attribute.pbo === undefined ) {
  61. const originalArray = attribute.array;
  62. const numElements = attribute.count * attribute.itemSize;
  63. const { itemSize } = attribute;
  64. let format = RedFormat;
  65. if ( itemSize === 2 ) {
  66. format = RGFormat;
  67. } else if ( itemSize === 3 ) {
  68. format = RGBFormat;
  69. } else if ( itemSize === 4 ) {
  70. format = RGBAFormat;
  71. }
  72. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  73. let height = Math.ceil( ( numElements / itemSize ) / width );
  74. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  75. const newSize = width * height * itemSize;
  76. const newArray = new Float32Array( newSize );
  77. newArray.set( originalArray, 0 );
  78. attribute.array = newArray;
  79. const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType );
  80. pboTexture.needsUpdate = true;
  81. pboTexture.isPBOTexture = true;
  82. const pbo = new UniformNode( pboTexture );
  83. pbo.setPrecision( 'high' );
  84. attribute.pboNode = pbo;
  85. attribute.pbo = pbo.value;
  86. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  87. }
  88. }
  89. generatePBO( storageArrayElementNode ) {
  90. const { node, indexNode } = storageArrayElementNode;
  91. const attribute = node.value;
  92. if ( this.renderer.backend.has( attribute ) ) {
  93. const attributeData = this.renderer.backend.get( attribute );
  94. attributeData.pbo = attribute.pbo;
  95. }
  96. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  97. const textureName = this.getPropertyName( nodeUniform );
  98. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  99. const indexSnippet = indexNode.build( this, 'uint' );
  100. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  101. let propertyName = elementNodeData.propertyName;
  102. if ( propertyName === undefined ) {
  103. // property element
  104. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  105. propertyName = this.getPropertyName( nodeVar );
  106. // property size
  107. const bufferNodeData = this.getDataFromNode( node );
  108. let propertySizeName = bufferNodeData.propertySizeName;
  109. if ( propertySizeName === undefined ) {
  110. propertySizeName = propertyName + 'Size';
  111. this.getVarFromNode( node, propertySizeName, 'uint' );
  112. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  113. bufferNodeData.propertySizeName = propertySizeName;
  114. }
  115. //
  116. const { itemSize } = attribute;
  117. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  118. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  119. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  120. //
  121. this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` );
  122. elementNodeData.propertyName = propertyName;
  123. }
  124. return propertyName;
  125. }
  126. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  127. if ( depthSnippet ) {
  128. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  129. } else {
  130. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  131. }
  132. }
  133. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  134. if ( texture.isDepthTexture ) {
  135. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  136. } else {
  137. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  138. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  139. }
  140. }
  141. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  142. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  143. }
  144. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  145. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  146. }
  147. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  148. if ( shaderStage === 'fragment' ) {
  149. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  150. } else {
  151. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  152. }
  153. }
  154. getVars( shaderStage ) {
  155. const snippets = [];
  156. const vars = this.vars[ shaderStage ];
  157. if ( vars !== undefined ) {
  158. for ( const variable of vars ) {
  159. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  160. }
  161. }
  162. return snippets.join( '\n\t' );
  163. }
  164. getUniforms( shaderStage ) {
  165. const uniforms = this.uniforms[ shaderStage ];
  166. const bindingSnippets = [];
  167. const uniformGroups = {};
  168. for ( const uniform of uniforms ) {
  169. let snippet = null;
  170. let group = false;
  171. if ( uniform.type === 'texture' ) {
  172. const texture = uniform.node.value;
  173. if ( texture.compareFunction ) {
  174. snippet = `sampler2DShadow ${ uniform.name };`;
  175. } else if ( texture.isDataArrayTexture === true ) {
  176. snippet = `sampler2DArray ${ uniform.name };`;
  177. } else {
  178. snippet = `sampler2D ${ uniform.name };`;
  179. }
  180. } else if ( uniform.type === 'cubeTexture' ) {
  181. snippet = `samplerCube ${ uniform.name };`;
  182. } else if ( uniform.type === 'texture3D' ) {
  183. snippet = `sampler3D ${ uniform.name };`;
  184. } else if ( uniform.type === 'buffer' ) {
  185. const bufferNode = uniform.node;
  186. const bufferType = this.getType( bufferNode.bufferType );
  187. const bufferCount = bufferNode.bufferCount;
  188. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  189. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  190. } else {
  191. const vectorType = this.getVectorType( uniform.type );
  192. snippet = `${vectorType} ${uniform.name};`;
  193. group = true;
  194. }
  195. const precision = uniform.node.precision;
  196. if ( precision !== null ) {
  197. snippet = precisionLib[ precision ] + ' ' + snippet;
  198. }
  199. if ( group ) {
  200. snippet = '\t' + snippet;
  201. const groupName = uniform.groupNode.name;
  202. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  203. groupSnippets.push( snippet );
  204. } else {
  205. snippet = 'uniform ' + snippet;
  206. bindingSnippets.push( snippet );
  207. }
  208. }
  209. let output = '';
  210. for ( const name in uniformGroups ) {
  211. const groupSnippets = uniformGroups[ name ];
  212. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  213. }
  214. output += bindingSnippets.join( '\n' );
  215. return output;
  216. }
  217. getTypeFromAttribute( attribute ) {
  218. let nodeType = super.getTypeFromAttribute( attribute );
  219. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  220. let dataAttribute = attribute;
  221. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  222. const array = dataAttribute.array;
  223. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  224. nodeType = nodeType.slice( 1 );
  225. }
  226. }
  227. return nodeType;
  228. }
  229. getAttributes( shaderStage ) {
  230. let snippet = '';
  231. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  232. const attributes = this.getAttributesArray();
  233. let location = 0;
  234. for ( const attribute of attributes ) {
  235. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  236. }
  237. }
  238. return snippet;
  239. }
  240. getStructMembers( struct ) {
  241. const snippets = [];
  242. const members = struct.getMemberTypes();
  243. for ( let i = 0; i < members.length; i ++ ) {
  244. const member = members[ i ];
  245. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  246. }
  247. return snippets.join( '\n' );
  248. }
  249. getStructs( shaderStage ) {
  250. const snippets = [];
  251. const structs = this.structs[ shaderStage ];
  252. if ( structs.length === 0 ) {
  253. return 'layout( location = 0 ) out vec4 fragColor;\n';
  254. }
  255. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  256. const struct = structs[ index ];
  257. let snippet = '\n';
  258. snippet += this.getStructMembers( struct );
  259. snippet += '\n';
  260. snippets.push( snippet );
  261. }
  262. return snippets.join( '\n\n' );
  263. }
  264. getVaryings( shaderStage ) {
  265. let snippet = '';
  266. const varyings = this.varyings;
  267. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  268. for ( const varying of varyings ) {
  269. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  270. const type = varying.type;
  271. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  272. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  273. }
  274. } else if ( shaderStage === 'fragment' ) {
  275. for ( const varying of varyings ) {
  276. if ( varying.needsInterpolation ) {
  277. const type = varying.type;
  278. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  279. snippet += `${flat}in ${type} ${varying.name};\n`;
  280. }
  281. }
  282. }
  283. return snippet;
  284. }
  285. getVertexIndex() {
  286. return 'uint( gl_VertexID )';
  287. }
  288. getInstanceIndex() {
  289. return 'uint( gl_InstanceID )';
  290. }
  291. getFrontFacing() {
  292. return 'gl_FrontFacing';
  293. }
  294. getFragCoord() {
  295. return 'gl_FragCoord';
  296. }
  297. getFragDepth() {
  298. return 'gl_FragDepth';
  299. }
  300. isAvailable( name ) {
  301. return supports[ name ] === true;
  302. }
  303. isFlipY() {
  304. return true;
  305. }
  306. registerTransform( varyingName, attributeNode ) {
  307. this.transforms.push( { varyingName, attributeNode } );
  308. }
  309. getTransforms( /* shaderStage */ ) {
  310. const transforms = this.transforms;
  311. let snippet = '';
  312. for ( let i = 0; i < transforms.length; i ++ ) {
  313. const transform = transforms[ i ];
  314. const attributeName = this.getPropertyName( transform.attributeNode );
  315. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  316. }
  317. return snippet;
  318. }
  319. _getGLSLUniformStruct( name, vars ) {
  320. return `
  321. layout( std140 ) uniform ${name} {
  322. ${vars}
  323. };`;
  324. }
  325. _getGLSLVertexCode( shaderData ) {
  326. return `#version 300 es
  327. ${ this.getSignature() }
  328. // precision
  329. ${ defaultPrecisions }
  330. // uniforms
  331. ${shaderData.uniforms}
  332. // varyings
  333. ${shaderData.varyings}
  334. // attributes
  335. ${shaderData.attributes}
  336. // codes
  337. ${shaderData.codes}
  338. void main() {
  339. // vars
  340. ${shaderData.vars}
  341. // transforms
  342. ${shaderData.transforms}
  343. // flow
  344. ${shaderData.flow}
  345. gl_PointSize = 1.0;
  346. }
  347. `;
  348. }
  349. _getGLSLFragmentCode( shaderData ) {
  350. return `#version 300 es
  351. ${ this.getSignature() }
  352. // precision
  353. ${ defaultPrecisions }
  354. // uniforms
  355. ${shaderData.uniforms}
  356. // varyings
  357. ${shaderData.varyings}
  358. // codes
  359. ${shaderData.codes}
  360. ${shaderData.structs}
  361. void main() {
  362. // vars
  363. ${shaderData.vars}
  364. // flow
  365. ${shaderData.flow}
  366. }
  367. `;
  368. }
  369. buildCode() {
  370. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  371. for ( const shaderStage in shadersData ) {
  372. let flow = '// code\n\n';
  373. flow += this.flowCode[ shaderStage ];
  374. const flowNodes = this.flowNodes[ shaderStage ];
  375. const mainNode = flowNodes[ flowNodes.length - 1 ];
  376. for ( const node of flowNodes ) {
  377. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  378. const slotName = node.name;
  379. if ( slotName ) {
  380. if ( flow.length > 0 ) flow += '\n';
  381. flow += `\t// flow -> ${ slotName }\n\t`;
  382. }
  383. flow += `${ flowSlotData.code }\n\t`;
  384. if ( node === mainNode && shaderStage !== 'compute' ) {
  385. flow += '// result\n\t';
  386. if ( shaderStage === 'vertex' ) {
  387. flow += 'gl_Position = ';
  388. flow += `${ flowSlotData.result };`;
  389. } else if ( shaderStage === 'fragment' ) {
  390. if ( ! node.outputNode.isOutputStructNode ) {
  391. flow += 'fragColor = ';
  392. flow += `${ flowSlotData.result };`;
  393. }
  394. }
  395. }
  396. }
  397. const stageData = shadersData[ shaderStage ];
  398. stageData.uniforms = this.getUniforms( shaderStage );
  399. stageData.attributes = this.getAttributes( shaderStage );
  400. stageData.varyings = this.getVaryings( shaderStage );
  401. stageData.vars = this.getVars( shaderStage );
  402. stageData.structs = this.getStructs( shaderStage );
  403. stageData.codes = this.getCodes( shaderStage );
  404. stageData.transforms = this.getTransforms( shaderStage );
  405. stageData.flow = flow;
  406. }
  407. if ( this.material !== null ) {
  408. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  409. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  410. } else {
  411. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  412. }
  413. }
  414. getUniformFromNode( node, type, shaderStage, name = null ) {
  415. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  416. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  417. let uniformGPU = nodeData.uniformGPU;
  418. if ( uniformGPU === undefined ) {
  419. if ( type === 'texture' ) {
  420. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  421. this.bindings[ shaderStage ].push( uniformGPU );
  422. } else if ( type === 'cubeTexture' ) {
  423. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  424. this.bindings[ shaderStage ].push( uniformGPU );
  425. } else if ( type === 'texture3D' ) {
  426. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node );
  427. this.bindings[ shaderStage ].push( uniformGPU );
  428. } else if ( type === 'buffer' ) {
  429. node.name = `NodeBuffer_${ node.id }`;
  430. uniformNode.name = `buffer${ node.id }`;
  431. const buffer = new NodeUniformBuffer( node );
  432. buffer.name = node.name;
  433. this.bindings[ shaderStage ].push( buffer );
  434. uniformGPU = buffer;
  435. } else {
  436. const group = node.groupNode;
  437. const groupName = group.name;
  438. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  439. let uniformsGroup = uniformsStage[ groupName ];
  440. if ( uniformsGroup === undefined ) {
  441. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  442. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  443. uniformsStage[ groupName ] = uniformsGroup;
  444. this.bindings[ shaderStage ].push( uniformsGroup );
  445. }
  446. uniformGPU = this.getNodeUniform( uniformNode, type );
  447. uniformsGroup.addUniform( uniformGPU );
  448. }
  449. nodeData.uniformGPU = uniformGPU;
  450. }
  451. return uniformNode;
  452. }
  453. }
  454. export default GLSLNodeBuilder;