NodeBuilder.js 26 KB

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