NodeBuilder.js 15 KB

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