2
0

WebGPUNodeBuilder.js 13 KB

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