material.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. import { serialize, SerializationHelper } from "../Misc/decorators";
  2. import { Tools, IAnimatable } from "../Misc/tools";
  3. import { SmartArray } from "../Misc/smartArray";
  4. import { Observer, Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { Scene } from "../scene";
  7. import { Plane, Matrix } from "../Maths/math";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { BaseSubMesh, SubMesh } from "../Meshes/subMesh";
  10. import { Geometry } from "../Meshes/geometry";
  11. import { AbstractMesh } from "../Meshes/abstractMesh";
  12. import { Mesh } from "../Meshes/mesh";
  13. import { UniformBuffer } from "./uniformBuffer";
  14. import { Effect } from "./effect";
  15. import { BaseTexture } from "../Materials/Textures/baseTexture";
  16. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  17. import { MaterialDefines } from "./materialDefines";
  18. import { Constants } from "../Engines/constants";
  19. import { Logger } from "../Misc/logger";
  20. import { IInspectable } from '../Misc/iInspectable';
  21. declare type Animation = import("../Animations/animation").Animation;
  22. declare type InstancedMesh = import('../Meshes/instancedMesh').InstancedMesh;
  23. declare var BABYLON: any;
  24. /**
  25. * Base class for the main features of a material in Babylon.js
  26. */
  27. export class Material implements IAnimatable {
  28. /**
  29. * Returns the triangle fill mode
  30. */
  31. public static readonly TriangleFillMode = Constants.MATERIAL_TriangleFillMode;
  32. /**
  33. * Returns the wireframe mode
  34. */
  35. public static readonly WireFrameFillMode = Constants.MATERIAL_WireFrameFillMode;
  36. /**
  37. * Returns the point fill mode
  38. */
  39. public static readonly PointFillMode = Constants.MATERIAL_PointFillMode;
  40. /**
  41. * Returns the point list draw mode
  42. */
  43. public static readonly PointListDrawMode = Constants.MATERIAL_PointListDrawMode;
  44. /**
  45. * Returns the line list draw mode
  46. */
  47. public static readonly LineListDrawMode = Constants.MATERIAL_LineListDrawMode;
  48. /**
  49. * Returns the line loop draw mode
  50. */
  51. public static readonly LineLoopDrawMode = Constants.MATERIAL_LineLoopDrawMode;
  52. /**
  53. * Returns the line strip draw mode
  54. */
  55. public static readonly LineStripDrawMode = Constants.MATERIAL_LineStripDrawMode;
  56. /**
  57. * Returns the triangle strip draw mode
  58. */
  59. public static readonly TriangleStripDrawMode = Constants.MATERIAL_TriangleStripDrawMode;
  60. /**
  61. * Returns the triangle fan draw mode
  62. */
  63. public static readonly TriangleFanDrawMode = Constants.MATERIAL_TriangleFanDrawMode;
  64. /**
  65. * Stores the clock-wise side orientation
  66. */
  67. public static readonly ClockWiseSideOrientation = Constants.MATERIAL_ClockWiseSideOrientation;
  68. /**
  69. * Stores the counter clock-wise side orientation
  70. */
  71. public static readonly CounterClockWiseSideOrientation = Constants.MATERIAL_CounterClockWiseSideOrientation;
  72. /**
  73. * The dirty texture flag value
  74. */
  75. public static readonly TextureDirtyFlag = Constants.MATERIAL_TextureDirtyFlag;
  76. /**
  77. * The dirty light flag value
  78. */
  79. public static readonly LightDirtyFlag = Constants.MATERIAL_LightDirtyFlag;
  80. /**
  81. * The dirty fresnel flag value
  82. */
  83. public static readonly FresnelDirtyFlag = Constants.MATERIAL_FresnelDirtyFlag;
  84. /**
  85. * The dirty attribute flag value
  86. */
  87. public static readonly AttributesDirtyFlag = Constants.MATERIAL_AttributesDirtyFlag;
  88. /**
  89. * The dirty misc flag value
  90. */
  91. public static readonly MiscDirtyFlag = Constants.MATERIAL_MiscDirtyFlag;
  92. /**
  93. * The all dirty flag value
  94. */
  95. public static readonly AllDirtyFlag = Constants.MATERIAL_AllDirtyFlag;
  96. /**
  97. * The ID of the material
  98. */
  99. @serialize()
  100. public id: string;
  101. /**
  102. * Gets or sets the unique id of the material
  103. */
  104. @serialize()
  105. public uniqueId: number;
  106. /**
  107. * The name of the material
  108. */
  109. @serialize()
  110. public name: string;
  111. /**
  112. * Gets or sets user defined metadata
  113. */
  114. public metadata: any = null;
  115. /**
  116. * For internal use only. Please do not use.
  117. */
  118. public reservedDataStore: any = null;
  119. /**
  120. * Specifies if the ready state should be checked on each call
  121. */
  122. @serialize()
  123. public checkReadyOnEveryCall = false;
  124. /**
  125. * Specifies if the ready state should be checked once
  126. */
  127. @serialize()
  128. public checkReadyOnlyOnce = false;
  129. /**
  130. * The state of the material
  131. */
  132. @serialize()
  133. public state = "";
  134. /**
  135. * The alpha value of the material
  136. */
  137. @serialize("alpha")
  138. protected _alpha = 1.0;
  139. /**
  140. * List of inspectable custom properties (used by the Inspector)
  141. * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility
  142. */
  143. public inspectableCustomProperties: IInspectable[];
  144. /**
  145. * Sets the alpha value of the material
  146. */
  147. public set alpha(value: number) {
  148. if (this._alpha === value) {
  149. return;
  150. }
  151. this._alpha = value;
  152. this.markAsDirty(Material.MiscDirtyFlag);
  153. }
  154. /**
  155. * Gets the alpha value of the material
  156. */
  157. public get alpha(): number {
  158. return this._alpha;
  159. }
  160. /**
  161. * Specifies if back face culling is enabled
  162. */
  163. @serialize("backFaceCulling")
  164. protected _backFaceCulling = true;
  165. /**
  166. * Sets the back-face culling state
  167. */
  168. public set backFaceCulling(value: boolean) {
  169. if (this._backFaceCulling === value) {
  170. return;
  171. }
  172. this._backFaceCulling = value;
  173. this.markAsDirty(Material.TextureDirtyFlag);
  174. }
  175. /**
  176. * Gets the back-face culling state
  177. */
  178. public get backFaceCulling(): boolean {
  179. return this._backFaceCulling;
  180. }
  181. /**
  182. * Stores the value for side orientation
  183. */
  184. @serialize()
  185. public sideOrientation: number;
  186. /**
  187. * Callback triggered when the material is compiled
  188. */
  189. public onCompiled: Nullable<(effect: Effect) => void> = null;
  190. /**
  191. * Callback triggered when an error occurs
  192. */
  193. public onError: Nullable<(effect: Effect, errors: string) => void> = null;
  194. /**
  195. * Callback triggered to get the render target textures
  196. */
  197. public getRenderTargetTextures: Nullable<() => SmartArray<RenderTargetTexture>> = null;
  198. /**
  199. * Gets a boolean indicating that current material needs to register RTT
  200. */
  201. public get hasRenderTargetTextures(): boolean {
  202. return false;
  203. }
  204. /**
  205. * Specifies if the material should be serialized
  206. */
  207. public doNotSerialize = false;
  208. /**
  209. * @hidden
  210. */
  211. public _storeEffectOnSubMeshes = false;
  212. /**
  213. * Stores the animations for the material
  214. */
  215. public animations: Nullable<Array<Animation>> = null;
  216. /**
  217. * An event triggered when the material is disposed
  218. */
  219. public onDisposeObservable = new Observable<Material>();
  220. /**
  221. * An observer which watches for dispose events
  222. */
  223. private _onDisposeObserver: Nullable<Observer<Material>> = null;
  224. private _onUnBindObservable: Nullable<Observable<Material>> = null;
  225. /**
  226. * Called during a dispose event
  227. */
  228. public set onDispose(callback: () => void) {
  229. if (this._onDisposeObserver) {
  230. this.onDisposeObservable.remove(this._onDisposeObserver);
  231. }
  232. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  233. }
  234. private _onBindObservable: Nullable<Observable<AbstractMesh>>;
  235. /**
  236. * An event triggered when the material is bound
  237. */
  238. public get onBindObservable(): Observable<AbstractMesh> {
  239. if (!this._onBindObservable) {
  240. this._onBindObservable = new Observable<AbstractMesh>();
  241. }
  242. return this._onBindObservable;
  243. }
  244. /**
  245. * An observer which watches for bind events
  246. */
  247. private _onBindObserver: Nullable<Observer<AbstractMesh>> = null;
  248. /**
  249. * Called during a bind event
  250. */
  251. public set onBind(callback: (Mesh: AbstractMesh) => void) {
  252. if (this._onBindObserver) {
  253. this.onBindObservable.remove(this._onBindObserver);
  254. }
  255. this._onBindObserver = this.onBindObservable.add(callback);
  256. }
  257. /**
  258. * An event triggered when the material is unbound
  259. */
  260. public get onUnBindObservable(): Observable<Material> {
  261. if (!this._onUnBindObservable) {
  262. this._onUnBindObservable = new Observable<Material>();
  263. }
  264. return this._onUnBindObservable;
  265. }
  266. /**
  267. * Stores the value of the alpha mode
  268. */
  269. @serialize("alphaMode")
  270. private _alphaMode: number = Constants.ALPHA_COMBINE;
  271. /**
  272. * Sets the value of the alpha mode.
  273. *
  274. * | Value | Type | Description |
  275. * | --- | --- | --- |
  276. * | 0 | ALPHA_DISABLE | |
  277. * | 1 | ALPHA_ADD | |
  278. * | 2 | ALPHA_COMBINE | |
  279. * | 3 | ALPHA_SUBTRACT | |
  280. * | 4 | ALPHA_MULTIPLY | |
  281. * | 5 | ALPHA_MAXIMIZED | |
  282. * | 6 | ALPHA_ONEONE | |
  283. * | 7 | ALPHA_PREMULTIPLIED | |
  284. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  285. * | 9 | ALPHA_INTERPOLATE | |
  286. * | 10 | ALPHA_SCREENMODE | |
  287. *
  288. */
  289. public set alphaMode(value: number) {
  290. if (this._alphaMode === value) {
  291. return;
  292. }
  293. this._alphaMode = value;
  294. this.markAsDirty(Material.TextureDirtyFlag);
  295. }
  296. /**
  297. * Gets the value of the alpha mode
  298. */
  299. public get alphaMode(): number {
  300. return this._alphaMode;
  301. }
  302. /**
  303. * Stores the state of the need depth pre-pass value
  304. */
  305. @serialize()
  306. private _needDepthPrePass = false;
  307. /**
  308. * Sets the need depth pre-pass value
  309. */
  310. public set needDepthPrePass(value: boolean) {
  311. if (this._needDepthPrePass === value) {
  312. return;
  313. }
  314. this._needDepthPrePass = value;
  315. if (this._needDepthPrePass) {
  316. this.checkReadyOnEveryCall = true;
  317. }
  318. }
  319. /**
  320. * Gets the depth pre-pass value
  321. */
  322. public get needDepthPrePass(): boolean {
  323. return this._needDepthPrePass;
  324. }
  325. /**
  326. * Specifies if depth writing should be disabled
  327. */
  328. @serialize()
  329. public disableDepthWrite = false;
  330. /**
  331. * Specifies if depth writing should be forced
  332. */
  333. @serialize()
  334. public forceDepthWrite = false;
  335. /**
  336. * Specifies if there should be a separate pass for culling
  337. */
  338. @serialize()
  339. public separateCullingPass = false;
  340. /**
  341. * Stores the state specifing if fog should be enabled
  342. */
  343. @serialize("fogEnabled")
  344. private _fogEnabled = true;
  345. /**
  346. * Sets the state for enabling fog
  347. */
  348. public set fogEnabled(value: boolean) {
  349. if (this._fogEnabled === value) {
  350. return;
  351. }
  352. this._fogEnabled = value;
  353. this.markAsDirty(Material.MiscDirtyFlag);
  354. }
  355. /**
  356. * Gets the value of the fog enabled state
  357. */
  358. public get fogEnabled(): boolean {
  359. return this._fogEnabled;
  360. }
  361. /**
  362. * Stores the size of points
  363. */
  364. @serialize()
  365. public pointSize = 1.0;
  366. /**
  367. * Stores the z offset value
  368. */
  369. @serialize()
  370. public zOffset = 0;
  371. /**
  372. * Gets a value specifying if wireframe mode is enabled
  373. */
  374. @serialize()
  375. public get wireframe(): boolean {
  376. switch (this._fillMode) {
  377. case Material.WireFrameFillMode:
  378. case Material.LineListDrawMode:
  379. case Material.LineLoopDrawMode:
  380. case Material.LineStripDrawMode:
  381. return true;
  382. }
  383. return this._scene.forceWireframe;
  384. }
  385. /**
  386. * Sets the state of wireframe mode
  387. */
  388. public set wireframe(value: boolean) {
  389. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  390. }
  391. /**
  392. * Gets the value specifying if point clouds are enabled
  393. */
  394. @serialize()
  395. public get pointsCloud(): boolean {
  396. switch (this._fillMode) {
  397. case Material.PointFillMode:
  398. case Material.PointListDrawMode:
  399. return true;
  400. }
  401. return this._scene.forcePointsCloud;
  402. }
  403. /**
  404. * Sets the state of point cloud mode
  405. */
  406. public set pointsCloud(value: boolean) {
  407. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  408. }
  409. /**
  410. * Gets the material fill mode
  411. */
  412. @serialize()
  413. public get fillMode(): number {
  414. return this._fillMode;
  415. }
  416. /**
  417. * Sets the material fill mode
  418. */
  419. public set fillMode(value: number) {
  420. if (this._fillMode === value) {
  421. return;
  422. }
  423. this._fillMode = value;
  424. this.markAsDirty(Material.MiscDirtyFlag);
  425. }
  426. /**
  427. * @hidden
  428. * Stores the effects for the material
  429. */
  430. public _effect: Nullable<Effect> = null;
  431. /**
  432. * @hidden
  433. * Specifies if the material was previously ready
  434. */
  435. public _wasPreviouslyReady = false;
  436. /**
  437. * Specifies if uniform buffers should be used
  438. */
  439. private _useUBO: boolean = false;
  440. /**
  441. * Stores a reference to the scene
  442. */
  443. private _scene: Scene;
  444. /**
  445. * Stores the fill mode state
  446. */
  447. private _fillMode = Material.TriangleFillMode;
  448. /**
  449. * Specifies if the depth write state should be cached
  450. */
  451. private _cachedDepthWriteState: boolean = false;
  452. /**
  453. * Stores the uniform buffer
  454. */
  455. protected _uniformBuffer: UniformBuffer;
  456. /** @hidden */
  457. public _indexInSceneMaterialArray = -1;
  458. /** @hidden */
  459. public meshMap: Nullable<{ [id: string]: AbstractMesh | undefined }> = null;
  460. /**
  461. * Creates a material instance
  462. * @param name defines the name of the material
  463. * @param scene defines the scene to reference
  464. * @param doNotAdd specifies if the material should be added to the scene
  465. */
  466. constructor(name: string, scene: Scene, doNotAdd?: boolean) {
  467. this.name = name;
  468. this.id = name || Tools.RandomId();
  469. this._scene = scene || EngineStore.LastCreatedScene;
  470. this.uniqueId = this._scene.getUniqueId();
  471. if (this._scene.useRightHandedSystem) {
  472. this.sideOrientation = Material.ClockWiseSideOrientation;
  473. } else {
  474. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  475. }
  476. this._uniformBuffer = new UniformBuffer(this._scene.getEngine());
  477. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  478. if (!doNotAdd) {
  479. this._scene.addMaterial(this);
  480. }
  481. if (this._scene.useMaterialMeshMap) {
  482. this.meshMap = {};
  483. }
  484. }
  485. /**
  486. * Returns a string representation of the current material
  487. * @param fullDetails defines a boolean indicating which levels of logging is desired
  488. * @returns a string with material information
  489. */
  490. public toString(fullDetails?: boolean): string {
  491. var ret = "Name: " + this.name;
  492. if (fullDetails) {
  493. }
  494. return ret;
  495. }
  496. /**
  497. * Gets the class name of the material
  498. * @returns a string with the class name of the material
  499. */
  500. public getClassName(): string {
  501. return "Material";
  502. }
  503. /**
  504. * Specifies if updates for the material been locked
  505. */
  506. public get isFrozen(): boolean {
  507. return this.checkReadyOnlyOnce;
  508. }
  509. /**
  510. * Locks updates for the material
  511. */
  512. public freeze(): void {
  513. this.checkReadyOnlyOnce = true;
  514. }
  515. /**
  516. * Unlocks updates for the material
  517. */
  518. public unfreeze(): void {
  519. this.checkReadyOnlyOnce = false;
  520. }
  521. /**
  522. * Specifies if the material is ready to be used
  523. * @param mesh defines the mesh to check
  524. * @param useInstances specifies if instances should be used
  525. * @returns a boolean indicating if the material is ready to be used
  526. */
  527. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  528. return true;
  529. }
  530. /**
  531. * Specifies that the submesh is ready to be used
  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: BaseSubMesh, useInstances?: boolean): boolean {
  538. return false;
  539. }
  540. /**
  541. * Returns the material effect
  542. * @returns the effect associated with the material
  543. */
  544. public getEffect(): Nullable<Effect> {
  545. return this._effect;
  546. }
  547. /**
  548. * Returns the current scene
  549. * @returns a Scene
  550. */
  551. public getScene(): Scene {
  552. return this._scene;
  553. }
  554. /**
  555. * Specifies if the material will require alpha blending
  556. * @returns a boolean specifying if alpha blending is needed
  557. */
  558. public needAlphaBlending(): boolean {
  559. return (this.alpha < 1.0);
  560. }
  561. /**
  562. * Specifies if the mesh will require alpha blending
  563. * @param mesh defines the mesh to check
  564. * @returns a boolean specifying if alpha blending is needed for the mesh
  565. */
  566. public needAlphaBlendingForMesh(mesh: AbstractMesh): boolean {
  567. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  568. }
  569. /**
  570. * Specifies if this material should be rendered in alpha test mode
  571. * @returns a boolean specifying if an alpha test is needed.
  572. */
  573. public needAlphaTesting(): boolean {
  574. return false;
  575. }
  576. /**
  577. * Gets the texture used for the alpha test
  578. * @returns the texture to use for alpha testing
  579. */
  580. public getAlphaTestTexture(): Nullable<BaseTexture> {
  581. return null;
  582. }
  583. /**
  584. * Marks the material to indicate that it needs to be re-calculated
  585. */
  586. public markDirty(): void {
  587. this._wasPreviouslyReady = false;
  588. }
  589. /** @hidden */
  590. public _preBind(effect?: Effect, overrideOrientation: Nullable<number> = null): boolean {
  591. var engine = this._scene.getEngine();
  592. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  593. var reverse = orientation === Material.ClockWiseSideOrientation;
  594. engine.enableEffect(effect ? effect : this._effect);
  595. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  596. return reverse;
  597. }
  598. /**
  599. * Binds the material to the mesh
  600. * @param world defines the world transformation matrix
  601. * @param mesh defines the mesh to bind the material to
  602. */
  603. public bind(world: Matrix, mesh?: Mesh): void {
  604. }
  605. /**
  606. * Binds the submesh to the material
  607. * @param world defines the world transformation matrix
  608. * @param mesh defines the mesh containing the submesh
  609. * @param subMesh defines the submesh to bind the material to
  610. */
  611. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  612. }
  613. /**
  614. * Binds the world matrix to the material
  615. * @param world defines the world transformation matrix
  616. */
  617. public bindOnlyWorldMatrix(world: Matrix): void {
  618. }
  619. /**
  620. * Binds the scene's uniform buffer to the effect.
  621. * @param effect defines the effect to bind to the scene uniform buffer
  622. * @param sceneUbo defines the uniform buffer storing scene data
  623. */
  624. public bindSceneUniformBuffer(effect: Effect, sceneUbo: UniformBuffer): void {
  625. sceneUbo.bindToEffect(effect, "Scene");
  626. }
  627. /**
  628. * Binds the view matrix to the effect
  629. * @param effect defines the effect to bind the view matrix to
  630. */
  631. public bindView(effect: Effect): void {
  632. if (!this._useUBO) {
  633. effect.setMatrix("view", this.getScene().getViewMatrix());
  634. } else {
  635. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  636. }
  637. }
  638. /**
  639. * Binds the view projection matrix to the effect
  640. * @param effect defines the effect to bind the view projection matrix to
  641. */
  642. public bindViewProjection(effect: Effect): void {
  643. if (!this._useUBO) {
  644. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  645. } else {
  646. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  647. }
  648. }
  649. /**
  650. * Specifies if material alpha testing should be turned on for the mesh
  651. * @param mesh defines the mesh to check
  652. */
  653. protected _shouldTurnAlphaTestOn(mesh: AbstractMesh): boolean {
  654. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  655. }
  656. /**
  657. * Processes to execute after binding the material to a mesh
  658. * @param mesh defines the rendered mesh
  659. */
  660. protected _afterBind(mesh?: Mesh): void {
  661. this._scene._cachedMaterial = this;
  662. if (mesh) {
  663. this._scene._cachedVisibility = mesh.visibility;
  664. } else {
  665. this._scene._cachedVisibility = 1;
  666. }
  667. if (this._onBindObservable && mesh) {
  668. this._onBindObservable.notifyObservers(mesh);
  669. }
  670. if (this.disableDepthWrite) {
  671. var engine = this._scene.getEngine();
  672. this._cachedDepthWriteState = engine.getDepthWrite();
  673. engine.setDepthWrite(false);
  674. }
  675. }
  676. /**
  677. * Unbinds the material from the mesh
  678. */
  679. public unbind(): void {
  680. if (this._onUnBindObservable) {
  681. this._onUnBindObservable.notifyObservers(this);
  682. }
  683. if (this.disableDepthWrite) {
  684. var engine = this._scene.getEngine();
  685. engine.setDepthWrite(this._cachedDepthWriteState);
  686. }
  687. }
  688. /**
  689. * Gets the active textures from the material
  690. * @returns an array of textures
  691. */
  692. public getActiveTextures(): BaseTexture[] {
  693. return [];
  694. }
  695. /**
  696. * Specifies if the material uses a texture
  697. * @param texture defines the texture to check against the material
  698. * @returns a boolean specifying if the material uses the texture
  699. */
  700. public hasTexture(texture: BaseTexture): boolean {
  701. return false;
  702. }
  703. /**
  704. * Makes a duplicate of the material, and gives it a new name
  705. * @param name defines the new name for the duplicated material
  706. * @returns the cloned material
  707. */
  708. public clone(name: string): Nullable<Material> {
  709. return null;
  710. }
  711. /**
  712. * Gets the meshes bound to the material
  713. * @returns an array of meshes bound to the material
  714. */
  715. public getBindedMeshes(): AbstractMesh[] {
  716. if (this.meshMap) {
  717. var result = new Array<AbstractMesh>();
  718. for (let meshId in this.meshMap) {
  719. const mesh = this.meshMap[meshId];
  720. if (mesh) {
  721. result.push(mesh);
  722. }
  723. }
  724. return result;
  725. }
  726. else {
  727. const meshes = this._scene.meshes;
  728. return meshes.filter((mesh) => mesh.material === this);
  729. }
  730. }
  731. /**
  732. * Force shader compilation
  733. * @param mesh defines the mesh associated with this material
  734. * @param onCompiled defines a function to execute once the material is compiled
  735. * @param options defines the options to configure the compilation
  736. */
  737. public forceCompilation(mesh: AbstractMesh, onCompiled?: (material: Material) => void, options?: Partial<{ clipPlane: boolean }>): void {
  738. let localOptions = {
  739. clipPlane: false,
  740. ...options
  741. };
  742. var subMesh = new BaseSubMesh();
  743. var scene = this.getScene();
  744. var checkReady = () => {
  745. if (!this._scene || !this._scene.getEngine()) {
  746. return;
  747. }
  748. if (subMesh._materialDefines) {
  749. subMesh._materialDefines._renderId = -1;
  750. }
  751. var clipPlaneState = scene.clipPlane;
  752. if (localOptions.clipPlane) {
  753. scene.clipPlane = new Plane(0, 0, 0, 1);
  754. }
  755. if (this._storeEffectOnSubMeshes) {
  756. if (this.isReadyForSubMesh(mesh, subMesh)) {
  757. if (onCompiled) {
  758. onCompiled(this);
  759. }
  760. }
  761. else {
  762. setTimeout(checkReady, 16);
  763. }
  764. } else {
  765. if (this.isReady()) {
  766. if (onCompiled) {
  767. onCompiled(this);
  768. }
  769. }
  770. else {
  771. setTimeout(checkReady, 16);
  772. }
  773. }
  774. if (localOptions.clipPlane) {
  775. scene.clipPlane = clipPlaneState;
  776. }
  777. };
  778. checkReady();
  779. }
  780. /**
  781. * Force shader compilation
  782. * @param mesh defines the mesh that will use this material
  783. * @param options defines additional options for compiling the shaders
  784. * @returns a promise that resolves when the compilation completes
  785. */
  786. public forceCompilationAsync(mesh: AbstractMesh, options?: Partial<{ clipPlane: boolean }>): Promise<void> {
  787. return new Promise((resolve) => {
  788. this.forceCompilation(mesh, () => {
  789. resolve();
  790. }, options);
  791. });
  792. }
  793. private static readonly _AllDirtyCallBack = (defines: MaterialDefines) => defines.markAllAsDirty();
  794. private static readonly _ImageProcessingDirtyCallBack = (defines: MaterialDefines) => defines.markAsImageProcessingDirty();
  795. private static readonly _TextureDirtyCallBack = (defines: MaterialDefines) => defines.markAsTexturesDirty();
  796. private static readonly _FresnelDirtyCallBack = (defines: MaterialDefines) => defines.markAsFresnelDirty();
  797. private static readonly _MiscDirtyCallBack = (defines: MaterialDefines) => defines.markAsMiscDirty();
  798. private static readonly _LightsDirtyCallBack = (defines: MaterialDefines) => defines.markAsLightDirty();
  799. private static readonly _AttributeDirtyCallBack = (defines: MaterialDefines) => defines.markAsAttributesDirty();
  800. private static _FresnelAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  801. Material._FresnelDirtyCallBack(defines);
  802. Material._MiscDirtyCallBack(defines);
  803. }
  804. private static _TextureAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  805. Material._TextureDirtyCallBack(defines);
  806. Material._MiscDirtyCallBack(defines);
  807. }
  808. private static readonly _DirtyCallbackArray: Array<(defines: MaterialDefines) => void> = [];
  809. private static readonly _RunDirtyCallBacks = (defines: MaterialDefines) => {
  810. for (const cb of Material._DirtyCallbackArray) {
  811. cb(defines);
  812. }
  813. }
  814. /**
  815. * Marks a define in the material to indicate that it needs to be re-computed
  816. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  817. */
  818. public markAsDirty(flag: number): void {
  819. if (this.getScene().blockMaterialDirtyMechanism) {
  820. return;
  821. }
  822. Material._DirtyCallbackArray.length = 0;
  823. if (flag & Material.TextureDirtyFlag) {
  824. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  825. }
  826. if (flag & Material.LightDirtyFlag) {
  827. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  828. }
  829. if (flag & Material.FresnelDirtyFlag) {
  830. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  831. }
  832. if (flag & Material.AttributesDirtyFlag) {
  833. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  834. }
  835. if (flag & Material.MiscDirtyFlag) {
  836. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  837. }
  838. if (Material._DirtyCallbackArray.length) {
  839. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  840. }
  841. this.getScene().resetCachedMaterial();
  842. }
  843. /**
  844. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  845. * @param func defines a function which checks material defines against the submeshes
  846. */
  847. protected _markAllSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  848. if (this.getScene().blockMaterialDirtyMechanism) {
  849. return;
  850. }
  851. const meshes = this.getScene().meshes;
  852. for (var mesh of meshes) {
  853. if (!mesh.subMeshes) {
  854. continue;
  855. }
  856. for (var subMesh of mesh.subMeshes) {
  857. if (subMesh.getMaterial() !== this) {
  858. continue;
  859. }
  860. if (!subMesh._materialDefines) {
  861. continue;
  862. }
  863. func(subMesh._materialDefines);
  864. }
  865. }
  866. }
  867. /**
  868. * Indicates that we need to re-calculated for all submeshes
  869. */
  870. protected _markAllSubMeshesAsAllDirty() {
  871. this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);
  872. }
  873. /**
  874. * Indicates that image processing needs to be re-calculated for all submeshes
  875. */
  876. protected _markAllSubMeshesAsImageProcessingDirty() {
  877. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  878. }
  879. /**
  880. * Indicates that textures need to be re-calculated for all submeshes
  881. */
  882. protected _markAllSubMeshesAsTexturesDirty() {
  883. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  884. }
  885. /**
  886. * Indicates that fresnel needs to be re-calculated for all submeshes
  887. */
  888. protected _markAllSubMeshesAsFresnelDirty() {
  889. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  890. }
  891. /**
  892. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  893. */
  894. protected _markAllSubMeshesAsFresnelAndMiscDirty() {
  895. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  896. }
  897. /**
  898. * Indicates that lights need to be re-calculated for all submeshes
  899. */
  900. protected _markAllSubMeshesAsLightsDirty() {
  901. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  902. }
  903. /**
  904. * Indicates that attributes need to be re-calculated for all submeshes
  905. */
  906. protected _markAllSubMeshesAsAttributesDirty() {
  907. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  908. }
  909. /**
  910. * Indicates that misc needs to be re-calculated for all submeshes
  911. */
  912. protected _markAllSubMeshesAsMiscDirty() {
  913. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  914. }
  915. /**
  916. * Indicates that textures and misc need to be re-calculated for all submeshes
  917. */
  918. protected _markAllSubMeshesAsTexturesAndMiscDirty() {
  919. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  920. }
  921. /**
  922. * Disposes the material
  923. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  924. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  925. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  926. */
  927. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  928. const scene = this.getScene();
  929. // Animations
  930. scene.stopAnimation(this);
  931. scene.freeProcessedMaterials();
  932. // Remove from scene
  933. scene.removeMaterial(this);
  934. if (notBoundToMesh !== true) {
  935. // Remove from meshes
  936. if (this.meshMap) {
  937. for (let meshId in this.meshMap) {
  938. const mesh = this.meshMap[meshId];
  939. if (mesh) {
  940. mesh.material = null; // will set the entry in the map to undefined
  941. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  942. }
  943. }
  944. }
  945. else {
  946. const meshes = scene.meshes;
  947. for (let mesh of meshes) {
  948. if (mesh.material === this && !(mesh as InstancedMesh).sourceMesh) {
  949. mesh.material = null;
  950. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  951. }
  952. }
  953. }
  954. }
  955. this._uniformBuffer.dispose();
  956. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  957. if (forceDisposeEffect && this._effect) {
  958. if (!this._storeEffectOnSubMeshes) {
  959. this._effect.dispose();
  960. }
  961. this._effect = null;
  962. }
  963. // Callback
  964. this.onDisposeObservable.notifyObservers(this);
  965. this.onDisposeObservable.clear();
  966. if (this._onBindObservable) {
  967. this._onBindObservable.clear();
  968. }
  969. if (this._onUnBindObservable) {
  970. this._onUnBindObservable.clear();
  971. }
  972. }
  973. /** @hidden */
  974. private releaseVertexArrayObject(mesh: AbstractMesh, forceDisposeEffect?: boolean) {
  975. if ((<Mesh>mesh).geometry) {
  976. var geometry = <Geometry>((<Mesh>mesh).geometry);
  977. if (this._storeEffectOnSubMeshes) {
  978. for (var subMesh of mesh.subMeshes) {
  979. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  980. if (forceDisposeEffect && subMesh._materialEffect) {
  981. subMesh._materialEffect.dispose();
  982. }
  983. }
  984. } else {
  985. geometry._releaseVertexArrayObject(this._effect);
  986. }
  987. }
  988. }
  989. /**
  990. * Serializes this material
  991. * @returns the serialized material object
  992. */
  993. public serialize(): any {
  994. return SerializationHelper.Serialize(this);
  995. }
  996. /**
  997. * Creates a material from parsed material data
  998. * @param parsedMaterial defines parsed material data
  999. * @param scene defines the hosting scene
  1000. * @param rootUrl defines the root URL to use to load textures
  1001. * @returns a new material
  1002. */
  1003. public static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): Nullable<Material> {
  1004. if (!parsedMaterial.customType) {
  1005. parsedMaterial.customType = "BABYLON.StandardMaterial";
  1006. }
  1007. else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  1008. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  1009. if (!BABYLON.LegacyPBRMaterial) {
  1010. Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  1011. return null;
  1012. }
  1013. }
  1014. var materialType = Tools.Instantiate(parsedMaterial.customType);
  1015. return materialType.Parse(parsedMaterial, scene, rootUrl);
  1016. }
  1017. }