material.ts 35 KB

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