WGSLNodeBuilder.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import { NoColorSpace, FloatType } from 'three';
  2. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  3. import NodeSampler from '../../common/nodes/NodeSampler.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. import UniformBuffer from '../../common/UniformBuffer.js';
  6. import StorageBuffer from '../../common/StorageBuffer.js';
  7. import { getVectorLength, getStrideLength } from '../../common/BufferUtils.js';
  8. import { NodeBuilder, CodeNode, NodeMaterial, FunctionNode } from '../../../nodes/Nodes.js';
  9. import { getFormat } from '../utils/WebGPUTextureUtils.js';
  10. import WGSLNodeParser from './WGSLNodeParser.js';
  11. const gpuShaderStageLib = {
  12. 'vertex': GPUShaderStage.VERTEX,
  13. 'fragment': GPUShaderStage.FRAGMENT,
  14. 'compute': GPUShaderStage.COMPUTE
  15. };
  16. const supports = {
  17. instance: true
  18. };
  19. const wgslTypeLib = {
  20. float: 'f32',
  21. int: 'i32',
  22. uint: 'u32',
  23. bool: 'bool',
  24. color: 'vec3<f32>',
  25. vec2: 'vec2<f32>',
  26. ivec2: 'vec2<i32>',
  27. uvec2: 'vec2<u32>',
  28. bvec2: 'vec2<bool>',
  29. vec3: 'vec3<f32>',
  30. ivec3: 'vec3<i32>',
  31. uvec3: 'vec3<u32>',
  32. bvec3: 'vec3<bool>',
  33. vec4: 'vec4<f32>',
  34. ivec4: 'vec4<i32>',
  35. uvec4: 'vec4<u32>',
  36. bvec4: 'vec4<bool>',
  37. mat3: 'mat3x3<f32>',
  38. imat3: 'mat3x3<i32>',
  39. umat3: 'mat3x3<u32>',
  40. bmat3: 'mat3x3<bool>',
  41. mat4: 'mat4x4<f32>',
  42. imat4: 'mat4x4<i32>',
  43. umat4: 'mat4x4<u32>',
  44. bmat4: 'mat4x4<bool>'
  45. };
  46. const wgslMethods = {
  47. dFdx: 'dpdx',
  48. dFdy: '- dpdy',
  49. mod: 'threejs_mod',
  50. lessThanEqual: 'threejs_lessThanEqual',
  51. inversesqrt: 'inverseSqrt'
  52. };
  53. const wgslPolyfill = {
  54. lessThanEqual: new CodeNode( `
  55. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  56. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  57. }
  58. ` ),
  59. mod: new CodeNode( `
  60. fn threejs_mod( x : f32, y : f32 ) -> f32 {
  61. return x - y * floor( x / y );
  62. }
  63. ` ),
  64. repeatWrapping: new CodeNode( `
  65. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  66. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  67. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  68. }
  69. ` )
  70. };
  71. class WGSLNodeBuilder extends NodeBuilder {
  72. constructor( object, renderer, scene = null ) {
  73. super( object, renderer, new WGSLNodeParser(), scene );
  74. this.uniformGroups = {};
  75. this.builtins = {
  76. vertex: new Map(),
  77. fragment: new Map(),
  78. compute: new Map(),
  79. attribute: new Map()
  80. };
  81. }
  82. build() {
  83. const { object, material } = this;
  84. if ( material !== null ) {
  85. NodeMaterial.fromMaterial( material ).build( this );
  86. } else {
  87. this.addFlow( 'compute', object );
  88. }
  89. return super.build();
  90. }
  91. needsColorSpaceToLinear( texture ) {
  92. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  93. }
  94. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  95. if ( shaderStage === 'fragment' ) {
  96. if ( depthSnippet ) {
  97. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  98. } else {
  99. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  100. }
  101. } else {
  102. return this.generateTextureLod( texture, textureProperty, uvSnippet );
  103. }
  104. }
  105. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  106. if ( shaderStage === 'fragment' ) {
  107. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  108. } else {
  109. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  110. }
  111. }
  112. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  113. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  114. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  115. } else {
  116. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  117. }
  118. }
  119. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  120. this._include( 'repeatWrapping' );
  121. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  122. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  123. }
  124. isUnfilterable( texture ) {
  125. return texture.isDataTexture === true && texture.type === FloatType;
  126. }
  127. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  128. let snippet = null;
  129. if ( texture.isVideoTexture === true ) {
  130. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  131. } else if ( this.isUnfilterable( texture ) ) {
  132. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  133. } else {
  134. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  135. }
  136. return snippet;
  137. }
  138. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  139. if ( shaderStage === 'fragment' ) {
  140. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  141. } else {
  142. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  143. }
  144. }
  145. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  146. let snippet = null;
  147. if ( texture.isVideoTexture === true ) {
  148. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  149. } else {
  150. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  151. }
  152. return snippet;
  153. }
  154. getPropertyName( node, shaderStage = this.shaderStage ) {
  155. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  156. if ( shaderStage === 'vertex' ) {
  157. return `NodeVaryings.${ node.name }`;
  158. }
  159. } else if ( node.isNodeUniform === true ) {
  160. const name = node.name;
  161. const type = node.type;
  162. if ( type === 'texture' || type === 'cubeTexture' ) {
  163. return name;
  164. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  165. return `NodeBuffer_${ node.id }.${name}`;
  166. } else {
  167. return node.groupNode.name + '.' + name;
  168. }
  169. }
  170. return super.getPropertyName( node );
  171. }
  172. _getUniformGroupCount( shaderStage ) {
  173. return Object.keys( this.uniforms[ shaderStage ] ).length;
  174. }
  175. getUniformFromNode( node, type, shaderStage, name = null ) {
  176. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  177. const nodeData = this.getDataFromNode( node, shaderStage );
  178. if ( nodeData.uniformGPU === undefined ) {
  179. let uniformGPU;
  180. const bindings = this.bindings[ shaderStage ];
  181. if ( type === 'texture' || type === 'cubeTexture' ) {
  182. let texture = null;
  183. if ( type === 'texture' ) {
  184. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  185. } else if ( type === 'cubeTexture' ) {
  186. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  187. }
  188. texture.store = node.isStoreTextureNode === true;
  189. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  190. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  191. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  192. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  193. bindings.push( sampler, texture );
  194. uniformGPU = [ sampler, texture ];
  195. } else {
  196. bindings.push( texture );
  197. uniformGPU = [ texture ];
  198. }
  199. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  200. const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer;
  201. const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value );
  202. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  203. bindings.push( buffer );
  204. uniformGPU = buffer;
  205. } else {
  206. const group = node.groupNode;
  207. const groupName = group.name;
  208. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  209. let uniformsGroup = uniformsStage[ groupName ];
  210. if ( uniformsGroup === undefined ) {
  211. uniformsGroup = new NodeUniformsGroup( groupName, group );
  212. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  213. uniformsStage[ groupName ] = uniformsGroup;
  214. bindings.push( uniformsGroup );
  215. }
  216. if ( node.isArrayUniformNode === true ) {
  217. uniformGPU = [];
  218. for ( const uniformNode of node.nodes ) {
  219. const uniformNodeGPU = this.getNodeUniform( uniformNode, type );
  220. // fit bounds to buffer
  221. uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize );
  222. uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize );
  223. uniformsGroup.addUniform( uniformNodeGPU );
  224. uniformGPU.push( uniformNodeGPU );
  225. }
  226. } else {
  227. uniformGPU = this.getNodeUniform( uniformNode, type );
  228. uniformsGroup.addUniform( uniformGPU );
  229. }
  230. }
  231. nodeData.uniformGPU = uniformGPU;
  232. if ( shaderStage === 'vertex' ) {
  233. this.bindingsOffset[ 'fragment' ] = bindings.length;
  234. }
  235. }
  236. return uniformNode;
  237. }
  238. isReference( type ) {
  239. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube' || type === 'texture_storage_2d';
  240. }
  241. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  242. const map = this.builtins[ shaderStage ];
  243. if ( map.has( name ) === false ) {
  244. map.set( name, {
  245. name,
  246. property,
  247. type
  248. } );
  249. }
  250. return property;
  251. }
  252. getVertexIndex() {
  253. if ( this.shaderStage === 'vertex' ) {
  254. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  255. }
  256. return 'vertexIndex';
  257. }
  258. buildFunctionNode( shaderNode ) {
  259. const layout = shaderNode.layout;
  260. const flowData = this.flowShaderNode( shaderNode );
  261. const parameters = [];
  262. for ( const input of layout.inputs ) {
  263. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  264. }
  265. //
  266. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  267. ${ flowData.vars }
  268. ${ flowData.code }
  269. return ${ flowData.result };
  270. }`;
  271. //
  272. return new FunctionNode( code );
  273. }
  274. getInstanceIndex() {
  275. if ( this.shaderStage === 'vertex' ) {
  276. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  277. }
  278. return 'instanceIndex';
  279. }
  280. getFrontFacing() {
  281. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  282. }
  283. getFragCoord() {
  284. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>', 'fragment' ) + '.xy';
  285. }
  286. isFlipY() {
  287. return false;
  288. }
  289. getAttributes( shaderStage ) {
  290. const snippets = [];
  291. if ( shaderStage === 'compute' ) {
  292. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  293. }
  294. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  295. for ( const { name, property, type } of this.builtins.attribute.values() ) {
  296. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  297. }
  298. const attributes = this.getAttributesArray();
  299. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  300. const attribute = attributes[ index ];
  301. const name = attribute.name;
  302. const type = this.getType( attribute.type );
  303. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  304. }
  305. }
  306. return snippets.join( ',\n\t' );
  307. }
  308. getStructMembers( struct ) {
  309. const snippets = [];
  310. const members = struct.getMemberTypes();
  311. for ( let i = 0; i < members.length; i ++ ) {
  312. const member = members[ i ];
  313. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  314. }
  315. return snippets.join( ',\n' );
  316. }
  317. getStructs( shaderStage ) {
  318. const snippets = [];
  319. const structs = this.structs[ shaderStage ];
  320. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  321. const struct = structs[ index ];
  322. const name = struct.name;
  323. let snippet = `\struct ${ name } {\n`;
  324. snippet += this.getStructMembers( struct );
  325. snippet += '\n}';
  326. snippets.push( snippet );
  327. }
  328. return snippets.join( '\n\n' );
  329. }
  330. getVar( type, name ) {
  331. return `var ${ name } : ${ this.getType( type ) }`;
  332. }
  333. getVars( shaderStage ) {
  334. const snippets = [];
  335. const vars = this.vars[ shaderStage ];
  336. if ( vars !== undefined ) {
  337. for ( const variable of vars ) {
  338. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  339. }
  340. }
  341. return `\n${ snippets.join( '\n' ) }\n`;
  342. }
  343. getVaryings( shaderStage ) {
  344. const snippets = [];
  345. if ( shaderStage === 'vertex' ) {
  346. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  347. }
  348. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  349. const varyings = this.varyings;
  350. const vars = this.vars[ shaderStage ];
  351. for ( let index = 0; index < varyings.length; index ++ ) {
  352. const varying = varyings[ index ];
  353. if ( varying.needsInterpolation ) {
  354. let attributesSnippet = `@location( ${index} )`;
  355. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  356. attributesSnippet += ' @interpolate( flat )';
  357. }
  358. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  359. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  360. vars.push( varying );
  361. }
  362. }
  363. }
  364. for ( const { name, property, type } of this.builtins[ shaderStage ].values() ) {
  365. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  366. }
  367. const code = snippets.join( ',\n\t' );
  368. return shaderStage === 'vertex' ? this._getWGSLStruct( 'NodeVaryingsStruct', '\t' + code ) : code;
  369. }
  370. getUniforms( shaderStage ) {
  371. const uniforms = this.uniforms[ shaderStage ];
  372. const bindingSnippets = [];
  373. const bufferSnippets = [];
  374. const structSnippets = [];
  375. const uniformGroups = {};
  376. let index = this.bindingsOffset[ shaderStage ];
  377. for ( const uniform of uniforms ) {
  378. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) {
  379. const texture = uniform.node.value;
  380. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStoreTextureNode !== true ) {
  381. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  382. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler_comparison;` );
  383. } else {
  384. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler;` );
  385. }
  386. }
  387. let textureType;
  388. if ( texture.isCubeTexture === true ) {
  389. textureType = 'texture_cube<f32>';
  390. } else if ( texture.isDataArrayTexture === true ) {
  391. textureType = 'texture_2d_array<f32>';
  392. } else if ( texture.isDepthTexture === true ) {
  393. textureType = 'texture_depth_2d';
  394. } else if ( texture.isVideoTexture === true ) {
  395. textureType = 'texture_external';
  396. } else if ( uniform.node.isStoreTextureNode === true ) {
  397. const format = getFormat( texture );
  398. textureType = 'texture_storage_2d<' + format + ', write>';
  399. } else {
  400. textureType = 'texture_2d<f32>';
  401. }
  402. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name} : ${textureType};` );
  403. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  404. const bufferNode = uniform.node;
  405. const bufferType = this.getType( bufferNode.bufferType );
  406. const bufferCount = bufferNode.bufferCount;
  407. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  408. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}${bufferCountSnippet} >\n`;
  409. const bufferAccessMode = bufferNode.isStorageBufferNode ? 'storage,read_write' : 'uniform';
  410. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, index ++ ) );
  411. } else {
  412. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  413. const groupName = uniform.groupNode.name;
  414. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  415. index: index ++,
  416. snippets: []
  417. } );
  418. if ( Array.isArray( uniform.value ) === true ) {
  419. const length = uniform.value.length;
  420. group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` );
  421. } else {
  422. group.snippets.push( `\t${uniform.name} : ${ vectorType}` );
  423. }
  424. }
  425. }
  426. for ( const name in uniformGroups ) {
  427. const group = uniformGroups[ name ];
  428. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index ) );
  429. }
  430. let code = bindingSnippets.join( '\n' );
  431. code += bufferSnippets.join( '\n' );
  432. code += structSnippets.join( '\n' );
  433. return code;
  434. }
  435. buildCode() {
  436. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  437. for ( const shaderStage in shadersData ) {
  438. let flow = '// code\n\n';
  439. flow += this.flowCode[ shaderStage ];
  440. const flowNodes = this.flowNodes[ shaderStage ];
  441. const mainNode = flowNodes[ flowNodes.length - 1 ];
  442. for ( const node of flowNodes ) {
  443. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  444. const slotName = node.name;
  445. if ( slotName ) {
  446. if ( flow.length > 0 ) flow += '\n';
  447. flow += `\t// flow -> ${ slotName }\n\t`;
  448. }
  449. flow += `${ flowSlotData.code }\n\t`;
  450. if ( node === mainNode && shaderStage !== 'compute' ) {
  451. flow += '// result\n\t';
  452. if ( shaderStage === 'vertex' ) {
  453. flow += 'NodeVaryings.Vertex = ';
  454. } else if ( shaderStage === 'fragment' ) {
  455. flow += 'return ';
  456. }
  457. flow += `${ flowSlotData.result };`;
  458. }
  459. }
  460. const outputNode = mainNode.outputNode;
  461. const stageData = shadersData[ shaderStage ];
  462. stageData.uniforms = this.getUniforms( shaderStage );
  463. stageData.attributes = this.getAttributes( shaderStage );
  464. stageData.varyings = this.getVaryings( shaderStage );
  465. stageData.structs = this.getStructs( shaderStage );
  466. stageData.vars = this.getVars( shaderStage );
  467. stageData.codes = this.getCodes( shaderStage );
  468. stageData.returnType = ( outputNode !== undefined && outputNode.isOutputStructNode === true ) ? outputNode.nodeType : '@location( 0 ) vec4<f32>';
  469. stageData.flow = flow;
  470. }
  471. if ( this.material !== null ) {
  472. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  473. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  474. } else {
  475. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  476. }
  477. }
  478. getMethod( method ) {
  479. if ( wgslPolyfill[ method ] !== undefined ) {
  480. this._include( method );
  481. }
  482. return wgslMethods[ method ] || method;
  483. }
  484. getType( type ) {
  485. return wgslTypeLib[ type ] || type;
  486. }
  487. isAvailable( name ) {
  488. return supports[ name ] === true;
  489. }
  490. _include( name ) {
  491. wgslPolyfill[ name ].build( this );
  492. }
  493. _getWGSLVertexCode( shaderData ) {
  494. return `${ this.getSignature() }
  495. // uniforms
  496. ${shaderData.uniforms}
  497. // varyings
  498. ${shaderData.varyings}
  499. // codes
  500. ${shaderData.codes}
  501. @vertex
  502. fn main( ${shaderData.attributes} ) -> NodeVaryingsStruct {
  503. // system
  504. var NodeVaryings: NodeVaryingsStruct;
  505. // vars
  506. ${shaderData.vars}
  507. // flow
  508. ${shaderData.flow}
  509. return NodeVaryings;
  510. }
  511. `;
  512. }
  513. _getWGSLFragmentCode( shaderData ) {
  514. return `${ this.getSignature() }
  515. // uniforms
  516. ${shaderData.uniforms}
  517. // structs
  518. ${shaderData.structs}
  519. // codes
  520. ${shaderData.codes}
  521. @fragment
  522. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  523. // vars
  524. ${shaderData.vars}
  525. // flow
  526. ${shaderData.flow}
  527. }
  528. `;
  529. }
  530. _getWGSLComputeCode( shaderData, workgroupSize ) {
  531. return `${ this.getSignature() }
  532. // system
  533. var<private> instanceIndex : u32;
  534. // uniforms
  535. ${shaderData.uniforms}
  536. // codes
  537. ${shaderData.codes}
  538. @compute @workgroup_size( ${workgroupSize} )
  539. fn main( ${shaderData.attributes} ) {
  540. // system
  541. instanceIndex = id.x;
  542. // vars
  543. ${shaderData.vars}
  544. // flow
  545. ${shaderData.flow}
  546. }
  547. `;
  548. }
  549. _getWGSLStruct( name, vars ) {
  550. return `
  551. struct ${name} {
  552. ${vars}
  553. };`;
  554. }
  555. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  556. const structName = name + 'Struct';
  557. const structSnippet = this._getWGSLStruct( structName, vars );
  558. return `${structSnippet}
  559. @binding( ${binding} ) @group( ${group} )
  560. var<${access}> ${name} : ${structName};`;
  561. }
  562. }
  563. export default WGSLNodeBuilder;