nodeMaterial.ts 42 KB

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