pbrSubSurfaceConfiguration.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import { Nullable } from "../../types";
  2. import { IAnimatable } from "../../Misc/tools";
  3. import { SerializationHelper, serialize, serializeAsTexture, expandToProperty, serializeAsColor3 } from "../../Misc/decorators";
  4. import { Color3 } from "../../Maths/math";
  5. import { SmartArray } from "../../Misc/smartArray";
  6. import { BaseTexture } from "../../Materials/Textures/baseTexture";
  7. import { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
  8. import { Effect, EffectFallbacks } from "../../Materials/effect";
  9. import { MaterialFlags } from "../materialFlags";
  10. import { UniformBuffer } from "../../Materials/uniformBuffer";
  11. import { MaterialHelper } from "../../Materials/materialHelper";
  12. declare type Engine = import("../../Engines/engine").Engine;
  13. declare type Scene = import("../../scene").Scene;
  14. /**
  15. * @hidden
  16. */
  17. export interface IMaterialSubSurfaceDefines {
  18. SUBSURFACE: boolean;
  19. SS_REFRACTION: boolean;
  20. SS_TRANSLUCENCY: boolean;
  21. SS_SCATERRING: boolean;
  22. SS_THICKNESSANDMASK_TEXTURE: boolean;
  23. SS_THICKNESSANDMASK_TEXTUREDIRECTUV: number;
  24. SS_REFRACTIONMAP_3D: boolean;
  25. SS_REFRACTIONMAP_OPPOSITEZ: boolean;
  26. SS_LODINREFRACTIONALPHA: boolean;
  27. SS_GAMMAREFRACTION: boolean;
  28. SS_RGBDREFRACTION: boolean;
  29. SS_LINKREFRACTIONTOTRANSPARENCY: boolean;
  30. SS_MASK_FROM_THICKNESS_TEXTURE: boolean;
  31. /** @hidden */
  32. _areTexturesDirty: boolean;
  33. }
  34. /**
  35. * Define the code related to the sub surface parameters of the pbr material.
  36. */
  37. export class PBRSubSurfaceConfiguration {
  38. @serialize()
  39. private _isRefractionEnabled = false;
  40. /**
  41. * Defines if the refraction is enabled in the material.
  42. */
  43. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44. public isRefractionEnabled = false;
  45. @serialize()
  46. private _isTranslucencyEnabled = false;
  47. /**
  48. * Defines if the translucency is enabled in the material.
  49. */
  50. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  51. public isTranslucencyEnabled = false;
  52. @serialize()
  53. private _isScatteringEnabled = false;
  54. // /**
  55. // * Defines if the sub surface scattering is enabled in the material.
  56. // */
  57. // @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  58. // public isScatteringEnabled = false;
  59. /**
  60. * Defines the refraction intensity of the material.
  61. * The refraction when enabled replaces the Diffuse part of the material.
  62. * The intensity helps transitionning between diffuse and refraction.
  63. */
  64. @serialize()
  65. public refractionIntensity: number = 1;
  66. /**
  67. * Defines the translucency intensity of the material.
  68. * When translucency has been enabled, this defines how much of the "translucency"
  69. * is addded to the diffuse part of the material.
  70. */
  71. @serialize()
  72. public translucencyIntensity: number = 1;
  73. /**
  74. * Defines the scattering intensity of the material.
  75. * When scattering has been enabled, this defines how much of the "scattered light"
  76. * is addded to the diffuse part of the material.
  77. */
  78. @serialize()
  79. public scatteringIntensity: number = 1;
  80. @serializeAsTexture()
  81. private _thicknessTexture: Nullable<BaseTexture> = null;
  82. /**
  83. * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly).
  84. * The red channel of the texture should contain the thickness remapped between 0 and 1.
  85. * 0 would mean minimumThickness
  86. * 1 would mean maximumThickness
  87. * The other channels might be use as a mask to vary the different effects intensity.
  88. */
  89. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90. public thicknessTexture: Nullable<BaseTexture> = null;
  91. private _refractionTexture: Nullable<BaseTexture> = null;
  92. /**
  93. * Defines the texture to use for refraction.
  94. */
  95. @serializeAsTexture()
  96. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97. public refractionTexture: Nullable<BaseTexture> = null;
  98. private _indexOfRefraction = 1;
  99. /**
  100. * Defines the indice of refraction used in the material.
  101. * https://en.wikipedia.org/wiki/List_of_refractive_indices
  102. */
  103. @serialize()
  104. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105. public indexOfRefraction = 1;
  106. private _invertRefractionY = false;
  107. /**
  108. * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
  109. */
  110. @serialize()
  111. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112. public invertRefractionY = false;
  113. private _linkRefractionWithTransparency = false;
  114. /**
  115. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  116. * Materials half opaque for instance using refraction could benefit from this control.
  117. */
  118. @serialize()
  119. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  120. public linkRefractionWithTransparency = false;
  121. /**
  122. * Defines the minimum thickness stored in the thickness map.
  123. * If no thickness map is defined, this value will be used to simulate thickness.
  124. */
  125. @serialize()
  126. public minimumThickness: number = 0;
  127. /**
  128. * Defines the maximum thickness stored in the thickness map.
  129. */
  130. @serialize()
  131. public maximumThickness: number = 1;
  132. /**
  133. * Defines the volume tint of the material.
  134. * This is used for both translucency and scattering.
  135. */
  136. @serializeAsColor3()
  137. public tintColor = Color3.White();
  138. /**
  139. * Defines the distance at which the tint color should be found in the media.
  140. * This is used for refraction only.
  141. */
  142. @serialize()
  143. public tintColorAtDistance = 1;
  144. /**
  145. * Defines how far each channel transmit through the media.
  146. * It is defined as a color to simplify it selection.
  147. */
  148. @serializeAsColor3()
  149. public diffusionDistance = Color3.White();
  150. @serialize()
  151. private _useMaskFromThicknessTexture = false;
  152. /**
  153. * Stores the intensity of the different subsurface effects in the thickness texture.
  154. * * the green channel is the translucency intensity.
  155. * * the blue channel is the scattering intensity.
  156. * * the alpha channel is the refraction intensity.
  157. */
  158. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  159. public useMaskFromThicknessTexture: boolean = false;
  160. /** @hidden */
  161. private _internalMarkAllSubMeshesAsTexturesDirty: () => void;
  162. /** @hidden */
  163. public _markAllSubMeshesAsTexturesDirty(): void {
  164. this._internalMarkAllSubMeshesAsTexturesDirty();
  165. }
  166. /**
  167. * Instantiate a new istance of sub surface configuration.
  168. * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty
  169. */
  170. constructor(markAllSubMeshesAsTexturesDirty: () => void) {
  171. this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty;
  172. }
  173. /**
  174. * Gets wehter the submesh is ready to be used or not.
  175. * @param defines the list of "defines" to update.
  176. * @param scene defines the scene the material belongs to.
  177. * @returns - boolean indicating that the submesh is ready or not.
  178. */
  179. public isReadyForSubMesh(defines: IMaterialSubSurfaceDefines, scene: Scene): boolean {
  180. if (defines._areTexturesDirty) {
  181. if (scene.texturesEnabled) {
  182. if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
  183. if (!this._thicknessTexture.isReadyOrNotBlocking()) {
  184. return false;
  185. }
  186. }
  187. var refractionTexture = this._getRefractionTexture(scene);
  188. if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
  189. if (!refractionTexture.isReadyOrNotBlocking()) {
  190. return false;
  191. }
  192. }
  193. }
  194. }
  195. return true;
  196. }
  197. /**
  198. * Checks to see if a texture is used in the material.
  199. * @param defines the list of "defines" to update.
  200. * @param scene defines the scene to the material belongs to.
  201. */
  202. public prepareDefines(defines: IMaterialSubSurfaceDefines, scene: Scene): void {
  203. if (defines._areTexturesDirty) {
  204. defines.SUBSURFACE = false;
  205. defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;
  206. defines.SS_SCATERRING = this._isScatteringEnabled;
  207. defines.SS_THICKNESSANDMASK_TEXTURE = false;
  208. defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;
  209. defines.SS_REFRACTION = false;
  210. defines.SS_REFRACTIONMAP_3D = false;
  211. defines.SS_GAMMAREFRACTION = false;
  212. defines.SS_RGBDREFRACTION = false;
  213. defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
  214. defines.SS_LODINREFRACTIONALPHA = false;
  215. defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
  216. if (this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled) {
  217. defines.SUBSURFACE = true;
  218. if (defines._areTexturesDirty) {
  219. if (scene.texturesEnabled) {
  220. if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
  221. MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE");
  222. }
  223. }
  224. }
  225. defines.SS_MASK_FROM_THICKNESS_TEXTURE = this._useMaskFromThicknessTexture;
  226. }
  227. if (this._isRefractionEnabled) {
  228. if (scene.texturesEnabled) {
  229. var refractionTexture = this._getRefractionTexture(scene);
  230. if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
  231. defines.SS_REFRACTION = true;
  232. defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;
  233. defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;
  234. defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;
  235. defines.SS_REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  236. defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  237. defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;
  238. }
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Binds the material data.
  245. * @param uniformBuffer defines the Uniform buffer to fill in.
  246. * @param scene defines the scene the material belongs to.
  247. * @param engine defines the engine the material belongs to.
  248. * @param isFrozen defines wether the material is frozen or not.
  249. * @param lodBasedMicrosurface defines wether the material relies on lod based microsurface or not.
  250. */
  251. public bindForSubMesh(uniformBuffer: UniformBuffer, scene: Scene, engine: Engine, isFrozen: boolean, lodBasedMicrosurface: boolean): void {
  252. var refractionTexture = this._getRefractionTexture(scene);
  253. if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
  254. if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
  255. uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);
  256. MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness");
  257. }
  258. uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness, this.maximumThickness - this.minimumThickness);
  259. if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
  260. uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  261. var depth = 1.0;
  262. if (!refractionTexture.isCube) {
  263. if ((<any>refractionTexture).depth) {
  264. depth = (<any>refractionTexture).depth;
  265. }
  266. }
  267. uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  268. uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",
  269. refractionTexture.getSize().width,
  270. refractionTexture.lodGenerationScale,
  271. refractionTexture.lodGenerationOffset);
  272. }
  273. uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance);
  274. uniformBuffer.updateFloat4("vTintColor", this.tintColor.r,
  275. this.tintColor.g,
  276. this.tintColor.b,
  277. this.tintColorAtDistance);
  278. uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, this.scatteringIntensity);
  279. }
  280. // Textures
  281. if (scene.texturesEnabled) {
  282. if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
  283. uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture);
  284. }
  285. if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
  286. if (lodBasedMicrosurface) {
  287. uniformBuffer.setTexture("refractionSampler", refractionTexture);
  288. }
  289. else {
  290. uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  291. uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  292. uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  293. }
  294. }
  295. }
  296. }
  297. /**
  298. * Unbinds the material from the mesh.
  299. * @param activeEffect defines the effect that should be unbound from.
  300. * @returns true if unbound, otherwise false
  301. */
  302. public unbind(activeEffect: Effect): boolean {
  303. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  304. activeEffect.setTexture("refractionSampler", null);
  305. return true;
  306. }
  307. return false;
  308. }
  309. /**
  310. * Returns the texture used for refraction or null if none is used.
  311. * @param scene defines the scene the material belongs to.
  312. * @returns - Refraction texture if present. If no refraction texture and refraction
  313. * is linked with transparency, returns environment texture. Otherwise, returns null.
  314. */
  315. private _getRefractionTexture(scene: Scene): Nullable<BaseTexture> {
  316. if (this._refractionTexture) {
  317. return this._refractionTexture;
  318. }
  319. if (this._linkRefractionWithTransparency) {
  320. return scene.environmentTexture;
  321. }
  322. return null;
  323. }
  324. /**
  325. * Returns true if alpha blending should be disabled.
  326. */
  327. public get disableAlphaBlending(): boolean {
  328. return this._linkRefractionWithTransparency;
  329. }
  330. /**
  331. * Fills the list of render target textures.
  332. * @param renderTargets the list of render targets to update
  333. */
  334. public fillRenderTargetTextures(renderTargets: SmartArray<RenderTargetTexture>): void {
  335. if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  336. renderTargets.push(<RenderTargetTexture>this._refractionTexture);
  337. }
  338. }
  339. /**
  340. * Checks to see if a texture is used in the material.
  341. * @param texture - Base texture to use.
  342. * @returns - Boolean specifying if a texture is used in the material.
  343. */
  344. public hasTexture(texture: BaseTexture): boolean {
  345. if (this._thicknessTexture === texture) {
  346. return true;
  347. }
  348. if (this._refractionTexture === texture) {
  349. return true;
  350. }
  351. return false;
  352. }
  353. /**
  354. * Gets a boolean indicating that current material needs to register RTT
  355. * @returns true if this uses a render target otherwise false.
  356. */
  357. public hasRenderTargetTextures(): boolean {
  358. if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  359. return true;
  360. }
  361. return false;
  362. }
  363. /**
  364. * Returns an array of the actively used textures.
  365. * @param activeTextures Array of BaseTextures
  366. */
  367. public getActiveTextures(activeTextures: BaseTexture[]): void {
  368. if (this._thicknessTexture) {
  369. activeTextures.push(this._thicknessTexture);
  370. }
  371. if (this._refractionTexture) {
  372. activeTextures.push(this._refractionTexture);
  373. }
  374. }
  375. /**
  376. * Returns the animatable textures.
  377. * @param animatables Array of animatable textures.
  378. */
  379. public getAnimatables(animatables: IAnimatable[]): void {
  380. if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
  381. animatables.push(this._thicknessTexture);
  382. }
  383. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  384. animatables.push(this._refractionTexture);
  385. }
  386. }
  387. /**
  388. * Disposes the resources of the material.
  389. * @param forceDisposeTextures - Forces the disposal of all textures.
  390. */
  391. public dispose(forceDisposeTextures?: boolean): void {
  392. if (forceDisposeTextures) {
  393. if (this._thicknessTexture) {
  394. this._thicknessTexture.dispose();
  395. }
  396. if (this._refractionTexture) {
  397. this._refractionTexture.dispose();
  398. }
  399. }
  400. }
  401. /**
  402. * Get the current class name of the texture useful for serialization or dynamic coding.
  403. * @returns "PBRSubSurfaceConfiguration"
  404. */
  405. public getClassName(): string {
  406. return "PBRSubSurfaceConfiguration";
  407. }
  408. /**
  409. * Add fallbacks to the effect fallbacks list.
  410. * @param defines defines the Base texture to use.
  411. * @param fallbacks defines the current fallback list.
  412. * @param currentRank defines the current fallback rank.
  413. * @returns the new fallback rank.
  414. */
  415. public static AddFallbacks(defines: IMaterialSubSurfaceDefines, fallbacks: EffectFallbacks, currentRank: number): number {
  416. if (defines.SS_SCATERRING) {
  417. fallbacks.addFallback(currentRank++, "SS_SCATERRING");
  418. }
  419. if (defines.SS_TRANSLUCENCY) {
  420. fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY");
  421. }
  422. return currentRank;
  423. }
  424. /**
  425. * Add the required uniforms to the current list.
  426. * @param uniforms defines the current uniform list.
  427. */
  428. public static AddUniforms(uniforms: string[]): void {
  429. uniforms.push(
  430. "vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity",
  431. "vRefractionMicrosurfaceInfos",
  432. "vRefractionInfos", "vThicknessInfos", "vThicknessParam",
  433. "refractionMatrix", "thicknessMatrix");
  434. }
  435. /**
  436. * Add the required samplers to the current list.
  437. * @param samplers defines the current sampler list.
  438. */
  439. public static AddSamplers(samplers: string[]): void {
  440. samplers.push("thicknessSampler",
  441. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh");
  442. }
  443. /**
  444. * Add the required uniforms to the current buffer.
  445. * @param uniformBuffer defines the current uniform buffer.
  446. */
  447. public static PrepareUniformBuffer(uniformBuffer: UniformBuffer): void {
  448. uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  449. uniformBuffer.addUniform("vRefractionInfos", 4);
  450. uniformBuffer.addUniform("refractionMatrix", 16);
  451. uniformBuffer.addUniform("vThicknessInfos", 2);
  452. uniformBuffer.addUniform("thicknessMatrix", 16);
  453. uniformBuffer.addUniform("vThicknessParam", 2);
  454. uniformBuffer.addUniform("vDiffusionDistance", 3);
  455. uniformBuffer.addUniform("vTintColor", 4);
  456. uniformBuffer.addUniform("vSubSurfaceIntensity", 3);
  457. }
  458. /**
  459. * Makes a duplicate of the current configuration into another one.
  460. * @param configuration define the config where to copy the info
  461. */
  462. public copyTo(configuration: PBRSubSurfaceConfiguration): void {
  463. SerializationHelper.Clone(() => configuration, this);
  464. }
  465. /**
  466. * Serializes this Sub Surface configuration.
  467. * @returns - An object with the serialized config.
  468. */
  469. public serialize(): any {
  470. return SerializationHelper.Serialize(this);
  471. }
  472. /**
  473. * Parses a Sub Surface Configuration from a serialized object.
  474. * @param source - Serialized object.
  475. */
  476. public parse(source: any): void {
  477. SerializationHelper.Parse(() => this, source, null);
  478. }
  479. }