nodeMaterial.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. /** 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. // 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.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);
  811. var worldPos = new TransformBlock("worldPos");
  812. positionInput.connectTo(worldPos);
  813. worldInput.connectTo(worldPos);
  814. var viewProjectionInput = new InputBlock("viewProjection");
  815. viewProjectionInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.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. nodeMaterial.build();
  999. return nodeMaterial;
  1000. }
  1001. /**
  1002. * Creates a new node material set to default basic configuration
  1003. * @param name defines the name of the material
  1004. * @param scene defines the hosting scene
  1005. * @returns a new NodeMaterial
  1006. */
  1007. public static CreateDefault(name: string, scene?: Scene) {
  1008. let newMaterial = new NodeMaterial(name, scene);
  1009. newMaterial.setToDefault();
  1010. newMaterial.build();
  1011. return newMaterial;
  1012. }
  1013. }
  1014. _TypeStore.RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;