nodeMaterial.ts 43 KB

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