NodeBuilder.js 22 KB

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