NodeBuilder.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. isReference( type ) {
  147. return type === 'void' || type === 'property' || type === 'sampler';
  148. }
  149. isShaderStage( shaderStage ) {
  150. return this.shaderStage === shaderStage;
  151. }
  152. getTextureEncodingFromMap( map ) {
  153. let encoding;
  154. if ( map && map.isTexture ) {
  155. encoding = map.encoding;
  156. } else if ( map && map.isWebGLRenderTarget ) {
  157. encoding = map.texture.encoding;
  158. } else {
  159. encoding = LinearEncoding;
  160. }
  161. return encoding;
  162. }
  163. getComponentType( type ) {
  164. type = this.getVectorType( type );
  165. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  166. if ( componentType === null ) return null;
  167. if ( componentType[ 1 ] === 'b' ) return 'bool';
  168. if ( componentType[ 1 ] === 'i' ) return 'int';
  169. if ( componentType[ 1 ] === 'u' ) return 'uint';
  170. return 'float';
  171. }
  172. getVectorType( type ) {
  173. if ( type === 'color' ) return 'vec3';
  174. if ( type === 'texture' ) return 'vec4';
  175. return type;
  176. }
  177. getTypeFromLength( type ) {
  178. if ( type === 1 ) return 'float';
  179. if ( type === 2 ) return 'vec2';
  180. if ( type === 3 ) return 'vec3';
  181. if ( type === 4 ) return 'vec4';
  182. return 0;
  183. }
  184. getTypeLength( type ) {
  185. const vecType = this.getVectorType( type );
  186. const vecNum = /vec([2-4])/.exec( vecType );
  187. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  188. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  189. return 0;
  190. }
  191. getVectorFromMatrix( type ) {
  192. return type.replace( 'mat', 'vec' );
  193. }
  194. getDataFromNode( node, shaderStage = this.shaderStage ) {
  195. let nodeData = this.nodesData.get( node );
  196. if ( nodeData === undefined ) {
  197. nodeData = { vertex: {}, fragment: {} };
  198. this.nodesData.set( node, nodeData );
  199. }
  200. return shaderStage !== null ? nodeData[ shaderStage ] : nodeData;
  201. }
  202. getUniformFromNode( node, shaderStage, type ) {
  203. const nodeData = this.getDataFromNode( node, shaderStage );
  204. let nodeUniform = nodeData.uniform;
  205. if ( nodeUniform === undefined ) {
  206. const index = this.uniforms.index ++;
  207. nodeUniform = new NodeUniform( 'nodeUniform' + index, type, node );
  208. this.uniforms[ shaderStage ].push( nodeUniform );
  209. nodeData.uniform = nodeUniform;
  210. }
  211. return nodeUniform;
  212. }
  213. getVarFromNode( node, type, shaderStage = this.shaderStage ) {
  214. const nodeData = this.getDataFromNode( node, shaderStage );
  215. let nodeVar = nodeData.variable;
  216. if ( nodeVar === undefined ) {
  217. const vars = this.vars[ shaderStage ];
  218. const index = vars.length;
  219. nodeVar = new NodeVar( 'nodeVar' + index, type );
  220. vars.push( nodeVar );
  221. nodeData.variable = nodeVar;
  222. }
  223. return nodeVar;
  224. }
  225. getVaryFromNode( node, type ) {
  226. const nodeData = this.getDataFromNode( node, null );
  227. let nodeVary = nodeData.vary;
  228. if ( nodeVary === undefined ) {
  229. const varys = this.varys;
  230. const index = varys.length;
  231. nodeVary = new NodeVary( 'nodeVary' + index, type );
  232. varys.push( nodeVary );
  233. nodeData.vary = nodeVary;
  234. }
  235. return nodeVary;
  236. }
  237. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  238. const nodeData = this.getDataFromNode( node );
  239. let nodeCode = nodeData.code;
  240. if ( nodeCode === undefined ) {
  241. const codes = this.codes[ shaderStage ];
  242. const index = codes.length;
  243. nodeCode = new NodeCode( 'nodeCode' + index, type );
  244. codes.push( nodeCode );
  245. nodeData.code = nodeCode;
  246. }
  247. return nodeCode;
  248. }
  249. addFlowCode( code ) {
  250. this.flow.code += code;
  251. }
  252. getFlowData( shaderStage, node ) {
  253. return this.flowsData.get( node );
  254. }
  255. flowNode( node ) {
  256. this.node = node;
  257. const output = node.getNodeType( this );
  258. const flowData = this.flowChildNode( node, output );
  259. this.flowsData.set( node, flowData );
  260. this.node = null;
  261. return flowData;
  262. }
  263. flowChildNode( node, output = null ) {
  264. const previousFlow = this.flow;
  265. const flow = {
  266. code: '',
  267. };
  268. this.flow = flow;
  269. flow.result = node.build( this, output );
  270. this.flow = previousFlow;
  271. return flow;
  272. }
  273. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  274. const previousShaderStage = this.shaderStage;
  275. this.setShaderStage( shaderStage );
  276. const flowData = this.flowChildNode( node, output );
  277. if ( propertyName !== null ) {
  278. flowData.code += `${propertyName} = ${flowData.result};\n\t`;
  279. }
  280. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  281. this.setShaderStage( previousShaderStage );
  282. return flowData;
  283. }
  284. getAttributes( /*shaderStage*/ ) {
  285. console.warn( 'Abstract function.' );
  286. }
  287. getVarys( /*shaderStage*/ ) {
  288. console.warn( 'Abstract function.' );
  289. }
  290. getVars( shaderStage ) {
  291. let snippet = '';
  292. const vars = this.vars[ shaderStage ];
  293. for ( let index = 0; index < vars.length; index ++ ) {
  294. const variable = vars[ index ];
  295. snippet += `${variable.type} ${variable.name}; `;
  296. }
  297. return snippet;
  298. }
  299. getUniforms( /*shaderStage*/ ) {
  300. console.warn( 'Abstract function.' );
  301. }
  302. getCodes( shaderStage ) {
  303. const codes = this.codes[ shaderStage ];
  304. let code = '';
  305. for ( const nodeCode of codes ) {
  306. code += nodeCode.code + '\n';
  307. }
  308. return code;
  309. }
  310. getHash() {
  311. return this.vertexShader + this.fragmentShader;
  312. }
  313. getShaderStage() {
  314. return this.shaderStage;
  315. }
  316. setShaderStage( shaderStage ) {
  317. this.shaderStage = shaderStage;
  318. }
  319. buildCode() {
  320. console.warn( 'Abstract function.' );
  321. }
  322. build() {
  323. // stage 1: analyze nodes to possible optimization and validation
  324. for ( const shaderStage of shaderStages ) {
  325. this.setShaderStage( shaderStage );
  326. const flowNodes = this.flowNodes[ shaderStage ];
  327. for ( const node of flowNodes ) {
  328. node.analyze( this );
  329. }
  330. }
  331. // stage 2: pre-build vertex code used in fragment shader
  332. if ( this.context.vertex && this.context.vertex.isNode ) {
  333. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  334. }
  335. // stage 3: generate shader
  336. for ( const shaderStage of shaderStages ) {
  337. this.setShaderStage( shaderStage );
  338. const flowNodes = this.flowNodes[ shaderStage ];
  339. for ( const node of flowNodes ) {
  340. this.flowNode( node, shaderStage );
  341. }
  342. }
  343. this.setShaderStage( null );
  344. // stage 4: build code for a specific output
  345. this.buildCode();
  346. return this;
  347. }
  348. format( snippet, fromType, toType ) {
  349. fromType = this.getVectorType( fromType );
  350. toType = this.getVectorType( toType );
  351. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  352. return snippet;
  353. }
  354. const fromTypeLength = this.getTypeLength( fromType );
  355. const toTypeLength = this.getTypeLength( toType );
  356. if ( fromTypeLength === 0 ) { // fromType is matrix-like
  357. const vectorType = this.getVectorFromMatrix( fromType );
  358. return this.format( `( ${ snippet } * ${ this.getType( vectorType ) }( 1.0 ) )`, vectorType, toType );
  359. }
  360. if ( toTypeLength === 0 ) { // toType is matrix-like
  361. // ignore for now
  362. //return `${ this.getType( toType ) }( ${ snippet } )`;
  363. return snippet;
  364. }
  365. if ( fromTypeLength === toTypeLength ) {
  366. return `${ this.getType( toType ) }( ${ snippet } )`;
  367. }
  368. if ( fromTypeLength > toTypeLength ) {
  369. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength ), toType );
  370. }
  371. if ( toTypeLength === 4 ) { // toType is vec4-like
  372. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  373. }
  374. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  375. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  376. }
  377. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  378. }
  379. getSignature() {
  380. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  381. }
  382. }
  383. export default NodeBuilder;