nodeMaterialBlock.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. import { NodeMaterialBlockConnectionPointTypes } from './Enums/nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  3. import { Nullable } from '../../types';
  4. import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from './nodeMaterialBlockConnectionPoint';
  5. import { NodeMaterialBlockTargets } from './Enums/nodeMaterialBlockTargets';
  6. import { Effect } from '../effect';
  7. import { AbstractMesh } from '../../Meshes/abstractMesh';
  8. import { Mesh } from '../../Meshes/mesh';
  9. import { NodeMaterial, NodeMaterialDefines } from './nodeMaterial';
  10. import { InputBlock } from './Blocks/Input/inputBlock';
  11. import { UniqueIdGenerator } from '../../Misc/uniqueIdGenerator';
  12. import { Scene } from '../../scene';
  13. import { _TypeStore } from '../../Misc/typeStore';
  14. import { EffectFallbacks } from '../effectFallbacks';
  15. /**
  16. * Defines a block that can be used inside a node based material
  17. */
  18. export class NodeMaterialBlock {
  19. private _buildId: number;
  20. private _buildTarget: NodeMaterialBlockTargets;
  21. private _target: NodeMaterialBlockTargets;
  22. private _isFinalMerger = false;
  23. private _isInput = false;
  24. protected _isUnique = false;
  25. /** Gets or sets a boolean indicating that only one input can be connected at a time */
  26. public inputsAreExclusive = false;
  27. /** @hidden */
  28. public _codeVariableName = "";
  29. /** @hidden */
  30. public _inputs = new Array<NodeMaterialConnectionPoint>();
  31. /** @hidden */
  32. public _outputs = new Array<NodeMaterialConnectionPoint>();
  33. /** @hidden */
  34. public _preparationId: number;
  35. /**
  36. * Gets or sets the name of the block
  37. */
  38. public name: string;
  39. /**
  40. * Gets or sets the unique id of the node
  41. */
  42. public uniqueId: number;
  43. /**
  44. * Gets or sets the comments associated with this block
  45. */
  46. public comments: string = "";
  47. /**
  48. * Gets a boolean indicating that this block can only be used once per NodeMaterial
  49. */
  50. public get isUnique() {
  51. return this._isUnique;
  52. }
  53. /**
  54. * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
  55. */
  56. public get isFinalMerger(): boolean {
  57. return this._isFinalMerger;
  58. }
  59. /**
  60. * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)
  61. */
  62. public get isInput(): boolean {
  63. return this._isInput;
  64. }
  65. /**
  66. * Gets or sets the build Id
  67. */
  68. public get buildId(): number {
  69. return this._buildId;
  70. }
  71. public set buildId(value: number) {
  72. this._buildId = value;
  73. }
  74. /**
  75. * Gets or sets the target of the block
  76. */
  77. public get target() {
  78. return this._target;
  79. }
  80. public set target(value: NodeMaterialBlockTargets) {
  81. if ((this._target & value) !== 0) {
  82. return;
  83. }
  84. this._target = value;
  85. }
  86. /**
  87. * Gets the list of input points
  88. */
  89. public get inputs(): NodeMaterialConnectionPoint[] {
  90. return this._inputs;
  91. }
  92. /** Gets the list of output points */
  93. public get outputs(): NodeMaterialConnectionPoint[] {
  94. return this._outputs;
  95. }
  96. /**
  97. * Find an input by its name
  98. * @param name defines the name of the input to look for
  99. * @returns the input or null if not found
  100. */
  101. public getInputByName(name: string) {
  102. let filter = this._inputs.filter((e) => e.name === name);
  103. if (filter.length) {
  104. return filter[0];
  105. }
  106. return null;
  107. }
  108. /**
  109. * Find an output by its name
  110. * @param name defines the name of the outputto look for
  111. * @returns the output or null if not found
  112. */
  113. public getOutputByName(name: string) {
  114. let filter = this._outputs.filter((e) => e.name === name);
  115. if (filter.length) {
  116. return filter[0];
  117. }
  118. return null;
  119. }
  120. /**
  121. * Creates a new NodeMaterialBlock
  122. * @param name defines the block name
  123. * @param target defines the target of that block (Vertex by default)
  124. * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
  125. * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false
  126. */
  127. public constructor(name: string, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {
  128. this.name = name;
  129. this._target = target;
  130. this._isFinalMerger = isFinalMerger;
  131. this._isInput = isInput;
  132. this.uniqueId = UniqueIdGenerator.UniqueId;
  133. }
  134. /**
  135. * Initialize the block and prepare the context for build
  136. * @param state defines the state that will be used for the build
  137. */
  138. public initialize(state: NodeMaterialBuildState) {
  139. // Do nothing
  140. }
  141. /**
  142. * Bind data to effect. Will only be called for blocks with isBindable === true
  143. * @param effect defines the effect to bind data to
  144. * @param nodeMaterial defines the hosting NodeMaterial
  145. * @param mesh defines the mesh that will be rendered
  146. */
  147. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  148. // Do nothing
  149. }
  150. protected _declareOutput(output: NodeMaterialConnectionPoint, state: NodeMaterialBuildState): string {
  151. return `${state._getGLType(output.type)} ${output.associatedVariableName}`;
  152. }
  153. protected _writeVariable(currentPoint: NodeMaterialConnectionPoint): string {
  154. let connectionPoint = currentPoint.connectedPoint;
  155. if (connectionPoint) {
  156. return `${currentPoint.associatedVariableName}`;
  157. }
  158. return `0.`;
  159. }
  160. protected _writeFloat(value: number) {
  161. let stringVersion = value.toString();
  162. if (stringVersion.indexOf(".") === -1) {
  163. stringVersion += ".0";
  164. }
  165. return `${stringVersion}`;
  166. }
  167. /**
  168. * Gets the current class name e.g. "NodeMaterialBlock"
  169. * @returns the class name
  170. */
  171. public getClassName() {
  172. return "NodeMaterialBlock";
  173. }
  174. /**
  175. * Register a new input. Must be called inside a block constructor
  176. * @param name defines the connection point name
  177. * @param type defines the connection point type
  178. * @param isOptional defines a boolean indicating that this input can be omitted
  179. * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
  180. * @returns the current block
  181. */
  182. public registerInput(name: string, type: NodeMaterialBlockConnectionPointTypes, isOptional: boolean = false, target?: NodeMaterialBlockTargets) {
  183. let point = new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Input);
  184. point.type = type;
  185. point.isOptional = isOptional;
  186. if (target) {
  187. point.target = target;
  188. }
  189. this._inputs.push(point);
  190. return this;
  191. }
  192. /**
  193. * Register a new output. Must be called inside a block constructor
  194. * @param name defines the connection point name
  195. * @param type defines the connection point type
  196. * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
  197. * @returns the current block
  198. */
  199. public registerOutput(name: string, type: NodeMaterialBlockConnectionPointTypes, target?: NodeMaterialBlockTargets) {
  200. let point = new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Output);
  201. point.type = type;
  202. if (target) {
  203. point.target = target;
  204. }
  205. this._outputs.push(point);
  206. return this;
  207. }
  208. /**
  209. * Will return the first available input e.g. the first one which is not an uniform or an attribute
  210. * @param forOutput defines an optional connection point to check compatibility with
  211. * @returns the first available input or null
  212. */
  213. public getFirstAvailableInput(forOutput: Nullable<NodeMaterialConnectionPoint> = null) {
  214. for (var input of this._inputs) {
  215. if (!input.connectedPoint) {
  216. if (!forOutput || (forOutput.type === input.type) || (input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect)) {
  217. return input;
  218. }
  219. }
  220. }
  221. return null;
  222. }
  223. /**
  224. * Will return the first available output e.g. the first one which is not yet connected and not a varying
  225. * @param forBlock defines an optional block to check compatibility with
  226. * @returns the first available input or null
  227. */
  228. public getFirstAvailableOutput(forBlock: Nullable<NodeMaterialBlock> = null) {
  229. for (var output of this._outputs) {
  230. if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {
  231. return output;
  232. }
  233. }
  234. return null;
  235. }
  236. /**
  237. * Gets the sibling of the given output
  238. * @param current defines the current output
  239. * @returns the next output in the list or null
  240. */
  241. public getSiblingOutput(current: NodeMaterialConnectionPoint) {
  242. let index = this._outputs.indexOf(current);
  243. if (index === -1 || index >= this._outputs.length) {
  244. return null;
  245. }
  246. return this._outputs[index + 1];
  247. }
  248. /**
  249. * Connect current block with another block
  250. * @param other defines the block to connect with
  251. * @param options define the various options to help pick the right connections
  252. * @returns the current block
  253. */
  254. public connectTo(other: NodeMaterialBlock, options?: {
  255. input?: string,
  256. output?: string,
  257. outputSwizzle?: string
  258. }) {
  259. if (this._outputs.length === 0) {
  260. return;
  261. }
  262. let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
  263. let notFound = true;
  264. while (notFound) {
  265. let input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
  266. if (output && input && output.canConnectTo(input)) {
  267. output.connectTo(input);
  268. notFound = false;
  269. } else if (!output) {
  270. throw "Unable to find a compatible match";
  271. } else {
  272. output = this.getSiblingOutput(output);
  273. }
  274. }
  275. return this;
  276. }
  277. protected _buildBlock(state: NodeMaterialBuildState) {
  278. // Empty. Must be defined by child nodes
  279. }
  280. /**
  281. * Add uniforms, samplers and uniform buffers at compilation time
  282. * @param state defines the state to update
  283. * @param nodeMaterial defines the node material requesting the update
  284. * @param defines defines the material defines to update
  285. * @param uniformBuffers defines the list of uniform buffer names
  286. */
  287. public updateUniformsAndSamples(state: NodeMaterialBuildState, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, uniformBuffers: string[]) {
  288. // Do nothing
  289. }
  290. /**
  291. * Add potential fallbacks if shader compilation fails
  292. * @param mesh defines the mesh to be rendered
  293. * @param fallbacks defines the current prioritized list of fallbacks
  294. */
  295. public provideFallbacks(mesh: AbstractMesh, fallbacks: EffectFallbacks) {
  296. // Do nothing
  297. }
  298. /**
  299. * Initialize defines for shader compilation
  300. * @param mesh defines the mesh to be rendered
  301. * @param nodeMaterial defines the node material requesting the update
  302. * @param defines defines the material defines to update
  303. * @param useInstances specifies that instances should be used
  304. */
  305. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  306. }
  307. /**
  308. * Update defines for shader compilation
  309. * @param mesh defines the mesh to be rendered
  310. * @param nodeMaterial defines the node material requesting the update
  311. * @param defines defines the material defines to update
  312. * @param useInstances specifies that instances should be used
  313. */
  314. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  315. // Do nothing
  316. }
  317. /**
  318. * Lets the block try to connect some inputs automatically
  319. * @param material defines the hosting NodeMaterial
  320. */
  321. public autoConfigure(material: NodeMaterial) {
  322. // Do nothing
  323. }
  324. /**
  325. * Function called when a block is declared as repeatable content generator
  326. * @param vertexShaderState defines the current compilation state for the vertex shader
  327. * @param fragmentShaderState defines the current compilation state for the fragment shader
  328. * @param mesh defines the mesh to be rendered
  329. * @param defines defines the material defines to update
  330. */
  331. public replaceRepeatableContent(vertexShaderState: NodeMaterialBuildState, fragmentShaderState: NodeMaterialBuildState, mesh: AbstractMesh, defines: NodeMaterialDefines) {
  332. // Do nothing
  333. }
  334. /**
  335. * Checks if the block is ready
  336. * @param mesh defines the mesh to be rendered
  337. * @param nodeMaterial defines the node material requesting the update
  338. * @param defines defines the material defines to update
  339. * @param useInstances specifies that instances should be used
  340. * @returns true if the block is ready
  341. */
  342. public isReady(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  343. return true;
  344. }
  345. protected _linkConnectionTypes(inputIndex0: number, inputIndex1: number) {
  346. this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
  347. this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
  348. }
  349. private _processBuild(block: NodeMaterialBlock, state: NodeMaterialBuildState, input: NodeMaterialConnectionPoint, activeBlocks: NodeMaterialBlock[]) {
  350. block.build(state, activeBlocks);
  351. const localBlockIsFragment = (state._vertexState != null);
  352. const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment;
  353. if (localBlockIsFragment && (
  354. ((block.target & block._buildTarget) === 0) ||
  355. ((block.target & input.target) === 0) ||
  356. (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader)
  357. )) { // context switch! We need a varying
  358. if ((!block.isInput && state.target !== block._buildTarget) // block was already emitted by vertex shader
  359. || (block.isInput && (block as InputBlock).isAttribute) // block is an attribute
  360. ) {
  361. let connectedPoint = input.connectedPoint!;
  362. if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) {
  363. state._vertexState.compilationString += `${"v_" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\r\n`;
  364. }
  365. input.associatedVariableName = "v_" + connectedPoint.associatedVariableName;
  366. input._enforceAssociatedVariableName = true;
  367. }
  368. }
  369. }
  370. /**
  371. * Compile the current node and generate the shader code
  372. * @param state defines the current compilation state (uniforms, samplers, current string)
  373. * @param activeBlocks defines the list of active blocks (i.e. blocks to compile)
  374. * @returns true if already built
  375. */
  376. public build(state: NodeMaterialBuildState, activeBlocks: NodeMaterialBlock[]): boolean {
  377. if (this._buildId === state.sharedData.buildId) {
  378. return true;
  379. }
  380. if (!this.isInput) {
  381. /** Prepare outputs */
  382. for (var output of this._outputs) {
  383. if (!output.associatedVariableName) {
  384. output.associatedVariableName = state._getFreeVariableName(output.name);
  385. }
  386. }
  387. }
  388. // Check if "parent" blocks are compiled
  389. for (var input of this._inputs) {
  390. if (!input.connectedPoint) {
  391. if (!input.isOptional) { // Emit a warning
  392. state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
  393. }
  394. continue;
  395. }
  396. if (this.target !== NodeMaterialBlockTargets.Neutral) {
  397. if ((input.target & this.target!) === 0) {
  398. continue;
  399. }
  400. if ((input.target & state.target!) === 0) {
  401. continue;
  402. }
  403. }
  404. let block = input.connectedPoint.ownerBlock;
  405. if (block && block !== this) {
  406. this._processBuild(block, state, input, activeBlocks);
  407. }
  408. }
  409. if (this._buildId === state.sharedData.buildId) {
  410. return true; // Need to check again as inputs can be connected multiple time to this endpoint
  411. }
  412. // Logs
  413. if (state.sharedData.verbose) {
  414. console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
  415. }
  416. // Checks final outputs
  417. if (this.isFinalMerger) {
  418. switch (state.target) {
  419. case NodeMaterialBlockTargets.Vertex:
  420. state.sharedData.checks.emitVertex = true;
  421. break;
  422. case NodeMaterialBlockTargets.Fragment:
  423. state.sharedData.checks.emitFragment = true;
  424. break;
  425. }
  426. }
  427. if (!this.isInput && state.sharedData.emitComments) {
  428. state.compilationString += `\r\n//${this.name}\r\n`;
  429. }
  430. this._buildBlock(state);
  431. this._buildId = state.sharedData.buildId;
  432. this._buildTarget = state.target;
  433. // Compile connected blocks
  434. for (var output of this._outputs) {
  435. if ((output.target & state.target) === 0) {
  436. continue;
  437. }
  438. for (var endpoint of output.endpoints) {
  439. let block = endpoint.ownerBlock;
  440. if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {
  441. this._processBuild(block, state, endpoint, activeBlocks);
  442. }
  443. }
  444. }
  445. return false;
  446. }
  447. protected _inputRename(name: string) {
  448. return name;
  449. }
  450. protected _outputRename(name: string) {
  451. return name;
  452. }
  453. protected _dumpPropertiesCode() {
  454. return "";
  455. }
  456. /** @hidden */
  457. public _dumpCode(uniqueNames: string[], alreadyDumped: NodeMaterialBlock[]) {
  458. alreadyDumped.push(this);
  459. let codeString: string;
  460. // Get unique name
  461. let nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
  462. this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;
  463. if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
  464. let index = 0;
  465. do {
  466. index++;
  467. this._codeVariableName = nameAsVariableName + index;
  468. }
  469. while (uniqueNames.indexOf(this._codeVariableName) !== -1);
  470. }
  471. uniqueNames.push(this._codeVariableName);
  472. // Declaration
  473. codeString = `\r\n// ${this.getClassName()}\r\n`;
  474. if (this.comments) {
  475. codeString += `// ${this.comments}\r\n`;
  476. }
  477. codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`;
  478. // Properties
  479. codeString += this._dumpPropertiesCode();
  480. // Inputs
  481. for (var input of this.inputs) {
  482. if (!input.isConnected) {
  483. continue;
  484. }
  485. var connectedOutput = input.connectedPoint!;
  486. var connectedBlock = connectedOutput.ownerBlock;
  487. if (alreadyDumped.indexOf(connectedBlock) === -1) {
  488. codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
  489. }
  490. }
  491. // Outputs
  492. for (var output of this.outputs) {
  493. if (!output.hasEndpoints) {
  494. continue;
  495. }
  496. for (var endpoint of output.endpoints) {
  497. var connectedBlock = endpoint.ownerBlock;
  498. if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
  499. codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
  500. }
  501. }
  502. }
  503. return codeString;
  504. }
  505. /** @hidden */
  506. public _dumpCodeForOutputConnections(alreadyDumped: NodeMaterialBlock[]) {
  507. let codeString = "";
  508. if (alreadyDumped.indexOf(this) !== -1) {
  509. return codeString;
  510. }
  511. alreadyDumped.push(this);
  512. for (var input of this.inputs) {
  513. if (!input.isConnected) {
  514. continue;
  515. }
  516. var connectedOutput = input.connectedPoint!;
  517. var connectedBlock = connectedOutput.ownerBlock;
  518. codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
  519. codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\r\n`;
  520. }
  521. return codeString;
  522. }
  523. /**
  524. * Clone the current block to a new identical block
  525. * @param scene defines the hosting scene
  526. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  527. * @returns a copy of the current block
  528. */
  529. public clone(scene: Scene, rootUrl: string = "") {
  530. let serializationObject = this.serialize();
  531. let blockType = _TypeStore.GetClass(serializationObject.customType);
  532. if (blockType) {
  533. let block: NodeMaterialBlock = new blockType();
  534. block._deserialize(serializationObject, scene, rootUrl);
  535. return block;
  536. }
  537. return null;
  538. }
  539. /**
  540. * Serializes this block in a JSON representation
  541. * @returns the serialized block object
  542. */
  543. public serialize(): any {
  544. let serializationObject: any = {};
  545. serializationObject.customType = "BABYLON." + this.getClassName();
  546. serializationObject.id = this.uniqueId;
  547. serializationObject.name = this.name;
  548. serializationObject.comments = this.comments;
  549. serializationObject.inputs = [];
  550. for (var input of this.inputs) {
  551. serializationObject.inputs.push(input.serialize());
  552. }
  553. return serializationObject;
  554. }
  555. /** @hidden */
  556. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  557. this.name = serializationObject.name;
  558. this.comments = serializationObject.comments;
  559. }
  560. /**
  561. * Release resources
  562. */
  563. public dispose() {
  564. for (var input of this.inputs) {
  565. input.dispose();
  566. }
  567. for (var output of this.outputs) {
  568. output.dispose();
  569. }
  570. }
  571. }