NodeBuilder.js 23 KB

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