nodeMaterial.ts 42 KB

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