nodeMaterialBlock.ts 27 KB

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