WebGLNodeBuilder.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. import { defaultShaderStages, NodeFrame, MathNode, GLSLNodeParser, NodeBuilder } from 'three/nodes';
  2. import SlotNode from './SlotNode.js';
  3. import { PerspectiveCamera, ShaderChunk, ShaderLib, UniformsUtils, UniformsLib,
  4. LinearEncoding, RGBAFormat, UnsignedByteType, sRGBEncoding } from 'three';
  5. const nodeFrame = new NodeFrame();
  6. nodeFrame.camera = new PerspectiveCamera();
  7. const nodeShaderLib = {
  8. LineBasicNodeMaterial: ShaderLib.basic,
  9. MeshBasicNodeMaterial: ShaderLib.basic,
  10. PointsNodeMaterial: ShaderLib.points,
  11. MeshStandardNodeMaterial: ShaderLib.standard,
  12. MeshPhysicalNodeMaterial: ShaderLib.physical
  13. };
  14. const glslMethods = {
  15. [ MathNode.ATAN2 ]: 'atan'
  16. };
  17. function getIncludeSnippet( name ) {
  18. return `#include <${name}>`;
  19. }
  20. function getShaderStageProperty( shaderStage ) {
  21. return `${shaderStage}Shader`;
  22. }
  23. class WebGLNodeBuilder extends NodeBuilder {
  24. constructor( object, renderer, shader ) {
  25. super( object, renderer, new GLSLNodeParser() );
  26. this.shader = shader;
  27. this.slots = { vertex: [], fragment: [] };
  28. this._parseShaderLib();
  29. this._parseInclude( 'fragment', 'lights_physical_fragment', 'clearcoat_normal_fragment_begin', 'transmission_fragment' );
  30. this._parseObject();
  31. this._sortSlotsToFlow();
  32. }
  33. getMethod( method ) {
  34. return glslMethods[ method ] || method;
  35. }
  36. addSlot( shaderStage, slotNode ) {
  37. this.slots[ shaderStage ].push( slotNode );
  38. }
  39. addFlowCode( code ) {
  40. if ( ! /;\s*$/.test( code ) ) {
  41. code += ';';
  42. }
  43. super.addFlowCode( code + '\n\t' );
  44. }
  45. _parseShaderLib() {
  46. const type = this.material.type;
  47. // shader lib
  48. if ( nodeShaderLib[ type ] !== undefined ) {
  49. const shaderLib = nodeShaderLib[ type ];
  50. const shader = this.shader;
  51. shader.vertexShader = shaderLib.vertexShader;
  52. shader.fragmentShader = shaderLib.fragmentShader;
  53. shader.uniforms = UniformsUtils.merge( [ shaderLib.uniforms, UniformsLib.lights ] );
  54. }
  55. }
  56. _parseObject() {
  57. const { material, renderer } = this;
  58. if ( renderer.toneMappingNode?.isNode === true ) {
  59. this.addSlot( 'fragment', new SlotNode( {
  60. node: material.colorNode,
  61. nodeType: 'vec4',
  62. source: getIncludeSnippet( 'tonemapping_fragment' ),
  63. target: ''
  64. } ) );
  65. }
  66. // parse inputs
  67. if ( material.colorNode && material.colorNode.isNode ) {
  68. this.addSlot( 'fragment', new SlotNode( {
  69. node: material.colorNode,
  70. nodeType: 'vec4',
  71. source: 'vec4 diffuseColor = vec4( diffuse, opacity );',
  72. target: 'vec4 diffuseColor = %RESULT%;'
  73. } ) );
  74. }
  75. if ( material.opacityNode && material.opacityNode.isNode ) {
  76. this.addSlot( 'fragment', new SlotNode( {
  77. node: material.opacityNode,
  78. nodeType: 'float',
  79. source: getIncludeSnippet( 'alphatest_fragment' ),
  80. target: 'diffuseColor.a = %RESULT%;',
  81. inclusionType: 'append'
  82. } ) );
  83. } else {
  84. this.addCode( 'fragment', getIncludeSnippet( 'alphatest_fragment' ), 'diffuseColor.a = opacity;', this.shader );
  85. }
  86. if ( material.normalNode && material.normalNode.isNode ) {
  87. this.addSlot( 'fragment', new SlotNode( {
  88. node: material.normalNode,
  89. nodeType: 'vec3',
  90. source: getIncludeSnippet( 'normal_fragment_begin' ),
  91. target: 'normal = %RESULT%;',
  92. inclusionType: 'append'
  93. } ) );
  94. }
  95. if ( material.emissiveNode && material.emissiveNode.isNode ) {
  96. this.addSlot( 'fragment', new SlotNode( {
  97. node: material.emissiveNode,
  98. nodeType: 'vec3',
  99. source: getIncludeSnippet( 'emissivemap_fragment' ),
  100. target: 'totalEmissiveRadiance = %RESULT%;',
  101. inclusionType: 'append'
  102. } ) );
  103. }
  104. if ( material.isMeshStandardNodeMaterial ) {
  105. if ( material.metalnessNode && material.metalnessNode.isNode ) {
  106. this.addSlot( 'fragment', new SlotNode( {
  107. node: material.metalnessNode,
  108. nodeType: 'float',
  109. source: getIncludeSnippet( 'metalnessmap_fragment' ),
  110. target: 'metalnessFactor = %RESULT%;',
  111. inclusionType: 'append'
  112. } ) );
  113. }
  114. if ( material.roughnessNode && material.roughnessNode.isNode ) {
  115. this.addSlot( 'fragment', new SlotNode( {
  116. node: material.roughnessNode,
  117. nodeType: 'float',
  118. source: getIncludeSnippet( 'roughnessmap_fragment' ),
  119. target: 'roughnessFactor = %RESULT%;',
  120. inclusionType: 'append'
  121. } ) );
  122. }
  123. if ( material.isMeshPhysicalNodeMaterial ) {
  124. if ( material.clearcoatNode && material.clearcoatNode.isNode ) {
  125. this.addSlot( 'fragment', new SlotNode( {
  126. node: material.clearcoatNode,
  127. nodeType: 'float',
  128. source: 'material.clearcoat = clearcoat;',
  129. target: 'material.clearcoat = %RESULT%;'
  130. } ) );
  131. if ( material.clearcoatRoughnessNode && material.clearcoatRoughnessNode.isNode ) {
  132. this.addSlot( 'fragment', new SlotNode( {
  133. node: material.clearcoatRoughnessNode,
  134. nodeType: 'float',
  135. source: 'material.clearcoatRoughness = clearcoatRoughness;',
  136. target: 'material.clearcoatRoughness = %RESULT%;'
  137. } ) );
  138. }
  139. if ( material.clearcoatNormalNode && material.clearcoatNormalNode.isNode ) {
  140. this.addSlot( 'fragment', new SlotNode( {
  141. node: material.clearcoatNormalNode,
  142. nodeType: 'vec3',
  143. source: 'vec3 clearcoatNormal = geometryNormal;',
  144. target: 'vec3 clearcoatNormal = %RESULT%;'
  145. } ) );
  146. }
  147. material.defines.USE_CLEARCOAT = '';
  148. } else {
  149. delete material.defines.USE_CLEARCOAT;
  150. }
  151. if ( material.sheenNode && material.sheenNode.isNode ) {
  152. this.addSlot( 'fragment', new SlotNode( {
  153. node: material.sheenNode,
  154. nodeType: 'vec3',
  155. source: 'material.sheenColor = sheenColor;',
  156. target: 'material.sheenColor = %RESULT%;'
  157. } ) );
  158. if ( material.sheenRoughnessNode && material.sheenRoughnessNode.isNode ) {
  159. this.addSlot( 'fragment', new SlotNode( {
  160. node: material.sheenRoughnessNode,
  161. nodeType: 'float',
  162. source: 'material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );',
  163. target: 'material.sheenRoughness = clamp( %RESULT%, 0.07, 1.0 );'
  164. } ) );
  165. }
  166. material.defines.USE_SHEEN = '';
  167. } else {
  168. delete material.defines.USE_SHEEN;
  169. }
  170. if ( material.iridescenceNode && material.iridescenceNode.isNode ) {
  171. this.addSlot( 'fragment', new SlotNode( {
  172. node: material.iridescenceNode,
  173. nodeType: 'float',
  174. source: 'material.iridescence = iridescence;',
  175. target: 'material.iridescence = %RESULT%;'
  176. } ) );
  177. if ( material.iridescenceIORNode && material.iridescenceIORNode.isNode ) {
  178. this.addSlot( 'fragment', new SlotNode( {
  179. node: material.iridescenceIORNode,
  180. nodeType: 'float',
  181. source: 'material.iridescenceIOR = iridescenceIOR;',
  182. target: 'material.iridescenceIOR = %RESULT%;'
  183. } ) );
  184. }
  185. if ( material.iridescenceThicknessNode && material.iridescenceThicknessNode.isNode ) {
  186. this.addSlot( 'fragment', new SlotNode( {
  187. node: material.iridescenceThicknessNode,
  188. nodeType: 'float',
  189. source: 'material.iridescenceThickness = iridescenceThicknessMaximum;',
  190. target: 'material.iridescenceThickness = %RESULT%;'
  191. } ) );
  192. }
  193. material.defines.USE_IRIDESCENCE = '';
  194. } else {
  195. delete material.defines.USE_IRIDESCENCE;
  196. }
  197. if ( material.iorNode && material.iorNode.isNode ) {
  198. this.addSlot( 'fragment', new SlotNode( {
  199. node: material.iorNode,
  200. nodeType: 'float',
  201. source: 'material.ior = ior;',
  202. target: 'material.ior = %RESULT%;'
  203. } ) );
  204. }
  205. if ( material.specularColorNode && material.specularColorNode.isNode ) {
  206. this.addSlot( 'fragment', new SlotNode( {
  207. node: material.specularColorNode,
  208. nodeType: 'vec3',
  209. source: 'vec3 specularColorFactor = specularColor;',
  210. target: 'vec3 specularColorFactor = %RESULT%;'
  211. } ) );
  212. }
  213. if ( material.specularIntensityNode && material.specularIntensityNode.isNode ) {
  214. this.addSlot( 'fragment', new SlotNode( {
  215. node: material.specularIntensityNode,
  216. nodeType: 'float',
  217. source: 'float specularIntensityFactor = specularIntensity;',
  218. target: 'float specularIntensityFactor = %RESULT%;'
  219. } ) );
  220. }
  221. if ( material.transmissionNode && material.transmissionNode.isNode ) {
  222. this.addSlot( 'fragment', new SlotNode( {
  223. node: material.transmissionNode,
  224. nodeType: 'float',
  225. source: 'material.transmission = transmission;',
  226. target: 'material.transmission = %RESULT%;'
  227. } ) );
  228. if ( material.thicknessNode && material.thicknessNode.isNode ) {
  229. this.addSlot( 'fragment', new SlotNode( {
  230. node: material.thicknessNode,
  231. nodeType: 'float',
  232. source: 'material.thickness = thickness;',
  233. target: 'material.thickness = %RESULT%;'
  234. } ) );
  235. }
  236. if ( material.thicknessNode && material.thicknessNode.isNode ) {
  237. this.addSlot( 'fragment', new SlotNode( {
  238. node: material.thicknessNode,
  239. nodeType: 'float',
  240. source: 'material.thickness = thickness;',
  241. target: 'material.thickness = %RESULT%;'
  242. } ) );
  243. }
  244. if ( material.attenuationDistanceNode && material.attenuationDistanceNode.isNode ) {
  245. this.addSlot( 'fragment', new SlotNode( {
  246. node: material.attenuationDistanceNode,
  247. nodeType: 'float',
  248. source: 'material.attenuationDistance = attenuationDistance;',
  249. target: 'material.attenuationDistance = %RESULT%;'
  250. } ) );
  251. }
  252. if ( material.attenuationColorNode && material.attenuationColorNode.isNode ) {
  253. this.addSlot( 'fragment', new SlotNode( {
  254. node: material.attenuationColorNode,
  255. nodeType: 'vec3',
  256. source: 'material.attenuationColor = attenuationColor;',
  257. target: 'material.attenuationColor = %RESULT%;'
  258. } ) );
  259. }
  260. material.transmission = 1;
  261. material.defines.USE_TRANSMISSION = '';
  262. } else {
  263. material.transmission = 0;
  264. delete material.defines.USE_TRANSMISSION;
  265. }
  266. }
  267. }
  268. //
  269. if ( material.positionNode && material.positionNode.isNode ) {
  270. this.addSlot( 'vertex', new SlotNode( {
  271. node: material.positionNode,
  272. nodeType: 'vec3',
  273. source: getIncludeSnippet( 'begin_vertex' ),
  274. target: 'transformed = %RESULT%;',
  275. inclusionType: 'append'
  276. } ) );
  277. }
  278. if ( material.sizeNode && material.sizeNode.isNode ) {
  279. this.addSlot( 'vertex', new SlotNode( {
  280. node: material.sizeNode,
  281. nodeType: 'float',
  282. source: 'gl_PointSize = size;',
  283. target: 'gl_PointSize = %RESULT%;'
  284. } ) );
  285. }
  286. }
  287. getTexture( textureProperty, uvSnippet ) {
  288. return `texture2D( ${textureProperty}, ${uvSnippet} )`;
  289. }
  290. getTextureBias( textureProperty, uvSnippet, biasSnippet ) {
  291. if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
  292. return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
  293. }
  294. getCubeTexture( textureProperty, uvSnippet ) {
  295. return `textureCube( ${textureProperty}, ${uvSnippet} )`;
  296. }
  297. getCubeTextureBias( textureProperty, uvSnippet, biasSnippet ) {
  298. if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
  299. return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
  300. }
  301. getUniforms( shaderStage ) {
  302. const uniforms = this.uniforms[ shaderStage ];
  303. let snippet = '';
  304. for ( const uniform of uniforms ) {
  305. if ( uniform.type === 'texture' ) {
  306. snippet += `uniform sampler2D ${uniform.name}; `;
  307. } else if ( uniform.type === 'cubeTexture' ) {
  308. snippet += `uniform samplerCube ${uniform.name}; `;
  309. } else {
  310. const vectorType = this.getVectorType( uniform.type );
  311. snippet += `uniform ${vectorType} ${uniform.name}; `;
  312. }
  313. }
  314. return snippet;
  315. }
  316. getAttributes( shaderStage ) {
  317. let snippet = '';
  318. if ( shaderStage === 'vertex' ) {
  319. const attributes = this.attributes;
  320. for ( const attribute of attributes ) {
  321. // ignore common attributes to prevent redefinitions
  322. if ( attribute.name === 'uv' || attribute.name === 'position' || attribute.name === 'normal' )
  323. continue;
  324. snippet += `attribute ${attribute.type} ${attribute.name}; `;
  325. }
  326. }
  327. return snippet;
  328. }
  329. getVaryings( /* shaderStage */ ) {
  330. let snippet = '';
  331. const varyings = this.varyings;
  332. for ( const varying of varyings ) {
  333. snippet += `varying ${varying.type} ${varying.name}; `;
  334. }
  335. return snippet;
  336. }
  337. addCode( shaderStage, source, code, scope = this ) {
  338. const shaderProperty = getShaderStageProperty( shaderStage );
  339. let snippet = scope[ shaderProperty ];
  340. const index = snippet.indexOf( source );
  341. if ( index !== - 1 ) {
  342. const start = snippet.substring( 0, index + source.length );
  343. const end = snippet.substring( index + source.length );
  344. snippet = `${start}\n${code}\n${end}`;
  345. }
  346. scope[ shaderProperty ] = snippet;
  347. }
  348. replaceCode( shaderStage, source, target, scope = this ) {
  349. const shaderProperty = getShaderStageProperty( shaderStage );
  350. scope[ shaderProperty ] = scope[ shaderProperty ].replaceAll( source, target );
  351. }
  352. getTextureEncodingFromMap( map ) {
  353. const isWebGL2 = this.renderer.capabilities.isWebGL2;
  354. if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
  355. return LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  356. }
  357. return super.getTextureEncodingFromMap( map );
  358. }
  359. getFrontFacing() {
  360. return 'gl_FrontFacing';
  361. }
  362. buildCode() {
  363. const shaderData = {};
  364. for ( const shaderStage of defaultShaderStages ) {
  365. const uniforms = this.getUniforms( shaderStage );
  366. const attributes = this.getAttributes( shaderStage );
  367. const varyings = this.getVaryings( shaderStage );
  368. const vars = this.getVars( shaderStage );
  369. const codes = this.getCodes( shaderStage );
  370. shaderData[ shaderStage ] = `${this.getSignature()}
  371. // <node_builder>
  372. // uniforms
  373. ${uniforms}
  374. // attributes
  375. ${attributes}
  376. // varyings
  377. ${varyings}
  378. // vars
  379. ${vars}
  380. // codes
  381. ${codes}
  382. // </node_builder>
  383. ${this.shader[ getShaderStageProperty( shaderStage ) ]}
  384. `;
  385. }
  386. this.vertexShader = shaderData.vertex;
  387. this.fragmentShader = shaderData.fragment;
  388. }
  389. build() {
  390. super.build();
  391. this._addSnippets();
  392. this._addUniforms();
  393. this._updateUniforms();
  394. this.shader.vertexShader = this.vertexShader;
  395. this.shader.fragmentShader = this.fragmentShader;
  396. return this;
  397. }
  398. _parseInclude( shaderStage, ...includes ) {
  399. for ( const name of includes ) {
  400. const includeSnippet = getIncludeSnippet( name );
  401. const code = ShaderChunk[ name ];
  402. const shaderProperty = getShaderStageProperty( shaderStage );
  403. this.shader[ shaderProperty ] = this.shader[ shaderProperty ].replaceAll( includeSnippet, code );
  404. }
  405. }
  406. _sortSlotsToFlow() {
  407. for ( const shaderStage of defaultShaderStages ) {
  408. const sourceCode = this.shader[ getShaderStageProperty( shaderStage ) ];
  409. const slots = this.slots[ shaderStage ].sort( ( slotA, slotB ) => {
  410. return sourceCode.indexOf( slotA.source ) > sourceCode.indexOf( slotB.source ) ? 1 : - 1;
  411. } );
  412. for ( const slotNode of slots ) {
  413. this.addFlow( shaderStage, slotNode );
  414. }
  415. }
  416. }
  417. _addSnippets() {
  418. for ( const shaderStage of defaultShaderStages ) {
  419. for ( const slotNode of this.slots[ shaderStage ] ) {
  420. const flowData = this.getFlowData( slotNode/*, shaderStage*/ );
  421. const inclusionType = slotNode.inclusionType;
  422. const source = slotNode.source;
  423. const target = flowData.code + '\n\t' + slotNode.target.replace( '%RESULT%', flowData.result );
  424. if ( inclusionType === 'append' ) {
  425. this.addCode( shaderStage, source, target );
  426. } else if ( inclusionType === 'replace' ) {
  427. this.replaceCode( shaderStage, source, target );
  428. } else {
  429. console.warn( `Inclusion type "${ inclusionType }" not compatible.` );
  430. }
  431. }
  432. this.addCode(
  433. shaderStage,
  434. 'main() {',
  435. this.flowCode[ shaderStage ]
  436. );
  437. }
  438. }
  439. _addUniforms() {
  440. for ( const shaderStage of defaultShaderStages ) {
  441. // uniforms
  442. for ( const uniform of this.uniforms[ shaderStage ] ) {
  443. this.shader.uniforms[ uniform.name ] = uniform;
  444. }
  445. }
  446. }
  447. _updateUniforms() {
  448. nodeFrame.object = this.object;
  449. nodeFrame.renderer = this.renderer;
  450. for ( const node of this.updateNodes ) {
  451. nodeFrame.updateNode( node );
  452. }
  453. }
  454. }
  455. export { WebGLNodeBuilder };