WGSLNodeBuilder.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  138. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  139. }
  140. isUnfilterable( texture ) {
  141. return texture.isDataTexture === true && texture.type === FloatType;
  142. }
  143. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  144. let snippet = null;
  145. if ( texture.isVideoTexture === true ) {
  146. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  147. } else if ( this.isUnfilterable( texture ) ) {
  148. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  149. } else {
  150. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  151. }
  152. return snippet;
  153. }
  154. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  155. if ( shaderStage === 'fragment' ) {
  156. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  157. } else {
  158. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  159. }
  160. }
  161. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  162. let snippet = null;
  163. if ( texture.isVideoTexture === true ) {
  164. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  165. } else {
  166. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  167. }
  168. return snippet;
  169. }
  170. getPropertyName( node, shaderStage = this.shaderStage ) {
  171. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  172. if ( shaderStage === 'vertex' ) {
  173. return `varyings.${ node.name }`;
  174. }
  175. } else if ( node.isNodeUniform === true ) {
  176. const name = node.name;
  177. const type = node.type;
  178. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  179. return name;
  180. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  181. return `NodeBuffer_${ node.id }.${name}`;
  182. } else {
  183. return node.groupNode.name + '.' + name;
  184. }
  185. }
  186. return super.getPropertyName( node );
  187. }
  188. _getUniformGroupCount( shaderStage ) {
  189. return Object.keys( this.uniforms[ shaderStage ] ).length;
  190. }
  191. getFunctionOperator( op ) {
  192. const fnOp = wgslFnOpLib[ op ];
  193. if ( fnOp !== undefined ) {
  194. this._include( fnOp );
  195. return fnOp;
  196. }
  197. return null;
  198. }
  199. getUniformFromNode( node, type, shaderStage, name = null ) {
  200. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  201. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  202. if ( nodeData.uniformGPU === undefined ) {
  203. let uniformGPU;
  204. const bindings = this.bindings[ shaderStage ];
  205. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  206. let texture = null;
  207. if ( type === 'texture' || type === 'storageTexture' ) {
  208. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  209. } else if ( type === 'cubeTexture' ) {
  210. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  211. }
  212. texture.store = node.isStoreTextureNode === true;
  213. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  214. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  215. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  216. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  217. bindings.push( sampler, texture );
  218. uniformGPU = [ sampler, texture ];
  219. } else {
  220. bindings.push( texture );
  221. uniformGPU = [ texture ];
  222. }
  223. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  224. const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer;
  225. const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value );
  226. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  227. bindings.push( buffer );
  228. uniformGPU = buffer;
  229. } else {
  230. const group = node.groupNode;
  231. const groupName = group.name;
  232. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  233. let uniformsGroup = uniformsStage[ groupName ];
  234. if ( uniformsGroup === undefined ) {
  235. uniformsGroup = new NodeUniformsGroup( groupName, group );
  236. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  237. uniformsStage[ groupName ] = uniformsGroup;
  238. bindings.push( uniformsGroup );
  239. }
  240. if ( node.isArrayUniformNode === true ) {
  241. uniformGPU = [];
  242. for ( const uniformNode of node.nodes ) {
  243. const uniformNodeGPU = this.getNodeUniform( uniformNode, type );
  244. // fit bounds to buffer
  245. uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize );
  246. uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize );
  247. uniformsGroup.addUniform( uniformNodeGPU );
  248. uniformGPU.push( uniformNodeGPU );
  249. }
  250. } else {
  251. uniformGPU = this.getNodeUniform( uniformNode, type );
  252. uniformsGroup.addUniform( uniformGPU );
  253. }
  254. }
  255. nodeData.uniformGPU = uniformGPU;
  256. if ( shaderStage === 'vertex' ) {
  257. this.bindingsOffset[ 'fragment' ] = bindings.length;
  258. }
  259. }
  260. return uniformNode;
  261. }
  262. isReference( type ) {
  263. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube' || type === 'texture_depth_2d' || type === 'texture_storage_2d';
  264. }
  265. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  266. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  267. if ( map.has( name ) === false ) {
  268. map.set( name, {
  269. name,
  270. property,
  271. type
  272. } );
  273. }
  274. return property;
  275. }
  276. getVertexIndex() {
  277. if ( this.shaderStage === 'vertex' ) {
  278. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  279. }
  280. return 'vertexIndex';
  281. }
  282. buildFunctionCode( shaderNode ) {
  283. const layout = shaderNode.layout;
  284. const flowData = this.flowShaderNode( shaderNode );
  285. const parameters = [];
  286. for ( const input of layout.inputs ) {
  287. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  288. }
  289. //
  290. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  291. ${ flowData.vars }
  292. ${ flowData.code }
  293. return ${ flowData.result };
  294. }`;
  295. //
  296. return code;
  297. }
  298. getInstanceIndex() {
  299. if ( this.shaderStage === 'vertex' ) {
  300. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  301. }
  302. return 'instanceIndex';
  303. }
  304. getFrontFacing() {
  305. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  306. }
  307. getFragCoord() {
  308. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  309. }
  310. getFragDepth() {
  311. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  312. }
  313. isFlipY() {
  314. return false;
  315. }
  316. getBuiltins( shaderStage ) {
  317. const snippets = [];
  318. const builtins = this.builtins[ shaderStage ];
  319. if ( builtins !== undefined ) {
  320. for ( const { name, property, type } of builtins.values() ) {
  321. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  322. }
  323. }
  324. return snippets.join( ',\n\t' );
  325. }
  326. getAttributes( shaderStage ) {
  327. const snippets = [];
  328. if ( shaderStage === 'compute' ) {
  329. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  330. }
  331. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  332. const builtins = this.getBuiltins( 'attribute' );
  333. if ( builtins ) snippets.push( builtins );
  334. const attributes = this.getAttributesArray();
  335. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  336. const attribute = attributes[ index ];
  337. const name = attribute.name;
  338. const type = this.getType( attribute.type );
  339. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  340. }
  341. }
  342. return snippets.join( ',\n\t' );
  343. }
  344. getStructMembers( struct ) {
  345. const snippets = [];
  346. const members = struct.getMemberTypes();
  347. for ( let i = 0; i < members.length; i ++ ) {
  348. const member = members[ i ];
  349. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  350. }
  351. return snippets.join( ',\n' );
  352. }
  353. getStructs( shaderStage ) {
  354. const snippets = [];
  355. const structs = this.structs[ shaderStage ];
  356. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  357. const struct = structs[ index ];
  358. const name = struct.name;
  359. let snippet = `\struct ${ name } {\n`;
  360. snippet += this.getStructMembers( struct );
  361. snippet += '\n}';
  362. snippets.push( snippet );
  363. }
  364. return snippets.join( '\n\n' );
  365. }
  366. getVar( type, name ) {
  367. return `var ${ name } : ${ this.getType( type ) }`;
  368. }
  369. getVars( shaderStage ) {
  370. const snippets = [];
  371. const vars = this.vars[ shaderStage ];
  372. if ( vars !== undefined ) {
  373. for ( const variable of vars ) {
  374. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  375. }
  376. }
  377. return `\n${ snippets.join( '\n' ) }\n`;
  378. }
  379. getVaryings( shaderStage ) {
  380. const snippets = [];
  381. if ( shaderStage === 'vertex' ) {
  382. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  383. }
  384. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  385. const varyings = this.varyings;
  386. const vars = this.vars[ shaderStage ];
  387. for ( let index = 0; index < varyings.length; index ++ ) {
  388. const varying = varyings[ index ];
  389. if ( varying.needsInterpolation ) {
  390. let attributesSnippet = `@location( ${index} )`;
  391. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  392. attributesSnippet += ' @interpolate( flat )';
  393. }
  394. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  395. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  396. vars.push( varying );
  397. }
  398. }
  399. }
  400. const builtins = this.getBuiltins( shaderStage );
  401. if ( builtins ) snippets.push( builtins );
  402. const code = snippets.join( ',\n\t' );
  403. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  404. }
  405. getUniforms( shaderStage ) {
  406. const uniforms = this.uniforms[ shaderStage ];
  407. const bindingSnippets = [];
  408. const bufferSnippets = [];
  409. const structSnippets = [];
  410. const uniformGroups = {};
  411. let index = this.bindingsOffset[ shaderStage ];
  412. for ( const uniform of uniforms ) {
  413. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) {
  414. const texture = uniform.node.value;
  415. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStoreTextureNode !== true ) {
  416. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  417. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler_comparison;` );
  418. } else {
  419. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler;` );
  420. }
  421. }
  422. let textureType;
  423. if ( texture.isCubeTexture === true ) {
  424. textureType = 'texture_cube<f32>';
  425. } else if ( texture.isDataArrayTexture === true ) {
  426. textureType = 'texture_2d_array<f32>';
  427. } else if ( texture.isDepthTexture === true ) {
  428. textureType = 'texture_depth_2d';
  429. } else if ( texture.isVideoTexture === true ) {
  430. textureType = 'texture_external';
  431. } else if ( uniform.node.isStoreTextureNode === true ) {
  432. const format = getFormat( texture );
  433. textureType = 'texture_storage_2d<' + format + ', write>';
  434. } else {
  435. textureType = 'texture_2d<f32>';
  436. }
  437. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name} : ${textureType};` );
  438. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  439. const bufferNode = uniform.node;
  440. const bufferType = this.getType( bufferNode.bufferType );
  441. const bufferCount = bufferNode.bufferCount;
  442. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  443. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}${bufferCountSnippet} >\n`;
  444. const bufferAccessMode = bufferNode.isStorageBufferNode ? 'storage,read_write' : 'uniform';
  445. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, index ++ ) );
  446. } else {
  447. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  448. const groupName = uniform.groupNode.name;
  449. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  450. index: index ++,
  451. snippets: []
  452. } );
  453. if ( Array.isArray( uniform.value ) === true ) {
  454. const length = uniform.value.length;
  455. group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` );
  456. } else {
  457. group.snippets.push( `\t${uniform.name} : ${ vectorType}` );
  458. }
  459. }
  460. }
  461. for ( const name in uniformGroups ) {
  462. const group = uniformGroups[ name ];
  463. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index ) );
  464. }
  465. let code = bindingSnippets.join( '\n' );
  466. code += bufferSnippets.join( '\n' );
  467. code += structSnippets.join( '\n' );
  468. return code;
  469. }
  470. buildCode() {
  471. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  472. for ( const shaderStage in shadersData ) {
  473. const stageData = shadersData[ shaderStage ];
  474. stageData.uniforms = this.getUniforms( shaderStage );
  475. stageData.attributes = this.getAttributes( shaderStage );
  476. stageData.varyings = this.getVaryings( shaderStage );
  477. stageData.structs = this.getStructs( shaderStage );
  478. stageData.vars = this.getVars( shaderStage );
  479. stageData.codes = this.getCodes( shaderStage );
  480. //
  481. let flow = '// code\n\n';
  482. flow += this.flowCode[ shaderStage ];
  483. const flowNodes = this.flowNodes[ shaderStage ];
  484. const mainNode = flowNodes[ flowNodes.length - 1 ];
  485. const outputNode = mainNode.outputNode;
  486. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  487. for ( const node of flowNodes ) {
  488. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  489. const slotName = node.name;
  490. if ( slotName ) {
  491. if ( flow.length > 0 ) flow += '\n';
  492. flow += `\t// flow -> ${ slotName }\n\t`;
  493. }
  494. flow += `${ flowSlotData.code }\n\t`;
  495. if ( node === mainNode && shaderStage !== 'compute' ) {
  496. flow += '// result\n\n\t';
  497. if ( shaderStage === 'vertex' ) {
  498. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  499. } else if ( shaderStage === 'fragment' ) {
  500. if ( isOutputStruct ) {
  501. stageData.returnType = outputNode.nodeType;
  502. flow += `return ${ flowSlotData.result };`;
  503. } else {
  504. let structSnippet = '\t@location(0) color: vec4<f32>';
  505. const builtins = this.getBuiltins( 'output' );
  506. if ( builtins ) structSnippet += ',\n\t' + builtins;
  507. stageData.returnType = 'OutputStruct';
  508. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  509. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  510. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  511. }
  512. }
  513. }
  514. }
  515. stageData.flow = flow;
  516. }
  517. if ( this.material !== null ) {
  518. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  519. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  520. } else {
  521. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  522. }
  523. }
  524. getMethod( method, output = null ) {
  525. let wgslMethod;
  526. if ( output !== null ) {
  527. wgslMethod = this._getWGSLMethod( method + '_' + output );
  528. }
  529. if ( wgslMethod === undefined ) {
  530. wgslMethod = this._getWGSLMethod( method );
  531. }
  532. return wgslMethod || method;
  533. }
  534. getType( type ) {
  535. return wgslTypeLib[ type ] || type;
  536. }
  537. isAvailable( name ) {
  538. return supports[ name ] === true;
  539. }
  540. _getWGSLMethod( method ) {
  541. if ( wgslPolyfill[ method ] !== undefined ) {
  542. this._include( method );
  543. }
  544. return wgslMethods[ method ];
  545. }
  546. _include( name ) {
  547. const codeNode = wgslPolyfill[ name ];
  548. codeNode.build( this );
  549. if ( this.currentFunctionNode !== null ) {
  550. this.currentFunctionNode.includes.push( codeNode );
  551. }
  552. return codeNode;
  553. }
  554. _getWGSLVertexCode( shaderData ) {
  555. return `${ this.getSignature() }
  556. // uniforms
  557. ${shaderData.uniforms}
  558. // varyings
  559. ${shaderData.varyings}
  560. var<private> varyings : VaryingsStruct;
  561. // codes
  562. ${shaderData.codes}
  563. @vertex
  564. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  565. // vars
  566. ${shaderData.vars}
  567. // flow
  568. ${shaderData.flow}
  569. return varyings;
  570. }
  571. `;
  572. }
  573. _getWGSLFragmentCode( shaderData ) {
  574. return `${ this.getSignature() }
  575. // uniforms
  576. ${shaderData.uniforms}
  577. // structs
  578. ${shaderData.structs}
  579. // codes
  580. ${shaderData.codes}
  581. @fragment
  582. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  583. // vars
  584. ${shaderData.vars}
  585. // flow
  586. ${shaderData.flow}
  587. }
  588. `;
  589. }
  590. _getWGSLComputeCode( shaderData, workgroupSize ) {
  591. return `${ this.getSignature() }
  592. // system
  593. var<private> instanceIndex : u32;
  594. // uniforms
  595. ${shaderData.uniforms}
  596. // codes
  597. ${shaderData.codes}
  598. @compute @workgroup_size( ${workgroupSize} )
  599. fn main( ${shaderData.attributes} ) {
  600. // system
  601. instanceIndex = id.x;
  602. // vars
  603. ${shaderData.vars}
  604. // flow
  605. ${shaderData.flow}
  606. }
  607. `;
  608. }
  609. _getWGSLStruct( name, vars ) {
  610. return `
  611. struct ${name} {
  612. ${vars}
  613. };`;
  614. }
  615. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  616. const structName = name + 'Struct';
  617. const structSnippet = this._getWGSLStruct( structName, vars );
  618. return `${structSnippet}
  619. @binding( ${binding} ) @group( ${group} )
  620. var<${access}> ${name} : ${structName};`;
  621. }
  622. }
  623. export default WGSLNodeBuilder;