WebGPUNodeBuilder.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import WebGPUNodeUniformsGroup from './WebGPUNodeUniformsGroup.js';
  2. import {
  3. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  4. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  5. } from './WebGPUNodeUniform.js';
  6. import WebGPUNodeSampler from './WebGPUNodeSampler.js';
  7. import { WebGPUNodeSampledTexture, WebGPUNodeSampledCubeTexture } from './WebGPUNodeSampledTexture.js';
  8. import WebGPUUniformBuffer from '../WebGPUUniformBuffer.js';
  9. import { getVectorLength, getStrideLength } from '../WebGPUBufferUtils.js';
  10. import NodeBuilder from 'three-nodes/core/NodeBuilder.js';
  11. import WGSLNodeParser from 'three-nodes/parsers/WGSLNodeParser.js';
  12. import CodeNode from 'three-nodes/core/CodeNode.js';
  13. import { NodeMaterial } from 'three-nodes/materials/Materials.js';
  14. const wgslTypeLib = {
  15. float: 'f32',
  16. int: 'i32',
  17. uint: 'u32',
  18. bool: 'bool',
  19. vec2: 'vec2<f32>',
  20. ivec2: 'vec2<i32>',
  21. uvec2: 'vec2<u32>',
  22. bvec2: 'vec2<bool>',
  23. vec3: 'vec3<f32>',
  24. ivec3: 'vec3<i32>',
  25. uvec3: 'vec3<u32>',
  26. bvec3: 'vec3<bool>',
  27. vec4: 'vec4<f32>',
  28. ivec4: 'vec4<i32>',
  29. uvec4: 'vec4<u32>',
  30. bvec4: 'vec4<bool>',
  31. mat3: 'mat3x3<f32>',
  32. imat3: 'mat3x3<i32>',
  33. umat3: 'mat3x3<u32>',
  34. bmat3: 'mat3x3<bool>',
  35. mat4: 'mat4x4<f32>',
  36. imat4: 'mat4x4<i32>',
  37. umat4: 'mat4x4<u32>',
  38. bmat4: 'mat4x4<bool>'
  39. };
  40. const wgslMethods = {
  41. dFdx: 'dpdx',
  42. dFdy: 'dpdy'
  43. };
  44. const wgslPolyfill = {
  45. lessThanEqual: new CodeNode( `
  46. fn lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  47. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  48. }
  49. ` ),
  50. mod: new CodeNode( `
  51. fn mod( x : f32, y : f32 ) -> f32 {
  52. return x - y * floor( x / y );
  53. }
  54. ` ),
  55. repeatWrapping: new CodeNode( `
  56. fn repeatWrapping( uv : vec2<f32>, dimension : vec2<i32> ) -> vec2<i32> {
  57. let uvScaled = vec2<i32>( uv * vec2<f32>( dimension ) );
  58. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  59. }
  60. ` ),
  61. inversesqrt: new CodeNode( `
  62. fn inversesqrt( x : f32 ) -> f32 {
  63. return 1.0 / sqrt( x );
  64. }
  65. ` )
  66. };
  67. class WebGPUNodeBuilder extends NodeBuilder {
  68. constructor( object, renderer ) {
  69. super( object, renderer, new WGSLNodeParser() );
  70. this.lightNode = null;
  71. this.fogNode = null;
  72. this.bindings = { vertex: [], fragment: [] };
  73. this.bindingsOffset = { vertex: 0, fragment: 0 };
  74. this.uniformsGroup = {};
  75. }
  76. build() {
  77. NodeMaterial.fromMaterial( this.material ).build( this );
  78. return super.build();
  79. }
  80. addFlowCode( code ) {
  81. if ( ! /;\s*$/.test( code ) ) {
  82. code += ';';
  83. }
  84. super.addFlowCode( code + '\n\t' );
  85. }
  86. getSampler( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  87. if ( shaderStage === 'fragment' ) {
  88. return `textureSample( ${textureProperty}, ${textureProperty}_sampler, ${uvSnippet} )`;
  89. } else {
  90. this._include( 'repeatWrapping' );
  91. const dimension = `textureDimensions( ${textureProperty}, 0 )`;
  92. return `textureLoad( ${textureProperty}, repeatWrapping( ${uvSnippet}, ${dimension} ), 0 )`;
  93. }
  94. }
  95. getTexture( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  96. return this.getSampler( textureProperty, uvSnippet, shaderStage );
  97. }
  98. getCubeTexture( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  99. return this.getSampler( textureProperty, uvSnippet, shaderStage );
  100. }
  101. getPropertyName( node, shaderStage = this.shaderStage ) {
  102. if ( node.isNodeVary === true ) {
  103. if ( shaderStage === 'vertex' ) {
  104. return `NodeVarys.${ node.name }`;
  105. }
  106. } else if ( node.isNodeUniform === true ) {
  107. const name = node.name;
  108. const type = node.type;
  109. if ( type === 'texture' || type === 'cubeTexture' ) {
  110. return name;
  111. } else if ( type === 'buffer' ) {
  112. return `NodeBuffer.${name}`;
  113. } else {
  114. return `NodeUniforms.${name}`;
  115. }
  116. }
  117. return super.getPropertyName( node );
  118. }
  119. getBindings() {
  120. const bindings = this.bindings;
  121. return [ ...bindings.vertex, ...bindings.fragment ];
  122. }
  123. getUniformFromNode( node, shaderStage, type ) {
  124. const uniformNode = super.getUniformFromNode( node, shaderStage, type );
  125. const nodeData = this.getDataFromNode( node, shaderStage );
  126. if ( nodeData.uniformGPU === undefined ) {
  127. let uniformGPU;
  128. const bindings = this.bindings[ shaderStage ];
  129. if ( type === 'texture' || type === 'cubeTexture' ) {
  130. const sampler = new WebGPUNodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  131. let texture = null;
  132. if ( type === 'texture' ) {
  133. texture = new WebGPUNodeSampledTexture( uniformNode.name, uniformNode.node );
  134. } else if ( type === 'cubeTexture' ) {
  135. texture = new WebGPUNodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  136. }
  137. // add first textures in sequence and group for last
  138. const lastBinding = bindings[ bindings.length - 1 ];
  139. const index = lastBinding && lastBinding.isUniformsGroup ? bindings.length - 1 : bindings.length;
  140. if ( shaderStage === 'fragment' ) {
  141. bindings.splice( index, 0, sampler, texture );
  142. uniformGPU = [ sampler, texture ];
  143. } else {
  144. bindings.splice( index, 0, texture );
  145. uniformGPU = [ texture ];
  146. }
  147. } else if ( type === 'buffer' ) {
  148. const buffer = new WebGPUUniformBuffer( 'NodeBuffer', node.value );
  149. // add first textures in sequence and group for last
  150. const lastBinding = bindings[ bindings.length - 1 ];
  151. const index = lastBinding && lastBinding.isUniformsGroup ? bindings.length - 1 : bindings.length;
  152. bindings.splice( index, 0, buffer );
  153. uniformGPU = buffer;
  154. } else {
  155. let uniformsGroup = this.uniformsGroup[ shaderStage ];
  156. if ( uniformsGroup === undefined ) {
  157. uniformsGroup = new WebGPUNodeUniformsGroup( shaderStage );
  158. this.uniformsGroup[ shaderStage ] = uniformsGroup;
  159. bindings.push( uniformsGroup );
  160. }
  161. if ( node.isArrayUniformNode === true ) {
  162. uniformGPU = [];
  163. for ( const uniformNode of node.nodes ) {
  164. const uniformNodeGPU = this._getNodeUniform( uniformNode, type );
  165. // fit bounds to buffer
  166. uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize );
  167. uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize );
  168. uniformsGroup.addUniform( uniformNodeGPU );
  169. uniformGPU.push( uniformNodeGPU );
  170. }
  171. } else {
  172. uniformGPU = this._getNodeUniform( uniformNode, type );
  173. uniformsGroup.addUniform( uniformGPU );
  174. }
  175. }
  176. nodeData.uniformGPU = uniformGPU;
  177. if ( shaderStage === 'vertex' ) {
  178. this.bindingsOffset[ 'fragment' ] = bindings.length;
  179. }
  180. }
  181. return uniformNode;
  182. }
  183. isReference( type ) {
  184. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube';
  185. }
  186. getAttributes( shaderStage ) {
  187. const snippets = [];
  188. if ( shaderStage === 'vertex' ) {
  189. const attributes = this.attributes;
  190. const length = attributes.length;
  191. for ( let index = 0; index < length; index ++ ) {
  192. const attribute = attributes[ index ];
  193. const name = attribute.name;
  194. const type = this.getType( attribute.type );
  195. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  196. }
  197. }
  198. return snippets.join( ',\n\t' );
  199. }
  200. getVars( shaderStage ) {
  201. const snippets = [];
  202. const vars = this.vars[ shaderStage ];
  203. for ( let index = 0; index < vars.length; index ++ ) {
  204. const variable = vars[ index ];
  205. const name = variable.name;
  206. const type = this.getType( variable.type );
  207. snippets.push( `\tvar ${name} : ${type};` );
  208. }
  209. return `\n${ snippets.join( '\n' ) }\n`;
  210. }
  211. getVarys( shaderStage ) {
  212. const snippets = [];
  213. if ( shaderStage === 'vertex' ) {
  214. snippets.push( '@builtin( position ) Vertex: vec4<f32>' );
  215. const varys = this.varys;
  216. for ( let index = 0; index < varys.length; index ++ ) {
  217. const vary = varys[ index ];
  218. snippets.push( `@location( ${index} ) ${ vary.name } : ${ this.getType( vary.type ) }` );
  219. }
  220. } else if ( shaderStage === 'fragment' ) {
  221. const varys = this.varys;
  222. for ( let index = 0; index < varys.length; index ++ ) {
  223. const vary = varys[ index ];
  224. snippets.push( `@location( ${index} ) ${ vary.name } : ${ this.getType( vary.type ) }` );
  225. }
  226. }
  227. const code = snippets.join( ',\n\t' );
  228. return shaderStage === 'vertex' ? this._getWGSLStruct( 'NodeVarysStruct', code ) : code;
  229. }
  230. getUniforms( shaderStage ) {
  231. const uniforms = this.uniforms[ shaderStage ];
  232. const bindingSnippets = [];
  233. const bufferSnippets = [];
  234. const groupSnippets = [];
  235. let index = this.bindingsOffset[ shaderStage ];
  236. for ( const uniform of uniforms ) {
  237. if ( uniform.type === 'texture' ) {
  238. if ( shaderStage === 'fragment' ) {
  239. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name}_sampler : sampler;` );
  240. }
  241. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name} : texture_2d<f32>;` );
  242. } else if ( uniform.type === 'cubeTexture' ) {
  243. if ( shaderStage === 'fragment' ) {
  244. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name}_sampler : sampler;` );
  245. }
  246. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name} : texture_cube<f32>;` );
  247. } else if ( uniform.type === 'buffer' ) {
  248. const bufferNode = uniform.node;
  249. const bufferType = this.getType( bufferNode.bufferType );
  250. const bufferCount = bufferNode.bufferCount;
  251. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}, ${bufferCount} >\n`;
  252. bufferSnippets.push( this._getWGSLUniforms( 'NodeBuffer', bufferSnippet, index ++ ) );
  253. } else {
  254. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  255. if ( Array.isArray( uniform.value ) === true ) {
  256. const length = uniform.value.length;
  257. groupSnippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` );
  258. } else {
  259. groupSnippets.push( `\t${uniform.name} : ${ vectorType}` );
  260. }
  261. }
  262. }
  263. let code = bindingSnippets.join( '\n' );
  264. code += bufferSnippets.join( ',\n' );
  265. if ( groupSnippets.length > 0 ) {
  266. code += this._getWGSLUniforms( 'NodeUniforms', groupSnippets.join( ',\n' ), index ++ );
  267. }
  268. return code;
  269. }
  270. buildCode() {
  271. const shadersData = { fragment: {}, vertex: {} };
  272. for ( const shaderStage in shadersData ) {
  273. let flow = '// code\n';
  274. flow += `\t${ this.flowCode[ shaderStage ] }`;
  275. flow += '\n';
  276. const flowNodes = this.flowNodes[ shaderStage ];
  277. const mainNode = flowNodes[ flowNodes.length - 1 ];
  278. for ( const node of flowNodes ) {
  279. const flowSlotData = this.getFlowData( shaderStage, node );
  280. const slotName = node.name;
  281. if ( slotName ) {
  282. if ( flow.length > 0 ) flow += '\n';
  283. flow += `\t// FLOW -> ${ slotName }\n\t`;
  284. }
  285. flow += `${ flowSlotData.code }\n\t`;
  286. if ( node === mainNode ) {
  287. flow += '// FLOW RESULT\n\t';
  288. if ( shaderStage === 'vertex' ) {
  289. flow += 'NodeVarys.Vertex = ';
  290. } else if ( shaderStage === 'fragment' ) {
  291. flow += 'return ';
  292. }
  293. flow += `${ flowSlotData.result };`;
  294. }
  295. }
  296. const stageData = shadersData[ shaderStage ];
  297. stageData.uniforms = this.getUniforms( shaderStage );
  298. stageData.attributes = this.getAttributes( shaderStage );
  299. stageData.varys = this.getVarys( shaderStage );
  300. stageData.vars = this.getVars( shaderStage );
  301. stageData.codes = this.getCodes( shaderStage );
  302. stageData.flow = flow;
  303. }
  304. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  305. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  306. }
  307. getMethod( method ) {
  308. if ( wgslPolyfill[ method ] !== undefined ) {
  309. this._include( method );
  310. }
  311. return wgslMethods[ method ] || method;
  312. }
  313. getType( type ) {
  314. return wgslTypeLib[ type ] || type;
  315. }
  316. _include( name ) {
  317. wgslPolyfill[ name ].build( this );
  318. }
  319. _getNodeUniform( uniformNode, type ) {
  320. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  321. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  322. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  323. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  324. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  325. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  326. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  327. throw new Error( `Uniform "${type}" not declared.` );
  328. }
  329. _getWGSLVertexCode( shaderData ) {
  330. return `${ this.getSignature() }
  331. // uniforms
  332. ${shaderData.uniforms}
  333. // varys
  334. ${shaderData.varys}
  335. // codes
  336. ${shaderData.codes}
  337. @stage( vertex )
  338. fn main( ${shaderData.attributes} ) -> NodeVarysStruct {
  339. // system
  340. var NodeVarys: NodeVarysStruct;
  341. // vars
  342. ${shaderData.vars}
  343. // flow
  344. ${shaderData.flow}
  345. return NodeVarys;
  346. }
  347. `;
  348. }
  349. _getWGSLFragmentCode( shaderData ) {
  350. return `${ this.getSignature() }
  351. // uniforms
  352. ${shaderData.uniforms}
  353. // codes
  354. ${shaderData.codes}
  355. @stage( fragment )
  356. fn main( ${shaderData.varys} ) -> @location( 0 ) vec4<f32> {
  357. // vars
  358. ${shaderData.vars}
  359. // flow
  360. ${shaderData.flow}
  361. }
  362. `;
  363. }
  364. _getWGSLStruct( name, vars ) {
  365. return `
  366. struct ${name} {
  367. ${vars}
  368. };`;
  369. }
  370. _getWGSLUniforms( name, vars, binding = 0, group = 0 ) {
  371. const structName = name + 'Struct';
  372. const structSnippet = this._getWGSLStruct( structName, vars );
  373. return `${structSnippet}
  374. @binding( ${binding} ) @group( ${group} )
  375. var<uniform> ${name} : ${structName};`;
  376. }
  377. }
  378. export default WebGPUNodeBuilder;