nodeMaterial.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. import { NodeMaterialBlock } from './nodeMaterialBlock';
  2. import { PushMaterial } from '../pushMaterial';
  3. import { Scene } from '../../scene';
  4. import { AbstractMesh } from '../../Meshes/abstractMesh';
  5. import { Matrix } from '../../Maths/math.vector';
  6. import { Color4 } from '../../Maths/math.color';
  7. import { Mesh } from '../../Meshes/mesh';
  8. import { Engine } from '../../Engines/engine';
  9. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  10. import { IEffectCreationOptions } from '../effect';
  11. import { BaseTexture } from '../../Materials/Textures/baseTexture';
  12. import { Observable, Observer } from '../../Misc/observable';
  13. import { NodeMaterialBlockTargets } from './Enums/nodeMaterialBlockTargets';
  14. import { NodeMaterialBuildStateSharedData } from './nodeMaterialBuildStateSharedData';
  15. import { SubMesh } from '../../Meshes/subMesh';
  16. import { MaterialDefines } from '../../Materials/materialDefines';
  17. import { NodeMaterialOptimizer } from './Optimizers/nodeMaterialOptimizer';
  18. import { ImageProcessingConfiguration, IImageProcessingConfigurationDefines } from '../imageProcessingConfiguration';
  19. import { Nullable } from '../../types';
  20. import { VertexBuffer } from '../../Meshes/buffer';
  21. import { Tools } from '../../Misc/tools';
  22. import { TransformBlock } from './Blocks/transformBlock';
  23. import { VertexOutputBlock } from './Blocks/Vertex/vertexOutputBlock';
  24. import { FragmentOutputBlock } from './Blocks/Fragment/fragmentOutputBlock';
  25. import { InputBlock } from './Blocks/Input/inputBlock';
  26. import { _TypeStore } from '../../Misc/typeStore';
  27. import { SerializationHelper } from '../../Misc/decorators';
  28. import { TextureBlock } from './Blocks/Dual/textureBlock';
  29. import { ReflectionTextureBlock } from './Blocks/Dual/reflectionTextureBlock';
  30. import { EffectFallbacks } from '../effectFallbacks';
  31. import { WebRequest } from '../../Misc/webRequest';
  32. // declare NODEEDITOR namespace for compilation issue
  33. declare var NODEEDITOR: any;
  34. declare var BABYLON: any;
  35. /**
  36. * Interface used to configure the node material editor
  37. */
  38. export interface INodeMaterialEditorOptions {
  39. /** Define the URl to load node editor script */
  40. editorURL?: string;
  41. }
  42. /** @hidden */
  43. export class NodeMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
  44. public NORMAL = false;
  45. public TANGENT = false;
  46. public UV1 = false;
  47. /** BONES */
  48. public NUM_BONE_INFLUENCERS = 0;
  49. public BonesPerMesh = 0;
  50. public BONETEXTURE = false;
  51. /** MORPH TARGETS */
  52. public MORPHTARGETS = false;
  53. public MORPHTARGETS_NORMAL = false;
  54. public MORPHTARGETS_TANGENT = false;
  55. public MORPHTARGETS_UV = false;
  56. public NUM_MORPH_INFLUENCERS = 0;
  57. /** IMAGE PROCESSING */
  58. public IMAGEPROCESSING = false;
  59. public VIGNETTE = false;
  60. public VIGNETTEBLENDMODEMULTIPLY = false;
  61. public VIGNETTEBLENDMODEOPAQUE = false;
  62. public TONEMAPPING = false;
  63. public TONEMAPPING_ACES = false;
  64. public CONTRAST = false;
  65. public EXPOSURE = false;
  66. public COLORCURVES = false;
  67. public COLORGRADING = false;
  68. public COLORGRADING3D = false;
  69. public SAMPLER3DGREENDEPTH = false;
  70. public SAMPLER3DBGRMAP = false;
  71. public IMAGEPROCESSINGPOSTPROCESS = false;
  72. /** MISC. */
  73. public BUMPDIRECTUV = 0;
  74. constructor() {
  75. super();
  76. this.rebuild();
  77. }
  78. public setValue(name: string, value: boolean) {
  79. if (this[name] === undefined) {
  80. this._keys.push(name);
  81. }
  82. this[name] = value;
  83. }
  84. }
  85. /**
  86. * Class used to configure NodeMaterial
  87. */
  88. export interface INodeMaterialOptions {
  89. /**
  90. * Defines if blocks should emit comments
  91. */
  92. emitComments: boolean;
  93. }
  94. /**
  95. * Class used to create a node based material built by assembling shader blocks
  96. */
  97. export class NodeMaterial extends PushMaterial {
  98. private static _BuildIdGenerator: number = 0;
  99. private _options: INodeMaterialOptions;
  100. private _vertexCompilationState: NodeMaterialBuildState;
  101. private _fragmentCompilationState: NodeMaterialBuildState;
  102. private _sharedData: NodeMaterialBuildStateSharedData;
  103. private _buildId: number = NodeMaterial._BuildIdGenerator++;
  104. private _buildWasSuccessful = false;
  105. private _cachedWorldViewMatrix = new Matrix();
  106. private _cachedWorldViewProjectionMatrix = new Matrix();
  107. private _optimizers = new Array<NodeMaterialOptimizer>();
  108. private _animationFrame = -1;
  109. /** Define the Url to load node editor script */
  110. public static EditorURL = `https://unpkg.com/babylonjs-node-editor@${Engine.Version}/babylon.nodeEditor.js`;
  111. /** Define the Url to load snippets */
  112. public static SnippetUrl = "https://snippet.babylonjs.com";
  113. private BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();
  114. /** Get the inspector from bundle or global */
  115. private _getGlobalNodeMaterialEditor(): any {
  116. // UMD Global name detection from Webpack Bundle UMD Name.
  117. if (typeof NODEEDITOR !== 'undefined') {
  118. return NODEEDITOR;
  119. }
  120. // In case of module let's check the global emitted from the editor entry point.
  121. if (typeof BABYLON !== 'undefined' && typeof BABYLON.NodeEditor !== 'undefined') {
  122. return BABYLON;
  123. }
  124. return undefined;
  125. }
  126. /**
  127. * Gets or sets data used by visual editor
  128. * @see https://nme.babylonjs.com
  129. */
  130. public editorData: any = null;
  131. /**
  132. * Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material)
  133. */
  134. public ignoreAlpha = false;
  135. /**
  136. * Defines the maximum number of lights that can be used in the material
  137. */
  138. public maxSimultaneousLights = 4;
  139. /**
  140. * Observable raised when the material is built
  141. */
  142. public onBuildObservable = new Observable<NodeMaterial>();
  143. /**
  144. * Gets or sets the root nodes of the material vertex shader
  145. */
  146. public _vertexOutputNodes = new Array<NodeMaterialBlock>();
  147. /**
  148. * Gets or sets the root nodes of the material fragment (pixel) shader
  149. */
  150. public _fragmentOutputNodes = new Array<NodeMaterialBlock>();
  151. /** Gets or sets options to control the node material overall behavior */
  152. public get options() {
  153. return this._options;
  154. }
  155. public set options(options: INodeMaterialOptions) {
  156. this._options = options;
  157. }
  158. /**
  159. * Default configuration related to image processing available in the standard Material.
  160. */
  161. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  162. /**
  163. * Gets the image processing configuration used either in this material.
  164. */
  165. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  166. return this._imageProcessingConfiguration;
  167. }
  168. /**
  169. * Sets the Default image processing configuration used either in the this material.
  170. *
  171. * If sets to null, the scene one is in use.
  172. */
  173. public set imageProcessingConfiguration(value: ImageProcessingConfiguration) {
  174. this._attachImageProcessingConfiguration(value);
  175. // Ensure the effect will be rebuilt.
  176. this._markAllSubMeshesAsTexturesDirty();
  177. }
  178. /**
  179. * Gets an array of blocks that needs to be serialized even if they are not yet connected
  180. */
  181. public attachedBlocks = new Array<NodeMaterialBlock>();
  182. /**
  183. * Create a new node based material
  184. * @param name defines the material name
  185. * @param scene defines the hosting scene
  186. * @param options defines creation option
  187. */
  188. constructor(name: string, scene?: Scene, options: Partial<INodeMaterialOptions> = {}) {
  189. super(name, scene || Engine.LastCreatedScene!);
  190. this._options = {
  191. emitComments: false,
  192. ...options
  193. };
  194. // Setup the default processing configuration to the scene.
  195. this._attachImageProcessingConfiguration(null);
  196. }
  197. /**
  198. * Gets the current class name of the material e.g. "NodeMaterial"
  199. * @returns the class name
  200. */
  201. public getClassName(): string {
  202. return "NodeMaterial";
  203. }
  204. /**
  205. * Keep track of the image processing observer to allow dispose and replace.
  206. */
  207. private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>>;
  208. /**
  209. * Attaches a new image processing configuration to the Standard Material.
  210. * @param configuration
  211. */
  212. protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
  213. if (configuration === this._imageProcessingConfiguration) {
  214. return;
  215. }
  216. // Detaches observer.
  217. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  218. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  219. }
  220. // Pick the scene configuration if needed.
  221. if (!configuration) {
  222. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  223. }
  224. else {
  225. this._imageProcessingConfiguration = configuration;
  226. }
  227. // Attaches observer.
  228. if (this._imageProcessingConfiguration) {
  229. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
  230. this._markAllSubMeshesAsImageProcessingDirty();
  231. });
  232. }
  233. }
  234. /**
  235. * Get a block by its name
  236. * @param name defines the name of the block to retrieve
  237. * @returns the required block or null if not found
  238. */
  239. public getBlockByName(name: string) {
  240. for (var block of this.attachedBlocks) {
  241. if (block.name === name) {
  242. return block;
  243. }
  244. }
  245. return null;
  246. }
  247. /**
  248. * Get a block by its name
  249. * @param predicate defines the predicate used to find the good candidate
  250. * @returns the required block or null if not found
  251. */
  252. public getBlockByPredicate(predicate: (block: NodeMaterialBlock) => boolean) {
  253. for (var block of this.attachedBlocks) {
  254. if (predicate(block)) {
  255. return block;
  256. }
  257. }
  258. return null;
  259. }
  260. /**
  261. * Get an input block by its name
  262. * @param predicate defines the predicate used to find the good candidate
  263. * @returns the required input block or null if not found
  264. */
  265. public getInputBlockByPredicate(predicate: (block: InputBlock) => boolean): Nullable<InputBlock> {
  266. for (var block of this.attachedBlocks) {
  267. if (block.isInput && predicate(block as InputBlock)) {
  268. return block as InputBlock;
  269. }
  270. }
  271. return null;
  272. }
  273. /**
  274. * Gets the list of input blocks attached to this material
  275. * @returns an array of InputBlocks
  276. */
  277. public getInputBlocks() {
  278. let blocks: InputBlock[] = [];
  279. for (var block of this.attachedBlocks) {
  280. if (block.isInput) {
  281. blocks.push(block as InputBlock);
  282. }
  283. }
  284. return blocks;
  285. }
  286. /**
  287. * Adds a new optimizer to the list of optimizers
  288. * @param optimizer defines the optimizers to add
  289. * @returns the current material
  290. */
  291. public registerOptimizer(optimizer: NodeMaterialOptimizer) {
  292. let index = this._optimizers.indexOf(optimizer);
  293. if (index > -1) {
  294. return;
  295. }
  296. this._optimizers.push(optimizer);
  297. return this;
  298. }
  299. /**
  300. * Remove an optimizer from the list of optimizers
  301. * @param optimizer defines the optimizers to remove
  302. * @returns the current material
  303. */
  304. public unregisterOptimizer(optimizer: NodeMaterialOptimizer) {
  305. let index = this._optimizers.indexOf(optimizer);
  306. if (index === -1) {
  307. return;
  308. }
  309. this._optimizers.splice(index, 1);
  310. return this;
  311. }
  312. /**
  313. * Add a new block to the list of output nodes
  314. * @param node defines the node to add
  315. * @returns the current material
  316. */
  317. public addOutputNode(node: NodeMaterialBlock) {
  318. if (node.target === null) {
  319. throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
  320. }
  321. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  322. this._addVertexOutputNode(node);
  323. }
  324. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  325. this._addFragmentOutputNode(node);
  326. }
  327. return this;
  328. }
  329. /**
  330. * Remove a block from the list of root nodes
  331. * @param node defines the node to remove
  332. * @returns the current material
  333. */
  334. public removeOutputNode(node: NodeMaterialBlock) {
  335. if (node.target === null) {
  336. return this;
  337. }
  338. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  339. this._removeVertexOutputNode(node);
  340. }
  341. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  342. this._removeFragmentOutputNode(node);
  343. }
  344. return this;
  345. }
  346. private _addVertexOutputNode(node: NodeMaterialBlock) {
  347. if (this._vertexOutputNodes.indexOf(node) !== -1) {
  348. return;
  349. }
  350. node.target = NodeMaterialBlockTargets.Vertex;
  351. this._vertexOutputNodes.push(node);
  352. return this;
  353. }
  354. private _removeVertexOutputNode(node: NodeMaterialBlock) {
  355. let index = this._vertexOutputNodes.indexOf(node);
  356. if (index === -1) {
  357. return;
  358. }
  359. this._vertexOutputNodes.splice(index, 1);
  360. return this;
  361. }
  362. private _addFragmentOutputNode(node: NodeMaterialBlock) {
  363. if (this._fragmentOutputNodes.indexOf(node) !== -1) {
  364. return;
  365. }
  366. node.target = NodeMaterialBlockTargets.Fragment;
  367. this._fragmentOutputNodes.push(node);
  368. return this;
  369. }
  370. private _removeFragmentOutputNode(node: NodeMaterialBlock) {
  371. let index = this._fragmentOutputNodes.indexOf(node);
  372. if (index === -1) {
  373. return;
  374. }
  375. this._fragmentOutputNodes.splice(index, 1);
  376. return this;
  377. }
  378. /**
  379. * Specifies if the material will require alpha blending
  380. * @returns a boolean specifying if alpha blending is needed
  381. */
  382. public needAlphaBlending(): boolean {
  383. if (this.ignoreAlpha) {
  384. return false;
  385. }
  386. return (this.alpha < 1.0) || (this._sharedData && this._sharedData.hints.needAlphaBlending);
  387. }
  388. /**
  389. * Specifies if this material should be rendered in alpha test mode
  390. * @returns a boolean specifying if an alpha test is needed.
  391. */
  392. public needAlphaTesting(): boolean {
  393. return this._sharedData && this._sharedData.hints.needAlphaTesting;
  394. }
  395. private _initializeBlock(node: NodeMaterialBlock, state: NodeMaterialBuildState, nodesToProcessForOtherBuildState: NodeMaterialBlock[]) {
  396. node.initialize(state);
  397. node.autoConfigure(this);
  398. node._preparationId = this._buildId;
  399. if (this.attachedBlocks.indexOf(node) === -1) {
  400. if (node.isUnique) {
  401. const className = node.getClassName();
  402. for (var other of this.attachedBlocks) {
  403. if (other.getClassName() === className) {
  404. throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`;
  405. }
  406. }
  407. }
  408. this.attachedBlocks.push(node);
  409. }
  410. for (var input of node.inputs) {
  411. input.associatedVariableName = "";
  412. let connectedPoint = input.connectedPoint;
  413. if (connectedPoint) {
  414. let block = connectedPoint.ownerBlock;
  415. if (block !== node) {
  416. if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {
  417. nodesToProcessForOtherBuildState.push(block);
  418. } else if (state.target === NodeMaterialBlockTargets.Fragment
  419. && block.target === NodeMaterialBlockTargets.Vertex
  420. && block._preparationId !== this._buildId) {
  421. nodesToProcessForOtherBuildState.push(block);
  422. }
  423. this._initializeBlock(block, state, nodesToProcessForOtherBuildState);
  424. }
  425. }
  426. }
  427. for (var output of node.outputs) {
  428. output.associatedVariableName = "";
  429. }
  430. }
  431. private _resetDualBlocks(node: NodeMaterialBlock, id: number) {
  432. if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {
  433. node.buildId = id;
  434. }
  435. for (var inputs of node.inputs) {
  436. let connectedPoint = inputs.connectedPoint;
  437. if (connectedPoint) {
  438. let block = connectedPoint.ownerBlock;
  439. if (block !== node) {
  440. this._resetDualBlocks(block, id);
  441. }
  442. }
  443. }
  444. }
  445. /**
  446. * Remove a block from the current node material
  447. * @param block defines the block to remove
  448. */
  449. public removeBlock(block: NodeMaterialBlock) {
  450. let attachedBlockIndex = this.attachedBlocks.indexOf(block);
  451. if (attachedBlockIndex > -1) {
  452. this.attachedBlocks.splice(attachedBlockIndex, 1);
  453. }
  454. if (block.isFinalMerger) {
  455. this.removeOutputNode(block);
  456. }
  457. }
  458. /**
  459. * Build the material and generates the inner effect
  460. * @param verbose defines if the build should log activity
  461. */
  462. public build(verbose: boolean = false) {
  463. this._buildWasSuccessful = false;
  464. var engine = this.getScene().getEngine();
  465. if (this._vertexOutputNodes.length === 0) {
  466. throw "You must define at least one vertexOutputNode";
  467. }
  468. if (this._fragmentOutputNodes.length === 0) {
  469. throw "You must define at least one fragmentOutputNode";
  470. }
  471. // Compilation state
  472. this._vertexCompilationState = new NodeMaterialBuildState();
  473. this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  474. this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;
  475. this._fragmentCompilationState = new NodeMaterialBuildState();
  476. this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  477. this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;
  478. // Shared data
  479. this._sharedData = new NodeMaterialBuildStateSharedData();
  480. this._vertexCompilationState.sharedData = this._sharedData;
  481. this._fragmentCompilationState.sharedData = this._sharedData;
  482. this._sharedData.buildId = this._buildId;
  483. this._sharedData.emitComments = this._options.emitComments;
  484. this._sharedData.verbose = verbose;
  485. this._sharedData.scene = this.getScene();
  486. // Initialize blocks
  487. let vertexNodes: NodeMaterialBlock[] = [];
  488. let fragmentNodes: NodeMaterialBlock[] = [];
  489. for (var vertexOutputNode of this._vertexOutputNodes) {
  490. vertexNodes.push(vertexOutputNode);
  491. this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes);
  492. }
  493. for (var fragmentOutputNode of this._fragmentOutputNodes) {
  494. fragmentNodes.push(fragmentOutputNode);
  495. this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes);
  496. }
  497. // Optimize
  498. this.optimize();
  499. // Vertex
  500. for (var vertexOutputNode of vertexNodes) {
  501. vertexOutputNode.build(this._vertexCompilationState, vertexNodes);
  502. }
  503. // Fragment
  504. this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);
  505. this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;
  506. this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;
  507. this._fragmentCompilationState._vertexState = this._vertexCompilationState;
  508. for (var fragmentOutputNode of fragmentNodes) {
  509. this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);
  510. }
  511. for (var fragmentOutputNode of fragmentNodes) {
  512. fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);
  513. }
  514. // Finalize
  515. this._vertexCompilationState.finalize(this._vertexCompilationState);
  516. this._fragmentCompilationState.finalize(this._fragmentCompilationState);
  517. this._buildId = NodeMaterial._BuildIdGenerator++;
  518. // Errors
  519. this._sharedData.emitErrors();
  520. if (verbose) {
  521. console.log("Vertex shader:");
  522. console.log(this._vertexCompilationState.compilationString);
  523. console.log("Fragment shader:");
  524. console.log(this._fragmentCompilationState.compilationString);
  525. }
  526. this._buildWasSuccessful = true;
  527. this.onBuildObservable.notifyObservers(this);
  528. // Wipe defines
  529. const meshes = this.getScene().meshes;
  530. for (var mesh of meshes) {
  531. if (!mesh.subMeshes) {
  532. continue;
  533. }
  534. for (var subMesh of mesh.subMeshes) {
  535. if (subMesh.getMaterial() !== this) {
  536. continue;
  537. }
  538. if (!subMesh._materialDefines) {
  539. continue;
  540. }
  541. let defines = subMesh._materialDefines;
  542. defines.markAllAsDirty();
  543. defines.reset();
  544. }
  545. }
  546. }
  547. /**
  548. * Runs an otpimization phase to try to improve the shader code
  549. */
  550. public optimize() {
  551. for (var optimizer of this._optimizers) {
  552. optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);
  553. }
  554. }
  555. private _prepareDefinesForAttributes(mesh: AbstractMesh, defines: NodeMaterialDefines) {
  556. let oldNormal = defines["NORMAL"];
  557. let oldTangent = defines["TANGENT"];
  558. let oldUV1 = defines["UV1"];
  559. defines["NORMAL"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);
  560. defines["TANGENT"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);
  561. defines["UV1"] = mesh.isVerticesDataPresent(VertexBuffer.UVKind);
  562. if (oldNormal !== defines["NORMAL"] || oldTangent !== defines["TANGENT"] || oldUV1 !== defines["UV1"]) {
  563. defines.markAsAttributesDirty();
  564. }
  565. }
  566. /**
  567. * Get if the submesh is ready to be used and all its information available.
  568. * Child classes can use it to update shaders
  569. * @param mesh defines the mesh to check
  570. * @param subMesh defines which submesh to check
  571. * @param useInstances specifies that instances should be used
  572. * @returns a boolean indicating that the submesh is ready or not
  573. */
  574. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances: boolean = false): boolean {
  575. if (!this._buildWasSuccessful) {
  576. return false;
  577. }
  578. var scene = this.getScene();
  579. if (this._sharedData.animatedInputs) {
  580. let frameId = scene.getFrameId();
  581. if (this._animationFrame !== frameId) {
  582. for (var input of this._sharedData.animatedInputs) {
  583. input.animate(scene);
  584. }
  585. this._animationFrame = frameId;
  586. }
  587. }
  588. if (subMesh.effect && this.isFrozen) {
  589. if (subMesh.effect._wasPreviouslyReady) {
  590. return true;
  591. }
  592. }
  593. if (!subMesh._materialDefines) {
  594. subMesh._materialDefines = new NodeMaterialDefines();
  595. }
  596. var defines = <NodeMaterialDefines>subMesh._materialDefines;
  597. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  598. if (defines._renderId === scene.getRenderId()) {
  599. return true;
  600. }
  601. }
  602. var engine = scene.getEngine();
  603. this._prepareDefinesForAttributes(mesh, defines);
  604. // Check if blocks are ready
  605. if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {
  606. return false;
  607. }
  608. // Shared defines
  609. this._sharedData.blocksWithDefines.forEach((b) => {
  610. b.initializeDefines(mesh, this, defines, useInstances);
  611. });
  612. this._sharedData.blocksWithDefines.forEach((b) => {
  613. b.prepareDefines(mesh, this, defines, useInstances);
  614. });
  615. // Need to recompile?
  616. if (defines.isDirty) {
  617. defines.markAsProcessed();
  618. // Repeatable content generators
  619. this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
  620. this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
  621. this._sharedData.repeatableContentBlocks.forEach((b) => {
  622. b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);
  623. });
  624. // Uniforms
  625. let uniformBuffers: string[] = [];
  626. this._sharedData.dynamicUniformBlocks.forEach((b) => {
  627. b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);
  628. });
  629. let mergedUniforms = this._vertexCompilationState.uniforms;
  630. this._fragmentCompilationState.uniforms.forEach((u) => {
  631. let index = mergedUniforms.indexOf(u);
  632. if (index === -1) {
  633. mergedUniforms.push(u);
  634. }
  635. });
  636. // Samplers
  637. let mergedSamplers = this._vertexCompilationState.samplers;
  638. this._fragmentCompilationState.samplers.forEach((s) => {
  639. let index = mergedSamplers.indexOf(s);
  640. if (index === -1) {
  641. mergedSamplers.push(s);
  642. }
  643. });
  644. var fallbacks = new EffectFallbacks();
  645. this._sharedData.blocksWithFallbacks.forEach((b) => {
  646. b.provideFallbacks(mesh, fallbacks);
  647. });
  648. let previousEffect = subMesh.effect;
  649. // Compilation
  650. var join = defines.toString();
  651. var effect = engine.createEffect({
  652. vertex: "nodeMaterial" + this._buildId,
  653. fragment: "nodeMaterial" + this._buildId,
  654. vertexSource: this._vertexCompilationState.compilationString,
  655. fragmentSource: this._fragmentCompilationState.compilationString
  656. }, <IEffectCreationOptions>{
  657. attributes: this._vertexCompilationState.attributes,
  658. uniformsNames: mergedUniforms,
  659. uniformBuffersNames: uniformBuffers,
  660. samplers: mergedSamplers,
  661. defines: join,
  662. fallbacks: fallbacks,
  663. onCompiled: this.onCompiled,
  664. onError: this.onError,
  665. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  666. }, engine);
  667. if (effect) {
  668. // Use previous effect while new one is compiling
  669. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  670. effect = previousEffect;
  671. defines.markAsUnprocessed();
  672. } else {
  673. scene.resetCachedMaterial();
  674. subMesh.setEffect(effect, defines);
  675. }
  676. }
  677. }
  678. if (!subMesh.effect || !subMesh.effect.isReady()) {
  679. return false;
  680. }
  681. defines._renderId = scene.getRenderId();
  682. subMesh.effect._wasPreviouslyReady = true;
  683. return true;
  684. }
  685. /**
  686. * Get a string representing the shaders built by the current node graph
  687. */
  688. public get compiledShaders() {
  689. return `// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`;
  690. }
  691. /**
  692. * Binds the world matrix to the material
  693. * @param world defines the world transformation matrix
  694. */
  695. public bindOnlyWorldMatrix(world: Matrix): void {
  696. var scene = this.getScene();
  697. if (!this._activeEffect) {
  698. return;
  699. }
  700. let hints = this._sharedData.hints;
  701. if (hints.needWorldViewMatrix) {
  702. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  703. }
  704. if (hints.needWorldViewProjectionMatrix) {
  705. world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
  706. }
  707. // Connection points
  708. for (var inputBlock of this._sharedData.inputBlocks) {
  709. inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
  710. }
  711. }
  712. /**
  713. * Binds the submesh to this material by preparing the effect and shader to draw
  714. * @param world defines the world transformation matrix
  715. * @param mesh defines the mesh containing the submesh
  716. * @param subMesh defines the submesh to bind the material to
  717. */
  718. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  719. let scene = this.getScene();
  720. var effect = subMesh.effect;
  721. if (!effect) {
  722. return;
  723. }
  724. this._activeEffect = effect;
  725. // Matrices
  726. this.bindOnlyWorldMatrix(world);
  727. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  728. if (mustRebind) {
  729. let sharedData = this._sharedData;
  730. if (effect && scene.getCachedEffect() !== effect) {
  731. // Bindable blocks
  732. for (var block of sharedData.bindableBlocks) {
  733. block.bind(effect, this, mesh);
  734. }
  735. // Connection points
  736. for (var inputBlock of sharedData.inputBlocks) {
  737. inputBlock._transmit(effect, scene);
  738. }
  739. }
  740. }
  741. this._afterBind(mesh, this._activeEffect);
  742. }
  743. /**
  744. * Gets the active textures from the material
  745. * @returns an array of textures
  746. */
  747. public getActiveTextures(): BaseTexture[] {
  748. var activeTextures = super.getActiveTextures();
  749. if (this._sharedData) {
  750. activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!));
  751. }
  752. return activeTextures;
  753. }
  754. /**
  755. * Gets the list of texture blocks
  756. * @returns an array of texture blocks
  757. */
  758. public getTextureBlocks(): (TextureBlock | ReflectionTextureBlock)[] {
  759. if (!this._sharedData) {
  760. return [];
  761. }
  762. return this._sharedData.textureBlocks;
  763. }
  764. /**
  765. * Specifies if the material uses a texture
  766. * @param texture defines the texture to check against the material
  767. * @returns a boolean specifying if the material uses the texture
  768. */
  769. public hasTexture(texture: BaseTexture): boolean {
  770. if (super.hasTexture(texture)) {
  771. return true;
  772. }
  773. if (!this._sharedData) {
  774. return false;
  775. }
  776. for (var t of this._sharedData.textureBlocks) {
  777. if (t.texture === texture) {
  778. return true;
  779. }
  780. }
  781. return false;
  782. }
  783. /**
  784. * Disposes the material
  785. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  786. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  787. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  788. */
  789. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  790. if (forceDisposeTextures) {
  791. for (var texture of this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!)) {
  792. texture.dispose();
  793. }
  794. }
  795. for (var block of this.attachedBlocks) {
  796. block.dispose();
  797. }
  798. this.onBuildObservable.clear();
  799. super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  800. }
  801. /** Creates the node editor window. */
  802. private _createNodeEditor() {
  803. this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
  804. this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
  805. nodeMaterial: this
  806. });
  807. }
  808. /**
  809. * Launch the node material editor
  810. * @param config Define the configuration of the editor
  811. * @return a promise fulfilled when the node editor is visible
  812. */
  813. public edit(config?: INodeMaterialEditorOptions): Promise<void> {
  814. return new Promise((resolve, reject) => {
  815. if (typeof this.BJSNODEMATERIALEDITOR == 'undefined') {
  816. const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
  817. // Load editor and add it to the DOM
  818. Tools.LoadScript(editorUrl, () => {
  819. this._createNodeEditor();
  820. resolve();
  821. });
  822. } else {
  823. // Otherwise creates the editor
  824. this._createNodeEditor();
  825. resolve();
  826. }
  827. });
  828. }
  829. /**
  830. * Clear the current material
  831. */
  832. public clear() {
  833. this._vertexOutputNodes = [];
  834. this._fragmentOutputNodes = [];
  835. this.attachedBlocks = [];
  836. }
  837. /**
  838. * Clear the current material and set it to a default state
  839. */
  840. public setToDefault() {
  841. this.clear();
  842. this.editorData = null;
  843. var positionInput = new InputBlock("Position");
  844. positionInput.setAsAttribute("position");
  845. var worldInput = new InputBlock("World");
  846. worldInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);
  847. var worldPos = new TransformBlock("WorldPos");
  848. positionInput.connectTo(worldPos);
  849. worldInput.connectTo(worldPos);
  850. var viewProjectionInput = new InputBlock("ViewProjection");
  851. viewProjectionInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.ViewProjection);
  852. var worldPosdMultipliedByViewProjection = new TransformBlock("WorldPos * ViewProjectionTransform");
  853. worldPos.connectTo(worldPosdMultipliedByViewProjection);
  854. viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
  855. var vertexOutput = new VertexOutputBlock("VertexOutput");
  856. worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
  857. // Pixel
  858. var pixelColor = new InputBlock("color");
  859. pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);
  860. var fragmentOutput = new FragmentOutputBlock("FragmentOutput");
  861. pixelColor.connectTo(fragmentOutput);
  862. // Add to nodes
  863. this.addOutputNode(vertexOutput);
  864. this.addOutputNode(fragmentOutput);
  865. }
  866. /**
  867. * Loads the current Node Material from a url pointing to a file save by the Node Material Editor
  868. * @param url defines the url to load from
  869. * @returns a promise that will fullfil when the material is fully loaded
  870. */
  871. public loadAsync(url: string) {
  872. return this.getScene()._loadFileAsync(url).then((data) => {
  873. const serializationObject = JSON.parse(data as string);
  874. this.loadFromSerialization(serializationObject, "");
  875. });
  876. }
  877. private _gatherBlocks(rootNode: NodeMaterialBlock, list: NodeMaterialBlock[]) {
  878. if (list.indexOf(rootNode) !== -1) {
  879. return;
  880. }
  881. list.push(rootNode);
  882. for (var input of rootNode.inputs) {
  883. let connectedPoint = input.connectedPoint;
  884. if (connectedPoint) {
  885. let block = connectedPoint.ownerBlock;
  886. if (block !== rootNode) {
  887. this._gatherBlocks(block, list);
  888. }
  889. }
  890. }
  891. }
  892. /**
  893. * Generate a string containing the code declaration required to create an equivalent of this material
  894. * @returns a string
  895. */
  896. public generateCode() {
  897. let alreadyDumped: NodeMaterialBlock[] = [];
  898. let vertexBlocks: NodeMaterialBlock[] = [];
  899. let uniqueNames: string[] = [];
  900. // Gets active blocks
  901. for (var outputNode of this._vertexOutputNodes) {
  902. this._gatherBlocks(outputNode, vertexBlocks);
  903. }
  904. let fragmentBlocks: NodeMaterialBlock[] = [];
  905. for (var outputNode of this._fragmentOutputNodes) {
  906. this._gatherBlocks(outputNode, fragmentBlocks);
  907. }
  908. // Generate vertex shader
  909. let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");\r\n`;
  910. for (var node of vertexBlocks) {
  911. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  912. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  913. }
  914. }
  915. // Generate fragment shader
  916. for (var node of fragmentBlocks) {
  917. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  918. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  919. }
  920. }
  921. // Connections
  922. alreadyDumped = [];
  923. codeString += "\r\n// Connections\r\n";
  924. for (var node of this._vertexOutputNodes) {
  925. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  926. }
  927. for (var node of this._fragmentOutputNodes) {
  928. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  929. }
  930. // Output nodes
  931. codeString += "\r\n// Output nodes\r\n";
  932. for (var node of this._vertexOutputNodes) {
  933. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  934. }
  935. for (var node of this._fragmentOutputNodes) {
  936. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  937. }
  938. codeString += `nodeMaterial.build();\r\n`;
  939. return codeString;
  940. }
  941. /**
  942. * Serializes this material in a JSON representation
  943. * @returns the serialized material object
  944. */
  945. public serialize(selectedBlocks?: NodeMaterialBlock[]): any {
  946. var serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
  947. serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy
  948. let blocks: NodeMaterialBlock[] = [];
  949. if (selectedBlocks) {
  950. blocks = selectedBlocks;
  951. } else {
  952. serializationObject.customType = "BABYLON.NodeMaterial";
  953. serializationObject.outputNodes = [];
  954. // Outputs
  955. for (var outputNode of this._vertexOutputNodes) {
  956. this._gatherBlocks(outputNode, blocks);
  957. serializationObject.outputNodes.push(outputNode.uniqueId);
  958. }
  959. for (var outputNode of this._fragmentOutputNodes) {
  960. this._gatherBlocks(outputNode, blocks);
  961. if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {
  962. serializationObject.outputNodes.push(outputNode.uniqueId);
  963. }
  964. }
  965. }
  966. // Blocks
  967. serializationObject.blocks = [];
  968. for (var block of blocks) {
  969. serializationObject.blocks.push(block.serialize());
  970. }
  971. if (!selectedBlocks) {
  972. for (var block of this.attachedBlocks) {
  973. if (blocks.indexOf(block) !== -1) {
  974. continue;
  975. }
  976. serializationObject.blocks.push(block.serialize());
  977. }
  978. }
  979. return serializationObject;
  980. }
  981. private _restoreConnections(block: NodeMaterialBlock, source: any, map: {[key: number]: NodeMaterialBlock}) {
  982. for (var outputPoint of block.outputs) {
  983. for (var candidate of source.blocks) {
  984. let target = map[candidate.id];
  985. for (var input of candidate.inputs) {
  986. if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
  987. let inputPoint = target.getInputByName(input.inputName);
  988. if (!inputPoint || inputPoint.isConnected) {
  989. continue;
  990. }
  991. outputPoint.connectTo(inputPoint, true);
  992. this._restoreConnections(target, source, map);
  993. continue;
  994. }
  995. }
  996. }
  997. }
  998. }
  999. /**
  1000. * Clear the current graph and load a new one from a serialization object
  1001. * @param source defines the JSON representation of the material
  1002. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1003. */
  1004. public loadFromSerialization(source: any, rootUrl: string = "") {
  1005. this.clear();
  1006. let map: {[key: number]: NodeMaterialBlock} = {};
  1007. // Create blocks
  1008. for (var parsedBlock of source.blocks) {
  1009. let blockType = _TypeStore.GetClass(parsedBlock.customType);
  1010. if (blockType) {
  1011. let block: NodeMaterialBlock = new blockType();
  1012. block._deserialize(parsedBlock, this.getScene(), rootUrl);
  1013. map[parsedBlock.id] = block;
  1014. this.attachedBlocks.push(block);
  1015. }
  1016. }
  1017. // Connections
  1018. // Starts with input blocks only
  1019. for (var blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
  1020. let parsedBlock = source.blocks[blockIndex];
  1021. let block = map[parsedBlock.id];
  1022. if (block.inputs.length) {
  1023. continue;
  1024. }
  1025. this._restoreConnections(block, source, map);
  1026. }
  1027. // Outputs
  1028. for (var outputNodeId of source.outputNodes) {
  1029. this.addOutputNode(map[outputNodeId]);
  1030. }
  1031. // UI related info
  1032. if (source.locations || source.editorData && source.editorData.locations) {
  1033. let locations: {
  1034. blockId: number;
  1035. x: number;
  1036. y: number;
  1037. }[] = source.locations || source.editorData.locations;
  1038. for (var location of locations) {
  1039. if (map[location.blockId]) {
  1040. location.blockId = map[location.blockId].uniqueId;
  1041. }
  1042. }
  1043. if (source.locations) {
  1044. this.editorData = {
  1045. locations: locations
  1046. };
  1047. } else {
  1048. this.editorData = source.editorData;
  1049. this.editorData.locations = locations;
  1050. }
  1051. let blockMap: number[] = [];
  1052. for (var key in map) {
  1053. blockMap[key] = map[key].uniqueId;
  1054. }
  1055. this.editorData.map = blockMap;
  1056. }
  1057. }
  1058. /**
  1059. * Makes a duplicate of the current material.
  1060. * @param name - name to use for the new material.
  1061. */
  1062. public clone(name: string): NodeMaterial {
  1063. const serializationObject = this.serialize();
  1064. const clone = SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this);
  1065. clone.id = name;
  1066. clone.name = name;
  1067. clone.loadFromSerialization(serializationObject);
  1068. clone.build();
  1069. return clone;
  1070. }
  1071. /**
  1072. * Creates a node material from parsed material data
  1073. * @param source defines the JSON representation of the material
  1074. * @param scene defines the hosting scene
  1075. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1076. * @returns a new node material
  1077. */
  1078. public static Parse(source: any, scene: Scene, rootUrl: string = ""): NodeMaterial {
  1079. let nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);
  1080. nodeMaterial.loadFromSerialization(source, rootUrl);
  1081. nodeMaterial.build();
  1082. return nodeMaterial;
  1083. }
  1084. /**
  1085. * Creates a node material from a snippet saved in a remote file
  1086. * @param name defines the name of the material to create
  1087. * @param url defines the url to load from
  1088. * @param scene defines the hosting scene
  1089. * @returns a promise that will resolve to the new node material
  1090. */
  1091. public static ParseFromFileAsync(name: string, url: string, scene: Scene): Promise<NodeMaterial> {
  1092. var material = new NodeMaterial(name, scene);
  1093. return new Promise((resolve, reject) => {
  1094. return material.loadAsync(url).then(() => resolve(material)).catch(reject);
  1095. });
  1096. }
  1097. /**
  1098. * Creates a node material from a snippet saved by the node material editor
  1099. * @param snippetId defines the snippet to load
  1100. * @param scene defines the hosting scene
  1101. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1102. * @returns a promise that will resolve to the new node material
  1103. */
  1104. public static ParseFromSnippetAsync(snippetId: string, scene: Scene, rootUrl: string = ""): Promise<NodeMaterial> {
  1105. return new Promise((resolve, reject) => {
  1106. var request = new WebRequest();
  1107. request.addEventListener("readystatechange", () => {
  1108. if (request.readyState == 4) {
  1109. if (request.status == 200) {
  1110. var snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
  1111. let serializationObject = JSON.parse(snippet.nodeMaterial);
  1112. let nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene), serializationObject, scene, rootUrl);
  1113. nodeMaterial.loadFromSerialization(serializationObject);
  1114. try {
  1115. nodeMaterial.build(true);
  1116. resolve(nodeMaterial);
  1117. } catch (err) {
  1118. reject(err);
  1119. }
  1120. } else {
  1121. reject("Unable to load the snippet " + snippetId);
  1122. }
  1123. }
  1124. });
  1125. request.open("GET", this.SnippetUrl + "/" + snippetId.replace("#", "/"));
  1126. request.send();
  1127. });
  1128. }
  1129. /**
  1130. * Creates a new node material set to default basic configuration
  1131. * @param name defines the name of the material
  1132. * @param scene defines the hosting scene
  1133. * @returns a new NodeMaterial
  1134. */
  1135. public static CreateDefault(name: string, scene?: Scene) {
  1136. let newMaterial = new NodeMaterial(name, scene);
  1137. newMaterial.setToDefault();
  1138. newMaterial.build();
  1139. return newMaterial;
  1140. }
  1141. }
  1142. _TypeStore.RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;