WGSLNodeBuilder.js 22 KB

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