nodeMaterial.ts 41 KB

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