NodeBuilder.js 26 KB

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