NodeBuilder.js 26 KB

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