NodeBuilder.js 14 KB

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