2
0

NodeBuilder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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 { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  9. import { REVISION, NoColorSpace, LinearEncoding, sRGBEncoding, SRGBColorSpace, Color, Vector2, Vector3, Vector4, Float16BufferAttribute } from 'three';
  10. import { stack } from './StackNode.js';
  11. import { maxMipLevel } from '../utils/MaxMipLevelNode.js';
  12. const typeFromLength = new Map( [
  13. [ 2, 'vec2' ],
  14. [ 3, 'vec3' ],
  15. [ 4, 'vec4' ],
  16. [ 9, 'mat3' ],
  17. [ 16, 'mat4' ]
  18. ] );
  19. const typeFromArray = new Map( [
  20. [ Int8Array, 'int' ],
  21. [ Int16Array, 'int' ],
  22. [ Int32Array, 'int' ],
  23. [ Uint8Array, 'uint' ],
  24. [ Uint16Array, 'uint' ],
  25. [ Uint32Array, 'uint' ],
  26. [ Float32Array, 'float' ]
  27. ] );
  28. const isNonPaddingElementArray = new Set( [ Int32Array, Uint32Array, Float32Array ] );
  29. const toFloat = ( value ) => {
  30. value = Number( value );
  31. return value + ( value % 1 ? '' : '.0' );
  32. };
  33. class NodeBuilder {
  34. constructor( object, renderer, parser ) {
  35. this.object = object;
  36. this.material = object && ( object.material || null );
  37. this.geometry = object && ( object.geometry || null );
  38. this.renderer = renderer;
  39. this.parser = parser;
  40. this.nodes = [];
  41. this.updateNodes = [];
  42. this.updateBeforeNodes = [];
  43. this.hashNodes = {};
  44. this.lightsNode = null;
  45. this.environmentNode = null;
  46. this.fogNode = null;
  47. this.toneMappingNode = null;
  48. this.vertexShader = null;
  49. this.fragmentShader = null;
  50. this.computeShader = null;
  51. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  52. this.flowCode = { vertex: '', fragment: '', compute: [] };
  53. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  54. this.codes = { vertex: [], fragment: [], compute: [] };
  55. this.attributes = [];
  56. this.varyings = [];
  57. this.vars = { vertex: [], fragment: [], compute: [] };
  58. this.flow = { code: '' };
  59. this.chaining = [];
  60. this.stack = stack();
  61. this.tab = '\t';
  62. this.context = {
  63. keywords: new NodeKeywords(),
  64. material: this.material,
  65. getMIPLevelAlgorithmNode: ( textureNode, levelNode ) => levelNode.mul( maxMipLevel( textureNode ) )
  66. };
  67. this.cache = new NodeCache();
  68. this.globalCache = this.cache;
  69. this.flowsData = new WeakMap();
  70. this.shaderStage = null;
  71. this.buildStage = null;
  72. }
  73. setHashNode( node, hash ) {
  74. this.hashNodes[ hash ] = node;
  75. }
  76. addNode( node ) {
  77. if ( this.nodes.indexOf( node ) === - 1 ) {
  78. const updateType = node.getUpdateType();
  79. const updateBeforeType = node.getUpdateBeforeType();
  80. if ( updateType !== NodeUpdateType.NONE ) {
  81. this.updateNodes.push( node );
  82. }
  83. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  84. this.updateBeforeNodes.push( node );
  85. }
  86. this.nodes.push( node );
  87. this.setHashNode( node, node.getHash( this ) );
  88. }
  89. }
  90. get currentNode() {
  91. return this.chaining[ this.chaining.length - 1 ];
  92. }
  93. addChain( node ) {
  94. /*
  95. if ( this.chaining.indexOf( node ) !== - 1 ) {
  96. console.warn( 'Recursive node: ', node );
  97. }
  98. */
  99. this.chaining.push( node );
  100. }
  101. removeChain( node ) {
  102. const lastChain = this.chaining.pop();
  103. if ( lastChain !== node ) {
  104. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  105. }
  106. }
  107. getMethod( method ) {
  108. return method;
  109. }
  110. getNodeFromHash( hash ) {
  111. return this.hashNodes[ hash ];
  112. }
  113. addFlow( shaderStage, node ) {
  114. this.flowNodes[ shaderStage ].push( node );
  115. return node;
  116. }
  117. setContext( context ) {
  118. this.context = context;
  119. }
  120. getContext() {
  121. return this.context;
  122. }
  123. setCache( cache ) {
  124. this.cache = cache;
  125. }
  126. getCache() {
  127. return this.cache;
  128. }
  129. isAvailable( /*name*/ ) {
  130. return false;
  131. }
  132. getInstanceIndex() {
  133. console.warn( 'Abstract function.' );
  134. }
  135. getFrontFacing() {
  136. console.warn( 'Abstract function.' );
  137. }
  138. getFragCoord() {
  139. console.warn( 'Abstract function.' );
  140. }
  141. isFlipY() {
  142. return false;
  143. }
  144. getTexture( /* texture, textureProperty, uvSnippet */ ) {
  145. console.warn( 'Abstract function.' );
  146. }
  147. getTextureLevel( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  148. console.warn( 'Abstract function.' );
  149. }
  150. // @TODO: rename to .generateConst()
  151. getConst( type, value = null ) {
  152. if ( value === null ) {
  153. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  154. else if ( type === 'bool' ) value = false;
  155. else if ( type === 'color' ) value = new Color();
  156. else if ( type === 'vec2' ) value = new Vector2();
  157. else if ( type === 'vec3' ) value = new Vector3();
  158. else if ( type === 'vec4' ) value = new Vector4();
  159. }
  160. if ( type === 'float' ) return toFloat( value );
  161. if ( type === 'int' ) return `${ Math.round( value ) }`;
  162. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  163. if ( type === 'bool' ) return value ? 'true' : 'false';
  164. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  165. const typeLength = this.getTypeLength( type );
  166. const componentType = this.getComponentType( type );
  167. const getConst = value => this.getConst( componentType, value );
  168. if ( typeLength === 2 ) {
  169. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) } )`;
  170. } else if ( typeLength === 3 ) {
  171. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) } )`;
  172. } else if ( typeLength === 4 ) {
  173. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) }, ${ getConst( value.w ) } )`;
  174. } else if ( typeLength > 4 ) {
  175. return `${ this.getType( type ) }()`;
  176. }
  177. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  178. }
  179. getType( type ) {
  180. return type;
  181. }
  182. generateMethod( method ) {
  183. return method;
  184. }
  185. hasGeometryAttribute( name ) {
  186. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  187. }
  188. getAttribute( name, type ) {
  189. const attributes = this.attributes;
  190. // find attribute
  191. for ( const attribute of attributes ) {
  192. if ( attribute.name === name ) {
  193. return attribute;
  194. }
  195. }
  196. // create a new if no exist
  197. const attribute = new NodeAttribute( name, type );
  198. attributes.push( attribute );
  199. return attribute;
  200. }
  201. getPropertyName( node/*, shaderStage*/ ) {
  202. return node.name;
  203. }
  204. isVector( type ) {
  205. return /vec\d/.test( type );
  206. }
  207. isMatrix( type ) {
  208. return /mat\d/.test( type );
  209. }
  210. isReference( type ) {
  211. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture';
  212. }
  213. isShaderStage( shaderStage ) {
  214. return this.shaderStage === shaderStage;
  215. }
  216. /** @deprecated, r152 */
  217. getTextureEncodingFromMap( map ) {
  218. console.warn( 'THREE.NodeBuilder: Method .getTextureEncodingFromMap replaced by .getTextureColorSpaceFromMap in r152+.' );
  219. return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  220. }
  221. getTextureColorSpaceFromMap( map ) {
  222. let colorSpace;
  223. if ( map && map.isTexture ) {
  224. colorSpace = map.colorSpace;
  225. } else if ( map && map.isWebGLRenderTarget ) {
  226. colorSpace = map.texture.colorSpace;
  227. } else {
  228. colorSpace = NoColorSpace;
  229. }
  230. return colorSpace;
  231. }
  232. getComponentType( type ) {
  233. type = this.getVectorType( type );
  234. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  235. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  236. if ( componentType === null ) return null;
  237. if ( componentType[ 1 ] === 'b' ) return 'bool';
  238. if ( componentType[ 1 ] === 'i' ) return 'int';
  239. if ( componentType[ 1 ] === 'u' ) return 'uint';
  240. return 'float';
  241. }
  242. getVectorType( type ) {
  243. if ( type === 'color' ) return 'vec3';
  244. if ( type === 'texture' ) return 'vec4';
  245. return type;
  246. }
  247. getTypeFromLength( length, componentType = 'float' ) {
  248. if ( length === 1 ) return componentType;
  249. const baseType = typeFromLength.get( length );
  250. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  251. return prefix + baseType;
  252. }
  253. getTypeFromArray( array ) {
  254. return typeFromArray.get( array.constructor );
  255. }
  256. getTypeFromAttribute( attribute ) {
  257. let dataAttribute = attribute;
  258. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  259. const array = dataAttribute.array;
  260. const itemSize = isNonPaddingElementArray.has( array.constructor ) ? attribute.itemSize : dataAttribute.stride || attribute.itemSize;
  261. const normalized = attribute.normalized;
  262. let arrayType;
  263. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  264. arrayType = this.getTypeFromArray( array );
  265. }
  266. return this.getTypeFromLength( itemSize, arrayType );
  267. }
  268. getTypeLength( type ) {
  269. const vecType = this.getVectorType( type );
  270. const vecNum = /vec([2-4])/.exec( vecType );
  271. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  272. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  273. if ( /mat3/.test( type ) === true ) return 9;
  274. if ( /mat4/.test( type ) === true ) return 16;
  275. return 0;
  276. }
  277. getVectorFromMatrix( type ) {
  278. return type.replace( 'mat', 'vec' );
  279. }
  280. changeComponentType( type, newComponentType ) {
  281. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  282. }
  283. getIntegerType( type ) {
  284. const componentType = this.getComponentType( type );
  285. if ( componentType === 'int' || componentType === 'uint' ) return type;
  286. return this.changeComponentType( type, 'int' );
  287. }
  288. addStack() {
  289. this.stack = stack( this.stack );
  290. return this.stack;
  291. }
  292. removeStack() {
  293. const currentStack = this.stack;
  294. this.stack = currentStack.parent;
  295. return currentStack;
  296. }
  297. getDataFromNode( node, shaderStage = this.shaderStage ) {
  298. const cache = node.isGlobal( this ) ? this.globalCache : this.cache;
  299. let nodeData = cache.getNodeData( node );
  300. if ( nodeData === undefined ) {
  301. nodeData = { vertex: {}, fragment: {}, compute: {} };
  302. cache.setNodeData( node, nodeData );
  303. }
  304. return shaderStage !== null ? nodeData[ shaderStage ] : nodeData;
  305. }
  306. getNodeProperties( node, shaderStage = this.shaderStage ) {
  307. const nodeData = this.getDataFromNode( node, shaderStage );
  308. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  309. }
  310. getUniformFromNode( node, shaderStage, type ) {
  311. const nodeData = this.getDataFromNode( node, shaderStage );
  312. let nodeUniform = nodeData.uniform;
  313. if ( nodeUniform === undefined ) {
  314. const index = this.uniforms.index ++;
  315. nodeUniform = new NodeUniform( 'nodeUniform' + index, type, node );
  316. this.uniforms[ shaderStage ].push( nodeUniform );
  317. nodeData.uniform = nodeUniform;
  318. }
  319. return nodeUniform;
  320. }
  321. getVarFromNode( node, type, shaderStage = this.shaderStage ) {
  322. const nodeData = this.getDataFromNode( node, shaderStage );
  323. let nodeVar = nodeData.variable;
  324. if ( nodeVar === undefined ) {
  325. const vars = this.vars[ shaderStage ];
  326. const index = vars.length;
  327. nodeVar = new NodeVar( 'nodeVar' + index, type );
  328. vars.push( nodeVar );
  329. nodeData.variable = nodeVar;
  330. }
  331. return nodeVar;
  332. }
  333. getVaryingFromNode( node, type ) {
  334. const nodeData = this.getDataFromNode( node, null );
  335. let nodeVarying = nodeData.varying;
  336. if ( nodeVarying === undefined ) {
  337. const varyings = this.varyings;
  338. const index = varyings.length;
  339. nodeVarying = new NodeVarying( 'nodeVarying' + index, type );
  340. varyings.push( nodeVarying );
  341. nodeData.varying = nodeVarying;
  342. }
  343. return nodeVarying;
  344. }
  345. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  346. const nodeData = this.getDataFromNode( node );
  347. let nodeCode = nodeData.code;
  348. if ( nodeCode === undefined ) {
  349. const codes = this.codes[ shaderStage ];
  350. const index = codes.length;
  351. nodeCode = new NodeCode( 'nodeCode' + index, type );
  352. codes.push( nodeCode );
  353. nodeData.code = nodeCode;
  354. }
  355. return nodeCode;
  356. }
  357. addLineFlowCode( code ) {
  358. if ( code === '' ) return this;
  359. code = this.tab + code;
  360. if ( ! /;\s*$/.test( code ) ) {
  361. code = code + ';\n';
  362. }
  363. this.flow.code += code;
  364. return this;
  365. }
  366. addFlowCode( code ) {
  367. this.flow.code += code;
  368. return this;
  369. }
  370. addFlowTab() {
  371. this.tab += '\t';
  372. return this;
  373. }
  374. removeFlowTab() {
  375. this.tab = this.tab.slice( 0, - 1 );
  376. return this;
  377. }
  378. getFlowData( node/*, shaderStage*/ ) {
  379. return this.flowsData.get( node );
  380. }
  381. flowNode( node ) {
  382. const output = node.getNodeType( this );
  383. const flowData = this.flowChildNode( node, output );
  384. this.flowsData.set( node, flowData );
  385. return flowData;
  386. }
  387. flowChildNode( node, output = null ) {
  388. const previousFlow = this.flow;
  389. const flow = {
  390. code: '',
  391. };
  392. this.flow = flow;
  393. flow.result = node.build( this, output );
  394. this.flow = previousFlow;
  395. return flow;
  396. }
  397. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  398. const previousShaderStage = this.shaderStage;
  399. this.setShaderStage( shaderStage );
  400. const flowData = this.flowChildNode( node, output );
  401. if ( propertyName !== null ) {
  402. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  403. }
  404. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  405. this.setShaderStage( previousShaderStage );
  406. return flowData;
  407. }
  408. getAttributes( /*shaderStage*/ ) {
  409. console.warn( 'Abstract function.' );
  410. }
  411. getVaryings( /*shaderStage*/ ) {
  412. console.warn( 'Abstract function.' );
  413. }
  414. getVars( shaderStage ) {
  415. let snippet = '';
  416. const vars = this.vars[ shaderStage ];
  417. for ( const variable of vars ) {
  418. snippet += `${variable.type} ${variable.name}; `;
  419. }
  420. return snippet;
  421. }
  422. getUniforms( /*shaderStage*/ ) {
  423. console.warn( 'Abstract function.' );
  424. }
  425. getCodes( shaderStage ) {
  426. const codes = this.codes[ shaderStage ];
  427. let code = '';
  428. for ( const nodeCode of codes ) {
  429. code += nodeCode.code + '\n';
  430. }
  431. return code;
  432. }
  433. getHash() {
  434. return this.vertexShader + this.fragmentShader + this.computeShader;
  435. }
  436. setShaderStage( shaderStage ) {
  437. this.shaderStage = shaderStage;
  438. }
  439. getShaderStage() {
  440. return this.shaderStage;
  441. }
  442. setBuildStage( buildStage ) {
  443. this.buildStage = buildStage;
  444. }
  445. getBuildStage() {
  446. return this.buildStage;
  447. }
  448. buildCode() {
  449. console.warn( 'Abstract function.' );
  450. }
  451. build() {
  452. // construct() -> stage 1: create possible new nodes and returns an output reference node
  453. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  454. // generate() -> stage 3: generate shader
  455. for ( const buildStage of defaultBuildStages ) {
  456. this.setBuildStage( buildStage );
  457. if ( this.context.vertex && this.context.vertex.isNode ) {
  458. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  459. }
  460. for ( const shaderStage of shaderStages ) {
  461. this.setShaderStage( shaderStage );
  462. const flowNodes = this.flowNodes[ shaderStage ];
  463. for ( const node of flowNodes ) {
  464. if ( buildStage === 'generate' ) {
  465. this.flowNode( node );
  466. } else {
  467. node.build( this );
  468. }
  469. }
  470. }
  471. }
  472. this.setBuildStage( null );
  473. this.setShaderStage( null );
  474. // stage 4: build code for a specific output
  475. this.buildCode();
  476. return this;
  477. }
  478. format( snippet, fromType, toType ) {
  479. fromType = this.getVectorType( fromType );
  480. toType = this.getVectorType( toType );
  481. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  482. return snippet;
  483. }
  484. const fromTypeLength = this.getTypeLength( fromType );
  485. const toTypeLength = this.getTypeLength( toType );
  486. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  487. // @TODO: ignore for now
  488. return snippet;
  489. }
  490. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  491. // @TODO: ignore for now
  492. return snippet;
  493. }
  494. if ( fromTypeLength === toTypeLength ) {
  495. return `${ this.getType( toType ) }( ${ snippet } )`;
  496. }
  497. if ( fromTypeLength > toTypeLength ) {
  498. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  499. }
  500. if ( toTypeLength === 4 ) { // toType is vec4-like
  501. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  502. }
  503. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  504. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  505. }
  506. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  507. }
  508. getSignature() {
  509. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  510. }
  511. }
  512. export default NodeBuilder;