pbrBaseMaterial.ts 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  1. import { serialize, serializeAsImageProcessingConfiguration, expandToProperty } from "../../Misc/decorators";
  2. import { Observer } from "../../Misc/observable";
  3. import { Logger } from "../../Misc/logger";
  4. import { SmartArray } from "../../Misc/smartArray";
  5. import { BRDFTextureTools } from "../../Misc/brdfTextureTools";
  6. import { Nullable } from "../../types";
  7. import { Camera } from "../../Cameras/camera";
  8. import { Scene } from "../../scene";
  9. import { Matrix, Vector4 } from "../../Maths/math.vector";
  10. import { VertexBuffer } from "../../Meshes/buffer";
  11. import { SubMesh } from "../../Meshes/subMesh";
  12. import { AbstractMesh } from "../../Meshes/abstractMesh";
  13. import { Mesh } from "../../Meshes/mesh";
  14. import { IMaterialClearCoatDefines, PBRClearCoatConfiguration } from "./pbrClearCoatConfiguration";
  15. import { IMaterialAnisotropicDefines, PBRAnisotropicConfiguration } from "./pbrAnisotropicConfiguration";
  16. import { IMaterialBRDFDefines, PBRBRDFConfiguration } from "./pbrBRDFConfiguration";
  17. import { IMaterialSheenDefines, PBRSheenConfiguration } from "./pbrSheenConfiguration";
  18. import { IMaterialSubSurfaceDefines, PBRSubSurfaceConfiguration } from "./pbrSubSurfaceConfiguration";
  19. import { Color3, TmpColors } from '../../Maths/math.color';
  20. import { Scalar } from "../../Maths/math.scalar";
  21. import { ImageProcessingConfiguration, IImageProcessingConfigurationDefines } from "../../Materials/imageProcessingConfiguration";
  22. import { Effect, IEffectCreationOptions } from "../../Materials/effect";
  23. import { Material, IMaterialCompilationOptions, ICustomShaderNameResolveOptions } from "../../Materials/material";
  24. import { MaterialDefines } from "../../Materials/materialDefines";
  25. import { PushMaterial } from "../../Materials/pushMaterial";
  26. import { MaterialHelper } from "../../Materials/materialHelper";
  27. import { BaseTexture } from "../../Materials/Textures/baseTexture";
  28. import { Texture } from "../../Materials/Textures/texture";
  29. import { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
  30. import { CubeTexture } from "../../Materials/Textures/cubeTexture";
  31. import { MaterialFlags } from "../materialFlags";
  32. import { Constants } from "../../Engines/constants";
  33. import { IAnimatable } from '../../Animations/animatable.interface';
  34. import "../../Materials/Textures/baseTexture.polynomial";
  35. import "../../Shaders/pbr.fragment";
  36. import "../../Shaders/pbr.vertex";
  37. import { EffectFallbacks } from '../effectFallbacks';
  38. import { IMaterialDetailMapDefines, DetailMapConfiguration } from '../material.detailMapConfiguration';
  39. declare type PrePassRenderer = import("../../Rendering/prePassRenderer").PrePassRenderer;
  40. const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
  41. /**
  42. * Manages the defines for the PBR Material.
  43. * @hidden
  44. */
  45. export class PBRMaterialDefines extends MaterialDefines
  46. implements IImageProcessingConfigurationDefines,
  47. IMaterialClearCoatDefines,
  48. IMaterialAnisotropicDefines,
  49. IMaterialBRDFDefines,
  50. IMaterialSheenDefines,
  51. IMaterialSubSurfaceDefines,
  52. IMaterialDetailMapDefines {
  53. public PBR = true;
  54. public NUM_SAMPLES = "0";
  55. public REALTIME_FILTERING = false;
  56. public MAINUV1 = false;
  57. public MAINUV2 = false;
  58. public UV1 = false;
  59. public UV2 = false;
  60. public ALBEDO = false;
  61. public GAMMAALBEDO = false;
  62. public ALBEDODIRECTUV = 0;
  63. public VERTEXCOLOR = false;
  64. public DETAIL = false;
  65. public DETAILDIRECTUV = 0;
  66. public DETAIL_NORMALBLENDMETHOD = 0;
  67. public AMBIENT = false;
  68. public AMBIENTDIRECTUV = 0;
  69. public AMBIENTINGRAYSCALE = false;
  70. public OPACITY = false;
  71. public VERTEXALPHA = false;
  72. public OPACITYDIRECTUV = 0;
  73. public OPACITYRGB = false;
  74. public ALPHATEST = false;
  75. public DEPTHPREPASS = false;
  76. public ALPHABLEND = false;
  77. public ALPHAFROMALBEDO = false;
  78. public ALPHATESTVALUE = "0.5";
  79. public SPECULAROVERALPHA = false;
  80. public RADIANCEOVERALPHA = false;
  81. public ALPHAFRESNEL = false;
  82. public LINEARALPHAFRESNEL = false;
  83. public PREMULTIPLYALPHA = false;
  84. public EMISSIVE = false;
  85. public EMISSIVEDIRECTUV = 0;
  86. public REFLECTIVITY = false;
  87. public REFLECTIVITYDIRECTUV = 0;
  88. public SPECULARTERM = false;
  89. public MICROSURFACEFROMREFLECTIVITYMAP = false;
  90. public MICROSURFACEAUTOMATIC = false;
  91. public LODBASEDMICROSFURACE = false;
  92. public MICROSURFACEMAP = false;
  93. public MICROSURFACEMAPDIRECTUV = 0;
  94. public METALLICWORKFLOW = false;
  95. public ROUGHNESSSTOREINMETALMAPALPHA = false;
  96. public ROUGHNESSSTOREINMETALMAPGREEN = false;
  97. public METALLNESSSTOREINMETALMAPBLUE = false;
  98. public AOSTOREINMETALMAPRED = false;
  99. public METALLIC_REFLECTANCE = false;
  100. public METALLIC_REFLECTANCEDIRECTUV = 0;
  101. public ENVIRONMENTBRDF = false;
  102. public ENVIRONMENTBRDF_RGBD = false;
  103. public NORMAL = false;
  104. public TANGENT = false;
  105. public BUMP = false;
  106. public BUMPDIRECTUV = 0;
  107. public OBJECTSPACE_NORMALMAP = false;
  108. public PARALLAX = false;
  109. public PARALLAXOCCLUSION = false;
  110. public NORMALXYSCALE = true;
  111. public LIGHTMAP = false;
  112. public LIGHTMAPDIRECTUV = 0;
  113. public USELIGHTMAPASSHADOWMAP = false;
  114. public GAMMALIGHTMAP = false;
  115. public RGBDLIGHTMAP = false;
  116. public REFLECTION = false;
  117. public REFLECTIONMAP_3D = false;
  118. public REFLECTIONMAP_SPHERICAL = false;
  119. public REFLECTIONMAP_PLANAR = false;
  120. public REFLECTIONMAP_CUBIC = false;
  121. public USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  122. public REFLECTIONMAP_PROJECTION = false;
  123. public REFLECTIONMAP_SKYBOX = false;
  124. public REFLECTIONMAP_EXPLICIT = false;
  125. public REFLECTIONMAP_EQUIRECTANGULAR = false;
  126. public REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  127. public REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  128. public INVERTCUBICMAP = false;
  129. public USESPHERICALFROMREFLECTIONMAP = false;
  130. public USEIRRADIANCEMAP = false;
  131. public SPHERICAL_HARMONICS = false;
  132. public USESPHERICALINVERTEX = false;
  133. public REFLECTIONMAP_OPPOSITEZ = false;
  134. public LODINREFLECTIONALPHA = false;
  135. public GAMMAREFLECTION = false;
  136. public RGBDREFLECTION = false;
  137. public LINEARSPECULARREFLECTION = false;
  138. public RADIANCEOCCLUSION = false;
  139. public HORIZONOCCLUSION = false;
  140. public INSTANCES = false;
  141. public THIN_INSTANCES = false;
  142. public PREPASS = false;
  143. public PREPASS_IRRADIANCE = false;
  144. public PREPASS_IRRADIANCE_INDEX = -1;
  145. public PREPASS_ALBEDO = false;
  146. public PREPASS_ALBEDO_INDEX = -1;
  147. public PREPASS_DEPTHNORMAL = false;
  148. public PREPASS_DEPTHNORMAL_INDEX = -1;
  149. public SCENE_MRT_COUNT = 0;
  150. public NUM_BONE_INFLUENCERS = 0;
  151. public BonesPerMesh = 0;
  152. public BONETEXTURE = false;
  153. public NONUNIFORMSCALING = false;
  154. public MORPHTARGETS = false;
  155. public MORPHTARGETS_NORMAL = false;
  156. public MORPHTARGETS_TANGENT = false;
  157. public MORPHTARGETS_UV = false;
  158. public NUM_MORPH_INFLUENCERS = 0;
  159. public IMAGEPROCESSING = false;
  160. public VIGNETTE = false;
  161. public VIGNETTEBLENDMODEMULTIPLY = false;
  162. public VIGNETTEBLENDMODEOPAQUE = false;
  163. public TONEMAPPING = false;
  164. public TONEMAPPING_ACES = false;
  165. public CONTRAST = false;
  166. public COLORCURVES = false;
  167. public COLORGRADING = false;
  168. public COLORGRADING3D = false;
  169. public SAMPLER3DGREENDEPTH = false;
  170. public SAMPLER3DBGRMAP = false;
  171. public IMAGEPROCESSINGPOSTPROCESS = false;
  172. public EXPOSURE = false;
  173. public MULTIVIEW = false;
  174. public USEPHYSICALLIGHTFALLOFF = false;
  175. public USEGLTFLIGHTFALLOFF = false;
  176. public TWOSIDEDLIGHTING = false;
  177. public SHADOWFLOAT = false;
  178. public CLIPPLANE = false;
  179. public CLIPPLANE2 = false;
  180. public CLIPPLANE3 = false;
  181. public CLIPPLANE4 = false;
  182. public CLIPPLANE5 = false;
  183. public CLIPPLANE6 = false;
  184. public POINTSIZE = false;
  185. public FOG = false;
  186. public LOGARITHMICDEPTH = false;
  187. public FORCENORMALFORWARD = false;
  188. public SPECULARAA = false;
  189. public CLEARCOAT = false;
  190. public CLEARCOAT_DEFAULTIOR = false;
  191. public CLEARCOAT_TEXTURE = false;
  192. public CLEARCOAT_TEXTUREDIRECTUV = 0;
  193. public CLEARCOAT_BUMP = false;
  194. public CLEARCOAT_BUMPDIRECTUV = 0;
  195. public CLEARCOAT_TINT = false;
  196. public CLEARCOAT_TINT_TEXTURE = false;
  197. public CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
  198. public ANISOTROPIC = false;
  199. public ANISOTROPIC_TEXTURE = false;
  200. public ANISOTROPIC_TEXTUREDIRECTUV = 0;
  201. public BRDF_V_HEIGHT_CORRELATED = false;
  202. public MS_BRDF_ENERGY_CONSERVATION = false;
  203. public SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;
  204. public SHEEN = false;
  205. public SHEEN_TEXTURE = false;
  206. public SHEEN_TEXTURE_ROUGHNESS = false;
  207. public SHEEN_TEXTUREDIRECTUV = 0;
  208. public SHEEN_LINKWITHALBEDO = false;
  209. public SHEEN_ROUGHNESS = false;
  210. public SHEEN_ALBEDOSCALING = false;
  211. public SHEEN_USE_ROUGHNESS_FROM_TEXTURE = false;
  212. public SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false;
  213. public SUBSURFACE = false;
  214. public SS_REFRACTION = false;
  215. public SS_TRANSLUCENCY = false;
  216. public SS_SCATTERING = false;
  217. public SS_THICKNESSANDMASK_TEXTURE = false;
  218. public SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
  219. public SS_REFRACTIONMAP_3D = false;
  220. public SS_REFRACTIONMAP_OPPOSITEZ = false;
  221. public SS_LODINREFRACTIONALPHA = false;
  222. public SS_GAMMAREFRACTION = false;
  223. public SS_RGBDREFRACTION = false;
  224. public SS_LINEARSPECULARREFRACTION = false;
  225. public SS_LINKREFRACTIONTOTRANSPARENCY = false;
  226. public SS_ALBEDOFORREFRACTIONTINT = false;
  227. public SS_MASK_FROM_THICKNESS_TEXTURE = false;
  228. public UNLIT = false;
  229. public DEBUGMODE = 0;
  230. /**
  231. * Initializes the PBR Material defines.
  232. */
  233. constructor() {
  234. super();
  235. this.rebuild();
  236. }
  237. /**
  238. * Resets the PBR Material defines.
  239. */
  240. public reset(): void {
  241. super.reset();
  242. this.ALPHATESTVALUE = "0.5";
  243. this.PBR = true;
  244. }
  245. }
  246. /**
  247. * The Physically based material base class of BJS.
  248. *
  249. * This offers the main features of a standard PBR material.
  250. * For more information, please refer to the documentation :
  251. * https://doc.babylonjs.com/how_to/physically_based_rendering
  252. */
  253. export abstract class PBRBaseMaterial extends PushMaterial {
  254. /**
  255. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  256. */
  257. public static readonly PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE;
  258. /**
  259. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  260. */
  261. public static readonly PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST;
  262. /**
  263. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  264. */
  265. public static readonly PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND;
  266. /**
  267. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  268. * They are also discarded below the alpha cutoff threshold to improve performances.
  269. */
  270. public static readonly PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND;
  271. /**
  272. * Defines the default value of how much AO map is occluding the analytical lights
  273. * (point spot...).
  274. */
  275. public static DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;
  276. /**
  277. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  278. */
  279. public static readonly LIGHTFALLOFF_PHYSICAL = 0;
  280. /**
  281. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  282. * to enhance interoperability with other engines.
  283. */
  284. public static readonly LIGHTFALLOFF_GLTF = 1;
  285. /**
  286. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  287. * to enhance interoperability with other materials.
  288. */
  289. public static readonly LIGHTFALLOFF_STANDARD = 2;
  290. /**
  291. * Intensity of the direct lights e.g. the four lights available in your scene.
  292. * This impacts both the direct diffuse and specular highlights.
  293. */
  294. protected _directIntensity: number = 1.0;
  295. /**
  296. * Intensity of the emissive part of the material.
  297. * This helps controlling the emissive effect without modifying the emissive color.
  298. */
  299. protected _emissiveIntensity: number = 1.0;
  300. /**
  301. * Intensity of the environment e.g. how much the environment will light the object
  302. * either through harmonics for rough material or through the refelction for shiny ones.
  303. */
  304. protected _environmentIntensity: number = 1.0;
  305. /**
  306. * This is a special control allowing the reduction of the specular highlights coming from the
  307. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  308. */
  309. protected _specularIntensity: number = 1.0;
  310. /**
  311. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  312. */
  313. private _lightingInfos: Vector4 = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);
  314. /**
  315. * Debug Control allowing disabling the bump map on this material.
  316. */
  317. protected _disableBumpMap: boolean = false;
  318. /**
  319. * AKA Diffuse Texture in standard nomenclature.
  320. */
  321. protected _albedoTexture: Nullable<BaseTexture> = null;
  322. /**
  323. * AKA Occlusion Texture in other nomenclature.
  324. */
  325. protected _ambientTexture: Nullable<BaseTexture> = null;
  326. /**
  327. * AKA Occlusion Texture Intensity in other nomenclature.
  328. */
  329. protected _ambientTextureStrength: number = 1.0;
  330. /**
  331. * Defines how much the AO map is occluding the analytical lights (point spot...).
  332. * 1 means it completely occludes it
  333. * 0 mean it has no impact
  334. */
  335. protected _ambientTextureImpactOnAnalyticalLights: number = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  336. /**
  337. * Stores the alpha values in a texture.
  338. */
  339. protected _opacityTexture: Nullable<BaseTexture> = null;
  340. /**
  341. * Stores the reflection values in a texture.
  342. */
  343. protected _reflectionTexture: Nullable<BaseTexture> = null;
  344. /**
  345. * Stores the emissive values in a texture.
  346. */
  347. protected _emissiveTexture: Nullable<BaseTexture> = null;
  348. /**
  349. * AKA Specular texture in other nomenclature.
  350. */
  351. protected _reflectivityTexture: Nullable<BaseTexture> = null;
  352. /**
  353. * Used to switch from specular/glossiness to metallic/roughness workflow.
  354. */
  355. protected _metallicTexture: Nullable<BaseTexture> = null;
  356. /**
  357. * Specifies the metallic scalar of the metallic/roughness workflow.
  358. * Can also be used to scale the metalness values of the metallic texture.
  359. */
  360. protected _metallic: Nullable<number> = null;
  361. /**
  362. * Specifies the roughness scalar of the metallic/roughness workflow.
  363. * Can also be used to scale the roughness values of the metallic texture.
  364. */
  365. protected _roughness: Nullable<number> = null;
  366. /**
  367. * In metallic workflow, specifies an F0 factor to help configuring the material F0.
  368. * By default the indexOfrefraction is used to compute F0;
  369. *
  370. * This is used as a factor against the default reflectance at normal incidence to tweak it.
  371. *
  372. * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;
  373. * F90 = metallicReflectanceColor;
  374. */
  375. protected _metallicF0Factor = 1;
  376. /**
  377. * In metallic workflow, specifies an F90 color to help configuring the material F90.
  378. * By default the F90 is always 1;
  379. *
  380. * Please note that this factor is also used as a factor against the default reflectance at normal incidence.
  381. *
  382. * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor
  383. * F90 = metallicReflectanceColor;
  384. */
  385. protected _metallicReflectanceColor = Color3.White();
  386. /**
  387. * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A
  388. * This is multiply against the scalar values defined in the material.
  389. */
  390. protected _metallicReflectanceTexture: Nullable<BaseTexture> = null;
  391. /**
  392. * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode.
  393. * Gray Scale represents roughness in metallic mode and glossiness in specular mode.
  394. */
  395. protected _microSurfaceTexture: Nullable<BaseTexture> = null;
  396. /**
  397. * Stores surface normal data used to displace a mesh in a texture.
  398. */
  399. protected _bumpTexture: Nullable<BaseTexture> = null;
  400. /**
  401. * Stores the pre-calculated light information of a mesh in a texture.
  402. */
  403. protected _lightmapTexture: Nullable<BaseTexture> = null;
  404. /**
  405. * The color of a material in ambient lighting.
  406. */
  407. protected _ambientColor = new Color3(0, 0, 0);
  408. /**
  409. * AKA Diffuse Color in other nomenclature.
  410. */
  411. protected _albedoColor = new Color3(1, 1, 1);
  412. /**
  413. * AKA Specular Color in other nomenclature.
  414. */
  415. protected _reflectivityColor = new Color3(1, 1, 1);
  416. /**
  417. * The color applied when light is reflected from a material.
  418. */
  419. protected _reflectionColor = new Color3(1, 1, 1);
  420. /**
  421. * The color applied when light is emitted from a material.
  422. */
  423. protected _emissiveColor = new Color3(0, 0, 0);
  424. /**
  425. * AKA Glossiness in other nomenclature.
  426. */
  427. protected _microSurface = 0.9;
  428. /**
  429. * Specifies that the material will use the light map as a show map.
  430. */
  431. protected _useLightmapAsShadowmap = false;
  432. /**
  433. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  434. * makes the reflect vector face the model (under horizon).
  435. */
  436. protected _useHorizonOcclusion = true;
  437. /**
  438. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  439. * too much the area relying on ambient texture to define their ambient occlusion.
  440. */
  441. protected _useRadianceOcclusion = true;
  442. /**
  443. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  444. */
  445. protected _useAlphaFromAlbedoTexture = false;
  446. /**
  447. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  448. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  449. */
  450. protected _useSpecularOverAlpha = true;
  451. /**
  452. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  453. */
  454. protected _useMicroSurfaceFromReflectivityMapAlpha = false;
  455. /**
  456. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  457. */
  458. protected _useRoughnessFromMetallicTextureAlpha = true;
  459. /**
  460. * Specifies if the metallic texture contains the roughness information in its green channel.
  461. */
  462. protected _useRoughnessFromMetallicTextureGreen = false;
  463. /**
  464. * Specifies if the metallic texture contains the metallness information in its blue channel.
  465. */
  466. protected _useMetallnessFromMetallicTextureBlue = false;
  467. /**
  468. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  469. */
  470. protected _useAmbientOcclusionFromMetallicTextureRed = false;
  471. /**
  472. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  473. */
  474. protected _useAmbientInGrayScale = false;
  475. /**
  476. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  477. * The material will try to infer what glossiness each pixel should be.
  478. */
  479. protected _useAutoMicroSurfaceFromReflectivityMap = false;
  480. /**
  481. * Defines the falloff type used in this material.
  482. * It by default is Physical.
  483. */
  484. protected _lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  485. /**
  486. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  487. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  488. */
  489. protected _useRadianceOverAlpha = true;
  490. /**
  491. * Allows using an object space normal map (instead of tangent space).
  492. */
  493. protected _useObjectSpaceNormalMap = false;
  494. /**
  495. * Allows using the bump map in parallax mode.
  496. */
  497. protected _useParallax = false;
  498. /**
  499. * Allows using the bump map in parallax occlusion mode.
  500. */
  501. protected _useParallaxOcclusion = false;
  502. /**
  503. * Controls the scale bias of the parallax mode.
  504. */
  505. protected _parallaxScaleBias = 0.05;
  506. /**
  507. * If sets to true, disables all the lights affecting the material.
  508. */
  509. protected _disableLighting = false;
  510. /**
  511. * Number of Simultaneous lights allowed on the material.
  512. */
  513. protected _maxSimultaneousLights = 4;
  514. /**
  515. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  516. */
  517. protected _invertNormalMapX = false;
  518. /**
  519. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  520. */
  521. protected _invertNormalMapY = false;
  522. /**
  523. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  524. */
  525. protected _twoSidedLighting = false;
  526. /**
  527. * Defines the alpha limits in alpha test mode.
  528. */
  529. protected _alphaCutOff = 0.4;
  530. /**
  531. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  532. */
  533. protected _forceAlphaTest = false;
  534. /**
  535. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  536. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  537. */
  538. protected _useAlphaFresnel = false;
  539. /**
  540. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  541. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  542. */
  543. protected _useLinearAlphaFresnel = false;
  544. /**
  545. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  546. * from cos thetav and roughness:
  547. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  548. */
  549. protected _environmentBRDFTexture: Nullable<BaseTexture> = null;
  550. /**
  551. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  552. */
  553. protected _forceIrradianceInFragment = false;
  554. private _realTimeFiltering: boolean = false;
  555. /**
  556. * Enables realtime filtering on the texture.
  557. */
  558. public get realTimeFiltering() {
  559. return this._realTimeFiltering;
  560. }
  561. public set realTimeFiltering(b: boolean) {
  562. this._realTimeFiltering = b;
  563. this.markAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  564. }
  565. private _realTimeFilteringQuality: number = Constants.TEXTURE_FILTERING_QUALITY_LOW;
  566. /**
  567. * Quality switch for realtime filtering
  568. */
  569. public get realTimeFilteringQuality() : number {
  570. return this._realTimeFilteringQuality;
  571. }
  572. public set realTimeFilteringQuality(n: number) {
  573. this._realTimeFilteringQuality = n;
  574. this.markAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  575. }
  576. /**
  577. * Can this material render to several textures at once
  578. */
  579. public get canRenderToMRT() {
  580. return true;
  581. }
  582. /**
  583. * Force normal to face away from face.
  584. */
  585. protected _forceNormalForward = false;
  586. /**
  587. * Enables specular anti aliasing in the PBR shader.
  588. * It will both interacts on the Geometry for analytical and IBL lighting.
  589. * It also prefilter the roughness map based on the bump values.
  590. */
  591. protected _enableSpecularAntiAliasing = false;
  592. /**
  593. * Default configuration related to image processing available in the PBR Material.
  594. */
  595. @serializeAsImageProcessingConfiguration()
  596. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  597. /**
  598. * Keep track of the image processing observer to allow dispose and replace.
  599. */
  600. private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>> = null;
  601. /**
  602. * Attaches a new image processing configuration to the PBR Material.
  603. * @param configuration
  604. */
  605. protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
  606. if (configuration === this._imageProcessingConfiguration) {
  607. return;
  608. }
  609. // Detaches observer.
  610. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  611. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  612. }
  613. // Pick the scene configuration if needed.
  614. if (!configuration) {
  615. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  616. }
  617. else {
  618. this._imageProcessingConfiguration = configuration;
  619. }
  620. // Attaches observer.
  621. if (this._imageProcessingConfiguration) {
  622. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
  623. this._markAllSubMeshesAsImageProcessingDirty();
  624. });
  625. }
  626. }
  627. /**
  628. * Stores the available render targets.
  629. */
  630. private _renderTargets = new SmartArray<RenderTargetTexture>(16);
  631. /**
  632. * Sets the global ambient color for the material used in lighting calculations.
  633. */
  634. private _globalAmbientColor = new Color3(0, 0, 0);
  635. /**
  636. * Enables the use of logarithmic depth buffers, which is good for wide depth buffers.
  637. */
  638. private _useLogarithmicDepth: boolean = false;
  639. /**
  640. * If set to true, no lighting calculations will be applied.
  641. */
  642. private _unlit = false;
  643. private _debugMode = 0;
  644. /**
  645. * @hidden
  646. * This is reserved for the inspector.
  647. * Defines the material debug mode.
  648. * It helps seeing only some components of the material while troubleshooting.
  649. */
  650. @expandToProperty("_markAllSubMeshesAsMiscDirty")
  651. public debugMode = 0;
  652. /**
  653. * @hidden
  654. * This is reserved for the inspector.
  655. * Specify from where on screen the debug mode should start.
  656. * The value goes from -1 (full screen) to 1 (not visible)
  657. * It helps with side by side comparison against the final render
  658. * This defaults to -1
  659. */
  660. private debugLimit = -1;
  661. /**
  662. * @hidden
  663. * This is reserved for the inspector.
  664. * As the default viewing range might not be enough (if the ambient is really small for instance)
  665. * You can use the factor to better multiply the final value.
  666. */
  667. private debugFactor = 1;
  668. /**
  669. * Defines the clear coat layer parameters for the material.
  670. */
  671. public readonly clearCoat = new PBRClearCoatConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this));
  672. /**
  673. * Defines the anisotropic parameters for the material.
  674. */
  675. public readonly anisotropy = new PBRAnisotropicConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this));
  676. /**
  677. * Defines the BRDF parameters for the material.
  678. */
  679. public readonly brdf = new PBRBRDFConfiguration(this._markAllSubMeshesAsMiscDirty.bind(this));
  680. /**
  681. * Defines the Sheen parameters for the material.
  682. */
  683. public readonly sheen = new PBRSheenConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this));
  684. /**
  685. * Defines the SubSurface parameters for the material.
  686. */
  687. public readonly subSurface: PBRSubSurfaceConfiguration;
  688. /**
  689. * Defines the detail map parameters for the material.
  690. */
  691. public readonly detailMap = new DetailMapConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this));
  692. protected _rebuildInParallel = false;
  693. /**
  694. * Instantiates a new PBRMaterial instance.
  695. *
  696. * @param name The material name
  697. * @param scene The scene the material will be use in.
  698. */
  699. constructor(name: string, scene: Scene) {
  700. super(name, scene);
  701. // Setup the default processing configuration to the scene.
  702. this._attachImageProcessingConfiguration(null);
  703. this.getRenderTargetTextures = (): SmartArray<RenderTargetTexture> => {
  704. this._renderTargets.reset();
  705. if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  706. this._renderTargets.push(<RenderTargetTexture>this._reflectionTexture);
  707. }
  708. this.subSurface.fillRenderTargetTextures(this._renderTargets);
  709. return this._renderTargets;
  710. };
  711. this._environmentBRDFTexture = BRDFTextureTools.GetEnvironmentBRDFTexture(scene);
  712. this.subSurface = new PBRSubSurfaceConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this), this._markScenePrePassDirty.bind(this), scene);
  713. }
  714. /**
  715. * Gets a boolean indicating that current material needs to register RTT
  716. */
  717. public get hasRenderTargetTextures(): boolean {
  718. if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  719. return true;
  720. }
  721. return this.subSurface.hasRenderTargetTextures();
  722. }
  723. /**
  724. * Gets the name of the material class.
  725. */
  726. public getClassName(): string {
  727. return "PBRBaseMaterial";
  728. }
  729. /**
  730. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  731. */
  732. @serialize()
  733. public get useLogarithmicDepth(): boolean {
  734. return this._useLogarithmicDepth;
  735. }
  736. /**
  737. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  738. */
  739. public set useLogarithmicDepth(value: boolean) {
  740. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  741. }
  742. /**
  743. * Returns true if alpha blending should be disabled.
  744. */
  745. protected get _disableAlphaBlending(): boolean {
  746. return (this.subSurface.disableAlphaBlending ||
  747. this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE ||
  748. this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
  749. }
  750. /**
  751. * Specifies whether or not this material should be rendered in alpha blend mode.
  752. */
  753. public needAlphaBlending(): boolean {
  754. if (this._disableAlphaBlending) {
  755. return false;
  756. }
  757. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  758. }
  759. /**
  760. * Specifies whether or not this material should be rendered in alpha test mode.
  761. */
  762. public needAlphaTesting(): boolean {
  763. if (this._forceAlphaTest) {
  764. return true;
  765. }
  766. if (this.subSurface.disableAlphaBlending) {
  767. return false;
  768. }
  769. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
  770. }
  771. /**
  772. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  773. */
  774. protected _shouldUseAlphaFromAlbedoTexture(): boolean {
  775. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;
  776. }
  777. /**
  778. * Gets the texture used for the alpha test.
  779. */
  780. public getAlphaTestTexture(): Nullable<BaseTexture> {
  781. return this._albedoTexture;
  782. }
  783. /**
  784. * Specifies that the submesh is ready to be used.
  785. * @param mesh - BJS mesh.
  786. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  787. * @param useInstances - Specifies that instances should be used.
  788. * @returns - boolean indicating that the submesh is ready or not.
  789. */
  790. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  791. if (subMesh.effect && this.isFrozen) {
  792. if (subMesh.effect._wasPreviouslyReady) {
  793. return true;
  794. }
  795. }
  796. if (!subMesh._materialDefines) {
  797. subMesh._materialDefines = new PBRMaterialDefines();
  798. }
  799. const defines = <PBRMaterialDefines>subMesh._materialDefines;
  800. if (this._isReadyForSubMesh(subMesh)) {
  801. return true;
  802. }
  803. const scene = this.getScene();
  804. const engine = scene.getEngine();
  805. if (defines._areTexturesDirty) {
  806. if (scene.texturesEnabled) {
  807. if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
  808. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  809. return false;
  810. }
  811. }
  812. if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
  813. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  814. return false;
  815. }
  816. }
  817. if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
  818. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  819. return false;
  820. }
  821. }
  822. var reflectionTexture = this._getReflectionTexture();
  823. if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
  824. if (!reflectionTexture.isReadyOrNotBlocking()) {
  825. return false;
  826. }
  827. if (reflectionTexture.irradianceTexture && !reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {
  828. return false;
  829. }
  830. }
  831. if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
  832. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  833. return false;
  834. }
  835. }
  836. if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
  837. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  838. return false;
  839. }
  840. }
  841. if (MaterialFlags.SpecularTextureEnabled) {
  842. if (this._metallicTexture) {
  843. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  844. return false;
  845. }
  846. }
  847. else if (this._reflectivityTexture) {
  848. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  849. return false;
  850. }
  851. }
  852. if (this._metallicReflectanceTexture) {
  853. if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {
  854. return false;
  855. }
  856. }
  857. if (this._microSurfaceTexture) {
  858. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  859. return false;
  860. }
  861. }
  862. }
  863. if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
  864. // Bump texture cannot be not blocking.
  865. if (!this._bumpTexture.isReady()) {
  866. return false;
  867. }
  868. }
  869. if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
  870. // This is blocking.
  871. if (!this._environmentBRDFTexture.isReady()) {
  872. return false;
  873. }
  874. }
  875. }
  876. }
  877. if (!this.subSurface.isReadyForSubMesh(defines, scene) ||
  878. !this.clearCoat.isReadyForSubMesh(defines, scene, engine, this._disableBumpMap) ||
  879. !this.sheen.isReadyForSubMesh(defines, scene) ||
  880. !this.anisotropy.isReadyForSubMesh(defines, scene) ||
  881. !this.detailMap.isReadyForSubMesh(defines, scene)) {
  882. return false;
  883. }
  884. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  885. if (!this._imageProcessingConfiguration.isReady()) {
  886. return false;
  887. }
  888. }
  889. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  890. mesh.createNormals(true);
  891. Logger.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  892. }
  893. const previousEffect = subMesh.effect;
  894. const lightDisposed = defines._areLightsDisposed;
  895. let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
  896. if (effect) {
  897. if (this._onEffectCreatedObservable) {
  898. onCreatedEffectParameters.effect = effect;
  899. onCreatedEffectParameters.subMesh = subMesh;
  900. this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
  901. }
  902. // Use previous effect while new one is compiling
  903. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  904. effect = previousEffect;
  905. this._rebuildInParallel = true;
  906. defines.markAsUnprocessed();
  907. if (lightDisposed) {
  908. // re register in case it takes more than one frame.
  909. defines._areLightsDisposed = true;
  910. return false;
  911. }
  912. } else {
  913. this._rebuildInParallel = false;
  914. scene.resetCachedMaterial();
  915. subMesh.setEffect(effect, defines);
  916. this.buildUniformLayout();
  917. }
  918. }
  919. if (!subMesh.effect || !subMesh.effect.isReady()) {
  920. return false;
  921. }
  922. defines._renderId = scene.getRenderId();
  923. subMesh.effect._wasPreviouslyReady = true;
  924. return true;
  925. }
  926. /**
  927. * Specifies if the material uses metallic roughness workflow.
  928. * @returns boolean specifiying if the material uses metallic roughness workflow.
  929. */
  930. public isMetallicWorkflow(): boolean {
  931. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  932. return true;
  933. }
  934. return false;
  935. }
  936. private _prepareEffect(mesh: AbstractMesh, defines: PBRMaterialDefines, onCompiled: Nullable<(effect: Effect) => void> = null, onError: Nullable<(effect: Effect, errors: string) => void> = null,
  937. useInstances: Nullable<boolean> = null, useClipPlane: Nullable<boolean> = null, useThinInstances: boolean): Nullable<Effect> {
  938. this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);
  939. if (!defines.isDirty) {
  940. return null;
  941. }
  942. defines.markAsProcessed();
  943. const scene = this.getScene();
  944. const engine = scene.getEngine();
  945. // Fallbacks
  946. var fallbacks = new EffectFallbacks();
  947. var fallbackRank = 0;
  948. if (defines.USESPHERICALINVERTEX) {
  949. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  950. }
  951. if (defines.FOG) {
  952. fallbacks.addFallback(fallbackRank, "FOG");
  953. }
  954. if (defines.SPECULARAA) {
  955. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  956. }
  957. if (defines.POINTSIZE) {
  958. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  959. }
  960. if (defines.LOGARITHMICDEPTH) {
  961. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  962. }
  963. if (defines.PARALLAX) {
  964. fallbacks.addFallback(fallbackRank, "PARALLAX");
  965. }
  966. if (defines.PARALLAXOCCLUSION) {
  967. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  968. }
  969. fallbackRank = PBRAnisotropicConfiguration.AddFallbacks(defines, fallbacks, fallbackRank);
  970. fallbackRank = PBRAnisotropicConfiguration.AddFallbacks(defines, fallbacks, fallbackRank);
  971. fallbackRank = PBRSubSurfaceConfiguration.AddFallbacks(defines, fallbacks, fallbackRank);
  972. fallbackRank = PBRSheenConfiguration.AddFallbacks(defines, fallbacks, fallbackRank);
  973. if (defines.ENVIRONMENTBRDF) {
  974. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  975. }
  976. if (defines.TANGENT) {
  977. fallbacks.addFallback(fallbackRank++, "TANGENT");
  978. }
  979. if (defines.BUMP) {
  980. fallbacks.addFallback(fallbackRank++, "BUMP");
  981. }
  982. fallbackRank = MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  983. if (defines.SPECULARTERM) {
  984. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  985. }
  986. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  987. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  988. }
  989. if (defines.USEIRRADIANCEMAP) {
  990. fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP");
  991. }
  992. if (defines.LIGHTMAP) {
  993. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  994. }
  995. if (defines.NORMAL) {
  996. fallbacks.addFallback(fallbackRank++, "NORMAL");
  997. }
  998. if (defines.AMBIENT) {
  999. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  1000. }
  1001. if (defines.EMISSIVE) {
  1002. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  1003. }
  1004. if (defines.VERTEXCOLOR) {
  1005. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  1006. }
  1007. if (defines.MORPHTARGETS) {
  1008. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  1009. }
  1010. if (defines.MULTIVIEW) {
  1011. fallbacks.addFallback(0, "MULTIVIEW");
  1012. }
  1013. //Attributes
  1014. var attribs = [VertexBuffer.PositionKind];
  1015. if (defines.NORMAL) {
  1016. attribs.push(VertexBuffer.NormalKind);
  1017. }
  1018. if (defines.TANGENT) {
  1019. attribs.push(VertexBuffer.TangentKind);
  1020. }
  1021. if (defines.UV1) {
  1022. attribs.push(VertexBuffer.UVKind);
  1023. }
  1024. if (defines.UV2) {
  1025. attribs.push(VertexBuffer.UV2Kind);
  1026. }
  1027. if (defines.VERTEXCOLOR) {
  1028. attribs.push(VertexBuffer.ColorKind);
  1029. }
  1030. MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  1031. MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  1032. MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  1033. var shaderName = "pbr";
  1034. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vMetallicReflectanceFactors", "vEmissiveColor", "visibility", "vReflectionColor",
  1035. "vFogInfos", "vFogColor", "pointSize",
  1036. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos", "vReflectionFilteringInfo", "vMetallicReflectanceInfos",
  1037. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos",
  1038. "mBones",
  1039. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "metallicReflectanceMatrix",
  1040. "vLightingIntensity",
  1041. "logarithmicDepthConstant",
  1042. "vSphericalX", "vSphericalY", "vSphericalZ",
  1043. "vSphericalXX_ZZ", "vSphericalYY_ZZ", "vSphericalZZ",
  1044. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  1045. "vSphericalL00",
  1046. "vSphericalL1_1", "vSphericalL10", "vSphericalL11",
  1047. "vSphericalL2_2", "vSphericalL2_1", "vSphericalL20", "vSphericalL21", "vSphericalL22",
  1048. "vReflectionMicrosurfaceInfos",
  1049. "vTangentSpaceParams", "boneTextureWidth",
  1050. "vDebugMode"
  1051. ];
  1052. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  1053. "bumpSampler", "lightmapSampler", "opacitySampler",
  1054. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler",
  1055. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler", "metallicReflectanceSampler"];
  1056. var uniformBuffers = ["Material", "Scene"];
  1057. DetailMapConfiguration.AddUniforms(uniforms);
  1058. DetailMapConfiguration.AddSamplers(samplers);
  1059. PBRSubSurfaceConfiguration.AddUniforms(uniforms);
  1060. PBRSubSurfaceConfiguration.AddSamplers(samplers);
  1061. PBRClearCoatConfiguration.AddUniforms(uniforms);
  1062. PBRClearCoatConfiguration.AddSamplers(samplers);
  1063. PBRAnisotropicConfiguration.AddUniforms(uniforms);
  1064. PBRAnisotropicConfiguration.AddSamplers(samplers);
  1065. PBRSheenConfiguration.AddUniforms(uniforms);
  1066. PBRSheenConfiguration.AddSamplers(samplers);
  1067. if (ImageProcessingConfiguration) {
  1068. ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  1069. ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  1070. }
  1071. MaterialHelper.PrepareUniformsAndSamplersList(<IEffectCreationOptions>{
  1072. uniformsNames: uniforms,
  1073. uniformBuffersNames: uniformBuffers,
  1074. samplers: samplers,
  1075. defines: defines,
  1076. maxSimultaneousLights: this._maxSimultaneousLights
  1077. });
  1078. const csnrOptions: ICustomShaderNameResolveOptions = {};
  1079. if (this.customShaderNameResolve) {
  1080. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
  1081. }
  1082. var join = defines.toString();
  1083. return engine.createEffect(shaderName, <IEffectCreationOptions>{
  1084. attributes: attribs,
  1085. uniformsNames: uniforms,
  1086. uniformBuffersNames: uniformBuffers,
  1087. samplers: samplers,
  1088. defines: join,
  1089. fallbacks: fallbacks,
  1090. onCompiled: onCompiled,
  1091. onError: onError,
  1092. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },
  1093. processFinalCode: csnrOptions.processFinalCode,
  1094. multiTarget: defines.PREPASS
  1095. }, engine);
  1096. }
  1097. private _prepareDefines(mesh: AbstractMesh, defines: PBRMaterialDefines, useInstances: Nullable<boolean> = null, useClipPlane: Nullable<boolean> = null, useThinInstances: boolean = false): void {
  1098. const scene = this.getScene();
  1099. const engine = scene.getEngine();
  1100. // Lights
  1101. MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  1102. defines._needNormals = true;
  1103. // Multiview
  1104. MaterialHelper.PrepareDefinesForMultiview(scene, defines);
  1105. // PrePass
  1106. MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT);
  1107. // Textures
  1108. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  1109. if (defines._areTexturesDirty) {
  1110. defines._needUVs = false;
  1111. if (scene.texturesEnabled) {
  1112. if (scene.getEngine().getCaps().textureLOD) {
  1113. defines.LODBASEDMICROSFURACE = true;
  1114. }
  1115. if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
  1116. MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  1117. defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;
  1118. } else {
  1119. defines.ALBEDO = false;
  1120. }
  1121. if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
  1122. MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  1123. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  1124. } else {
  1125. defines.AMBIENT = false;
  1126. }
  1127. if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
  1128. MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  1129. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  1130. } else {
  1131. defines.OPACITY = false;
  1132. }
  1133. var reflectionTexture = this._getReflectionTexture();
  1134. if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
  1135. defines.REFLECTION = true;
  1136. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  1137. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  1138. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  1139. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  1140. defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;
  1141. if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {
  1142. defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality;
  1143. if (engine.webGLVersion > 1) {
  1144. defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u";
  1145. }
  1146. defines.REALTIME_FILTERING = true;
  1147. } else {
  1148. defines.REALTIME_FILTERING = false;
  1149. }
  1150. if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {
  1151. defines.INVERTCUBICMAP = true;
  1152. }
  1153. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  1154. defines.REFLECTIONMAP_CUBIC = false;
  1155. defines.REFLECTIONMAP_EXPLICIT = false;
  1156. defines.REFLECTIONMAP_PLANAR = false;
  1157. defines.REFLECTIONMAP_PROJECTION = false;
  1158. defines.REFLECTIONMAP_SKYBOX = false;
  1159. defines.REFLECTIONMAP_SPHERICAL = false;
  1160. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  1161. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  1162. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  1163. switch (reflectionTexture.coordinatesMode) {
  1164. case Texture.EXPLICIT_MODE:
  1165. defines.REFLECTIONMAP_EXPLICIT = true;
  1166. break;
  1167. case Texture.PLANAR_MODE:
  1168. defines.REFLECTIONMAP_PLANAR = true;
  1169. break;
  1170. case Texture.PROJECTION_MODE:
  1171. defines.REFLECTIONMAP_PROJECTION = true;
  1172. break;
  1173. case Texture.SKYBOX_MODE:
  1174. defines.REFLECTIONMAP_SKYBOX = true;
  1175. break;
  1176. case Texture.SPHERICAL_MODE:
  1177. defines.REFLECTIONMAP_SPHERICAL = true;
  1178. break;
  1179. case Texture.EQUIRECTANGULAR_MODE:
  1180. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  1181. break;
  1182. case Texture.FIXED_EQUIRECTANGULAR_MODE:
  1183. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  1184. break;
  1185. case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  1186. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  1187. break;
  1188. case Texture.CUBIC_MODE:
  1189. case Texture.INVCUBIC_MODE:
  1190. default:
  1191. defines.REFLECTIONMAP_CUBIC = true;
  1192. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = (<any>reflectionTexture).boundingBoxSize ? true : false;
  1193. break;
  1194. }
  1195. if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
  1196. if (reflectionTexture.irradianceTexture) {
  1197. defines.USEIRRADIANCEMAP = true;
  1198. defines.USESPHERICALFROMREFLECTIONMAP = false;
  1199. }
  1200. // Assume using spherical polynomial if the reflection texture is a cube map
  1201. else if (reflectionTexture.isCube) {
  1202. defines.USESPHERICALFROMREFLECTIONMAP = true;
  1203. defines.USEIRRADIANCEMAP = false;
  1204. if (this._forceIrradianceInFragment || this.realTimeFiltering || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  1205. defines.USESPHERICALINVERTEX = false;
  1206. }
  1207. else {
  1208. defines.USESPHERICALINVERTEX = true;
  1209. }
  1210. }
  1211. }
  1212. } else {
  1213. defines.REFLECTION = false;
  1214. defines.REFLECTIONMAP_3D = false;
  1215. defines.REFLECTIONMAP_SPHERICAL = false;
  1216. defines.REFLECTIONMAP_PLANAR = false;
  1217. defines.REFLECTIONMAP_CUBIC = false;
  1218. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  1219. defines.REFLECTIONMAP_PROJECTION = false;
  1220. defines.REFLECTIONMAP_SKYBOX = false;
  1221. defines.REFLECTIONMAP_EXPLICIT = false;
  1222. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  1223. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  1224. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  1225. defines.INVERTCUBICMAP = false;
  1226. defines.USESPHERICALFROMREFLECTIONMAP = false;
  1227. defines.USEIRRADIANCEMAP = false;
  1228. defines.USESPHERICALINVERTEX = false;
  1229. defines.REFLECTIONMAP_OPPOSITEZ = false;
  1230. defines.LODINREFLECTIONALPHA = false;
  1231. defines.GAMMAREFLECTION = false;
  1232. defines.RGBDREFLECTION = false;
  1233. defines.LINEARSPECULARREFLECTION = false;
  1234. }
  1235. if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
  1236. MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  1237. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  1238. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  1239. defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
  1240. } else {
  1241. defines.LIGHTMAP = false;
  1242. }
  1243. if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
  1244. MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  1245. } else {
  1246. defines.EMISSIVE = false;
  1247. }
  1248. if (MaterialFlags.SpecularTextureEnabled) {
  1249. if (this._metallicTexture) {
  1250. MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  1251. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  1252. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  1253. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  1254. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  1255. }
  1256. else if (this._reflectivityTexture) {
  1257. MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  1258. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  1259. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  1260. } else {
  1261. defines.REFLECTIVITY = false;
  1262. }
  1263. if (this._metallicReflectanceTexture) {
  1264. MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE");
  1265. } else {
  1266. defines.METALLIC_REFLECTANCE = false;
  1267. }
  1268. if (this._microSurfaceTexture) {
  1269. MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  1270. } else {
  1271. defines.MICROSURFACEMAP = false;
  1272. }
  1273. } else {
  1274. defines.REFLECTIVITY = false;
  1275. defines.MICROSURFACEMAP = false;
  1276. }
  1277. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
  1278. MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  1279. if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
  1280. defines.PARALLAX = true;
  1281. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  1282. }
  1283. else {
  1284. defines.PARALLAX = false;
  1285. }
  1286. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  1287. } else {
  1288. defines.BUMP = false;
  1289. }
  1290. if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
  1291. defines.ENVIRONMENTBRDF = true;
  1292. // Not actual true RGBD, only the B chanel is encoded as RGBD for sheen.
  1293. defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;
  1294. } else {
  1295. defines.ENVIRONMENTBRDF = false;
  1296. defines.ENVIRONMENTBRDF_RGBD = false;
  1297. }
  1298. if (this._shouldUseAlphaFromAlbedoTexture()) {
  1299. defines.ALPHAFROMALBEDO = true;
  1300. } else {
  1301. defines.ALPHAFROMALBEDO = false;
  1302. }
  1303. }
  1304. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  1305. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  1306. defines.USEPHYSICALLIGHTFALLOFF = false;
  1307. defines.USEGLTFLIGHTFALLOFF = false;
  1308. }
  1309. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  1310. defines.USEPHYSICALLIGHTFALLOFF = false;
  1311. defines.USEGLTFLIGHTFALLOFF = true;
  1312. }
  1313. else {
  1314. defines.USEPHYSICALLIGHTFALLOFF = true;
  1315. defines.USEGLTFLIGHTFALLOFF = false;
  1316. }
  1317. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  1318. if (!this.backFaceCulling && this._twoSidedLighting) {
  1319. defines.TWOSIDEDLIGHTING = true;
  1320. } else {
  1321. defines.TWOSIDEDLIGHTING = false;
  1322. }
  1323. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  1324. }
  1325. if (defines._areTexturesDirty || defines._areMiscDirty) {
  1326. defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? "." : ""}`;
  1327. defines.PREMULTIPLYALPHA = (this.alphaMode === Constants.ALPHA_PREMULTIPLIED || this.alphaMode === Constants.ALPHA_PREMULTIPLIED_PORTERDUFF);
  1328. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  1329. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  1330. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  1331. }
  1332. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  1333. this._imageProcessingConfiguration.prepareDefines(defines);
  1334. }
  1335. defines.FORCENORMALFORWARD = this._forceNormalForward;
  1336. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  1337. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  1338. // Misc.
  1339. if (defines._areMiscDirty) {
  1340. MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  1341. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind));
  1342. defines.DEBUGMODE = this._debugMode;
  1343. }
  1344. // External config
  1345. this.detailMap.prepareDefines(defines, scene);
  1346. this.subSurface.prepareDefines(defines, scene);
  1347. this.clearCoat.prepareDefines(defines, scene);
  1348. this.anisotropy.prepareDefines(defines, mesh, scene);
  1349. this.brdf.prepareDefines(defines);
  1350. this.sheen.prepareDefines(defines, scene);
  1351. // Values that need to be evaluated on every frame
  1352. MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane, useThinInstances);
  1353. // Attribs
  1354. MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);
  1355. }
  1356. /**
  1357. * Force shader compilation
  1358. */
  1359. public forceCompilation(mesh: AbstractMesh, onCompiled?: (material: Material) => void, options?: Partial<IMaterialCompilationOptions>): void {
  1360. const localOptions = {
  1361. clipPlane: false,
  1362. useInstances: false,
  1363. ...options
  1364. };
  1365. const defines = new PBRMaterialDefines();
  1366. const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances)!;
  1367. if (this._onEffectCreatedObservable) {
  1368. onCreatedEffectParameters.effect = effect;
  1369. onCreatedEffectParameters.subMesh = null;
  1370. this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
  1371. }
  1372. if (effect.isReady()) {
  1373. if (onCompiled) {
  1374. onCompiled(this);
  1375. }
  1376. }
  1377. else {
  1378. effect.onCompileObservable.add(() => {
  1379. if (onCompiled) {
  1380. onCompiled(this);
  1381. }
  1382. });
  1383. }
  1384. }
  1385. /**
  1386. * Initializes the uniform buffer layout for the shader.
  1387. */
  1388. public buildUniformLayout(): void {
  1389. // Order is important !
  1390. let ubo = this._uniformBuffer;
  1391. ubo.addUniform("vAlbedoInfos", 2);
  1392. ubo.addUniform("vAmbientInfos", 4);
  1393. ubo.addUniform("vOpacityInfos", 2);
  1394. ubo.addUniform("vEmissiveInfos", 2);
  1395. ubo.addUniform("vLightmapInfos", 2);
  1396. ubo.addUniform("vReflectivityInfos", 3);
  1397. ubo.addUniform("vMicroSurfaceSamplerInfos", 2);
  1398. ubo.addUniform("vReflectionInfos", 2);
  1399. ubo.addUniform("vReflectionFilteringInfo", 2);
  1400. ubo.addUniform("vReflectionPosition", 3);
  1401. ubo.addUniform("vReflectionSize", 3);
  1402. ubo.addUniform("vBumpInfos", 3);
  1403. ubo.addUniform("albedoMatrix", 16);
  1404. ubo.addUniform("ambientMatrix", 16);
  1405. ubo.addUniform("opacityMatrix", 16);
  1406. ubo.addUniform("emissiveMatrix", 16);
  1407. ubo.addUniform("lightmapMatrix", 16);
  1408. ubo.addUniform("reflectivityMatrix", 16);
  1409. ubo.addUniform("microSurfaceSamplerMatrix", 16);
  1410. ubo.addUniform("bumpMatrix", 16);
  1411. ubo.addUniform("vTangentSpaceParams", 2);
  1412. ubo.addUniform("reflectionMatrix", 16);
  1413. ubo.addUniform("vReflectionColor", 3);
  1414. ubo.addUniform("vAlbedoColor", 4);
  1415. ubo.addUniform("vLightingIntensity", 4);
  1416. ubo.addUniform("vReflectionMicrosurfaceInfos", 3);
  1417. ubo.addUniform("pointSize", 1);
  1418. ubo.addUniform("vReflectivityColor", 4);
  1419. ubo.addUniform("vEmissiveColor", 3);
  1420. ubo.addUniform("visibility", 1);
  1421. ubo.addUniform("vMetallicReflectanceFactors", 4);
  1422. ubo.addUniform("vMetallicReflectanceInfos", 2);
  1423. ubo.addUniform("metallicReflectanceMatrix", 16);
  1424. PBRClearCoatConfiguration.PrepareUniformBuffer(ubo);
  1425. PBRAnisotropicConfiguration.PrepareUniformBuffer(ubo);
  1426. PBRSheenConfiguration.PrepareUniformBuffer(ubo);
  1427. PBRSubSurfaceConfiguration.PrepareUniformBuffer(ubo);
  1428. DetailMapConfiguration.PrepareUniformBuffer(ubo);
  1429. ubo.create();
  1430. }
  1431. /**
  1432. * Unbinds the material from the mesh
  1433. */
  1434. public unbind(): void {
  1435. if (this._activeEffect) {
  1436. let needFlag = false;
  1437. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  1438. this._activeEffect.setTexture("reflection2DSampler", null);
  1439. needFlag = true;
  1440. }
  1441. if (this.subSurface.unbind(this._activeEffect)) {
  1442. needFlag = true;
  1443. }
  1444. if (needFlag) {
  1445. this._markAllSubMeshesAsTexturesDirty();
  1446. }
  1447. }
  1448. super.unbind();
  1449. }
  1450. /**
  1451. * Binds the submesh data.
  1452. * @param world - The world matrix.
  1453. * @param mesh - The BJS mesh.
  1454. * @param subMesh - A submesh of the BJS mesh.
  1455. */
  1456. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  1457. var scene = this.getScene();
  1458. var defines = <PBRMaterialDefines>subMesh._materialDefines;
  1459. if (!defines) {
  1460. return;
  1461. }
  1462. var effect = subMesh.effect;
  1463. if (!effect) {
  1464. return;
  1465. }
  1466. this._activeEffect = effect;
  1467. // Matrices
  1468. if (!defines.INSTANCES || defines.THIN_INSTANCES) {
  1469. this.bindOnlyWorldMatrix(world);
  1470. }
  1471. // Normal Matrix
  1472. if (defines.OBJECTSPACE_NORMALMAP) {
  1473. world.toNormalMatrix(this._normalMatrix);
  1474. this.bindOnlyNormalMatrix(this._normalMatrix);
  1475. }
  1476. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  1477. // Bones
  1478. MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  1479. let reflectionTexture: Nullable<BaseTexture> = null;
  1480. let ubo = this._uniformBuffer;
  1481. if (mustRebind) {
  1482. var engine = scene.getEngine();
  1483. ubo.bindToEffect(effect, "Material");
  1484. this.bindViewProjection(effect);
  1485. reflectionTexture = this._getReflectionTexture();
  1486. if (!ubo.useUbo || !this.isFrozen || !ubo.isSync) {
  1487. // Texture uniforms
  1488. if (scene.texturesEnabled) {
  1489. if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
  1490. ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  1491. MaterialHelper.BindTextureMatrix(this._albedoTexture, ubo, "albedo");
  1492. }
  1493. if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
  1494. ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  1495. MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, "ambient");
  1496. }
  1497. if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
  1498. ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  1499. MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, "opacity");
  1500. }
  1501. if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
  1502. ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  1503. ubo.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  1504. if ((<any>reflectionTexture).boundingBoxSize) {
  1505. let cubeTexture = <CubeTexture>reflectionTexture;
  1506. ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  1507. ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  1508. }
  1509. if (this.realTimeFiltering) {
  1510. const width = reflectionTexture.getSize().width;
  1511. ubo.updateFloat2("vReflectionFilteringInfo", width, Scalar.Log2(width));
  1512. }
  1513. if (!defines.USEIRRADIANCEMAP) {
  1514. var polynomials = reflectionTexture.sphericalPolynomial;
  1515. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  1516. if (defines.SPHERICAL_HARMONICS) {
  1517. const preScaledHarmonics = polynomials.preScaledHarmonics;
  1518. this._activeEffect.setVector3("vSphericalL00", preScaledHarmonics.l00);
  1519. this._activeEffect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
  1520. this._activeEffect.setVector3("vSphericalL10", preScaledHarmonics.l10);
  1521. this._activeEffect.setVector3("vSphericalL11", preScaledHarmonics.l11);
  1522. this._activeEffect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
  1523. this._activeEffect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
  1524. this._activeEffect.setVector3("vSphericalL20", preScaledHarmonics.l20);
  1525. this._activeEffect.setVector3("vSphericalL21", preScaledHarmonics.l21);
  1526. this._activeEffect.setVector3("vSphericalL22", preScaledHarmonics.l22);
  1527. }
  1528. else {
  1529. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  1530. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  1531. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  1532. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x,
  1533. polynomials.xx.y - polynomials.zz.y,
  1534. polynomials.xx.z - polynomials.zz.z);
  1535. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x,
  1536. polynomials.yy.y - polynomials.zz.y,
  1537. polynomials.yy.z - polynomials.zz.z);
  1538. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  1539. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  1540. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  1541. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  1542. }
  1543. }
  1544. }
  1545. ubo.updateFloat3("vReflectionMicrosurfaceInfos",
  1546. reflectionTexture.getSize().width,
  1547. reflectionTexture.lodGenerationScale,
  1548. reflectionTexture.lodGenerationOffset);
  1549. }
  1550. if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
  1551. ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  1552. MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
  1553. }
  1554. if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
  1555. ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  1556. MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
  1557. }
  1558. if (MaterialFlags.SpecularTextureEnabled) {
  1559. if (this._metallicTexture) {
  1560. ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  1561. MaterialHelper.BindTextureMatrix(this._metallicTexture, ubo, "reflectivity");
  1562. }
  1563. else if (this._reflectivityTexture) {
  1564. ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  1565. MaterialHelper.BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity");
  1566. }
  1567. if (this._metallicReflectanceTexture) {
  1568. ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);
  1569. MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance");
  1570. }
  1571. if (this._microSurfaceTexture) {
  1572. ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  1573. MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler");
  1574. }
  1575. }
  1576. if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
  1577. ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  1578. MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, "bump");
  1579. if (scene._mirroredCameraPosition) {
  1580. ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  1581. } else {
  1582. ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  1583. }
  1584. }
  1585. }
  1586. // Point size
  1587. if (this.pointsCloud) {
  1588. ubo.updateFloat("pointSize", this.pointSize);
  1589. }
  1590. // Colors
  1591. if (defines.METALLICWORKFLOW) {
  1592. TmpColors.Color3[0].r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  1593. TmpColors.Color3[0].g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  1594. ubo.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1);
  1595. const ior = this.subSurface.indexOfRefraction;
  1596. const outside_ior = 1; // consider air as clear coat and other layaers would remap in the shader.
  1597. // We are here deriving our default reflectance from a common value for none metallic surface.
  1598. // Based of the schlick fresnel approximation model
  1599. // for dielectrics.
  1600. const f0 = Math.pow((ior - outside_ior) / (ior + outside_ior), 2);
  1601. // Tweak the default F0 and F90 based on our given setup
  1602. this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);
  1603. const metallicF90 = this._metallicF0Factor;
  1604. ubo.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], metallicF90);
  1605. }
  1606. else {
  1607. ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  1608. }
  1609. ubo.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly);
  1610. ubo.updateColor3("vReflectionColor", this._reflectionColor);
  1611. if (!defines.SS_REFRACTION && this.subSurface.linkRefractionWithTransparency) {
  1612. ubo.updateColor4("vAlbedoColor", this._albedoColor, 1);
  1613. }
  1614. else {
  1615. ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha);
  1616. }
  1617. // Misc
  1618. this._lightingInfos.x = this._directIntensity;
  1619. this._lightingInfos.y = this._emissiveIntensity;
  1620. this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;
  1621. this._lightingInfos.w = this._specularIntensity;
  1622. ubo.updateVector4("vLightingIntensity", this._lightingInfos);
  1623. }
  1624. // Visibility
  1625. ubo.updateFloat("visibility", mesh.visibility);
  1626. // Textures
  1627. if (scene.texturesEnabled) {
  1628. if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
  1629. ubo.setTexture("albedoSampler", this._albedoTexture);
  1630. }
  1631. if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
  1632. ubo.setTexture("ambientSampler", this._ambientTexture);
  1633. }
  1634. if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
  1635. ubo.setTexture("opacitySampler", this._opacityTexture);
  1636. }
  1637. if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
  1638. if (defines.LODBASEDMICROSFURACE) {
  1639. ubo.setTexture("reflectionSampler", reflectionTexture);
  1640. }
  1641. else {
  1642. ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  1643. ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  1644. ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  1645. }
  1646. if (defines.USEIRRADIANCEMAP) {
  1647. ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture);
  1648. }
  1649. }
  1650. if (defines.ENVIRONMENTBRDF) {
  1651. ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  1652. }
  1653. if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
  1654. ubo.setTexture("emissiveSampler", this._emissiveTexture);
  1655. }
  1656. if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
  1657. ubo.setTexture("lightmapSampler", this._lightmapTexture);
  1658. }
  1659. if (MaterialFlags.SpecularTextureEnabled) {
  1660. if (this._metallicTexture) {
  1661. ubo.setTexture("reflectivitySampler", this._metallicTexture);
  1662. }
  1663. else if (this._reflectivityTexture) {
  1664. ubo.setTexture("reflectivitySampler", this._reflectivityTexture);
  1665. }
  1666. if (this._metallicReflectanceTexture) {
  1667. ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture);
  1668. }
  1669. if (this._microSurfaceTexture) {
  1670. ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  1671. }
  1672. }
  1673. if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
  1674. ubo.setTexture("bumpSampler", this._bumpTexture);
  1675. }
  1676. }
  1677. this.detailMap.bindForSubMesh(ubo, scene, this.isFrozen);
  1678. this.subSurface.bindForSubMesh(ubo, scene, engine, this.isFrozen, defines.LODBASEDMICROSFURACE, this.realTimeFiltering);
  1679. this.clearCoat.bindForSubMesh(ubo, scene, engine, this._disableBumpMap, this.isFrozen, this._invertNormalMapX, this._invertNormalMapY);
  1680. this.anisotropy.bindForSubMesh(ubo, scene, this.isFrozen);
  1681. this.sheen.bindForSubMesh(ubo, scene, this.isFrozen);
  1682. // Clip plane
  1683. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  1684. // Colors
  1685. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  1686. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : (<Camera>scene.activeCamera).globalPosition);
  1687. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  1688. effect.setFloat4("vEyePosition",
  1689. eyePosition.x,
  1690. eyePosition.y,
  1691. eyePosition.z,
  1692. invertNormal ? -1 : 1);
  1693. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  1694. effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor);
  1695. }
  1696. if (mustRebind || !this.isFrozen) {
  1697. // Lights
  1698. if (scene.lightsEnabled && !this._disableLighting) {
  1699. MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._rebuildInParallel);
  1700. }
  1701. // View
  1702. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE || reflectionTexture) {
  1703. this.bindView(effect);
  1704. }
  1705. // Fog
  1706. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  1707. // Morph targets
  1708. if (defines.NUM_MORPH_INFLUENCERS) {
  1709. MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  1710. }
  1711. // image processing
  1712. this._imageProcessingConfiguration!.bind(this._activeEffect);
  1713. // Log. depth
  1714. MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  1715. }
  1716. ubo.update();
  1717. this._afterBind(mesh, this._activeEffect);
  1718. }
  1719. /**
  1720. * Returns the animatable textures.
  1721. * @returns - Array of animatable textures.
  1722. */
  1723. public getAnimatables(): IAnimatable[] {
  1724. var results = [];
  1725. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  1726. results.push(this._albedoTexture);
  1727. }
  1728. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  1729. results.push(this._ambientTexture);
  1730. }
  1731. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  1732. results.push(this._opacityTexture);
  1733. }
  1734. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  1735. results.push(this._reflectionTexture);
  1736. }
  1737. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  1738. results.push(this._emissiveTexture);
  1739. }
  1740. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  1741. results.push(this._metallicTexture);
  1742. }
  1743. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  1744. results.push(this._reflectivityTexture);
  1745. }
  1746. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  1747. results.push(this._bumpTexture);
  1748. }
  1749. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  1750. results.push(this._lightmapTexture);
  1751. }
  1752. this.detailMap.getAnimatables(results);
  1753. this.subSurface.getAnimatables(results);
  1754. this.clearCoat.getAnimatables(results);
  1755. this.sheen.getAnimatables(results);
  1756. this.anisotropy.getAnimatables(results);
  1757. return results;
  1758. }
  1759. /**
  1760. * Returns the texture used for reflections.
  1761. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  1762. */
  1763. private _getReflectionTexture(): Nullable<BaseTexture> {
  1764. if (this._reflectionTexture) {
  1765. return this._reflectionTexture;
  1766. }
  1767. return this.getScene().environmentTexture;
  1768. }
  1769. /**
  1770. * Returns an array of the actively used textures.
  1771. * @returns - Array of BaseTextures
  1772. */
  1773. public getActiveTextures(): BaseTexture[] {
  1774. var activeTextures = super.getActiveTextures();
  1775. if (this._albedoTexture) {
  1776. activeTextures.push(this._albedoTexture);
  1777. }
  1778. if (this._ambientTexture) {
  1779. activeTextures.push(this._ambientTexture);
  1780. }
  1781. if (this._opacityTexture) {
  1782. activeTextures.push(this._opacityTexture);
  1783. }
  1784. if (this._reflectionTexture) {
  1785. activeTextures.push(this._reflectionTexture);
  1786. }
  1787. if (this._emissiveTexture) {
  1788. activeTextures.push(this._emissiveTexture);
  1789. }
  1790. if (this._reflectivityTexture) {
  1791. activeTextures.push(this._reflectivityTexture);
  1792. }
  1793. if (this._metallicTexture) {
  1794. activeTextures.push(this._metallicTexture);
  1795. }
  1796. if (this._metallicReflectanceTexture) {
  1797. activeTextures.push(this._metallicReflectanceTexture);
  1798. }
  1799. if (this._microSurfaceTexture) {
  1800. activeTextures.push(this._microSurfaceTexture);
  1801. }
  1802. if (this._bumpTexture) {
  1803. activeTextures.push(this._bumpTexture);
  1804. }
  1805. if (this._lightmapTexture) {
  1806. activeTextures.push(this._lightmapTexture);
  1807. }
  1808. this.detailMap.getActiveTextures(activeTextures);
  1809. this.subSurface.getActiveTextures(activeTextures);
  1810. this.clearCoat.getActiveTextures(activeTextures);
  1811. this.sheen.getActiveTextures(activeTextures);
  1812. this.anisotropy.getActiveTextures(activeTextures);
  1813. return activeTextures;
  1814. }
  1815. /**
  1816. * Checks to see if a texture is used in the material.
  1817. * @param texture - Base texture to use.
  1818. * @returns - Boolean specifying if a texture is used in the material.
  1819. */
  1820. public hasTexture(texture: BaseTexture): boolean {
  1821. if (super.hasTexture(texture)) {
  1822. return true;
  1823. }
  1824. if (this._albedoTexture === texture) {
  1825. return true;
  1826. }
  1827. if (this._ambientTexture === texture) {
  1828. return true;
  1829. }
  1830. if (this._opacityTexture === texture) {
  1831. return true;
  1832. }
  1833. if (this._reflectionTexture === texture) {
  1834. return true;
  1835. }
  1836. if (this._reflectivityTexture === texture) {
  1837. return true;
  1838. }
  1839. if (this._metallicTexture === texture) {
  1840. return true;
  1841. }
  1842. if (this._metallicReflectanceTexture === texture) {
  1843. return true;
  1844. }
  1845. if (this._microSurfaceTexture === texture) {
  1846. return true;
  1847. }
  1848. if (this._bumpTexture === texture) {
  1849. return true;
  1850. }
  1851. if (this._lightmapTexture === texture) {
  1852. return true;
  1853. }
  1854. return this.detailMap.hasTexture(texture) ||
  1855. this.subSurface.hasTexture(texture) ||
  1856. this.clearCoat.hasTexture(texture) ||
  1857. this.sheen.hasTexture(texture) ||
  1858. this.anisotropy.hasTexture(texture);
  1859. }
  1860. /**
  1861. * Sets the required values to the prepass renderer.
  1862. * @param prePassRenderer defines the prepass renderer to setup
  1863. */
  1864. public setPrePassRenderer(prePassRenderer: PrePassRenderer): boolean {
  1865. if (this.subSurface.isScatteringEnabled) {
  1866. let subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass();
  1867. if (subSurfaceConfiguration) {
  1868. subSurfaceConfiguration.enabled = true;
  1869. }
  1870. return true;
  1871. }
  1872. return false;
  1873. }
  1874. /**
  1875. * Disposes the resources of the material.
  1876. * @param forceDisposeEffect - Forces the disposal of effects.
  1877. * @param forceDisposeTextures - Forces the disposal of all textures.
  1878. */
  1879. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean): void {
  1880. if (forceDisposeTextures) {
  1881. if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {
  1882. this._environmentBRDFTexture.dispose();
  1883. }
  1884. this._albedoTexture?.dispose();
  1885. this._ambientTexture?.dispose();
  1886. this._opacityTexture?.dispose();
  1887. this._reflectionTexture?.dispose();
  1888. this._emissiveTexture?.dispose();
  1889. this._metallicTexture?.dispose();
  1890. this._reflectivityTexture?.dispose();
  1891. this._bumpTexture?.dispose();
  1892. this._lightmapTexture?.dispose();
  1893. this._metallicReflectanceTexture?.dispose();
  1894. this._microSurfaceTexture?.dispose();
  1895. }
  1896. this.detailMap.dispose(forceDisposeTextures);
  1897. this.subSurface.dispose(forceDisposeTextures);
  1898. this.clearCoat.dispose(forceDisposeTextures);
  1899. this.sheen.dispose(forceDisposeTextures);
  1900. this.anisotropy.dispose(forceDisposeTextures);
  1901. this._renderTargets.dispose();
  1902. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  1903. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  1904. }
  1905. super.dispose(forceDisposeEffect, forceDisposeTextures);
  1906. }
  1907. }