NodeBuilder.js 23 KB

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