WGSLNodeBuilder.js 26 KB

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