GLSLNodeBuilder.js 16 KB

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