babylon.material.ts 43 KB

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