WGSLNodeBuilder.js 25 KB

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