NodeBuilder.js 13 KB

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