NodeBuilder.js 12 KB

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