nodeMaterial.ts 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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. const lightDisposed = defines._areLightsDisposed;
  630. defines.markAsProcessed();
  631. // Repeatable content generators
  632. this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
  633. this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
  634. this._sharedData.repeatableContentBlocks.forEach((b) => {
  635. b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);
  636. });
  637. // Uniforms
  638. let uniformBuffers: string[] = [];
  639. this._sharedData.dynamicUniformBlocks.forEach((b) => {
  640. b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);
  641. });
  642. let mergedUniforms = this._vertexCompilationState.uniforms;
  643. this._fragmentCompilationState.uniforms.forEach((u) => {
  644. let index = mergedUniforms.indexOf(u);
  645. if (index === -1) {
  646. mergedUniforms.push(u);
  647. }
  648. });
  649. // Samplers
  650. let mergedSamplers = this._vertexCompilationState.samplers;
  651. this._fragmentCompilationState.samplers.forEach((s) => {
  652. let index = mergedSamplers.indexOf(s);
  653. if (index === -1) {
  654. mergedSamplers.push(s);
  655. }
  656. });
  657. var fallbacks = new EffectFallbacks();
  658. this._sharedData.blocksWithFallbacks.forEach((b) => {
  659. b.provideFallbacks(mesh, fallbacks);
  660. });
  661. let previousEffect = subMesh.effect;
  662. // Compilation
  663. var join = defines.toString();
  664. var effect = engine.createEffect({
  665. vertex: "nodeMaterial" + this._buildId,
  666. fragment: "nodeMaterial" + this._buildId,
  667. vertexSource: this._vertexCompilationState.compilationString,
  668. fragmentSource: this._fragmentCompilationState.compilationString
  669. }, <IEffectCreationOptions>{
  670. attributes: this._vertexCompilationState.attributes,
  671. uniformsNames: mergedUniforms,
  672. uniformBuffersNames: uniformBuffers,
  673. samplers: mergedSamplers,
  674. defines: join,
  675. fallbacks: fallbacks,
  676. onCompiled: this.onCompiled,
  677. onError: this.onError,
  678. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  679. }, engine);
  680. if (effect) {
  681. if (this._onEffectCreatedObservable) {
  682. onCreatedEffectParameters.effect = effect;
  683. onCreatedEffectParameters.subMesh = subMesh;
  684. this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
  685. }
  686. // Use previous effect while new one is compiling
  687. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  688. effect = previousEffect;
  689. defines.markAsUnprocessed();
  690. if (lightDisposed) {
  691. // re register in case it takes more than one frame.
  692. defines._areLightsDisposed = true;
  693. return false;
  694. }
  695. } else {
  696. scene.resetCachedMaterial();
  697. subMesh.setEffect(effect, defines);
  698. }
  699. }
  700. }
  701. if (!subMesh.effect || !subMesh.effect.isReady()) {
  702. return false;
  703. }
  704. defines._renderId = scene.getRenderId();
  705. subMesh.effect._wasPreviouslyReady = true;
  706. return true;
  707. }
  708. /**
  709. * Get a string representing the shaders built by the current node graph
  710. */
  711. public get compiledShaders() {
  712. return `// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`;
  713. }
  714. /**
  715. * Binds the world matrix to the material
  716. * @param world defines the world transformation matrix
  717. */
  718. public bindOnlyWorldMatrix(world: Matrix): void {
  719. var scene = this.getScene();
  720. if (!this._activeEffect) {
  721. return;
  722. }
  723. let hints = this._sharedData.hints;
  724. if (hints.needWorldViewMatrix) {
  725. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  726. }
  727. if (hints.needWorldViewProjectionMatrix) {
  728. world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
  729. }
  730. // Connection points
  731. for (var inputBlock of this._sharedData.inputBlocks) {
  732. inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
  733. }
  734. }
  735. /**
  736. * Binds the submesh to this material by preparing the effect and shader to draw
  737. * @param world defines the world transformation matrix
  738. * @param mesh defines the mesh containing the submesh
  739. * @param subMesh defines the submesh to bind the material to
  740. */
  741. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  742. let scene = this.getScene();
  743. var effect = subMesh.effect;
  744. if (!effect) {
  745. return;
  746. }
  747. this._activeEffect = effect;
  748. // Matrices
  749. this.bindOnlyWorldMatrix(world);
  750. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  751. if (mustRebind) {
  752. let sharedData = this._sharedData;
  753. if (effect && scene.getCachedEffect() !== effect) {
  754. // Bindable blocks
  755. for (var block of sharedData.bindableBlocks) {
  756. block.bind(effect, this, mesh, subMesh);
  757. }
  758. // Connection points
  759. for (var inputBlock of sharedData.inputBlocks) {
  760. inputBlock._transmit(effect, scene);
  761. }
  762. }
  763. }
  764. this._afterBind(mesh, this._activeEffect);
  765. }
  766. /**
  767. * Gets the active textures from the material
  768. * @returns an array of textures
  769. */
  770. public getActiveTextures(): BaseTexture[] {
  771. var activeTextures = super.getActiveTextures();
  772. if (this._sharedData) {
  773. activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!));
  774. }
  775. return activeTextures;
  776. }
  777. /**
  778. * Gets the list of texture blocks
  779. * @returns an array of texture blocks
  780. */
  781. public getTextureBlocks(): (TextureBlock | ReflectionTextureBaseBlock)[] {
  782. if (!this._sharedData) {
  783. return [];
  784. }
  785. return this._sharedData.textureBlocks;
  786. }
  787. /**
  788. * Specifies if the material uses a texture
  789. * @param texture defines the texture to check against the material
  790. * @returns a boolean specifying if the material uses the texture
  791. */
  792. public hasTexture(texture: BaseTexture): boolean {
  793. if (super.hasTexture(texture)) {
  794. return true;
  795. }
  796. if (!this._sharedData) {
  797. return false;
  798. }
  799. for (var t of this._sharedData.textureBlocks) {
  800. if (t.texture === texture) {
  801. return true;
  802. }
  803. }
  804. return false;
  805. }
  806. /**
  807. * Disposes the material
  808. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  809. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  810. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  811. */
  812. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  813. if (forceDisposeTextures) {
  814. for (var texture of this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!)) {
  815. texture.dispose();
  816. }
  817. }
  818. for (var block of this.attachedBlocks) {
  819. block.dispose();
  820. }
  821. this.onBuildObservable.clear();
  822. super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  823. }
  824. /** Creates the node editor window. */
  825. private _createNodeEditor() {
  826. this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
  827. this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
  828. nodeMaterial: this
  829. });
  830. }
  831. /**
  832. * Launch the node material editor
  833. * @param config Define the configuration of the editor
  834. * @return a promise fulfilled when the node editor is visible
  835. */
  836. public edit(config?: INodeMaterialEditorOptions): Promise<void> {
  837. return new Promise((resolve, reject) => {
  838. if (typeof this.BJSNODEMATERIALEDITOR == 'undefined') {
  839. const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
  840. // Load editor and add it to the DOM
  841. Tools.LoadScript(editorUrl, () => {
  842. this._createNodeEditor();
  843. resolve();
  844. });
  845. } else {
  846. // Otherwise creates the editor
  847. this._createNodeEditor();
  848. resolve();
  849. }
  850. });
  851. }
  852. /**
  853. * Clear the current material
  854. */
  855. public clear() {
  856. this._vertexOutputNodes = [];
  857. this._fragmentOutputNodes = [];
  858. this.attachedBlocks = [];
  859. }
  860. /**
  861. * Clear the current material and set it to a default state
  862. */
  863. public setToDefault() {
  864. this.clear();
  865. this.editorData = null;
  866. var positionInput = new InputBlock("Position");
  867. positionInput.setAsAttribute("position");
  868. var worldInput = new InputBlock("World");
  869. worldInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);
  870. var worldPos = new TransformBlock("WorldPos");
  871. positionInput.connectTo(worldPos);
  872. worldInput.connectTo(worldPos);
  873. var viewProjectionInput = new InputBlock("ViewProjection");
  874. viewProjectionInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.ViewProjection);
  875. var worldPosdMultipliedByViewProjection = new TransformBlock("WorldPos * ViewProjectionTransform");
  876. worldPos.connectTo(worldPosdMultipliedByViewProjection);
  877. viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
  878. var vertexOutput = new VertexOutputBlock("VertexOutput");
  879. worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
  880. // Pixel
  881. var pixelColor = new InputBlock("color");
  882. pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);
  883. var fragmentOutput = new FragmentOutputBlock("FragmentOutput");
  884. pixelColor.connectTo(fragmentOutput);
  885. // Add to nodes
  886. this.addOutputNode(vertexOutput);
  887. this.addOutputNode(fragmentOutput);
  888. }
  889. /**
  890. * Loads the current Node Material from a url pointing to a file save by the Node Material Editor
  891. * @param url defines the url to load from
  892. * @returns a promise that will fullfil when the material is fully loaded
  893. */
  894. public loadAsync(url: string) {
  895. return this.getScene()._loadFileAsync(url).then((data) => {
  896. const serializationObject = JSON.parse(data as string);
  897. this.loadFromSerialization(serializationObject, "");
  898. });
  899. }
  900. private _gatherBlocks(rootNode: NodeMaterialBlock, list: NodeMaterialBlock[]) {
  901. if (list.indexOf(rootNode) !== -1) {
  902. return;
  903. }
  904. list.push(rootNode);
  905. for (var input of rootNode.inputs) {
  906. let connectedPoint = input.connectedPoint;
  907. if (connectedPoint) {
  908. let block = connectedPoint.ownerBlock;
  909. if (block !== rootNode) {
  910. this._gatherBlocks(block, list);
  911. }
  912. }
  913. }
  914. }
  915. /**
  916. * Generate a string containing the code declaration required to create an equivalent of this material
  917. * @returns a string
  918. */
  919. public generateCode() {
  920. let alreadyDumped: NodeMaterialBlock[] = [];
  921. let vertexBlocks: NodeMaterialBlock[] = [];
  922. let uniqueNames: string[] = [];
  923. // Gets active blocks
  924. for (var outputNode of this._vertexOutputNodes) {
  925. this._gatherBlocks(outputNode, vertexBlocks);
  926. }
  927. let fragmentBlocks: NodeMaterialBlock[] = [];
  928. for (var outputNode of this._fragmentOutputNodes) {
  929. this._gatherBlocks(outputNode, fragmentBlocks);
  930. }
  931. // Generate vertex shader
  932. let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");\r\n`;
  933. for (var node of vertexBlocks) {
  934. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  935. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  936. }
  937. }
  938. // Generate fragment shader
  939. for (var node of fragmentBlocks) {
  940. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  941. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  942. }
  943. }
  944. // Connections
  945. alreadyDumped = [];
  946. codeString += "\r\n// Connections\r\n";
  947. for (var node of this._vertexOutputNodes) {
  948. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  949. }
  950. for (var node of this._fragmentOutputNodes) {
  951. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  952. }
  953. // Output nodes
  954. codeString += "\r\n// Output nodes\r\n";
  955. for (var node of this._vertexOutputNodes) {
  956. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  957. }
  958. for (var node of this._fragmentOutputNodes) {
  959. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  960. }
  961. codeString += `nodeMaterial.build();\r\n`;
  962. return codeString;
  963. }
  964. /**
  965. * Serializes this material in a JSON representation
  966. * @returns the serialized material object
  967. */
  968. public serialize(selectedBlocks?: NodeMaterialBlock[]): any {
  969. var serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
  970. serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy
  971. let blocks: NodeMaterialBlock[] = [];
  972. if (selectedBlocks) {
  973. blocks = selectedBlocks;
  974. } else {
  975. serializationObject.customType = "BABYLON.NodeMaterial";
  976. serializationObject.outputNodes = [];
  977. // Outputs
  978. for (var outputNode of this._vertexOutputNodes) {
  979. this._gatherBlocks(outputNode, blocks);
  980. serializationObject.outputNodes.push(outputNode.uniqueId);
  981. }
  982. for (var outputNode of this._fragmentOutputNodes) {
  983. this._gatherBlocks(outputNode, blocks);
  984. if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {
  985. serializationObject.outputNodes.push(outputNode.uniqueId);
  986. }
  987. }
  988. }
  989. // Blocks
  990. serializationObject.blocks = [];
  991. for (var block of blocks) {
  992. serializationObject.blocks.push(block.serialize());
  993. }
  994. if (!selectedBlocks) {
  995. for (var block of this.attachedBlocks) {
  996. if (blocks.indexOf(block) !== -1) {
  997. continue;
  998. }
  999. serializationObject.blocks.push(block.serialize());
  1000. }
  1001. }
  1002. return serializationObject;
  1003. }
  1004. private _restoreConnections(block: NodeMaterialBlock, source: any, map: {[key: number]: NodeMaterialBlock}) {
  1005. for (var outputPoint of block.outputs) {
  1006. for (var candidate of source.blocks) {
  1007. let target = map[candidate.id];
  1008. for (var input of candidate.inputs) {
  1009. if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
  1010. let inputPoint = target.getInputByName(input.inputName);
  1011. if (!inputPoint || inputPoint.isConnected) {
  1012. continue;
  1013. }
  1014. outputPoint.connectTo(inputPoint, true);
  1015. this._restoreConnections(target, source, map);
  1016. continue;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. /**
  1023. * Clear the current graph and load a new one from a serialization object
  1024. * @param source defines the JSON representation of the material
  1025. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1026. */
  1027. public loadFromSerialization(source: any, rootUrl: string = "") {
  1028. this.clear();
  1029. let map: {[key: number]: NodeMaterialBlock} = {};
  1030. // Create blocks
  1031. for (var parsedBlock of source.blocks) {
  1032. let blockType = _TypeStore.GetClass(parsedBlock.customType);
  1033. if (blockType) {
  1034. let block: NodeMaterialBlock = new blockType();
  1035. block._deserialize(parsedBlock, this.getScene(), rootUrl);
  1036. map[parsedBlock.id] = block;
  1037. this.attachedBlocks.push(block);
  1038. }
  1039. }
  1040. // Connections
  1041. // Starts with input blocks only
  1042. for (var blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
  1043. let parsedBlock = source.blocks[blockIndex];
  1044. let block = map[parsedBlock.id];
  1045. if (block.inputs.length) {
  1046. continue;
  1047. }
  1048. this._restoreConnections(block, source, map);
  1049. }
  1050. // Outputs
  1051. for (var outputNodeId of source.outputNodes) {
  1052. this.addOutputNode(map[outputNodeId]);
  1053. }
  1054. // UI related info
  1055. if (source.locations || source.editorData && source.editorData.locations) {
  1056. let locations: {
  1057. blockId: number;
  1058. x: number;
  1059. y: number;
  1060. }[] = source.locations || source.editorData.locations;
  1061. for (var location of locations) {
  1062. if (map[location.blockId]) {
  1063. location.blockId = map[location.blockId].uniqueId;
  1064. }
  1065. }
  1066. if (source.locations) {
  1067. this.editorData = {
  1068. locations: locations
  1069. };
  1070. } else {
  1071. this.editorData = source.editorData;
  1072. this.editorData.locations = locations;
  1073. }
  1074. let blockMap: number[] = [];
  1075. for (var key in map) {
  1076. blockMap[key] = map[key].uniqueId;
  1077. }
  1078. this.editorData.map = blockMap;
  1079. }
  1080. }
  1081. /**
  1082. * Makes a duplicate of the current material.
  1083. * @param name - name to use for the new material.
  1084. */
  1085. public clone(name: string): NodeMaterial {
  1086. const serializationObject = this.serialize();
  1087. const clone = SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this);
  1088. clone.id = name;
  1089. clone.name = name;
  1090. clone.loadFromSerialization(serializationObject);
  1091. clone.build();
  1092. return clone;
  1093. }
  1094. /**
  1095. * Creates a node material from parsed material data
  1096. * @param source defines the JSON representation of the material
  1097. * @param scene defines the hosting scene
  1098. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1099. * @returns a new node material
  1100. */
  1101. public static Parse(source: any, scene: Scene, rootUrl: string = ""): NodeMaterial {
  1102. let nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);
  1103. nodeMaterial.loadFromSerialization(source, rootUrl);
  1104. nodeMaterial.build();
  1105. return nodeMaterial;
  1106. }
  1107. /**
  1108. * Creates a node material from a snippet saved in a remote file
  1109. * @param name defines the name of the material to create
  1110. * @param url defines the url to load from
  1111. * @param scene defines the hosting scene
  1112. * @returns a promise that will resolve to the new node material
  1113. */
  1114. public static ParseFromFileAsync(name: string, url: string, scene: Scene): Promise<NodeMaterial> {
  1115. var material = new NodeMaterial(name, scene);
  1116. return new Promise((resolve, reject) => {
  1117. return material.loadAsync(url).then(() => resolve(material)).catch(reject);
  1118. });
  1119. }
  1120. /**
  1121. * Creates a node material from a snippet saved by the node material editor
  1122. * @param snippetId defines the snippet to load
  1123. * @param scene defines the hosting scene
  1124. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1125. * @param nodeMaterial defines a node material to update (instead of creating a new one)
  1126. * @returns a promise that will resolve to the new node material
  1127. */
  1128. public static ParseFromSnippetAsync(snippetId: string, scene: Scene, rootUrl: string = "", nodeMaterial?: NodeMaterial): Promise<NodeMaterial> {
  1129. return new Promise((resolve, reject) => {
  1130. var request = new WebRequest();
  1131. request.addEventListener("readystatechange", () => {
  1132. if (request.readyState == 4) {
  1133. if (request.status == 200) {
  1134. var snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
  1135. let serializationObject = JSON.parse(snippet.nodeMaterial);
  1136. if (!nodeMaterial) {
  1137. nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene), serializationObject, scene, rootUrl);
  1138. nodeMaterial.uniqueId = scene.getUniqueId();
  1139. }
  1140. nodeMaterial.loadFromSerialization(serializationObject);
  1141. nodeMaterial.snippetId = snippetId;
  1142. try {
  1143. nodeMaterial.build();
  1144. resolve(nodeMaterial);
  1145. } catch (err) {
  1146. reject(err);
  1147. }
  1148. } else {
  1149. reject("Unable to load the snippet " + snippetId);
  1150. }
  1151. }
  1152. });
  1153. request.open("GET", this.SnippetUrl + "/" + snippetId.replace("#", "/"));
  1154. request.send();
  1155. });
  1156. }
  1157. /**
  1158. * Creates a new node material set to default basic configuration
  1159. * @param name defines the name of the material
  1160. * @param scene defines the hosting scene
  1161. * @returns a new NodeMaterial
  1162. */
  1163. public static CreateDefault(name: string, scene?: Scene) {
  1164. let newMaterial = new NodeMaterial(name, scene);
  1165. newMaterial.setToDefault();
  1166. newMaterial.build();
  1167. return newMaterial;
  1168. }
  1169. }
  1170. _TypeStore.RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;