nodeMaterial.ts 49 KB

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