NodeBuilder.js 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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. hasGeometryAttribute( name ) {
  248. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  249. }
  250. getAttribute( name, type ) {
  251. const attributes = this.attributes;
  252. // find attribute
  253. for ( const attribute of attributes ) {
  254. if ( attribute.name === name ) {
  255. return attribute;
  256. }
  257. }
  258. // create a new if no exist
  259. const attribute = new NodeAttribute( name, type );
  260. attributes.push( attribute );
  261. return attribute;
  262. }
  263. getPropertyName( node/*, shaderStage*/ ) {
  264. return node.name;
  265. }
  266. isVector( type ) {
  267. return /vec\d/.test( type );
  268. }
  269. isMatrix( type ) {
  270. return /mat\d/.test( type );
  271. }
  272. isReference( type ) {
  273. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D';
  274. }
  275. needsColorSpaceToLinear( /*texture*/ ) {
  276. return false;
  277. }
  278. getComponentTypeFromTexture( texture ) {
  279. const type = texture.type;
  280. if ( texture.isDataTexture ) {
  281. if ( type === IntType ) return 'int';
  282. if ( type === UnsignedIntType ) return 'uint';
  283. }
  284. return 'float';
  285. }
  286. getElementType( type ) {
  287. if ( type === 'mat2' ) return 'vec2';
  288. if ( type === 'mat3' ) return 'vec3';
  289. if ( type === 'mat4' ) return 'vec4';
  290. return this.getComponentType( type );
  291. }
  292. getComponentType( type ) {
  293. type = this.getVectorType( type );
  294. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  295. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  296. if ( componentType === null ) return null;
  297. if ( componentType[ 1 ] === 'b' ) return 'bool';
  298. if ( componentType[ 1 ] === 'i' ) return 'int';
  299. if ( componentType[ 1 ] === 'u' ) return 'uint';
  300. return 'float';
  301. }
  302. getVectorType( type ) {
  303. if ( type === 'color' ) return 'vec3';
  304. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  305. return type;
  306. }
  307. getTypeFromLength( length, componentType = 'float' ) {
  308. if ( length === 1 ) return componentType;
  309. const baseType = typeFromLength.get( length );
  310. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  311. return prefix + baseType;
  312. }
  313. getTypeFromArray( array ) {
  314. return typeFromArray.get( array.constructor );
  315. }
  316. getTypeFromAttribute( attribute ) {
  317. let dataAttribute = attribute;
  318. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  319. const array = dataAttribute.array;
  320. const itemSize = attribute.itemSize;
  321. const normalized = attribute.normalized;
  322. let arrayType;
  323. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  324. arrayType = this.getTypeFromArray( array );
  325. }
  326. return this.getTypeFromLength( itemSize, arrayType );
  327. }
  328. getTypeLength( type ) {
  329. const vecType = this.getVectorType( type );
  330. const vecNum = /vec([2-4])/.exec( vecType );
  331. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  332. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  333. if ( /mat2/.test( type ) === true ) return 4;
  334. if ( /mat3/.test( type ) === true ) return 9;
  335. if ( /mat4/.test( type ) === true ) return 16;
  336. return 0;
  337. }
  338. getVectorFromMatrix( type ) {
  339. return type.replace( 'mat', 'vec' );
  340. }
  341. changeComponentType( type, newComponentType ) {
  342. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  343. }
  344. getIntegerType( type ) {
  345. const componentType = this.getComponentType( type );
  346. if ( componentType === 'int' || componentType === 'uint' ) return type;
  347. return this.changeComponentType( type, 'int' );
  348. }
  349. addStack() {
  350. this.stack = stack( this.stack );
  351. this.stacks.push( getCurrentStack() || this.stack );
  352. setCurrentStack( this.stack );
  353. return this.stack;
  354. }
  355. removeStack() {
  356. const lastStack = this.stack;
  357. this.stack = lastStack.parent;
  358. setCurrentStack( this.stacks.pop() );
  359. return lastStack;
  360. }
  361. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  362. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  363. let nodeData = cache.getNodeData( node );
  364. if ( nodeData === undefined ) {
  365. nodeData = {};
  366. cache.setNodeData( node, nodeData );
  367. }
  368. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  369. return nodeData[ shaderStage ];
  370. }
  371. getNodeProperties( node, shaderStage = 'any' ) {
  372. const nodeData = this.getDataFromNode( node, shaderStage );
  373. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  374. }
  375. getBufferAttributeFromNode( node, type ) {
  376. const nodeData = this.getDataFromNode( node );
  377. let bufferAttribute = nodeData.bufferAttribute;
  378. if ( bufferAttribute === undefined ) {
  379. const index = this.uniforms.index ++;
  380. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  381. this.bufferAttributes.push( bufferAttribute );
  382. nodeData.bufferAttribute = bufferAttribute;
  383. }
  384. return bufferAttribute;
  385. }
  386. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  387. const nodeData = this.getDataFromNode( node, shaderStage );
  388. if ( nodeData.structType === undefined ) {
  389. const index = this.structs.index ++;
  390. node.name = `StructType${ index }`;
  391. this.structs[ shaderStage ].push( node );
  392. nodeData.structType = node;
  393. }
  394. return node;
  395. }
  396. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  397. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  398. let nodeUniform = nodeData.uniform;
  399. if ( nodeUniform === undefined ) {
  400. const index = this.uniforms.index ++;
  401. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  402. this.uniforms[ shaderStage ].push( nodeUniform );
  403. nodeData.uniform = nodeUniform;
  404. }
  405. return nodeUniform;
  406. }
  407. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  408. const nodeData = this.getDataFromNode( node, shaderStage );
  409. let nodeVar = nodeData.variable;
  410. if ( nodeVar === undefined ) {
  411. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  412. if ( name === null ) name = 'nodeVar' + vars.length;
  413. nodeVar = new NodeVar( name, type );
  414. vars.push( nodeVar );
  415. nodeData.variable = nodeVar;
  416. }
  417. return nodeVar;
  418. }
  419. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  420. const nodeData = this.getDataFromNode( node, 'any' );
  421. let nodeVarying = nodeData.varying;
  422. if ( nodeVarying === undefined ) {
  423. const varyings = this.varyings;
  424. const index = varyings.length;
  425. if ( name === null ) name = 'nodeVarying' + index;
  426. nodeVarying = new NodeVarying( name, type );
  427. varyings.push( nodeVarying );
  428. nodeData.varying = nodeVarying;
  429. }
  430. return nodeVarying;
  431. }
  432. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  433. const nodeData = this.getDataFromNode( node );
  434. let nodeCode = nodeData.code;
  435. if ( nodeCode === undefined ) {
  436. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  437. const index = codes.length;
  438. nodeCode = new NodeCode( 'nodeCode' + index, type );
  439. codes.push( nodeCode );
  440. nodeData.code = nodeCode;
  441. }
  442. return nodeCode;
  443. }
  444. addLineFlowCode( code ) {
  445. if ( code === '' ) return this;
  446. code = this.tab + code;
  447. if ( ! /;\s*$/.test( code ) ) {
  448. code = code + ';\n';
  449. }
  450. this.flow.code += code;
  451. return this;
  452. }
  453. addFlowCode( code ) {
  454. this.flow.code += code;
  455. return this;
  456. }
  457. addFlowTab() {
  458. this.tab += '\t';
  459. return this;
  460. }
  461. removeFlowTab() {
  462. this.tab = this.tab.slice( 0, - 1 );
  463. return this;
  464. }
  465. getFlowData( node/*, shaderStage*/ ) {
  466. return this.flowsData.get( node );
  467. }
  468. flowNode( node ) {
  469. const output = node.getNodeType( this );
  470. const flowData = this.flowChildNode( node, output );
  471. this.flowsData.set( node, flowData );
  472. return flowData;
  473. }
  474. buildFunctionNode( shaderNode ) {
  475. const fn = new FunctionNode();
  476. const previous = this.currentFunctionNode;
  477. this.currentFunctionNode = fn;
  478. fn.code = this.buildFunctionCode( shaderNode );
  479. this.currentFunctionNode = previous;
  480. return fn;
  481. }
  482. flowShaderNode( shaderNode ) {
  483. const layout = shaderNode.layout;
  484. let inputs;
  485. if ( shaderNode.isArrayInput ) {
  486. inputs = [];
  487. for ( const input of layout.inputs ) {
  488. inputs.push( new ParameterNode( input.type, input.name ) );
  489. }
  490. } else {
  491. inputs = {};
  492. for ( const input of layout.inputs ) {
  493. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  494. }
  495. }
  496. //
  497. shaderNode.layout = null;
  498. const callNode = shaderNode.call( inputs );
  499. const flowData = this.flowStagesNode( callNode, layout.type );
  500. shaderNode.layout = layout;
  501. return flowData;
  502. }
  503. flowStagesNode( node, output = null ) {
  504. const previousFlow = this.flow;
  505. const previousVars = this.vars;
  506. const previousCache = this.cache;
  507. const previousBuildStage = this.buildStage;
  508. const previousStack = this.stack;
  509. const flow = {
  510. code: ''
  511. };
  512. this.flow = flow;
  513. this.vars = {};
  514. this.cache = new NodeCache();
  515. this.stack = stack();
  516. for ( const buildStage of defaultBuildStages ) {
  517. this.setBuildStage( buildStage );
  518. flow.result = node.build( this, output );
  519. }
  520. flow.vars = this.getVars( this.shaderStage );
  521. this.flow = previousFlow;
  522. this.vars = previousVars;
  523. this.cache = previousCache;
  524. this.stack = previousStack;
  525. this.setBuildStage( previousBuildStage );
  526. return flow;
  527. }
  528. getFunctionOperator() {
  529. return null;
  530. }
  531. flowChildNode( node, output = null ) {
  532. const previousFlow = this.flow;
  533. const flow = {
  534. code: ''
  535. };
  536. this.flow = flow;
  537. flow.result = node.build( this, output );
  538. this.flow = previousFlow;
  539. return flow;
  540. }
  541. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  542. const previousShaderStage = this.shaderStage;
  543. this.setShaderStage( shaderStage );
  544. const flowData = this.flowChildNode( node, output );
  545. if ( propertyName !== null ) {
  546. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  547. }
  548. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  549. this.setShaderStage( previousShaderStage );
  550. return flowData;
  551. }
  552. getAttributesArray() {
  553. return this.attributes.concat( this.bufferAttributes );
  554. }
  555. getAttributes( /*shaderStage*/ ) {
  556. console.warn( 'Abstract function.' );
  557. }
  558. getVaryings( /*shaderStage*/ ) {
  559. console.warn( 'Abstract function.' );
  560. }
  561. getVar( type, name ) {
  562. return `${ this.getType( type ) } ${ name }`;
  563. }
  564. getVars( shaderStage ) {
  565. let snippet = '';
  566. const vars = this.vars[ shaderStage ];
  567. if ( vars !== undefined ) {
  568. for ( const variable of vars ) {
  569. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  570. }
  571. }
  572. return snippet;
  573. }
  574. getUniforms( /*shaderStage*/ ) {
  575. console.warn( 'Abstract function.' );
  576. }
  577. getCodes( shaderStage ) {
  578. const codes = this.codes[ shaderStage ];
  579. let code = '';
  580. if ( codes !== undefined ) {
  581. for ( const nodeCode of codes ) {
  582. code += nodeCode.code + '\n';
  583. }
  584. }
  585. return code;
  586. }
  587. getHash() {
  588. return this.vertexShader + this.fragmentShader + this.computeShader;
  589. }
  590. setShaderStage( shaderStage ) {
  591. this.shaderStage = shaderStage;
  592. }
  593. getShaderStage() {
  594. return this.shaderStage;
  595. }
  596. setBuildStage( buildStage ) {
  597. this.buildStage = buildStage;
  598. }
  599. getBuildStage() {
  600. return this.buildStage;
  601. }
  602. buildCode() {
  603. console.warn( 'Abstract function.' );
  604. }
  605. build() {
  606. const { object, material } = this;
  607. if ( material !== null ) {
  608. NodeMaterial.fromMaterial( material ).build( this );
  609. } else {
  610. this.addFlow( 'compute', object );
  611. }
  612. // setup() -> stage 1: create possible new nodes and returns an output reference node
  613. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  614. // generate() -> stage 3: generate shader
  615. for ( const buildStage of defaultBuildStages ) {
  616. this.setBuildStage( buildStage );
  617. if ( this.context.vertex && this.context.vertex.isNode ) {
  618. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  619. }
  620. for ( const shaderStage of shaderStages ) {
  621. this.setShaderStage( shaderStage );
  622. const flowNodes = this.flowNodes[ shaderStage ];
  623. for ( const node of flowNodes ) {
  624. if ( buildStage === 'generate' ) {
  625. this.flowNode( node );
  626. } else {
  627. node.build( this );
  628. }
  629. }
  630. }
  631. }
  632. this.setBuildStage( null );
  633. this.setShaderStage( null );
  634. // stage 4: build code for a specific output
  635. this.buildCode();
  636. this.buildUpdateNodes();
  637. return this;
  638. }
  639. getNodeUniform( uniformNode, type ) {
  640. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  641. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  642. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  643. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  644. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  645. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  646. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  647. throw new Error( `Uniform "${type}" not declared.` );
  648. }
  649. createNodeMaterial( type = 'NodeMaterial' ) {
  650. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  651. return createNodeMaterialFromType( type );
  652. }
  653. format( snippet, fromType, toType ) {
  654. fromType = this.getVectorType( fromType );
  655. toType = this.getVectorType( toType );
  656. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  657. return snippet;
  658. }
  659. const fromTypeLength = this.getTypeLength( fromType );
  660. const toTypeLength = this.getTypeLength( toType );
  661. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  662. // @TODO: ignore for now
  663. return snippet;
  664. }
  665. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  666. // @TODO: ignore for now
  667. return snippet;
  668. }
  669. if ( fromTypeLength === toTypeLength ) {
  670. return `${ this.getType( toType ) }( ${ snippet } )`;
  671. }
  672. if ( fromTypeLength > toTypeLength ) {
  673. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  674. }
  675. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  676. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  677. }
  678. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  679. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  680. }
  681. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  682. // convert a number value to vector type, e.g:
  683. // vec3( 1u ) -> vec3( float( 1u ) )
  684. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  685. }
  686. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  687. }
  688. getSignature() {
  689. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  690. }
  691. }
  692. export default NodeBuilder;