nodeMaterial.ts 35 KB

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