NodeBuilder.js 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. import NodeUniform from './NodeUniform.js';
  2. import NodeAttribute from './NodeAttribute.js';
  3. import NodeVarying from './NodeVarying.js';
  4. import NodeVar from './NodeVar.js';
  5. import NodeCode from './NodeCode.js';
  6. import NodeKeywords from './NodeKeywords.js';
  7. import NodeCache from './NodeCache.js';
  8. import ParameterNode from './ParameterNode.js';
  9. import FunctionNode from '../code/FunctionNode.js';
  10. import { createNodeMaterialFromType, default as NodeMaterial } from '../materials/NodeMaterial.js';
  11. import { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  12. import {
  13. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  14. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  15. } from '../../renderers/common/nodes/NodeUniform.js';
  16. import { REVISION, RenderTarget, Color, Vector2, Vector3, Vector4, IntType, UnsignedIntType, Float16BufferAttribute } from 'three';
  17. import { stack } from './StackNode.js';
  18. import { getCurrentStack, setCurrentStack } from '../shadernode/ShaderNode.js';
  19. import CubeRenderTarget from '../../renderers/common/CubeRenderTarget.js';
  20. import ChainMap from '../../renderers/common/ChainMap.js';
  21. import PMREMGenerator from '../../renderers/common/extras/PMREMGenerator.js';
  22. const uniformsGroupCache = new ChainMap();
  23. const typeFromLength = new Map( [
  24. [ 2, 'vec2' ],
  25. [ 3, 'vec3' ],
  26. [ 4, 'vec4' ],
  27. [ 9, 'mat3' ],
  28. [ 16, 'mat4' ]
  29. ] );
  30. const typeFromArray = new Map( [
  31. [ Int8Array, 'int' ],
  32. [ Int16Array, 'int' ],
  33. [ Int32Array, 'int' ],
  34. [ Uint8Array, 'uint' ],
  35. [ Uint16Array, 'uint' ],
  36. [ Uint32Array, 'uint' ],
  37. [ Float32Array, 'float' ]
  38. ] );
  39. const toFloat = ( value ) => {
  40. value = Number( value );
  41. return value + ( value % 1 ? '' : '.0' );
  42. };
  43. class NodeBuilder {
  44. constructor( object, renderer, parser, scene = null, material = null ) {
  45. this.object = object;
  46. this.material = material || ( object && object.material ) || null;
  47. this.geometry = ( object && object.geometry ) || null;
  48. this.renderer = renderer;
  49. this.parser = parser;
  50. this.scene = scene;
  51. this.nodes = [];
  52. this.updateNodes = [];
  53. this.updateBeforeNodes = [];
  54. this.updateAfterNodes = [];
  55. this.hashNodes = {};
  56. this.lightsNode = null;
  57. this.environmentNode = null;
  58. this.fogNode = null;
  59. this.clippingContext = null;
  60. this.vertexShader = null;
  61. this.fragmentShader = null;
  62. this.computeShader = null;
  63. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  64. this.flowCode = { vertex: '', fragment: '', compute: '' };
  65. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  66. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  67. this.bindings = { vertex: [], fragment: [], compute: [] };
  68. this.bindingsOffset = { vertex: 0, fragment: 0, compute: 0 };
  69. this.bindingsArray = null;
  70. this.attributes = [];
  71. this.bufferAttributes = [];
  72. this.varyings = [];
  73. this.codes = {};
  74. this.vars = {};
  75. this.flow = { code: '' };
  76. this.chaining = [];
  77. this.stack = stack();
  78. this.stacks = [];
  79. this.tab = '\t';
  80. this.currentFunctionNode = null;
  81. this.context = {
  82. keywords: new NodeKeywords(),
  83. material: this.material
  84. };
  85. this.cache = new NodeCache();
  86. this.globalCache = this.cache;
  87. this.flowsData = new WeakMap();
  88. this.shaderStage = null;
  89. this.buildStage = null;
  90. }
  91. createRenderTarget( width, height, options ) {
  92. return new RenderTarget( width, height, options );
  93. }
  94. createCubeRenderTarget( size, options ) {
  95. return new CubeRenderTarget( size, options );
  96. }
  97. createPMREMGenerator() {
  98. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  99. return new PMREMGenerator( this.renderer );
  100. }
  101. includes( node ) {
  102. return this.nodes.includes( node );
  103. }
  104. _getSharedBindings( bindings ) {
  105. const shared = [];
  106. for ( const binding of bindings ) {
  107. if ( binding.shared === true ) {
  108. // nodes is the chainmap key
  109. const nodes = binding.getNodes();
  110. let sharedBinding = uniformsGroupCache.get( nodes );
  111. if ( sharedBinding === undefined ) {
  112. uniformsGroupCache.set( nodes, binding );
  113. sharedBinding = binding;
  114. }
  115. shared.push( sharedBinding );
  116. } else {
  117. shared.push( binding );
  118. }
  119. }
  120. return shared;
  121. }
  122. getBindings() {
  123. let bindingsArray = this.bindingsArray;
  124. if ( bindingsArray === null ) {
  125. const bindings = this.bindings;
  126. this.bindingsArray = bindingsArray = this._getSharedBindings( ( this.material !== null ) ? [ ...bindings.vertex, ...bindings.fragment ] : bindings.compute );
  127. }
  128. return bindingsArray;
  129. }
  130. setHashNode( node, hash ) {
  131. this.hashNodes[ hash ] = node;
  132. }
  133. addNode( node ) {
  134. if ( this.nodes.includes( node ) === false ) {
  135. this.nodes.push( node );
  136. this.setHashNode( node, node.getHash( this ) );
  137. }
  138. }
  139. buildUpdateNodes() {
  140. for ( const node of this.nodes ) {
  141. const updateType = node.getUpdateType();
  142. const updateBeforeType = node.getUpdateBeforeType();
  143. const updateAfterType = node.getUpdateAfterType();
  144. if ( updateType !== NodeUpdateType.NONE ) {
  145. this.updateNodes.push( node.getSelf() );
  146. }
  147. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  148. this.updateBeforeNodes.push( node );
  149. }
  150. if ( updateAfterType !== NodeUpdateType.NONE ) {
  151. this.updateAfterNodes.push( node );
  152. }
  153. }
  154. }
  155. get currentNode() {
  156. return this.chaining[ this.chaining.length - 1 ];
  157. }
  158. addChain( node ) {
  159. /*
  160. if ( this.chaining.indexOf( node ) !== - 1 ) {
  161. console.warn( 'Recursive node: ', node );
  162. }
  163. */
  164. this.chaining.push( node );
  165. }
  166. removeChain( node ) {
  167. const lastChain = this.chaining.pop();
  168. if ( lastChain !== node ) {
  169. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  170. }
  171. }
  172. getMethod( method ) {
  173. return method;
  174. }
  175. getNodeFromHash( hash ) {
  176. return this.hashNodes[ hash ];
  177. }
  178. addFlow( shaderStage, node ) {
  179. this.flowNodes[ shaderStage ].push( node );
  180. return node;
  181. }
  182. setContext( context ) {
  183. this.context = context;
  184. }
  185. getContext() {
  186. return this.context;
  187. }
  188. setCache( cache ) {
  189. this.cache = cache;
  190. }
  191. getCache() {
  192. return this.cache;
  193. }
  194. isAvailable( /*name*/ ) {
  195. return false;
  196. }
  197. getVertexIndex() {
  198. console.warn( 'Abstract function.' );
  199. }
  200. getInstanceIndex() {
  201. console.warn( 'Abstract function.' );
  202. }
  203. getFrontFacing() {
  204. console.warn( 'Abstract function.' );
  205. }
  206. getFragCoord() {
  207. console.warn( 'Abstract function.' );
  208. }
  209. isFlipY() {
  210. return false;
  211. }
  212. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  213. console.warn( 'Abstract function.' );
  214. }
  215. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  216. console.warn( 'Abstract function.' );
  217. }
  218. generateConst( type, value = null ) {
  219. if ( value === null ) {
  220. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  221. else if ( type === 'bool' ) value = false;
  222. else if ( type === 'color' ) value = new Color();
  223. else if ( type === 'vec2' ) value = new Vector2();
  224. else if ( type === 'vec3' ) value = new Vector3();
  225. else if ( type === 'vec4' ) value = new Vector4();
  226. }
  227. if ( type === 'float' ) return toFloat( value );
  228. if ( type === 'int' ) return `${ Math.round( value ) }`;
  229. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  230. if ( type === 'bool' ) return value ? 'true' : 'false';
  231. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  232. const typeLength = this.getTypeLength( type );
  233. const componentType = this.getComponentType( type );
  234. const generateConst = value => this.generateConst( componentType, value );
  235. if ( typeLength === 2 ) {
  236. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  237. } else if ( typeLength === 3 ) {
  238. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  239. } else if ( typeLength === 4 ) {
  240. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  241. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  242. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  243. } else if ( typeLength > 4 ) {
  244. return `${ this.getType( type ) }()`;
  245. }
  246. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  247. }
  248. getType( type ) {
  249. if ( type === 'color' ) return 'vec3';
  250. return type;
  251. }
  252. hasGeometryAttribute( name ) {
  253. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  254. }
  255. getAttribute( name, type ) {
  256. const attributes = this.attributes;
  257. // find attribute
  258. for ( const attribute of attributes ) {
  259. if ( attribute.name === name ) {
  260. return attribute;
  261. }
  262. }
  263. // create a new if no exist
  264. const attribute = new NodeAttribute( name, type );
  265. attributes.push( attribute );
  266. return attribute;
  267. }
  268. getPropertyName( node/*, shaderStage*/ ) {
  269. return node.name;
  270. }
  271. isVector( type ) {
  272. return /vec\d/.test( type );
  273. }
  274. isMatrix( type ) {
  275. return /mat\d/.test( type );
  276. }
  277. isReference( type ) {
  278. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D';
  279. }
  280. needsColorSpaceToLinear( /*texture*/ ) {
  281. return false;
  282. }
  283. getComponentTypeFromTexture( texture ) {
  284. const type = texture.type;
  285. if ( texture.isDataTexture ) {
  286. if ( type === IntType ) return 'int';
  287. if ( type === UnsignedIntType ) return 'uint';
  288. }
  289. return 'float';
  290. }
  291. getElementType( type ) {
  292. if ( type === 'mat2' ) return 'vec2';
  293. if ( type === 'mat3' ) return 'vec3';
  294. if ( type === 'mat4' ) return 'vec4';
  295. return this.getComponentType( type );
  296. }
  297. getComponentType( type ) {
  298. type = this.getVectorType( type );
  299. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  300. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  301. if ( componentType === null ) return null;
  302. if ( componentType[ 1 ] === 'b' ) return 'bool';
  303. if ( componentType[ 1 ] === 'i' ) return 'int';
  304. if ( componentType[ 1 ] === 'u' ) return 'uint';
  305. return 'float';
  306. }
  307. getVectorType( type ) {
  308. if ( type === 'color' ) return 'vec3';
  309. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  310. return type;
  311. }
  312. getTypeFromLength( length, componentType = 'float' ) {
  313. if ( length === 1 ) return componentType;
  314. const baseType = typeFromLength.get( length );
  315. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  316. return prefix + baseType;
  317. }
  318. getTypeFromArray( array ) {
  319. return typeFromArray.get( array.constructor );
  320. }
  321. getTypeFromAttribute( attribute ) {
  322. let dataAttribute = attribute;
  323. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  324. const array = dataAttribute.array;
  325. const itemSize = attribute.itemSize;
  326. const normalized = attribute.normalized;
  327. let arrayType;
  328. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  329. arrayType = this.getTypeFromArray( array );
  330. }
  331. return this.getTypeFromLength( itemSize, arrayType );
  332. }
  333. getTypeLength( type ) {
  334. const vecType = this.getVectorType( type );
  335. const vecNum = /vec([2-4])/.exec( vecType );
  336. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  337. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  338. if ( /mat2/.test( type ) === true ) return 4;
  339. if ( /mat3/.test( type ) === true ) return 9;
  340. if ( /mat4/.test( type ) === true ) return 16;
  341. return 0;
  342. }
  343. getVectorFromMatrix( type ) {
  344. return type.replace( 'mat', 'vec' );
  345. }
  346. changeComponentType( type, newComponentType ) {
  347. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  348. }
  349. getIntegerType( type ) {
  350. const componentType = this.getComponentType( type );
  351. if ( componentType === 'int' || componentType === 'uint' ) return type;
  352. return this.changeComponentType( type, 'int' );
  353. }
  354. addStack() {
  355. this.stack = stack( this.stack );
  356. this.stacks.push( getCurrentStack() || this.stack );
  357. setCurrentStack( this.stack );
  358. return this.stack;
  359. }
  360. removeStack() {
  361. const lastStack = this.stack;
  362. this.stack = lastStack.parent;
  363. setCurrentStack( this.stacks.pop() );
  364. return lastStack;
  365. }
  366. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  367. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  368. let nodeData = cache.getNodeData( node );
  369. if ( nodeData === undefined ) {
  370. nodeData = {};
  371. cache.setNodeData( node, nodeData );
  372. }
  373. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  374. return nodeData[ shaderStage ];
  375. }
  376. getNodeProperties( node, shaderStage = 'any' ) {
  377. const nodeData = this.getDataFromNode( node, shaderStage );
  378. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  379. }
  380. getBufferAttributeFromNode( node, type ) {
  381. const nodeData = this.getDataFromNode( node );
  382. let bufferAttribute = nodeData.bufferAttribute;
  383. if ( bufferAttribute === undefined ) {
  384. const index = this.uniforms.index ++;
  385. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  386. this.bufferAttributes.push( bufferAttribute );
  387. nodeData.bufferAttribute = bufferAttribute;
  388. }
  389. return bufferAttribute;
  390. }
  391. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  392. const nodeData = this.getDataFromNode( node, shaderStage );
  393. if ( nodeData.structType === undefined ) {
  394. const index = this.structs.index ++;
  395. node.name = `StructType${ index }`;
  396. this.structs[ shaderStage ].push( node );
  397. nodeData.structType = node;
  398. }
  399. return node;
  400. }
  401. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  402. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  403. let nodeUniform = nodeData.uniform;
  404. if ( nodeUniform === undefined ) {
  405. const index = this.uniforms.index ++;
  406. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  407. this.uniforms[ shaderStage ].push( nodeUniform );
  408. nodeData.uniform = nodeUniform;
  409. }
  410. return nodeUniform;
  411. }
  412. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  413. const nodeData = this.getDataFromNode( node, shaderStage );
  414. let nodeVar = nodeData.variable;
  415. if ( nodeVar === undefined ) {
  416. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  417. if ( name === null ) name = 'nodeVar' + vars.length;
  418. nodeVar = new NodeVar( name, type );
  419. vars.push( nodeVar );
  420. nodeData.variable = nodeVar;
  421. }
  422. return nodeVar;
  423. }
  424. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  425. const nodeData = this.getDataFromNode( node, 'any' );
  426. let nodeVarying = nodeData.varying;
  427. if ( nodeVarying === undefined ) {
  428. const varyings = this.varyings;
  429. const index = varyings.length;
  430. if ( name === null ) name = 'nodeVarying' + index;
  431. nodeVarying = new NodeVarying( name, type );
  432. varyings.push( nodeVarying );
  433. nodeData.varying = nodeVarying;
  434. }
  435. return nodeVarying;
  436. }
  437. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  438. const nodeData = this.getDataFromNode( node );
  439. let nodeCode = nodeData.code;
  440. if ( nodeCode === undefined ) {
  441. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  442. const index = codes.length;
  443. nodeCode = new NodeCode( 'nodeCode' + index, type );
  444. codes.push( nodeCode );
  445. nodeData.code = nodeCode;
  446. }
  447. return nodeCode;
  448. }
  449. addLineFlowCode( code ) {
  450. if ( code === '' ) return this;
  451. code = this.tab + code;
  452. if ( ! /;\s*$/.test( code ) ) {
  453. code = code + ';\n';
  454. }
  455. this.flow.code += code;
  456. return this;
  457. }
  458. addFlowCode( code ) {
  459. this.flow.code += code;
  460. return this;
  461. }
  462. addFlowTab() {
  463. this.tab += '\t';
  464. return this;
  465. }
  466. removeFlowTab() {
  467. this.tab = this.tab.slice( 0, - 1 );
  468. return this;
  469. }
  470. getFlowData( node/*, shaderStage*/ ) {
  471. return this.flowsData.get( node );
  472. }
  473. flowNode( node ) {
  474. const output = node.getNodeType( this );
  475. const flowData = this.flowChildNode( node, output );
  476. this.flowsData.set( node, flowData );
  477. return flowData;
  478. }
  479. buildFunctionNode( shaderNode ) {
  480. const fn = new FunctionNode();
  481. const previous = this.currentFunctionNode;
  482. this.currentFunctionNode = fn;
  483. fn.code = this.buildFunctionCode( shaderNode );
  484. this.currentFunctionNode = previous;
  485. return fn;
  486. }
  487. flowShaderNode( shaderNode ) {
  488. const layout = shaderNode.layout;
  489. let inputs;
  490. if ( shaderNode.isArrayInput ) {
  491. inputs = [];
  492. for ( const input of layout.inputs ) {
  493. inputs.push( new ParameterNode( input.type, input.name ) );
  494. }
  495. } else {
  496. inputs = {};
  497. for ( const input of layout.inputs ) {
  498. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  499. }
  500. }
  501. //
  502. shaderNode.layout = null;
  503. const callNode = shaderNode.call( inputs );
  504. const flowData = this.flowStagesNode( callNode, layout.type );
  505. shaderNode.layout = layout;
  506. return flowData;
  507. }
  508. flowStagesNode( node, output = null ) {
  509. const previousFlow = this.flow;
  510. const previousVars = this.vars;
  511. const previousCache = this.cache;
  512. const previousBuildStage = this.buildStage;
  513. const previousStack = this.stack;
  514. const flow = {
  515. code: ''
  516. };
  517. this.flow = flow;
  518. this.vars = {};
  519. this.cache = new NodeCache();
  520. this.stack = stack();
  521. for ( const buildStage of defaultBuildStages ) {
  522. this.setBuildStage( buildStage );
  523. flow.result = node.build( this, output );
  524. }
  525. flow.vars = this.getVars( this.shaderStage );
  526. this.flow = previousFlow;
  527. this.vars = previousVars;
  528. this.cache = previousCache;
  529. this.stack = previousStack;
  530. this.setBuildStage( previousBuildStage );
  531. return flow;
  532. }
  533. getFunctionOperator() {
  534. return null;
  535. }
  536. flowChildNode( node, output = null ) {
  537. const previousFlow = this.flow;
  538. const flow = {
  539. code: ''
  540. };
  541. this.flow = flow;
  542. flow.result = node.build( this, output );
  543. this.flow = previousFlow;
  544. return flow;
  545. }
  546. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  547. const previousShaderStage = this.shaderStage;
  548. this.setShaderStage( shaderStage );
  549. const flowData = this.flowChildNode( node, output );
  550. if ( propertyName !== null ) {
  551. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  552. }
  553. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  554. this.setShaderStage( previousShaderStage );
  555. return flowData;
  556. }
  557. getAttributesArray() {
  558. return this.attributes.concat( this.bufferAttributes );
  559. }
  560. getAttributes( /*shaderStage*/ ) {
  561. console.warn( 'Abstract function.' );
  562. }
  563. getVaryings( /*shaderStage*/ ) {
  564. console.warn( 'Abstract function.' );
  565. }
  566. getVar( type, name ) {
  567. return `${ this.getType( type ) } ${ name }`;
  568. }
  569. getVars( shaderStage ) {
  570. let snippet = '';
  571. const vars = this.vars[ shaderStage ];
  572. if ( vars !== undefined ) {
  573. for ( const variable of vars ) {
  574. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  575. }
  576. }
  577. return snippet;
  578. }
  579. getUniforms( /*shaderStage*/ ) {
  580. console.warn( 'Abstract function.' );
  581. }
  582. getCodes( shaderStage ) {
  583. const codes = this.codes[ shaderStage ];
  584. let code = '';
  585. if ( codes !== undefined ) {
  586. for ( const nodeCode of codes ) {
  587. code += nodeCode.code + '\n';
  588. }
  589. }
  590. return code;
  591. }
  592. getHash() {
  593. return this.vertexShader + this.fragmentShader + this.computeShader;
  594. }
  595. setShaderStage( shaderStage ) {
  596. this.shaderStage = shaderStage;
  597. }
  598. getShaderStage() {
  599. return this.shaderStage;
  600. }
  601. setBuildStage( buildStage ) {
  602. this.buildStage = buildStage;
  603. }
  604. getBuildStage() {
  605. return this.buildStage;
  606. }
  607. buildCode() {
  608. console.warn( 'Abstract function.' );
  609. }
  610. build() {
  611. const { object, material } = this;
  612. if ( material !== null ) {
  613. NodeMaterial.fromMaterial( material ).build( this );
  614. } else {
  615. this.addFlow( 'compute', object );
  616. }
  617. // setup() -> stage 1: create possible new nodes and returns an output reference node
  618. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  619. // generate() -> stage 3: generate shader
  620. for ( const buildStage of defaultBuildStages ) {
  621. this.setBuildStage( buildStage );
  622. if ( this.context.vertex && this.context.vertex.isNode ) {
  623. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  624. }
  625. for ( const shaderStage of shaderStages ) {
  626. this.setShaderStage( shaderStage );
  627. const flowNodes = this.flowNodes[ shaderStage ];
  628. for ( const node of flowNodes ) {
  629. if ( buildStage === 'generate' ) {
  630. this.flowNode( node );
  631. } else {
  632. node.build( this );
  633. }
  634. }
  635. }
  636. }
  637. this.setBuildStage( null );
  638. this.setShaderStage( null );
  639. // stage 4: build code for a specific output
  640. this.buildCode();
  641. this.buildUpdateNodes();
  642. return this;
  643. }
  644. getNodeUniform( uniformNode, type ) {
  645. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  646. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  647. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  648. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  649. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  650. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  651. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  652. throw new Error( `Uniform "${type}" not declared.` );
  653. }
  654. createNodeMaterial( type = 'NodeMaterial' ) {
  655. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  656. return createNodeMaterialFromType( type );
  657. }
  658. format( snippet, fromType, toType ) {
  659. fromType = this.getVectorType( fromType );
  660. toType = this.getVectorType( toType );
  661. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  662. return snippet;
  663. }
  664. const fromTypeLength = this.getTypeLength( fromType );
  665. const toTypeLength = this.getTypeLength( toType );
  666. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  667. // @TODO: ignore for now
  668. return snippet;
  669. }
  670. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  671. // @TODO: ignore for now
  672. return snippet;
  673. }
  674. if ( fromTypeLength === toTypeLength ) {
  675. return `${ this.getType( toType ) }( ${ snippet } )`;
  676. }
  677. if ( fromTypeLength > toTypeLength ) {
  678. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  679. }
  680. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  681. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  682. }
  683. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  684. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  685. }
  686. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  687. // convert a number value to vector type, e.g:
  688. // vec3( 1u ) -> vec3( float( 1u ) )
  689. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  690. }
  691. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  692. }
  693. getSignature() {
  694. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  695. }
  696. }
  697. export default NodeBuilder;