WGSLNodeBuilder.js 26 KB

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