NodeBuilder.js 22 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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 NodeCache from './NodeCache.js';
  8. import ParameterNode from './ParameterNode.js';
  9. import { createNodeMaterialFromType } from '../materials/NodeMaterial.js';
  10. import { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  11. import {
  12. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  13. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  14. } from '../../renderers/common/nodes/NodeUniform.js';
  15. import { REVISION, RenderTarget, NoColorSpace, LinearEncoding, sRGBEncoding, SRGBColorSpace, Color, Vector2, Vector3, Vector4, Float16BufferAttribute } from 'three';
  16. import { stack } from './StackNode.js';
  17. import { getCurrentStack, setCurrentStack } from '../shadernode/ShaderNode.js';
  18. import { maxMipLevel } from '../utils/MaxMipLevelNode.js';
  19. import CubeRenderTarget from '../../renderers/common/CubeRenderTarget.js';
  20. const typeFromLength = new Map( [
  21. [ 2, 'vec2' ],
  22. [ 3, 'vec3' ],
  23. [ 4, 'vec4' ],
  24. [ 9, 'mat3' ],
  25. [ 16, 'mat4' ]
  26. ] );
  27. const typeFromArray = new Map( [
  28. [ Int8Array, 'int' ],
  29. [ Int16Array, 'int' ],
  30. [ Int32Array, 'int' ],
  31. [ Uint8Array, 'uint' ],
  32. [ Uint16Array, 'uint' ],
  33. [ Uint32Array, 'uint' ],
  34. [ Float32Array, 'float' ]
  35. ] );
  36. const isNonPaddingElementArray = new Set( [ Int32Array, Uint32Array, Float32Array ] );
  37. const toFloat = ( value ) => {
  38. value = Number( value );
  39. return value + ( value % 1 ? '' : '.0' );
  40. };
  41. class NodeBuilder {
  42. constructor( object, renderer, parser, scene = null, material = null ) {
  43. this.object = object;
  44. this.material = material || ( object && object.material ) || null;
  45. this.geometry = ( object && object.geometry ) || null;
  46. this.renderer = renderer;
  47. this.parser = parser;
  48. this.scene = scene;
  49. this.nodes = [];
  50. this.updateNodes = [];
  51. this.updateBeforeNodes = [];
  52. this.hashNodes = {};
  53. this.lightsNode = null;
  54. this.environmentNode = null;
  55. this.fogNode = null;
  56. this.toneMappingNode = null;
  57. this.vertexShader = null;
  58. this.fragmentShader = null;
  59. this.computeShader = null;
  60. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  61. this.flowCode = { vertex: '', fragment: '', compute: [] };
  62. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  63. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  64. this.bindings = { vertex: [], fragment: [], compute: [] };
  65. this.bindingsOffset = { vertex: 0, fragment: 0, compute: 0 };
  66. this.bindingsArray = null;
  67. this.attributes = [];
  68. this.bufferAttributes = [];
  69. this.varyings = [];
  70. this.codes = {};
  71. this.vars = {};
  72. this.flow = { code: '' };
  73. this.chaining = [];
  74. this.stack = stack();
  75. this.stacks = [];
  76. this.tab = '\t';
  77. this.context = {
  78. keywords: new NodeKeywords(),
  79. material: this.material,
  80. getMIPLevelAlgorithmNode: ( textureNode, levelNode ) => levelNode.mul( maxMipLevel( textureNode ) )
  81. };
  82. this.cache = new NodeCache();
  83. this.globalCache = this.cache;
  84. this.flowsData = new WeakMap();
  85. this.shaderStage = null;
  86. this.buildStage = null;
  87. }
  88. getRenderTarget( width, height, options ) {
  89. return new RenderTarget( width, height, options );
  90. }
  91. getCubeRenderTarget( size, options ) {
  92. return new CubeRenderTarget( size, options );
  93. }
  94. includes( node ) {
  95. return this.nodes.includes( node );
  96. }
  97. getBindings() {
  98. let bindingsArray = this.bindingsArray;
  99. if ( bindingsArray === null ) {
  100. const bindings = this.bindings;
  101. this.bindingsArray = bindingsArray = ( this.material !== null ) ? [ ...bindings.vertex, ...bindings.fragment ] : bindings.compute;
  102. }
  103. return bindingsArray;
  104. }
  105. setHashNode( node, hash ) {
  106. this.hashNodes[ hash ] = node;
  107. }
  108. addNode( node ) {
  109. if ( this.nodes.includes( node ) === false ) {
  110. this.nodes.push( node );
  111. this.setHashNode( node, node.getHash( this ) );
  112. }
  113. }
  114. buildUpdateNodes() {
  115. for ( const node of this.nodes ) {
  116. const updateType = node.getUpdateType();
  117. const updateBeforeType = node.getUpdateBeforeType();
  118. if ( updateType !== NodeUpdateType.NONE ) {
  119. this.updateNodes.push( node.getSelf() );
  120. }
  121. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  122. this.updateBeforeNodes.push( node );
  123. }
  124. }
  125. }
  126. get currentNode() {
  127. return this.chaining[ this.chaining.length - 1 ];
  128. }
  129. addChain( node ) {
  130. /*
  131. if ( this.chaining.indexOf( node ) !== - 1 ) {
  132. console.warn( 'Recursive node: ', node );
  133. }
  134. */
  135. this.chaining.push( node );
  136. }
  137. removeChain( node ) {
  138. const lastChain = this.chaining.pop();
  139. if ( lastChain !== node ) {
  140. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  141. }
  142. }
  143. getMethod( method ) {
  144. return method;
  145. }
  146. getNodeFromHash( hash ) {
  147. return this.hashNodes[ hash ];
  148. }
  149. addFlow( shaderStage, node ) {
  150. this.flowNodes[ shaderStage ].push( node );
  151. return node;
  152. }
  153. setContext( context ) {
  154. this.context = context;
  155. }
  156. getContext() {
  157. return this.context;
  158. }
  159. setCache( cache ) {
  160. this.cache = cache;
  161. }
  162. getCache() {
  163. return this.cache;
  164. }
  165. isAvailable( /*name*/ ) {
  166. return false;
  167. }
  168. getVertexIndex() {
  169. console.warn( 'Abstract function.' );
  170. }
  171. getInstanceIndex() {
  172. console.warn( 'Abstract function.' );
  173. }
  174. getFrontFacing() {
  175. console.warn( 'Abstract function.' );
  176. }
  177. getFragCoord() {
  178. console.warn( 'Abstract function.' );
  179. }
  180. isFlipY() {
  181. return false;
  182. }
  183. getTexture( /* texture, textureProperty, uvSnippet */ ) {
  184. console.warn( 'Abstract function.' );
  185. }
  186. getTextureLevel( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  187. console.warn( 'Abstract function.' );
  188. }
  189. // @TODO: rename to .generateConst()
  190. getConst( type, value = null ) {
  191. if ( value === null ) {
  192. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  193. else if ( type === 'bool' ) value = false;
  194. else if ( type === 'color' ) value = new Color();
  195. else if ( type === 'vec2' ) value = new Vector2();
  196. else if ( type === 'vec3' ) value = new Vector3();
  197. else if ( type === 'vec4' ) value = new Vector4();
  198. }
  199. if ( type === 'float' ) return toFloat( value );
  200. if ( type === 'int' ) return `${ Math.round( value ) }`;
  201. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  202. if ( type === 'bool' ) return value ? 'true' : 'false';
  203. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  204. const typeLength = this.getTypeLength( type );
  205. const componentType = this.getComponentType( type );
  206. const getConst = value => this.getConst( componentType, value );
  207. if ( typeLength === 2 ) {
  208. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) } )`;
  209. } else if ( typeLength === 3 ) {
  210. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) } )`;
  211. } else if ( typeLength === 4 ) {
  212. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) }, ${ getConst( value.w ) } )`;
  213. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  214. return `${ this.getType( type ) }( ${ value.elements.map( getConst ).join( ', ' ) } )`;
  215. } else if ( typeLength > 4 ) {
  216. return `${ this.getType( type ) }()`;
  217. }
  218. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  219. }
  220. getType( type ) {
  221. if ( type === 'color' ) return 'vec3';
  222. return type;
  223. }
  224. generateMethod( method ) {
  225. return method;
  226. }
  227. hasGeometryAttribute( name ) {
  228. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  229. }
  230. getAttribute( name, type ) {
  231. const attributes = this.attributes;
  232. // find attribute
  233. for ( const attribute of attributes ) {
  234. if ( attribute.name === name ) {
  235. return attribute;
  236. }
  237. }
  238. // create a new if no exist
  239. const attribute = new NodeAttribute( name, type );
  240. attributes.push( attribute );
  241. return attribute;
  242. }
  243. getPropertyName( node/*, shaderStage*/ ) {
  244. return node.name;
  245. }
  246. isVector( type ) {
  247. return /vec\d/.test( type );
  248. }
  249. isMatrix( type ) {
  250. return /mat\d/.test( type );
  251. }
  252. isReference( type ) {
  253. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture';
  254. }
  255. needsColorSpaceToLinear( /*texture*/ ) {
  256. return false;
  257. }
  258. /** @deprecated, r152 */
  259. getTextureEncodingFromMap( map ) {
  260. console.warn( 'THREE.NodeBuilder: Method .getTextureEncodingFromMap replaced by .getTextureColorSpaceFromMap in r152+.' );
  261. return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  262. }
  263. getTextureColorSpaceFromMap( map ) {
  264. let colorSpace;
  265. if ( map && map.isTexture ) {
  266. colorSpace = map.colorSpace;
  267. } else if ( map && map.isWebGLRenderTarget ) {
  268. colorSpace = map.texture.colorSpace;
  269. } else {
  270. colorSpace = NoColorSpace;
  271. }
  272. return colorSpace;
  273. }
  274. getComponentType( type ) {
  275. type = this.getVectorType( type );
  276. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  277. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  278. if ( componentType === null ) return null;
  279. if ( componentType[ 1 ] === 'b' ) return 'bool';
  280. if ( componentType[ 1 ] === 'i' ) return 'int';
  281. if ( componentType[ 1 ] === 'u' ) return 'uint';
  282. return 'float';
  283. }
  284. getVectorType( type ) {
  285. if ( type === 'color' ) return 'vec3';
  286. if ( type === 'texture' ) return 'vec4';
  287. return type;
  288. }
  289. getTypeFromLength( length, componentType = 'float' ) {
  290. if ( length === 1 ) return componentType;
  291. const baseType = typeFromLength.get( length );
  292. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  293. return prefix + baseType;
  294. }
  295. getTypeFromArray( array ) {
  296. return typeFromArray.get( array.constructor );
  297. }
  298. getTypeFromAttribute( attribute ) {
  299. let dataAttribute = attribute;
  300. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  301. const array = dataAttribute.array;
  302. const itemSize = isNonPaddingElementArray.has( array.constructor ) ? attribute.itemSize : dataAttribute.stride || attribute.itemSize;
  303. const normalized = attribute.normalized;
  304. let arrayType;
  305. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  306. arrayType = this.getTypeFromArray( array );
  307. }
  308. return this.getTypeFromLength( itemSize, arrayType );
  309. }
  310. getTypeLength( type ) {
  311. const vecType = this.getVectorType( type );
  312. const vecNum = /vec([2-4])/.exec( vecType );
  313. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  314. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  315. if ( /mat3/.test( type ) === true ) return 9;
  316. if ( /mat4/.test( type ) === true ) return 16;
  317. return 0;
  318. }
  319. getVectorFromMatrix( type ) {
  320. return type.replace( 'mat', 'vec' );
  321. }
  322. changeComponentType( type, newComponentType ) {
  323. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  324. }
  325. getIntegerType( type ) {
  326. const componentType = this.getComponentType( type );
  327. if ( componentType === 'int' || componentType === 'uint' ) return type;
  328. return this.changeComponentType( type, 'int' );
  329. }
  330. addStack() {
  331. this.stack = stack( this.stack );
  332. this.stacks.push( getCurrentStack() || this.stack );
  333. setCurrentStack( this.stack );
  334. return this.stack;
  335. }
  336. removeStack() {
  337. const lastStack = this.stack;
  338. this.stack = lastStack.parent;
  339. setCurrentStack( this.stacks.pop() );
  340. return lastStack;
  341. }
  342. getDataFromNode( node, shaderStage = this.shaderStage ) {
  343. const cache = node.isGlobal( this ) ? this.globalCache : this.cache;
  344. let nodeData = cache.getNodeData( node );
  345. if ( nodeData === undefined ) {
  346. nodeData = {};
  347. cache.setNodeData( node, nodeData );
  348. }
  349. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  350. return nodeData[ shaderStage ];
  351. }
  352. getNodeProperties( node, shaderStage = 'any' ) {
  353. const nodeData = this.getDataFromNode( node, shaderStage );
  354. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  355. }
  356. getBufferAttributeFromNode( node, type ) {
  357. const nodeData = this.getDataFromNode( node );
  358. let bufferAttribute = nodeData.bufferAttribute;
  359. if ( bufferAttribute === undefined ) {
  360. const index = this.uniforms.index ++;
  361. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  362. this.bufferAttributes.push( bufferAttribute );
  363. nodeData.bufferAttribute = bufferAttribute;
  364. }
  365. return bufferAttribute;
  366. }
  367. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  368. const nodeData = this.getDataFromNode( node, shaderStage );
  369. if ( nodeData.structType === undefined ) {
  370. const index = this.structs.index ++;
  371. node.name = `StructType${ index }`;
  372. this.structs[ shaderStage ].push( node );
  373. nodeData.structType = node;
  374. }
  375. return node;
  376. }
  377. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  378. const nodeData = this.getDataFromNode( node, shaderStage );
  379. let nodeUniform = nodeData.uniform;
  380. if ( nodeUniform === undefined ) {
  381. const index = this.uniforms.index ++;
  382. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  383. this.uniforms[ shaderStage ].push( nodeUniform );
  384. nodeData.uniform = nodeUniform;
  385. }
  386. return nodeUniform;
  387. }
  388. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  389. const nodeData = this.getDataFromNode( node, shaderStage );
  390. let nodeVar = nodeData.variable;
  391. if ( nodeVar === undefined ) {
  392. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  393. if ( name === null ) name = 'nodeVar' + vars.length;
  394. nodeVar = new NodeVar( name, type );
  395. vars.push( nodeVar );
  396. nodeData.variable = nodeVar;
  397. }
  398. return nodeVar;
  399. }
  400. getVaryingFromNode( node, type ) {
  401. const nodeData = this.getDataFromNode( node, 'any' );
  402. let nodeVarying = nodeData.varying;
  403. if ( nodeVarying === undefined ) {
  404. const varyings = this.varyings;
  405. const index = varyings.length;
  406. nodeVarying = new NodeVarying( 'nodeVarying' + index, type );
  407. varyings.push( nodeVarying );
  408. nodeData.varying = nodeVarying;
  409. }
  410. return nodeVarying;
  411. }
  412. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  413. const nodeData = this.getDataFromNode( node );
  414. let nodeCode = nodeData.code;
  415. if ( nodeCode === undefined ) {
  416. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  417. const index = codes.length;
  418. nodeCode = new NodeCode( 'nodeCode' + index, type );
  419. codes.push( nodeCode );
  420. nodeData.code = nodeCode;
  421. }
  422. return nodeCode;
  423. }
  424. addLineFlowCode( code ) {
  425. if ( code === '' ) return this;
  426. code = this.tab + code;
  427. if ( ! /;\s*$/.test( code ) ) {
  428. code = code + ';\n';
  429. }
  430. this.flow.code += code;
  431. return this;
  432. }
  433. addFlowCode( code ) {
  434. this.flow.code += code;
  435. return this;
  436. }
  437. addFlowTab() {
  438. this.tab += '\t';
  439. return this;
  440. }
  441. removeFlowTab() {
  442. this.tab = this.tab.slice( 0, - 1 );
  443. return this;
  444. }
  445. getFlowData( node/*, shaderStage*/ ) {
  446. return this.flowsData.get( node );
  447. }
  448. flowNode( node ) {
  449. const output = node.getNodeType( this );
  450. const flowData = this.flowChildNode( node, output );
  451. this.flowsData.set( node, flowData );
  452. return flowData;
  453. }
  454. flowShaderNode( shaderNode ) {
  455. const layout = shaderNode.layout;
  456. let inputs;
  457. if ( shaderNode.isArrayInput ) {
  458. inputs = [];
  459. for ( const input of layout.inputs ) {
  460. inputs.push( new ParameterNode( input.type, input.name ) );
  461. }
  462. } else {
  463. inputs = {};
  464. for ( const input of layout.inputs ) {
  465. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  466. }
  467. }
  468. //
  469. shaderNode.layout = null;
  470. const callNode = shaderNode.call( inputs );
  471. const flowData = this.flowStagesNode( callNode, layout.type );
  472. shaderNode.layout = layout;
  473. return flowData;
  474. }
  475. flowStagesNode( node, output = null ) {
  476. const previousFlow = this.flow;
  477. const previousVars = this.vars;
  478. const previousBuildStage = this.buildStage;
  479. const flow = {
  480. code: ''
  481. };
  482. this.flow = flow;
  483. this.vars = {};
  484. for ( const buildStage of defaultBuildStages ) {
  485. this.setBuildStage( buildStage );
  486. flow.result = node.build( this, output );
  487. }
  488. flow.vars = this.getVars( this.shaderStage );
  489. this.flow = previousFlow;
  490. this.vars = previousVars;
  491. this.setBuildStage( previousBuildStage );
  492. return flow;
  493. }
  494. flowChildNode( node, output = null ) {
  495. const previousFlow = this.flow;
  496. const flow = {
  497. code: ''
  498. };
  499. this.flow = flow;
  500. flow.result = node.build( this, output );
  501. this.flow = previousFlow;
  502. return flow;
  503. }
  504. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  505. const previousShaderStage = this.shaderStage;
  506. this.setShaderStage( shaderStage );
  507. const flowData = this.flowChildNode( node, output );
  508. if ( propertyName !== null ) {
  509. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  510. }
  511. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  512. this.setShaderStage( previousShaderStage );
  513. return flowData;
  514. }
  515. getAttributesArray() {
  516. return this.attributes.concat( this.bufferAttributes );
  517. }
  518. getAttributes( /*shaderStage*/ ) {
  519. console.warn( 'Abstract function.' );
  520. }
  521. getVaryings( /*shaderStage*/ ) {
  522. console.warn( 'Abstract function.' );
  523. }
  524. getVar( type, name ) {
  525. return `${ this.getType( type ) } ${ name }`;
  526. }
  527. getVars( shaderStage ) {
  528. let snippet = '';
  529. const vars = this.vars[ shaderStage ];
  530. if ( vars !== undefined ) {
  531. for ( const variable of vars ) {
  532. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  533. }
  534. }
  535. return snippet;
  536. }
  537. getUniforms( /*shaderStage*/ ) {
  538. console.warn( 'Abstract function.' );
  539. }
  540. getCodes( shaderStage ) {
  541. const codes = this.codes[ shaderStage ];
  542. let code = '';
  543. if ( codes !== undefined ) {
  544. for ( const nodeCode of codes ) {
  545. code += nodeCode.code + '\n';
  546. }
  547. }
  548. return code;
  549. }
  550. getHash() {
  551. return this.vertexShader + this.fragmentShader + this.computeShader;
  552. }
  553. setShaderStage( shaderStage ) {
  554. this.shaderStage = shaderStage;
  555. }
  556. getShaderStage() {
  557. return this.shaderStage;
  558. }
  559. setBuildStage( buildStage ) {
  560. this.buildStage = buildStage;
  561. }
  562. getBuildStage() {
  563. return this.buildStage;
  564. }
  565. buildCode() {
  566. console.warn( 'Abstract function.' );
  567. }
  568. build() {
  569. // setup() -> stage 1: create possible new nodes and returns an output reference node
  570. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  571. // generate() -> stage 3: generate shader
  572. for ( const buildStage of defaultBuildStages ) {
  573. this.setBuildStage( buildStage );
  574. if ( this.context.vertex && this.context.vertex.isNode ) {
  575. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  576. }
  577. for ( const shaderStage of shaderStages ) {
  578. this.setShaderStage( shaderStage );
  579. const flowNodes = this.flowNodes[ shaderStage ];
  580. for ( const node of flowNodes ) {
  581. if ( buildStage === 'generate' ) {
  582. this.flowNode( node );
  583. } else {
  584. node.build( this );
  585. }
  586. }
  587. }
  588. }
  589. this.setBuildStage( null );
  590. this.setShaderStage( null );
  591. // stage 4: build code for a specific output
  592. this.buildCode();
  593. this.buildUpdateNodes();
  594. return this;
  595. }
  596. getNodeUniform( uniformNode, type ) {
  597. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  598. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  599. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  600. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  601. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  602. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  603. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  604. throw new Error( `Uniform "${type}" not declared.` );
  605. }
  606. createNodeMaterial( type ) {
  607. return createNodeMaterialFromType( type );
  608. }
  609. getPrimitiveType( type ) {
  610. let primitiveType;
  611. if ( type[ 0 ] === 'i' ) primitiveType = 'int';
  612. else if ( type[ 0 ] === 'u' ) primitiveType = 'uint';
  613. else primitiveType = 'float';
  614. return primitiveType;
  615. }
  616. format( snippet, fromType, toType ) {
  617. fromType = this.getVectorType( fromType );
  618. toType = this.getVectorType( toType );
  619. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  620. return snippet;
  621. }
  622. const fromTypeLength = this.getTypeLength( fromType );
  623. const toTypeLength = this.getTypeLength( toType );
  624. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  625. // @TODO: ignore for now
  626. return snippet;
  627. }
  628. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  629. // @TODO: ignore for now
  630. return snippet;
  631. }
  632. if ( fromTypeLength === toTypeLength ) {
  633. return `${ this.getType( toType ) }( ${ snippet } )`;
  634. }
  635. if ( fromTypeLength > toTypeLength ) {
  636. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  637. }
  638. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  639. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  640. }
  641. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  642. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  643. }
  644. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  645. // convert a number value to vector type, e.g:
  646. // vec3( 1u ) -> vec3( float( 1u ) )
  647. snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`;
  648. }
  649. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  650. }
  651. getSignature() {
  652. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  653. }
  654. }
  655. export default NodeBuilder;