babylon.pbrBaseMaterial.ts 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. module BABYLON {
  2. class PBRMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
  3. public PBR = true;
  4. public MAINUV1 = false;
  5. public MAINUV2 = false;
  6. public UV1 = false;
  7. public UV2 = false;
  8. public ALBEDO = false;
  9. public ALBEDODIRECTUV = 0;
  10. public VERTEXCOLOR = false;
  11. public AMBIENT = false;
  12. public AMBIENTDIRECTUV = 0;
  13. public AMBIENTINGRAYSCALE = false;
  14. public OPACITY = false;
  15. public VERTEXALPHA = false;
  16. public OPACITYDIRECTUV = 0;
  17. public OPACITYRGB = false;
  18. public ALPHATEST = false;
  19. public DEPTHPREPASS = false;
  20. public ALPHABLEND = false;
  21. public ALPHAFROMALBEDO = false;
  22. public ALPHATESTVALUE = 0.5;
  23. public SPECULAROVERALPHA = false;
  24. public RADIANCEOVERALPHA = false;
  25. public ALPHAFRESNEL = false;
  26. public LINEARALPHAFRESNEL = false;
  27. public PREMULTIPLYALPHA = false;
  28. public EMISSIVE = false;
  29. public EMISSIVEDIRECTUV = 0;
  30. public REFLECTIVITY = false;
  31. public REFLECTIVITYDIRECTUV = 0;
  32. public SPECULARTERM = false;
  33. public MICROSURFACEFROMREFLECTIVITYMAP = false;
  34. public MICROSURFACEAUTOMATIC = false;
  35. public LODBASEDMICROSFURACE = false;
  36. public MICROSURFACEMAP = false;
  37. public MICROSURFACEMAPDIRECTUV = 0;
  38. public METALLICWORKFLOW = false;
  39. public ROUGHNESSSTOREINMETALMAPALPHA = false;
  40. public ROUGHNESSSTOREINMETALMAPGREEN = false;
  41. public METALLNESSSTOREINMETALMAPBLUE = false;
  42. public AOSTOREINMETALMAPRED = false;
  43. public ENVIRONMENTBRDF = false;
  44. public NORMAL = false;
  45. public TANGENT = false;
  46. public BUMP = false;
  47. public BUMPDIRECTUV = 0;
  48. public PARALLAX = false;
  49. public PARALLAXOCCLUSION = false;
  50. public NORMALXYSCALE = true;
  51. public LIGHTMAP = false;
  52. public LIGHTMAPDIRECTUV = 0;
  53. public USELIGHTMAPASSHADOWMAP = false;
  54. public REFLECTION = false;
  55. public REFLECTIONMAP_3D = false;
  56. public REFLECTIONMAP_SPHERICAL = false;
  57. public REFLECTIONMAP_PLANAR = false;
  58. public REFLECTIONMAP_CUBIC = false;
  59. public REFLECTIONMAP_PROJECTION = false;
  60. public REFLECTIONMAP_SKYBOX = false;
  61. public REFLECTIONMAP_EXPLICIT = false;
  62. public REFLECTIONMAP_EQUIRECTANGULAR = false;
  63. public REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  64. public REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  65. public INVERTCUBICMAP = false;
  66. public USESPHERICALFROMREFLECTIONMAP = false;
  67. public USESPHERICALINVERTEX = false;
  68. public REFLECTIONMAP_OPPOSITEZ = false;
  69. public LODINREFLECTIONALPHA = false;
  70. public GAMMAREFLECTION = false;
  71. public RADIANCEOCCLUSION = false;
  72. public HORIZONOCCLUSION = false;
  73. public REFRACTION = false;
  74. public REFRACTIONMAP_3D = false;
  75. public REFRACTIONMAP_OPPOSITEZ = false;
  76. public LODINREFRACTIONALPHA = false;
  77. public GAMMAREFRACTION = false;
  78. public LINKREFRACTIONTOTRANSPARENCY = false;
  79. public INSTANCES = false;
  80. public NUM_BONE_INFLUENCERS = 0;
  81. public BonesPerMesh = 0;
  82. public NONUNIFORMSCALING = false;
  83. public MORPHTARGETS = false;
  84. public MORPHTARGETS_NORMAL = false;
  85. public MORPHTARGETS_TANGENT = false;
  86. public NUM_MORPH_INFLUENCERS = 0;
  87. public IMAGEPROCESSING = false;
  88. public VIGNETTE = false;
  89. public VIGNETTEBLENDMODEMULTIPLY = false;
  90. public VIGNETTEBLENDMODEOPAQUE = false;
  91. public TONEMAPPING = false;
  92. public CONTRAST = false;
  93. public COLORCURVES = false;
  94. public COLORGRADING = false;
  95. public COLORGRADING3D = false;
  96. public SAMPLER3DGREENDEPTH = false;
  97. public SAMPLER3DBGRMAP = false;
  98. public IMAGEPROCESSINGPOSTPROCESS = false;
  99. public EXPOSURE = false;
  100. public USEPHYSICALLIGHTFALLOFF = false;
  101. public TWOSIDEDLIGHTING = false;
  102. public SHADOWFLOAT = false;
  103. public CLIPPLANE = false;
  104. public POINTSIZE = false;
  105. public FOG = false;
  106. public LOGARITHMICDEPTH = false;
  107. public FORCENORMALFORWARD = false;
  108. constructor() {
  109. super();
  110. this.rebuild();
  111. }
  112. public reset(): void {
  113. super.reset();
  114. this.ALPHATESTVALUE = 0.5;
  115. this.PBR = true;
  116. }
  117. }
  118. /**
  119. * The Physically based material base class of BJS.
  120. *
  121. * This offers the main features of a standard PBR material.
  122. * For more information, please refer to the documentation :
  123. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  124. */
  125. export abstract class PBRBaseMaterial extends PushMaterial {
  126. /**
  127. * Intensity of the direct lights e.g. the four lights available in your scene.
  128. * This impacts both the direct diffuse and specular highlights.
  129. */
  130. protected _directIntensity: number = 1.0;
  131. /**
  132. * Intensity of the emissive part of the material.
  133. * This helps controlling the emissive effect without modifying the emissive color.
  134. */
  135. protected _emissiveIntensity: number = 1.0;
  136. /**
  137. * Intensity of the environment e.g. how much the environment will light the object
  138. * either through harmonics for rough material or through the refelction for shiny ones.
  139. */
  140. protected _environmentIntensity: number = 1.0;
  141. /**
  142. * This is a special control allowing the reduction of the specular highlights coming from the
  143. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  144. */
  145. protected _specularIntensity: number = 1.0;
  146. private _lightingInfos: Vector4 = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);
  147. /**
  148. * Debug Control allowing disabling the bump map on this material.
  149. */
  150. protected _disableBumpMap: boolean = false;
  151. /**
  152. * AKA Diffuse Texture in standard nomenclature.
  153. */
  154. protected _albedoTexture: BaseTexture;
  155. /**
  156. * AKA Occlusion Texture in other nomenclature.
  157. */
  158. protected _ambientTexture: BaseTexture;
  159. /**
  160. * AKA Occlusion Texture Intensity in other nomenclature.
  161. */
  162. protected _ambientTextureStrength: number = 1.0;
  163. protected _opacityTexture: BaseTexture;
  164. protected _reflectionTexture: BaseTexture;
  165. protected _refractionTexture: BaseTexture;
  166. protected _emissiveTexture: BaseTexture;
  167. /**
  168. * AKA Specular texture in other nomenclature.
  169. */
  170. protected _reflectivityTexture: BaseTexture;
  171. /**
  172. * Used to switch from specular/glossiness to metallic/roughness workflow.
  173. */
  174. protected _metallicTexture: BaseTexture;
  175. /**
  176. * Specifies the metallic scalar of the metallic/roughness workflow.
  177. * Can also be used to scale the metalness values of the metallic texture.
  178. */
  179. protected _metallic: number;
  180. /**
  181. * Specifies the roughness scalar of the metallic/roughness workflow.
  182. * Can also be used to scale the roughness values of the metallic texture.
  183. */
  184. protected _roughness: number;
  185. /**
  186. * Used to enable roughness/glossiness fetch from a separate chanel depending on the current mode.
  187. * Gray Scale represents roughness in metallic mode and glossiness in specular mode.
  188. */
  189. protected _microSurfaceTexture: BaseTexture;
  190. protected _bumpTexture: BaseTexture;
  191. protected _lightmapTexture: BaseTexture;
  192. protected _ambientColor = new Color3(0, 0, 0);
  193. /**
  194. * AKA Diffuse Color in other nomenclature.
  195. */
  196. protected _albedoColor = new Color3(1, 1, 1);
  197. /**
  198. * AKA Specular Color in other nomenclature.
  199. */
  200. protected _reflectivityColor = new Color3(1, 1, 1);
  201. protected _reflectionColor = new Color3(1, 1, 1);
  202. protected _emissiveColor = new Color3(0, 0, 0);
  203. /**
  204. * AKA Glossiness in other nomenclature.
  205. */
  206. protected _microSurface = 0.9;
  207. /**
  208. * source material index of refraction (IOR)' / 'destination material IOR.
  209. */
  210. protected _indexOfRefraction = 0.66;
  211. /**
  212. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  213. */
  214. protected _invertRefractionY = false;
  215. /**
  216. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  217. * Materials half opaque for instance using refraction could benefit from this control.
  218. */
  219. protected _linkRefractionWithTransparency = false;
  220. protected _useLightmapAsShadowmap = false;
  221. /**
  222. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  223. * makes the reflect vector face the model (under horizon).
  224. */
  225. protected _useHorizonOcclusion = true;
  226. /**
  227. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  228. * too much the area relying on ambient texture to define their ambient occlusion.
  229. */
  230. protected _useRadianceOcclusion = true;
  231. /**
  232. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  233. */
  234. protected _useAlphaFromAlbedoTexture = false;
  235. /**
  236. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  237. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  238. */
  239. protected _useSpecularOverAlpha = true;
  240. /**
  241. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  242. */
  243. protected _useMicroSurfaceFromReflectivityMapAlpha = false;
  244. /**
  245. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  246. */
  247. protected _useRoughnessFromMetallicTextureAlpha = true;
  248. /**
  249. * Specifies if the metallic texture contains the roughness information in its green channel.
  250. */
  251. protected _useRoughnessFromMetallicTextureGreen = false;
  252. /**
  253. * Specifies if the metallic texture contains the metallness information in its blue channel.
  254. */
  255. protected _useMetallnessFromMetallicTextureBlue = false;
  256. /**
  257. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  258. */
  259. protected _useAmbientOcclusionFromMetallicTextureRed = false;
  260. /**
  261. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  262. */
  263. protected _useAmbientInGrayScale = false;
  264. /**
  265. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  266. * The material will try to infer what glossiness each pixel should be.
  267. */
  268. protected _useAutoMicroSurfaceFromReflectivityMap = false;
  269. /**
  270. * BJS is using an harcoded light falloff based on a manually sets up range.
  271. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  272. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  273. */
  274. protected _usePhysicalLightFalloff = true;
  275. /**
  276. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  277. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  278. */
  279. protected _useRadianceOverAlpha = true;
  280. /**
  281. * Allows using the bump map in parallax mode.
  282. */
  283. protected _useParallax = false;
  284. /**
  285. * Allows using the bump map in parallax occlusion mode.
  286. */
  287. protected _useParallaxOcclusion = false;
  288. /**
  289. * Controls the scale bias of the parallax mode.
  290. */
  291. protected _parallaxScaleBias = 0.05;
  292. /**
  293. * If sets to true, disables all the lights affecting the material.
  294. */
  295. protected _disableLighting = false;
  296. /**
  297. * Number of Simultaneous lights allowed on the material.
  298. */
  299. protected _maxSimultaneousLights = 4;
  300. /**
  301. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  302. */
  303. protected _invertNormalMapX = false;
  304. /**
  305. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  306. */
  307. protected _invertNormalMapY = false;
  308. /**
  309. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  310. */
  311. protected _twoSidedLighting = false;
  312. /**
  313. * Defines the alpha limits in alpha test mode.
  314. */
  315. protected _alphaCutOff = 0.4;
  316. /**
  317. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  318. */
  319. protected _forceAlphaTest = false;
  320. /**
  321. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  322. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  323. */
  324. protected _useAlphaFresnel = false;
  325. /**
  326. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  327. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  328. */
  329. protected _useLinearAlphaFresnel = false;
  330. /**
  331. * The transparency mode of the material.
  332. */
  333. protected _transparencyMode: Nullable<number> = null;
  334. /**
  335. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  336. * from cos thetav and roughness:
  337. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  338. */
  339. protected _environmentBRDFTexture: Nullable<BaseTexture> = null;
  340. /**
  341. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  342. */
  343. protected _forceIrradianceInFragment = false;
  344. /**
  345. * Force normal to face away from face.
  346. */
  347. protected _forceNormalForward = false;
  348. /**
  349. * Force metallic workflow.
  350. */
  351. protected _forceMetallicWorkflow = false;
  352. /**
  353. * Default configuration related to image processing available in the PBR Material.
  354. */
  355. @serializeAsImageProcessingConfiguration()
  356. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  357. /**
  358. * Keep track of the image processing observer to allow dispose and replace.
  359. */
  360. private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>>;
  361. /**
  362. * Attaches a new image processing configuration to the PBR Material.
  363. * @param configuration
  364. */
  365. protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
  366. if (configuration === this._imageProcessingConfiguration) {
  367. return;
  368. }
  369. // Detaches observer.
  370. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  371. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  372. }
  373. // Pick the scene configuration if needed.
  374. if (!configuration) {
  375. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  376. }
  377. else {
  378. this._imageProcessingConfiguration = configuration;
  379. }
  380. // Attaches observer.
  381. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(conf => {
  382. this._markAllSubMeshesAsImageProcessingDirty();
  383. });
  384. }
  385. private _renderTargets = new SmartArray<RenderTargetTexture>(16);
  386. private _globalAmbientColor = new Color3(0, 0, 0);
  387. private _useLogarithmicDepth: boolean;
  388. /**
  389. * Instantiates a new PBRMaterial instance.
  390. *
  391. * @param name The material name
  392. * @param scene The scene the material will be use in.
  393. */
  394. constructor(name: string, scene: Scene) {
  395. super(name, scene);
  396. // Setup the default processing configuration to the scene.
  397. this._attachImageProcessingConfiguration(null);
  398. this.getRenderTargetTextures = (): SmartArray<RenderTargetTexture> => {
  399. this._renderTargets.reset();
  400. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  401. this._renderTargets.push(<RenderTargetTexture>this._reflectionTexture);
  402. }
  403. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  404. this._renderTargets.push(<RenderTargetTexture>this._refractionTexture);
  405. }
  406. return this._renderTargets;
  407. }
  408. this._environmentBRDFTexture = TextureTools.GetEnvironmentBRDFTexture(scene);
  409. }
  410. public getClassName(): string {
  411. return "PBRBaseMaterial";
  412. }
  413. @serialize()
  414. public get useLogarithmicDepth(): boolean {
  415. return this._useLogarithmicDepth;
  416. }
  417. public set useLogarithmicDepth(value: boolean) {
  418. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  419. }
  420. /**
  421. * Gets the current transparency mode.
  422. */
  423. @serialize()
  424. public get transparencyMode(): Nullable<number> {
  425. return this._transparencyMode;
  426. }
  427. /**
  428. * Sets the transparency mode of the material.
  429. */
  430. public set transparencyMode(value: Nullable<number>) {
  431. if (this._transparencyMode === value) {
  432. return;
  433. }
  434. this._transparencyMode = value;
  435. this._forceAlphaTest = (value === PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  436. this._markAllSubMeshesAsTexturesDirty();
  437. }
  438. /**
  439. * Returns true if alpha blending should be disabled.
  440. */
  441. private get _disableAlphaBlending(): boolean {
  442. return (this._linkRefractionWithTransparency ||
  443. this._transparencyMode === PBRMaterial.PBRMATERIAL_OPAQUE ||
  444. this._transparencyMode === PBRMaterial.PBRMATERIAL_ALPHATEST);
  445. }
  446. /**
  447. * Specifies whether or not this material should be rendered in alpha blend mode.
  448. */
  449. public needAlphaBlending(): boolean {
  450. if (this._disableAlphaBlending) {
  451. return false;
  452. }
  453. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  454. }
  455. /**
  456. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  457. */
  458. public needAlphaBlendingForMesh(mesh: AbstractMesh): boolean {
  459. if (this._disableAlphaBlending) {
  460. return false;
  461. }
  462. return super.needAlphaBlendingForMesh(mesh);
  463. }
  464. /**
  465. * Specifies whether or not this material should be rendered in alpha test mode.
  466. */
  467. public needAlphaTesting(): boolean {
  468. if (this._forceAlphaTest) {
  469. return true;
  470. }
  471. if (this._linkRefractionWithTransparency) {
  472. return false;
  473. }
  474. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === PBRMaterial.PBRMATERIAL_ALPHATEST);
  475. }
  476. /**
  477. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  478. */
  479. protected _shouldUseAlphaFromAlbedoTexture(): boolean {
  480. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE;
  481. }
  482. public getAlphaTestTexture(): BaseTexture {
  483. return this._albedoTexture;
  484. }
  485. private static _scaledReflectivity = new Color3();
  486. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  487. if (subMesh.effect && this.isFrozen) {
  488. if (this._wasPreviouslyReady) {
  489. return true;
  490. }
  491. }
  492. if (!subMesh._materialDefines) {
  493. subMesh._materialDefines = new PBRMaterialDefines();
  494. }
  495. var scene = this.getScene();
  496. var defines = <PBRMaterialDefines>subMesh._materialDefines;
  497. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  498. if (defines._renderId === scene.getRenderId()) {
  499. return true;
  500. }
  501. }
  502. var engine = scene.getEngine();
  503. // Lights
  504. MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  505. defines._needNormals = true;
  506. // Textures
  507. if (defines._areTexturesDirty) {
  508. defines._needUVs = false;
  509. if (scene.texturesEnabled) {
  510. if (scene.getEngine().getCaps().textureLOD) {
  511. defines.LODBASEDMICROSFURACE = true;
  512. }
  513. if (this._albedoTexture && StandardMaterial.DiffuseTextureEnabled) {
  514. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  515. return false;
  516. }
  517. MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  518. } else {
  519. defines.ALBEDO = false;
  520. }
  521. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  522. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  523. return false;
  524. }
  525. MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  526. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  527. } else {
  528. defines.AMBIENT = false;
  529. }
  530. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  531. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  532. return false;
  533. }
  534. MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  535. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  536. } else {
  537. defines.OPACITY = false;
  538. }
  539. var reflectionTexture = this._getReflectionTexture();
  540. if (reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  541. if (!reflectionTexture.isReadyOrNotBlocking()) {
  542. return false;
  543. }
  544. defines.REFLECTION = true;
  545. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  546. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  547. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  548. if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {
  549. defines.INVERTCUBICMAP = true;
  550. }
  551. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  552. switch (reflectionTexture.coordinatesMode) {
  553. case Texture.CUBIC_MODE:
  554. case Texture.INVCUBIC_MODE:
  555. defines.REFLECTIONMAP_CUBIC = true;
  556. break;
  557. case Texture.EXPLICIT_MODE:
  558. defines.REFLECTIONMAP_EXPLICIT = true;
  559. break;
  560. case Texture.PLANAR_MODE:
  561. defines.REFLECTIONMAP_PLANAR = true;
  562. break;
  563. case Texture.PROJECTION_MODE:
  564. defines.REFLECTIONMAP_PROJECTION = true;
  565. break;
  566. case Texture.SKYBOX_MODE:
  567. defines.REFLECTIONMAP_SKYBOX = true;
  568. break;
  569. case Texture.SPHERICAL_MODE:
  570. defines.REFLECTIONMAP_SPHERICAL = true;
  571. break;
  572. case Texture.EQUIRECTANGULAR_MODE:
  573. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  574. break;
  575. case Texture.FIXED_EQUIRECTANGULAR_MODE:
  576. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  577. break;
  578. case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  579. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  580. break;
  581. }
  582. if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
  583. if (reflectionTexture.sphericalPolynomial) {
  584. defines.USESPHERICALFROMREFLECTIONMAP = true;
  585. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  586. defines.USESPHERICALINVERTEX = false;
  587. }
  588. else {
  589. defines.USESPHERICALINVERTEX = true;
  590. }
  591. }
  592. }
  593. } else {
  594. defines.REFLECTION = false;
  595. defines.REFLECTIONMAP_3D = false;
  596. defines.REFLECTIONMAP_SPHERICAL = false;
  597. defines.REFLECTIONMAP_PLANAR = false;
  598. defines.REFLECTIONMAP_CUBIC = false;
  599. defines.REFLECTIONMAP_PROJECTION = false;
  600. defines.REFLECTIONMAP_SKYBOX = false;
  601. defines.REFLECTIONMAP_EXPLICIT = false;
  602. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  603. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  604. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  605. defines.INVERTCUBICMAP = false;
  606. defines.USESPHERICALFROMREFLECTIONMAP = false;
  607. defines.USESPHERICALINVERTEX = false;
  608. defines.REFLECTIONMAP_OPPOSITEZ = false;
  609. defines.LODINREFLECTIONALPHA = false;
  610. defines.GAMMAREFLECTION = false;
  611. }
  612. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  613. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  614. return false;
  615. }
  616. MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  617. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  618. } else {
  619. defines.LIGHTMAP = false;
  620. }
  621. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  622. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  623. return false;
  624. }
  625. MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  626. } else {
  627. defines.EMISSIVE = false;
  628. }
  629. if (StandardMaterial.SpecularTextureEnabled) {
  630. if (this._metallicTexture) {
  631. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  632. return false;
  633. }
  634. MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  635. defines.METALLICWORKFLOW = true;
  636. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  637. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  638. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  639. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  640. }
  641. else if (this._reflectivityTexture) {
  642. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  643. return false;
  644. }
  645. defines.METALLICWORKFLOW = false;
  646. MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  647. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  648. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  649. } else {
  650. defines.METALLICWORKFLOW = false;
  651. defines.REFLECTIVITY = false;
  652. }
  653. if (this._microSurfaceTexture) {
  654. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  655. return false;
  656. }
  657. MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  658. } else {
  659. defines.MICROSURFACEMAP = false;
  660. }
  661. } else {
  662. defines.REFLECTIVITY = false;
  663. defines.MICROSURFACEMAP = false;
  664. }
  665. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  666. // Bump texure can not be none blocking.
  667. if (!this._bumpTexture.isReady()) {
  668. return false;
  669. }
  670. MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  671. if (this._useParallax && this._albedoTexture && StandardMaterial.DiffuseTextureEnabled) {
  672. defines.PARALLAX = true;
  673. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  674. }
  675. else {
  676. defines.PARALLAX = false;
  677. }
  678. } else {
  679. defines.BUMP = false;
  680. }
  681. var refractionTexture = this._getRefractionTexture();
  682. if (refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  683. if (!refractionTexture.isReadyOrNotBlocking()) {
  684. return false;
  685. }
  686. defines.REFRACTION = true;
  687. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  688. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  689. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  690. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  691. if (this._linkRefractionWithTransparency) {
  692. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  693. }
  694. } else {
  695. defines.REFRACTION = false;
  696. }
  697. if (this._environmentBRDFTexture && StandardMaterial.ReflectionTextureEnabled) {
  698. // This is blocking.
  699. if (!this._environmentBRDFTexture.isReady()) {
  700. return false;
  701. }
  702. defines.ENVIRONMENTBRDF = true;
  703. } else {
  704. defines.ENVIRONMENTBRDF = false;
  705. }
  706. if (this._shouldUseAlphaFromAlbedoTexture()) {
  707. defines.ALPHAFROMALBEDO = true;
  708. } else {
  709. defines.ALPHAFROMALBEDO = false;
  710. }
  711. }
  712. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  713. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  714. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  715. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  716. defines.METALLICWORKFLOW = true;
  717. } else {
  718. defines.METALLICWORKFLOW = false;
  719. }
  720. if (!this.backFaceCulling && this._twoSidedLighting) {
  721. defines.TWOSIDEDLIGHTING = true;
  722. } else {
  723. defines.TWOSIDEDLIGHTING = false;
  724. }
  725. defines.ALPHATESTVALUE = this._alphaCutOff;
  726. defines.PREMULTIPLYALPHA = (this.alphaMode === Engine.ALPHA_PREMULTIPLIED || this.alphaMode === Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  727. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  728. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  729. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  730. }
  731. if (defines._areImageProcessingDirty) {
  732. if (!this._imageProcessingConfiguration.isReady()) {
  733. return false;
  734. }
  735. this._imageProcessingConfiguration.prepareDefines(defines);
  736. }
  737. defines.FORCENORMALFORWARD = this._forceNormalForward;
  738. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  739. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  740. // Misc.
  741. MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  742. // Values that need to be evaluated on every frame
  743. MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  744. // Attribs
  745. if (MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  746. let bufferMesh = null;
  747. if (mesh instanceof InstancedMesh) {
  748. bufferMesh = (mesh as InstancedMesh).sourceMesh;
  749. }
  750. else if (mesh instanceof Mesh) {
  751. bufferMesh = mesh as Mesh;
  752. }
  753. if (bufferMesh) {
  754. if (bufferMesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  755. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  756. let normalVertexBuffer = bufferMesh.getVertexBuffer(VertexBuffer.NormalKind);
  757. let normals = normalVertexBuffer!.getData();
  758. let vertexBufferOffset = normalVertexBuffer!.getOffset();
  759. let strideSize = normalVertexBuffer!.getStrideSize();
  760. let offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  761. if (normals![offset] === 0 && normals![offset + 1] === 0 && normals![offset + 2] === 0) {
  762. defines.NORMAL = false;
  763. }
  764. if (bufferMesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  765. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  766. let tangentVertexBuffer = bufferMesh.getVertexBuffer(VertexBuffer.TangentKind);
  767. let tangents = tangentVertexBuffer!.getData();
  768. let vertexBufferOffset = tangentVertexBuffer!.getOffset();
  769. let strideSize = tangentVertexBuffer!.getStrideSize();
  770. let offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  771. if (tangents![offset] === 0 && tangents![offset + 1] === 0 && tangents![offset + 2] === 0) {
  772. defines.TANGENT = false;
  773. }
  774. }
  775. }
  776. else {
  777. if (!scene.getEngine().getCaps().standardDerivatives) {
  778. bufferMesh.createNormals(true);
  779. Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  780. }
  781. }
  782. }
  783. }
  784. // Get correct effect
  785. if (defines.isDirty) {
  786. defines.markAsProcessed();
  787. scene.resetCachedMaterial();
  788. // Fallbacks
  789. var fallbacks = new EffectFallbacks();
  790. var fallbackRank = 0;
  791. if (defines.USESPHERICALINVERTEX) {
  792. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  793. }
  794. if (defines.FOG) {
  795. fallbacks.addFallback(fallbackRank, "FOG");
  796. }
  797. if (defines.POINTSIZE) {
  798. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  799. }
  800. if (defines.LOGARITHMICDEPTH) {
  801. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  802. }
  803. if (defines.PARALLAX) {
  804. fallbacks.addFallback(fallbackRank, "PARALLAX");
  805. }
  806. if (defines.PARALLAXOCCLUSION) {
  807. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  808. }
  809. if (defines.ENVIRONMENTBRDF) {
  810. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  811. }
  812. if (defines.TANGENT) {
  813. fallbacks.addFallback(fallbackRank++, "TANGENT");
  814. }
  815. if (defines.BUMP) {
  816. fallbacks.addFallback(fallbackRank++, "BUMP");
  817. }
  818. fallbackRank = MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  819. if (defines.SPECULARTERM) {
  820. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  821. }
  822. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  823. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  824. }
  825. if (defines.LIGHTMAP) {
  826. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  827. }
  828. if (defines.NORMAL) {
  829. fallbacks.addFallback(fallbackRank++, "NORMAL");
  830. }
  831. if (defines.AMBIENT) {
  832. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  833. }
  834. if (defines.EMISSIVE) {
  835. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  836. }
  837. if (defines.VERTEXCOLOR) {
  838. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  839. }
  840. if (defines.NUM_BONE_INFLUENCERS > 0) {
  841. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  842. }
  843. if (defines.MORPHTARGETS) {
  844. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  845. }
  846. //Attributes
  847. var attribs = [VertexBuffer.PositionKind];
  848. if (defines.NORMAL) {
  849. attribs.push(VertexBuffer.NormalKind);
  850. }
  851. if (defines.TANGENT) {
  852. attribs.push(VertexBuffer.TangentKind);
  853. }
  854. if (defines.UV1) {
  855. attribs.push(VertexBuffer.UVKind);
  856. }
  857. if (defines.UV2) {
  858. attribs.push(VertexBuffer.UV2Kind);
  859. }
  860. if (defines.VERTEXCOLOR) {
  861. attribs.push(VertexBuffer.ColorKind);
  862. }
  863. MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  864. MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  865. MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  866. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  867. "vFogInfos", "vFogColor", "pointSize",
  868. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  869. "mBones",
  870. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  871. "vLightingIntensity",
  872. "logarithmicDepthConstant",
  873. "vSphericalX", "vSphericalY", "vSphericalZ",
  874. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  875. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  876. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  877. "vTangentSpaceParams"
  878. ];
  879. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  880. "bumpSampler", "lightmapSampler", "opacitySampler",
  881. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  882. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  883. "microSurfaceSampler", "environmentBrdfSampler"];
  884. var uniformBuffers = ["Material", "Scene"];
  885. ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  886. ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  887. MaterialHelper.PrepareUniformsAndSamplersList(<EffectCreationOptions>{
  888. uniformsNames: uniforms,
  889. uniformBuffersNames: uniformBuffers,
  890. samplers: samplers,
  891. defines: defines,
  892. maxSimultaneousLights: this._maxSimultaneousLights
  893. });
  894. var onCompiled = (effect: Effect) => {
  895. if (this.onCompiled) {
  896. this.onCompiled(effect);
  897. }
  898. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  899. };
  900. var join = defines.toString();
  901. subMesh.setEffect(scene.getEngine().createEffect("pbr", <EffectCreationOptions>{
  902. attributes: attribs,
  903. uniformsNames: uniforms,
  904. uniformBuffersNames: uniformBuffers,
  905. samplers: samplers,
  906. defines: join,
  907. fallbacks: fallbacks,
  908. onCompiled: onCompiled,
  909. onError: this.onError,
  910. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  911. }, engine), defines);
  912. this.buildUniformLayout();
  913. }
  914. if (!subMesh.effect || !subMesh.effect.isReady()) {
  915. return false;
  916. }
  917. defines._renderId = scene.getRenderId();
  918. this._wasPreviouslyReady = true;
  919. return true;
  920. }
  921. public buildUniformLayout(): void {
  922. // Order is important !
  923. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  924. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  925. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  926. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  927. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  928. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  929. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  930. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  931. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  932. this._uniformBuffer.addUniform("vBumpInfos", 3);
  933. this._uniformBuffer.addUniform("albedoMatrix", 16);
  934. this._uniformBuffer.addUniform("ambientMatrix", 16);
  935. this._uniformBuffer.addUniform("opacityMatrix", 16);
  936. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  937. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  938. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  939. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  940. this._uniformBuffer.addUniform("bumpMatrix", 16);
  941. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  942. this._uniformBuffer.addUniform("refractionMatrix", 16);
  943. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  944. this._uniformBuffer.addUniform("vReflectionColor", 3);
  945. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  946. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  947. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  948. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  949. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  950. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  951. this._uniformBuffer.addUniform("pointSize", 1);
  952. this._uniformBuffer.create();
  953. }
  954. public unbind(): void {
  955. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  956. this._uniformBuffer.setTexture("reflectionSampler", null);
  957. }
  958. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  959. this._uniformBuffer.setTexture("refractionSampler", null);
  960. }
  961. super.unbind();
  962. }
  963. public bindOnlyWorldMatrix(world: Matrix): void {
  964. this._activeEffect.setMatrix("world", world);
  965. }
  966. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  967. var scene = this.getScene();
  968. var defines = <PBRMaterialDefines>subMesh._materialDefines;
  969. if (!defines) {
  970. return;
  971. }
  972. var effect = subMesh.effect;
  973. if (!effect) {
  974. return;
  975. }
  976. this._activeEffect = effect;
  977. // Matrices
  978. this.bindOnlyWorldMatrix(world);
  979. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  980. // Bones
  981. MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  982. let reflectionTexture: Nullable<BaseTexture> = null;
  983. if (mustRebind) {
  984. this._uniformBuffer.bindToEffect(effect, "Material");
  985. this.bindViewProjection(effect);
  986. reflectionTexture = this._getReflectionTexture();
  987. var refractionTexture = this._getRefractionTexture();
  988. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  989. // Texture uniforms
  990. if (scene.texturesEnabled) {
  991. if (this._albedoTexture && StandardMaterial.DiffuseTextureEnabled) {
  992. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  993. MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  994. }
  995. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  996. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  997. MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  998. }
  999. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  1000. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  1001. MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  1002. }
  1003. if (reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  1004. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  1005. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  1006. var polynomials = reflectionTexture.sphericalPolynomial;
  1007. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  1008. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  1009. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  1010. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  1011. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x,
  1012. polynomials.xx.y - polynomials.zz.y,
  1013. polynomials.xx.z - polynomials.zz.z);
  1014. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x,
  1015. polynomials.yy.y - polynomials.zz.y,
  1016. polynomials.yy.z - polynomials.zz.z);
  1017. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  1018. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  1019. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  1020. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  1021. }
  1022. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",
  1023. reflectionTexture.getSize().width,
  1024. reflectionTexture.lodGenerationScale,
  1025. reflectionTexture.lodGenerationOffset);
  1026. }
  1027. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  1028. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  1029. MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  1030. }
  1031. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  1032. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  1033. MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  1034. }
  1035. if (StandardMaterial.SpecularTextureEnabled) {
  1036. if (this._metallicTexture) {
  1037. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  1038. MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  1039. }
  1040. else if (this._reflectivityTexture) {
  1041. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  1042. MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  1043. }
  1044. if (this._microSurfaceTexture) {
  1045. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  1046. MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  1047. }
  1048. }
  1049. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  1050. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  1051. MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  1052. if (scene._mirroredCameraPosition) {
  1053. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  1054. } else {
  1055. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  1056. }
  1057. }
  1058. if (refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  1059. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  1060. var depth = 1.0;
  1061. if (!refractionTexture.isCube) {
  1062. if ((<any>refractionTexture).depth) {
  1063. depth = (<any>refractionTexture).depth;
  1064. }
  1065. }
  1066. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  1067. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos",
  1068. refractionTexture.getSize().width,
  1069. refractionTexture.lodGenerationScale,
  1070. refractionTexture.lodGenerationOffset);
  1071. }
  1072. }
  1073. // Point size
  1074. if (this.pointsCloud) {
  1075. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  1076. }
  1077. // Colors
  1078. if (defines.METALLICWORKFLOW) {
  1079. PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  1080. PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  1081. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  1082. }
  1083. else {
  1084. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  1085. }
  1086. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  1087. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  1088. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  1089. // Misc
  1090. this._lightingInfos.x = this._directIntensity;
  1091. this._lightingInfos.y = this._emissiveIntensity;
  1092. this._lightingInfos.z = this._environmentIntensity;
  1093. this._lightingInfos.w = this._specularIntensity;
  1094. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  1095. }
  1096. // Textures
  1097. if (scene.texturesEnabled) {
  1098. if (this._albedoTexture && StandardMaterial.DiffuseTextureEnabled) {
  1099. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  1100. }
  1101. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  1102. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  1103. }
  1104. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  1105. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  1106. }
  1107. if (reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  1108. if (defines.LODBASEDMICROSFURACE) {
  1109. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  1110. }
  1111. else {
  1112. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  1113. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  1114. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  1115. }
  1116. }
  1117. if (defines.ENVIRONMENTBRDF) {
  1118. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  1119. }
  1120. if (refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  1121. if (defines.LODBASEDMICROSFURACE) {
  1122. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  1123. }
  1124. else {
  1125. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  1126. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  1127. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  1128. }
  1129. }
  1130. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  1131. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  1132. }
  1133. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  1134. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  1135. }
  1136. if (StandardMaterial.SpecularTextureEnabled) {
  1137. if (this._metallicTexture) {
  1138. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  1139. }
  1140. else if (this._reflectivityTexture) {
  1141. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  1142. }
  1143. if (this._microSurfaceTexture) {
  1144. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  1145. }
  1146. }
  1147. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  1148. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  1149. }
  1150. }
  1151. // Clip plane
  1152. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  1153. // Colors
  1154. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  1155. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : (<Camera>scene.activeCamera).globalPosition);
  1156. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  1157. effect.setFloat4("vEyePosition",
  1158. eyePosition.x,
  1159. eyePosition.y,
  1160. eyePosition.z,
  1161. invertNormal ? -1 : 1);
  1162. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  1163. }
  1164. if (mustRebind || !this.isFrozen) {
  1165. // Lights
  1166. if (scene.lightsEnabled && !this._disableLighting) {
  1167. MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  1168. }
  1169. // View
  1170. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE || reflectionTexture) {
  1171. this.bindView(effect);
  1172. }
  1173. // Fog
  1174. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  1175. // Morph targets
  1176. if (defines.NUM_MORPH_INFLUENCERS) {
  1177. MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  1178. }
  1179. // image processing
  1180. this._imageProcessingConfiguration.bind(this._activeEffect);
  1181. // Log. depth
  1182. MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  1183. }
  1184. this._uniformBuffer.update();
  1185. this._afterBind(mesh);
  1186. }
  1187. public getAnimatables(): IAnimatable[] {
  1188. var results = [];
  1189. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  1190. results.push(this._albedoTexture);
  1191. }
  1192. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  1193. results.push(this._ambientTexture);
  1194. }
  1195. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  1196. results.push(this._opacityTexture);
  1197. }
  1198. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  1199. results.push(this._reflectionTexture);
  1200. }
  1201. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  1202. results.push(this._emissiveTexture);
  1203. }
  1204. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  1205. results.push(this._metallicTexture);
  1206. }
  1207. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  1208. results.push(this._reflectivityTexture);
  1209. }
  1210. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  1211. results.push(this._bumpTexture);
  1212. }
  1213. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  1214. results.push(this._lightmapTexture);
  1215. }
  1216. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  1217. results.push(this._refractionTexture);
  1218. }
  1219. return results;
  1220. }
  1221. private _getReflectionTexture(): BaseTexture {
  1222. if (this._reflectionTexture) {
  1223. return this._reflectionTexture;
  1224. }
  1225. return this.getScene().environmentTexture;
  1226. }
  1227. private _getRefractionTexture(): Nullable<BaseTexture> {
  1228. if (this._refractionTexture) {
  1229. return this._refractionTexture;
  1230. }
  1231. if (this._linkRefractionWithTransparency) {
  1232. return this.getScene().environmentTexture;
  1233. }
  1234. return null;
  1235. }
  1236. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean): void {
  1237. if (forceDisposeTextures) {
  1238. if (this._albedoTexture) {
  1239. this._albedoTexture.dispose();
  1240. }
  1241. if (this._ambientTexture) {
  1242. this._ambientTexture.dispose();
  1243. }
  1244. if (this._opacityTexture) {
  1245. this._opacityTexture.dispose();
  1246. }
  1247. if (this._reflectionTexture) {
  1248. this._reflectionTexture.dispose();
  1249. }
  1250. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  1251. this._environmentBRDFTexture.dispose();
  1252. }
  1253. if (this._emissiveTexture) {
  1254. this._emissiveTexture.dispose();
  1255. }
  1256. if (this._metallicTexture) {
  1257. this._metallicTexture.dispose();
  1258. }
  1259. if (this._reflectivityTexture) {
  1260. this._reflectivityTexture.dispose();
  1261. }
  1262. if (this._bumpTexture) {
  1263. this._bumpTexture.dispose();
  1264. }
  1265. if (this._lightmapTexture) {
  1266. this._lightmapTexture.dispose();
  1267. }
  1268. if (this._refractionTexture) {
  1269. this._refractionTexture.dispose();
  1270. }
  1271. }
  1272. this._renderTargets.dispose();
  1273. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  1274. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  1275. }
  1276. super.dispose(forceDisposeEffect, forceDisposeTextures);
  1277. }
  1278. }
  1279. }