WGSLNodeBuilder.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. import { NoColorSpace, FloatType } from 'three';
  2. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  3. import NodeSampler from '../../common/nodes/NodeSampler.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. import UniformBuffer from '../../common/UniformBuffer.js';
  6. import StorageBuffer from '../../common/StorageBuffer.js';
  7. import { getVectorLength, getStrideLength } from '../../common/BufferUtils.js';
  8. import { NodeBuilder, CodeNode } from '../../../nodes/Nodes.js';
  9. import { getFormat } from '../utils/WebGPUTextureUtils.js';
  10. import WGSLNodeParser from './WGSLNodeParser.js';
  11. // GPUShaderStage is not defined in browsers not supporting WebGPU
  12. const GPUShaderStage = self.GPUShaderStage;
  13. const gpuShaderStageLib = {
  14. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  15. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  16. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  17. };
  18. const supports = {
  19. instance: true,
  20. storageBuffer: true
  21. };
  22. const wgslFnOpLib = {
  23. '^^': 'threejs_xor'
  24. };
  25. const wgslTypeLib = {
  26. float: 'f32',
  27. int: 'i32',
  28. uint: 'u32',
  29. bool: 'bool',
  30. color: 'vec3<f32>',
  31. vec2: 'vec2<f32>',
  32. ivec2: 'vec2<i32>',
  33. uvec2: 'vec2<u32>',
  34. bvec2: 'vec2<bool>',
  35. vec3: 'vec3<f32>',
  36. ivec3: 'vec3<i32>',
  37. uvec3: 'vec3<u32>',
  38. bvec3: 'vec3<bool>',
  39. vec4: 'vec4<f32>',
  40. ivec4: 'vec4<i32>',
  41. uvec4: 'vec4<u32>',
  42. bvec4: 'vec4<bool>',
  43. mat3: 'mat3x3<f32>',
  44. imat3: 'mat3x3<i32>',
  45. umat3: 'mat3x3<u32>',
  46. bmat3: 'mat3x3<bool>',
  47. mat4: 'mat4x4<f32>',
  48. imat4: 'mat4x4<i32>',
  49. umat4: 'mat4x4<u32>',
  50. bmat4: 'mat4x4<bool>'
  51. };
  52. const wgslMethods = {
  53. dFdx: 'dpdx',
  54. dFdy: '- dpdy',
  55. mod_float: 'threejs_mod_float',
  56. mod_vec2: 'threejs_mod_vec2',
  57. mod_vec3: 'threejs_mod_vec3',
  58. mod_vec4: 'threejs_mod_vec4',
  59. lessThanEqual: 'threejs_lessThanEqual',
  60. greaterThan: 'threejs_greaterThan',
  61. inversesqrt: 'inverseSqrt',
  62. bitcast: 'bitcast<f32>'
  63. };
  64. const wgslPolyfill = {
  65. threejs_xor: new CodeNode( `
  66. fn threejs_xor( a : bool, b : bool ) -> bool {
  67. return ( a || b ) && !( a && b );
  68. }
  69. ` ),
  70. lessThanEqual: new CodeNode( `
  71. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  72. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  73. }
  74. ` ),
  75. greaterThan: new CodeNode( `
  76. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  77. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  78. }
  79. ` ),
  80. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  81. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  82. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  83. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  84. repeatWrapping: new CodeNode( `
  85. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  86. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  87. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  88. }
  89. ` )
  90. };
  91. class WGSLNodeBuilder extends NodeBuilder {
  92. constructor( object, renderer, scene = null ) {
  93. super( object, renderer, new WGSLNodeParser(), scene );
  94. this.uniformGroups = {};
  95. this.builtins = {};
  96. }
  97. needsColorSpaceToLinear( texture ) {
  98. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  99. }
  100. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  101. if ( shaderStage === 'fragment' ) {
  102. if ( depthSnippet ) {
  103. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  104. } else {
  105. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  106. }
  107. } else {
  108. return this.generateTextureLod( texture, textureProperty, uvSnippet );
  109. }
  110. }
  111. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  112. if ( shaderStage === 'fragment' ) {
  113. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  114. } else {
  115. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  116. }
  117. }
  118. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  119. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  120. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  121. } else {
  122. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  123. }
  124. }
  125. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  126. this._include( 'repeatWrapping' );
  127. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  128. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  129. }
  130. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  131. if ( depthSnippet ) {
  132. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  133. } else {
  134. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  135. }
  136. }
  137. isUnfilterable( texture ) {
  138. return texture.isDataTexture === true && texture.type === FloatType;
  139. }
  140. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  141. let snippet = null;
  142. if ( texture.isVideoTexture === true ) {
  143. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  144. } else if ( this.isUnfilterable( texture ) ) {
  145. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  146. } else {
  147. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  148. }
  149. return snippet;
  150. }
  151. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  152. if ( shaderStage === 'fragment' ) {
  153. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  154. } else {
  155. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  156. }
  157. }
  158. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  159. let snippet = null;
  160. if ( texture.isVideoTexture === true ) {
  161. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  162. } else {
  163. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  164. }
  165. return snippet;
  166. }
  167. getPropertyName( node, shaderStage = this.shaderStage ) {
  168. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  169. if ( shaderStage === 'vertex' ) {
  170. return `varyings.${ node.name }`;
  171. }
  172. } else if ( node.isNodeUniform === true ) {
  173. const name = node.name;
  174. const type = node.type;
  175. if ( type === 'texture' || type === 'cubeTexture' ) {
  176. return name;
  177. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  178. return `NodeBuffer_${ node.id }.${name}`;
  179. } else {
  180. return node.groupNode.name + '.' + name;
  181. }
  182. }
  183. return super.getPropertyName( node );
  184. }
  185. _getUniformGroupCount( shaderStage ) {
  186. return Object.keys( this.uniforms[ shaderStage ] ).length;
  187. }
  188. getFunctionOperator( op ) {
  189. const fnOp = wgslFnOpLib[ op ];
  190. if ( fnOp !== undefined ) {
  191. this._include( fnOp );
  192. return fnOp;
  193. }
  194. return null;
  195. }
  196. getUniformFromNode( node, type, shaderStage, name = null ) {
  197. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  198. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  199. if ( nodeData.uniformGPU === undefined ) {
  200. let uniformGPU;
  201. const bindings = this.bindings[ shaderStage ];
  202. if ( type === 'texture' || type === 'cubeTexture' ) {
  203. let texture = null;
  204. if ( type === 'texture' ) {
  205. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  206. } else if ( type === 'cubeTexture' ) {
  207. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  208. }
  209. texture.store = node.isStoreTextureNode === true;
  210. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  211. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  212. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  213. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  214. bindings.push( sampler, texture );
  215. uniformGPU = [ sampler, texture ];
  216. } else {
  217. bindings.push( texture );
  218. uniformGPU = [ texture ];
  219. }
  220. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  221. const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer;
  222. const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value );
  223. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  224. bindings.push( buffer );
  225. uniformGPU = buffer;
  226. } else {
  227. const group = node.groupNode;
  228. const groupName = group.name;
  229. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  230. let uniformsGroup = uniformsStage[ groupName ];
  231. if ( uniformsGroup === undefined ) {
  232. uniformsGroup = new NodeUniformsGroup( groupName, group );
  233. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  234. uniformsStage[ groupName ] = uniformsGroup;
  235. bindings.push( uniformsGroup );
  236. }
  237. if ( node.isArrayUniformNode === true ) {
  238. uniformGPU = [];
  239. for ( const uniformNode of node.nodes ) {
  240. const uniformNodeGPU = this.getNodeUniform( uniformNode, type );
  241. // fit bounds to buffer
  242. uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize );
  243. uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize );
  244. uniformsGroup.addUniform( uniformNodeGPU );
  245. uniformGPU.push( uniformNodeGPU );
  246. }
  247. } else {
  248. uniformGPU = this.getNodeUniform( uniformNode, type );
  249. uniformsGroup.addUniform( uniformGPU );
  250. }
  251. }
  252. nodeData.uniformGPU = uniformGPU;
  253. if ( shaderStage === 'vertex' ) {
  254. this.bindingsOffset[ 'fragment' ] = bindings.length;
  255. }
  256. }
  257. return uniformNode;
  258. }
  259. isReference( type ) {
  260. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube' || type === 'texture_depth_2d' || type === 'texture_storage_2d';
  261. }
  262. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  263. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  264. if ( map.has( name ) === false ) {
  265. map.set( name, {
  266. name,
  267. property,
  268. type
  269. } );
  270. }
  271. return property;
  272. }
  273. getVertexIndex() {
  274. if ( this.shaderStage === 'vertex' ) {
  275. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  276. }
  277. return 'vertexIndex';
  278. }
  279. buildFunctionCode( shaderNode ) {
  280. const layout = shaderNode.layout;
  281. const flowData = this.flowShaderNode( shaderNode );
  282. const parameters = [];
  283. for ( const input of layout.inputs ) {
  284. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  285. }
  286. //
  287. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  288. ${ flowData.vars }
  289. ${ flowData.code }
  290. return ${ flowData.result };
  291. }`;
  292. //
  293. return code;
  294. }
  295. getInstanceIndex() {
  296. if ( this.shaderStage === 'vertex' ) {
  297. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  298. }
  299. return 'instanceIndex';
  300. }
  301. getFrontFacing() {
  302. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  303. }
  304. getFragCoord() {
  305. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  306. }
  307. getFragDepth() {
  308. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  309. }
  310. isFlipY() {
  311. return false;
  312. }
  313. getBuiltins( shaderStage ) {
  314. const snippets = [];
  315. const builtins = this.builtins[ shaderStage ];
  316. if ( builtins !== undefined ) {
  317. for ( const { name, property, type } of builtins.values() ) {
  318. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  319. }
  320. }
  321. return snippets.join( ',\n\t' );
  322. }
  323. getAttributes( shaderStage ) {
  324. const snippets = [];
  325. if ( shaderStage === 'compute' ) {
  326. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  327. }
  328. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  329. const builtins = this.getBuiltins( 'attribute' );
  330. if ( builtins ) snippets.push( builtins );
  331. const attributes = this.getAttributesArray();
  332. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  333. const attribute = attributes[ index ];
  334. const name = attribute.name;
  335. const type = this.getType( attribute.type );
  336. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  337. }
  338. }
  339. return snippets.join( ',\n\t' );
  340. }
  341. getStructMembers( struct ) {
  342. const snippets = [];
  343. const members = struct.getMemberTypes();
  344. for ( let i = 0; i < members.length; i ++ ) {
  345. const member = members[ i ];
  346. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  347. }
  348. return snippets.join( ',\n' );
  349. }
  350. getStructs( shaderStage ) {
  351. const snippets = [];
  352. const structs = this.structs[ shaderStage ];
  353. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  354. const struct = structs[ index ];
  355. const name = struct.name;
  356. let snippet = `\struct ${ name } {\n`;
  357. snippet += this.getStructMembers( struct );
  358. snippet += '\n}';
  359. snippets.push( snippet );
  360. }
  361. return snippets.join( '\n\n' );
  362. }
  363. getVar( type, name ) {
  364. return `var ${ name } : ${ this.getType( type ) }`;
  365. }
  366. getVars( shaderStage ) {
  367. const snippets = [];
  368. const vars = this.vars[ shaderStage ];
  369. if ( vars !== undefined ) {
  370. for ( const variable of vars ) {
  371. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  372. }
  373. }
  374. return `\n${ snippets.join( '\n' ) }\n`;
  375. }
  376. getVaryings( shaderStage ) {
  377. const snippets = [];
  378. if ( shaderStage === 'vertex' ) {
  379. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  380. }
  381. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  382. const varyings = this.varyings;
  383. const vars = this.vars[ shaderStage ];
  384. for ( let index = 0; index < varyings.length; index ++ ) {
  385. const varying = varyings[ index ];
  386. if ( varying.needsInterpolation ) {
  387. let attributesSnippet = `@location( ${index} )`;
  388. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  389. attributesSnippet += ' @interpolate( flat )';
  390. }
  391. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  392. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  393. vars.push( varying );
  394. }
  395. }
  396. }
  397. const builtins = this.getBuiltins( shaderStage );
  398. if ( builtins ) snippets.push( builtins );
  399. const code = snippets.join( ',\n\t' );
  400. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  401. }
  402. getUniforms( shaderStage ) {
  403. const uniforms = this.uniforms[ shaderStage ];
  404. const bindingSnippets = [];
  405. const bufferSnippets = [];
  406. const structSnippets = [];
  407. const uniformGroups = {};
  408. let index = this.bindingsOffset[ shaderStage ];
  409. for ( const uniform of uniforms ) {
  410. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) {
  411. const texture = uniform.node.value;
  412. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStoreTextureNode !== true ) {
  413. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  414. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler_comparison;` );
  415. } else {
  416. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler;` );
  417. }
  418. }
  419. let textureType;
  420. if ( texture.isCubeTexture === true ) {
  421. textureType = 'texture_cube<f32>';
  422. } else if ( texture.isDataArrayTexture === true ) {
  423. textureType = 'texture_2d_array<f32>';
  424. } else if ( texture.isDepthTexture === true ) {
  425. textureType = 'texture_depth_2d';
  426. } else if ( texture.isVideoTexture === true ) {
  427. textureType = 'texture_external';
  428. } else if ( uniform.node.isStoreTextureNode === true ) {
  429. const format = getFormat( texture );
  430. textureType = 'texture_storage_2d<' + format + ', write>';
  431. } else {
  432. textureType = 'texture_2d<f32>';
  433. }
  434. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name} : ${textureType};` );
  435. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  436. const bufferNode = uniform.node;
  437. const bufferType = this.getType( bufferNode.bufferType );
  438. const bufferCount = bufferNode.bufferCount;
  439. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  440. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}${bufferCountSnippet} >\n`;
  441. const bufferAccessMode = bufferNode.isStorageBufferNode ? 'storage,read_write' : 'uniform';
  442. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, index ++ ) );
  443. } else {
  444. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  445. const groupName = uniform.groupNode.name;
  446. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  447. index: index ++,
  448. snippets: []
  449. } );
  450. if ( Array.isArray( uniform.value ) === true ) {
  451. const length = uniform.value.length;
  452. group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` );
  453. } else {
  454. group.snippets.push( `\t${uniform.name} : ${ vectorType}` );
  455. }
  456. }
  457. }
  458. for ( const name in uniformGroups ) {
  459. const group = uniformGroups[ name ];
  460. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index ) );
  461. }
  462. let code = bindingSnippets.join( '\n' );
  463. code += bufferSnippets.join( '\n' );
  464. code += structSnippets.join( '\n' );
  465. return code;
  466. }
  467. buildCode() {
  468. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  469. for ( const shaderStage in shadersData ) {
  470. const stageData = shadersData[ shaderStage ];
  471. stageData.uniforms = this.getUniforms( shaderStage );
  472. stageData.attributes = this.getAttributes( shaderStage );
  473. stageData.varyings = this.getVaryings( shaderStage );
  474. stageData.structs = this.getStructs( shaderStage );
  475. stageData.vars = this.getVars( shaderStage );
  476. stageData.codes = this.getCodes( shaderStage );
  477. //
  478. let flow = '// code\n\n';
  479. flow += this.flowCode[ shaderStage ];
  480. const flowNodes = this.flowNodes[ shaderStage ];
  481. const mainNode = flowNodes[ flowNodes.length - 1 ];
  482. const outputNode = mainNode.outputNode;
  483. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  484. for ( const node of flowNodes ) {
  485. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  486. const slotName = node.name;
  487. if ( slotName ) {
  488. if ( flow.length > 0 ) flow += '\n';
  489. flow += `\t// flow -> ${ slotName }\n\t`;
  490. }
  491. flow += `${ flowSlotData.code }\n\t`;
  492. if ( node === mainNode && shaderStage !== 'compute' ) {
  493. flow += '// result\n\n\t';
  494. if ( shaderStage === 'vertex' ) {
  495. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  496. } else if ( shaderStage === 'fragment' ) {
  497. if ( isOutputStruct ) {
  498. stageData.returnType = outputNode.nodeType;
  499. flow += `return ${ flowSlotData.result };`;
  500. } else {
  501. let structSnippet = '\t@location(0) color: vec4<f32>';
  502. const builtins = this.getBuiltins( 'output' );
  503. if ( builtins ) structSnippet += ',\n\t' + builtins;
  504. stageData.returnType = 'OutputStruct';
  505. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  506. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  507. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  508. }
  509. }
  510. }
  511. }
  512. stageData.flow = flow;
  513. }
  514. if ( this.material !== null ) {
  515. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  516. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  517. } else {
  518. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  519. }
  520. }
  521. getMethod( method, output = null ) {
  522. let wgslMethod;
  523. if ( output !== null ) {
  524. wgslMethod = this._getWGSLMethod( method + '_' + output );
  525. }
  526. if ( wgslMethod === undefined ) {
  527. wgslMethod = this._getWGSLMethod( method );
  528. }
  529. return wgslMethod || method;
  530. }
  531. getType( type ) {
  532. return wgslTypeLib[ type ] || type;
  533. }
  534. isAvailable( name ) {
  535. return supports[ name ] === true;
  536. }
  537. _getWGSLMethod( method ) {
  538. if ( wgslPolyfill[ method ] !== undefined ) {
  539. this._include( method );
  540. }
  541. return wgslMethods[ method ];
  542. }
  543. _include( name ) {
  544. const codeNode = wgslPolyfill[ name ];
  545. codeNode.build( this );
  546. if ( this.currentFunctionNode !== null ) {
  547. this.currentFunctionNode.includes.push( codeNode );
  548. }
  549. return codeNode;
  550. }
  551. _getWGSLVertexCode( shaderData ) {
  552. return `${ this.getSignature() }
  553. // uniforms
  554. ${shaderData.uniforms}
  555. // varyings
  556. ${shaderData.varyings}
  557. var<private> varyings : VaryingsStruct;
  558. // codes
  559. ${shaderData.codes}
  560. @vertex
  561. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  562. // vars
  563. ${shaderData.vars}
  564. // flow
  565. ${shaderData.flow}
  566. return varyings;
  567. }
  568. `;
  569. }
  570. _getWGSLFragmentCode( shaderData ) {
  571. return `${ this.getSignature() }
  572. // uniforms
  573. ${shaderData.uniforms}
  574. // structs
  575. ${shaderData.structs}
  576. // codes
  577. ${shaderData.codes}
  578. @fragment
  579. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  580. // vars
  581. ${shaderData.vars}
  582. // flow
  583. ${shaderData.flow}
  584. }
  585. `;
  586. }
  587. _getWGSLComputeCode( shaderData, workgroupSize ) {
  588. return `${ this.getSignature() }
  589. // system
  590. var<private> instanceIndex : u32;
  591. // uniforms
  592. ${shaderData.uniforms}
  593. // codes
  594. ${shaderData.codes}
  595. @compute @workgroup_size( ${workgroupSize} )
  596. fn main( ${shaderData.attributes} ) {
  597. // system
  598. instanceIndex = id.x;
  599. // vars
  600. ${shaderData.vars}
  601. // flow
  602. ${shaderData.flow}
  603. }
  604. `;
  605. }
  606. _getWGSLStruct( name, vars ) {
  607. return `
  608. struct ${name} {
  609. ${vars}
  610. };`;
  611. }
  612. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  613. const structName = name + 'Struct';
  614. const structSnippet = this._getWGSLStruct( structName, vars );
  615. return `${structSnippet}
  616. @binding( ${binding} ) @group( ${group} )
  617. var<${access}> ${name} : ${structName};`;
  618. }
  619. }
  620. export default WGSLNodeBuilder;