WGSLNodeBuilder.js 25 KB

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