NodeBuilder.js 13 KB

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