babylon.pbrMaterial.js 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var maxSimultaneousLights = 4;
  5. var PBRMaterialDefines = (function (_super) {
  6. __extends(PBRMaterialDefines, _super);
  7. function PBRMaterialDefines() {
  8. _super.call(this);
  9. this.ALBEDO = false;
  10. this.AMBIENT = false;
  11. this.OPACITY = false;
  12. this.OPACITYRGB = false;
  13. this.REFLECTION = false;
  14. this.EMISSIVE = false;
  15. this.REFLECTIVITY = false;
  16. this.BUMP = false;
  17. this.SPECULAROVERALPHA = false;
  18. this.CLIPPLANE = false;
  19. this.ALPHATEST = false;
  20. this.ALPHAFROMALBEDO = false;
  21. this.POINTSIZE = false;
  22. this.FOG = false;
  23. this.LIGHT0 = false;
  24. this.LIGHT1 = false;
  25. this.LIGHT2 = false;
  26. this.LIGHT3 = false;
  27. this.SPOTLIGHT0 = false;
  28. this.SPOTLIGHT1 = false;
  29. this.SPOTLIGHT2 = false;
  30. this.SPOTLIGHT3 = false;
  31. this.HEMILIGHT0 = false;
  32. this.HEMILIGHT1 = false;
  33. this.HEMILIGHT2 = false;
  34. this.HEMILIGHT3 = false;
  35. this.POINTLIGHT0 = false;
  36. this.POINTLIGHT1 = false;
  37. this.POINTLIGHT2 = false;
  38. this.POINTLIGHT3 = false;
  39. this.DIRLIGHT0 = false;
  40. this.DIRLIGHT1 = false;
  41. this.DIRLIGHT2 = false;
  42. this.DIRLIGHT3 = false;
  43. this.SPECULARTERM = false;
  44. this.SHADOW0 = false;
  45. this.SHADOW1 = false;
  46. this.SHADOW2 = false;
  47. this.SHADOW3 = false;
  48. this.SHADOWS = false;
  49. this.SHADOWVSM0 = false;
  50. this.SHADOWVSM1 = false;
  51. this.SHADOWVSM2 = false;
  52. this.SHADOWVSM3 = false;
  53. this.SHADOWPCF0 = false;
  54. this.SHADOWPCF1 = false;
  55. this.SHADOWPCF2 = false;
  56. this.SHADOWPCF3 = false;
  57. this.OPACITYFRESNEL = false;
  58. this.EMISSIVEFRESNEL = false;
  59. this.FRESNEL = false;
  60. this.NORMAL = false;
  61. this.UV1 = false;
  62. this.UV2 = false;
  63. this.VERTEXCOLOR = false;
  64. this.VERTEXALPHA = false;
  65. this.NUM_BONE_INFLUENCERS = 0;
  66. this.BonesPerMesh = 0;
  67. this.INSTANCES = false;
  68. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  69. this.EMISSIVEASILLUMINATION = false;
  70. this.LINKEMISSIVEWITHALBEDO = false;
  71. this.LIGHTMAP = false;
  72. this.USELIGHTMAPASSHADOWMAP = false;
  73. this.REFLECTIONMAP_3D = false;
  74. this.REFLECTIONMAP_SPHERICAL = false;
  75. this.REFLECTIONMAP_PLANAR = false;
  76. this.REFLECTIONMAP_CUBIC = false;
  77. this.REFLECTIONMAP_PROJECTION = false;
  78. this.REFLECTIONMAP_SKYBOX = false;
  79. this.REFLECTIONMAP_EXPLICIT = false;
  80. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  81. this.INVERTCUBICMAP = false;
  82. this.LOGARITHMICDEPTH = false;
  83. this.CAMERATONEMAP = false;
  84. this.CAMERACONTRAST = false;
  85. this.OVERLOADEDVALUES = false;
  86. this.OVERLOADEDSHADOWVALUES = false;
  87. this.USESPHERICALFROMREFLECTIONMAP = false;
  88. this.REFRACTION = false;
  89. this.REFRACTIONMAP_3D = false;
  90. this.LINKREFRACTIONTOTRANSPARENCY = false;
  91. this.REFRACTIONMAPINLINEARSPACE = false;
  92. this._keys = Object.keys(this);
  93. }
  94. return PBRMaterialDefines;
  95. })(BABYLON.MaterialDefines);
  96. var PBRMaterial = (function (_super) {
  97. __extends(PBRMaterial, _super);
  98. function PBRMaterial(name, scene) {
  99. var _this = this;
  100. _super.call(this, name, scene);
  101. this.directIntensity = 1.0;
  102. this.emissiveIntensity = 1.0;
  103. this.environmentIntensity = 1.0;
  104. this.specularIntensity = 1.0;
  105. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  106. this.overloadedShadowIntensity = 1.0;
  107. this.overloadedShadeIntensity = 1.0;
  108. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  109. this.cameraExposure = 1.0;
  110. this.cameraContrast = 1.0;
  111. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  112. this.overloadedAmbientIntensity = 0.0;
  113. this.overloadedAlbedoIntensity = 0.0;
  114. this.overloadedReflectivityIntensity = 0.0;
  115. this.overloadedEmissiveIntensity = 0.0;
  116. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  117. this.overloadedAmbient = BABYLON.Color3.White();
  118. this.overloadedAlbedo = BABYLON.Color3.White();
  119. this.overloadedReflectivity = BABYLON.Color3.White();
  120. this.overloadedEmissive = BABYLON.Color3.White();
  121. this.overloadedReflection = BABYLON.Color3.White();
  122. this.overloadedMicroSurface = 0.0;
  123. this.overloadedMicroSurfaceIntensity = 0.0;
  124. this.overloadedReflectionIntensity = 0.0;
  125. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  126. this.disableBumpMap = false;
  127. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  128. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  129. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  130. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  131. this.microSurface = 0.5;
  132. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  133. this.useAlphaFromAlbedoTexture = false;
  134. this.useEmissiveAsIllumination = false;
  135. this.linkEmissiveWithAlbedo = false;
  136. this.useSpecularOverAlpha = true;
  137. this.disableLighting = false;
  138. this.indexOfRefraction = 0.66;
  139. this.invertRefractionY = false;
  140. this.linkRefractionWithTransparency = false;
  141. this.useLightmapAsShadowmap = false;
  142. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  143. this._renderTargets = new BABYLON.SmartArray(16);
  144. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  145. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  146. this._tempColor = new BABYLON.Color3();
  147. this._defines = new PBRMaterialDefines();
  148. this._cachedDefines = new PBRMaterialDefines();
  149. this._myScene = null;
  150. this._myShadowGenerator = null;
  151. this._cachedDefines.BonesPerMesh = -1;
  152. this.getRenderTargetTextures = function () {
  153. _this._renderTargets.reset();
  154. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  155. _this._renderTargets.push(_this.reflectionTexture);
  156. }
  157. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  158. _this._renderTargets.push(_this.refractionTexture);
  159. }
  160. return _this._renderTargets;
  161. };
  162. }
  163. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  164. get: function () {
  165. return this._useLogarithmicDepth;
  166. },
  167. set: function (value) {
  168. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  169. },
  170. enumerable: true,
  171. configurable: true
  172. });
  173. PBRMaterial.prototype.needAlphaBlending = function () {
  174. if (this.linkRefractionWithTransparency) {
  175. return false;
  176. }
  177. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  178. };
  179. PBRMaterial.prototype.needAlphaTesting = function () {
  180. if (this.linkRefractionWithTransparency) {
  181. return false;
  182. }
  183. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  184. };
  185. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  186. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  187. };
  188. PBRMaterial.prototype.getAlphaTestTexture = function () {
  189. return this.albedoTexture;
  190. };
  191. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  192. if (!mesh) {
  193. return true;
  194. }
  195. if (this._defines.INSTANCES !== useInstances) {
  196. return false;
  197. }
  198. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  199. return true;
  200. }
  201. return false;
  202. };
  203. PBRMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  204. var lightIndex = 0;
  205. var needNormals = false;
  206. for (var index = 0; index < scene.lights.length; index++) {
  207. var light = scene.lights[index];
  208. if (!light.isEnabled()) {
  209. continue;
  210. }
  211. // Excluded check
  212. if (light._excludedMeshesIds.length > 0) {
  213. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  214. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  215. if (excludedMesh) {
  216. light.excludedMeshes.push(excludedMesh);
  217. }
  218. }
  219. light._excludedMeshesIds = [];
  220. }
  221. // Included check
  222. if (light._includedOnlyMeshesIds.length > 0) {
  223. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  224. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  225. if (includedOnlyMesh) {
  226. light.includedOnlyMeshes.push(includedOnlyMesh);
  227. }
  228. }
  229. light._includedOnlyMeshesIds = [];
  230. }
  231. if (!light.canAffectMesh(mesh)) {
  232. continue;
  233. }
  234. needNormals = true;
  235. defines["LIGHT" + lightIndex] = true;
  236. var type;
  237. if (light instanceof BABYLON.SpotLight) {
  238. type = "SPOTLIGHT" + lightIndex;
  239. }
  240. else if (light instanceof BABYLON.HemisphericLight) {
  241. type = "HEMILIGHT" + lightIndex;
  242. }
  243. else if (light instanceof BABYLON.PointLight) {
  244. type = "POINTLIGHT" + lightIndex;
  245. }
  246. else {
  247. type = "DIRLIGHT" + lightIndex;
  248. }
  249. defines[type] = true;
  250. // Specular
  251. if (!light.specular.equalsFloats(0, 0, 0)) {
  252. defines["SPECULARTERM"] = true;
  253. }
  254. // Shadows
  255. if (scene.shadowsEnabled) {
  256. var shadowGenerator = light.getShadowGenerator();
  257. if (mesh && mesh.receiveShadows && shadowGenerator) {
  258. defines["SHADOW" + lightIndex] = true;
  259. defines["SHADOWS"] = true;
  260. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  261. defines["SHADOWVSM" + lightIndex] = true;
  262. }
  263. if (shadowGenerator.usePoissonSampling) {
  264. defines["SHADOWPCF" + lightIndex] = true;
  265. }
  266. }
  267. }
  268. lightIndex++;
  269. if (lightIndex === maxSimultaneousLights)
  270. break;
  271. }
  272. return needNormals;
  273. };
  274. PBRMaterial.BindLights = function (scene, mesh, effect, defines) {
  275. var lightIndex = 0;
  276. var depthValuesAlreadySet = false;
  277. for (var index = 0; index < scene.lights.length; index++) {
  278. var light = scene.lights[index];
  279. if (!light.isEnabled()) {
  280. continue;
  281. }
  282. if (!light.canAffectMesh(mesh)) {
  283. continue;
  284. }
  285. if (light instanceof BABYLON.PointLight) {
  286. // Point Light
  287. light.transferToEffect(effect, "vLightData" + lightIndex);
  288. }
  289. else if (light instanceof BABYLON.DirectionalLight) {
  290. // Directional Light
  291. light.transferToEffect(effect, "vLightData" + lightIndex);
  292. }
  293. else if (light instanceof BABYLON.SpotLight) {
  294. // Spot Light
  295. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  296. }
  297. else if (light instanceof BABYLON.HemisphericLight) {
  298. // Hemispheric Light
  299. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  300. }
  301. // GAMMA CORRECTION.
  302. light.diffuse.toLinearSpaceToRef(PBRMaterial._scaledAlbedo);
  303. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  304. light.diffuse.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  305. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  306. if (defines["SPECULARTERM"]) {
  307. light.specular.toLinearSpaceToRef(PBRMaterial._scaledReflectivity);
  308. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  309. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  310. }
  311. // Shadows
  312. if (scene.shadowsEnabled) {
  313. var shadowGenerator = light.getShadowGenerator();
  314. if (mesh.receiveShadows && shadowGenerator) {
  315. if (!light.needCube()) {
  316. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  317. }
  318. else {
  319. if (!depthValuesAlreadySet) {
  320. depthValuesAlreadySet = true;
  321. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  322. }
  323. }
  324. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  325. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  326. }
  327. }
  328. lightIndex++;
  329. if (lightIndex === maxSimultaneousLights)
  330. break;
  331. }
  332. };
  333. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  334. if (this.checkReadyOnlyOnce) {
  335. if (this._wasPreviouslyReady) {
  336. return true;
  337. }
  338. }
  339. var scene = this.getScene();
  340. if (!this.checkReadyOnEveryCall) {
  341. if (this._renderId === scene.getRenderId()) {
  342. if (this._checkCache(scene, mesh, useInstances)) {
  343. return true;
  344. }
  345. }
  346. }
  347. var engine = scene.getEngine();
  348. var needNormals = false;
  349. var needUVs = false;
  350. this._defines.reset();
  351. if (scene.texturesEnabled) {
  352. // Textures
  353. if (scene.texturesEnabled) {
  354. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  355. if (!this.albedoTexture.isReady()) {
  356. return false;
  357. }
  358. else {
  359. needUVs = true;
  360. this._defines.ALBEDO = true;
  361. }
  362. }
  363. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  364. if (!this.ambientTexture.isReady()) {
  365. return false;
  366. }
  367. else {
  368. needUVs = true;
  369. this._defines.AMBIENT = true;
  370. }
  371. }
  372. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  373. if (!this.opacityTexture.isReady()) {
  374. return false;
  375. }
  376. else {
  377. needUVs = true;
  378. this._defines.OPACITY = true;
  379. if (this.opacityTexture.getAlphaFromRGB) {
  380. this._defines.OPACITYRGB = true;
  381. }
  382. }
  383. }
  384. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  385. if (!this.reflectionTexture.isReady()) {
  386. return false;
  387. }
  388. else {
  389. needNormals = true;
  390. this._defines.REFLECTION = true;
  391. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  392. this._defines.INVERTCUBICMAP = true;
  393. }
  394. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  395. switch (this.reflectionTexture.coordinatesMode) {
  396. case BABYLON.Texture.CUBIC_MODE:
  397. case BABYLON.Texture.INVCUBIC_MODE:
  398. this._defines.REFLECTIONMAP_CUBIC = true;
  399. break;
  400. case BABYLON.Texture.EXPLICIT_MODE:
  401. this._defines.REFLECTIONMAP_EXPLICIT = true;
  402. break;
  403. case BABYLON.Texture.PLANAR_MODE:
  404. this._defines.REFLECTIONMAP_PLANAR = true;
  405. break;
  406. case BABYLON.Texture.PROJECTION_MODE:
  407. this._defines.REFLECTIONMAP_PROJECTION = true;
  408. break;
  409. case BABYLON.Texture.SKYBOX_MODE:
  410. this._defines.REFLECTIONMAP_SKYBOX = true;
  411. break;
  412. case BABYLON.Texture.SPHERICAL_MODE:
  413. this._defines.REFLECTIONMAP_SPHERICAL = true;
  414. break;
  415. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  416. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  417. break;
  418. }
  419. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture) {
  420. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  421. needNormals = true;
  422. }
  423. }
  424. }
  425. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  426. if (!this.lightmapTexture.isReady()) {
  427. return false;
  428. }
  429. else {
  430. needUVs = true;
  431. this._defines.LIGHTMAP = true;
  432. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  433. }
  434. }
  435. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  436. if (!this.emissiveTexture.isReady()) {
  437. return false;
  438. }
  439. else {
  440. needUVs = true;
  441. this._defines.EMISSIVE = true;
  442. }
  443. }
  444. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  445. if (!this.reflectivityTexture.isReady()) {
  446. return false;
  447. }
  448. else {
  449. needUVs = true;
  450. this._defines.REFLECTIVITY = true;
  451. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  452. }
  453. }
  454. }
  455. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  456. if (!this.bumpTexture.isReady()) {
  457. return false;
  458. }
  459. else {
  460. needUVs = true;
  461. this._defines.BUMP = true;
  462. }
  463. }
  464. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  465. if (!this.refractionTexture.isReady()) {
  466. return false;
  467. }
  468. else {
  469. needUVs = true;
  470. this._defines.REFRACTION = true;
  471. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  472. if (this.linkRefractionWithTransparency) {
  473. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  474. }
  475. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  476. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  477. }
  478. }
  479. }
  480. }
  481. // Effect
  482. if (scene.clipPlane) {
  483. this._defines.CLIPPLANE = true;
  484. }
  485. if (engine.getAlphaTesting()) {
  486. this._defines.ALPHATEST = true;
  487. }
  488. if (this._shouldUseAlphaFromAlbedoTexture()) {
  489. this._defines.ALPHAFROMALBEDO = true;
  490. }
  491. if (this.useEmissiveAsIllumination) {
  492. this._defines.EMISSIVEASILLUMINATION = true;
  493. }
  494. if (this.linkEmissiveWithAlbedo) {
  495. this._defines.LINKEMISSIVEWITHALBEDO = true;
  496. }
  497. if (this.useLogarithmicDepth) {
  498. this._defines.LOGARITHMICDEPTH = true;
  499. }
  500. if (this.cameraContrast != 1) {
  501. this._defines.CAMERACONTRAST = true;
  502. }
  503. if (this.cameraExposure != 1) {
  504. this._defines.CAMERATONEMAP = true;
  505. }
  506. if (this.overloadedShadeIntensity != 1 ||
  507. this.overloadedShadowIntensity != 1) {
  508. this._defines.OVERLOADEDSHADOWVALUES = true;
  509. }
  510. if (this.overloadedMicroSurfaceIntensity > 0 ||
  511. this.overloadedEmissiveIntensity > 0 ||
  512. this.overloadedReflectivityIntensity > 0 ||
  513. this.overloadedAlbedoIntensity > 0 ||
  514. this.overloadedAmbientIntensity > 0 ||
  515. this.overloadedReflectionIntensity > 0) {
  516. this._defines.OVERLOADEDVALUES = true;
  517. }
  518. // Point size
  519. if (this.pointsCloud || scene.forcePointsCloud) {
  520. this._defines.POINTSIZE = true;
  521. }
  522. // Fog
  523. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  524. this._defines.FOG = true;
  525. }
  526. if (scene.lightsEnabled && !this.disableLighting) {
  527. needNormals = PBRMaterial.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  528. }
  529. if (BABYLON.StandardMaterial.FresnelEnabled) {
  530. // Fresnel
  531. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  532. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  533. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  534. this._defines.OPACITYFRESNEL = true;
  535. }
  536. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  537. this._defines.EMISSIVEFRESNEL = true;
  538. }
  539. needNormals = true;
  540. this._defines.FRESNEL = true;
  541. }
  542. }
  543. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  544. this._defines.SPECULAROVERALPHA = true;
  545. }
  546. // Attribs
  547. if (mesh) {
  548. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  549. this._defines.NORMAL = true;
  550. }
  551. if (needUVs) {
  552. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  553. this._defines.UV1 = true;
  554. }
  555. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  556. this._defines.UV2 = true;
  557. }
  558. }
  559. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  560. this._defines.VERTEXCOLOR = true;
  561. if (mesh.hasVertexAlpha) {
  562. this._defines.VERTEXALPHA = true;
  563. }
  564. }
  565. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  566. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  567. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  568. }
  569. // Instances
  570. if (useInstances) {
  571. this._defines.INSTANCES = true;
  572. }
  573. }
  574. // Get correct effect
  575. if (!this._defines.isEqual(this._cachedDefines)) {
  576. this._defines.cloneTo(this._cachedDefines);
  577. scene.resetCachedMaterial();
  578. // Fallbacks
  579. var fallbacks = new BABYLON.EffectFallbacks();
  580. if (this._defines.REFLECTION) {
  581. fallbacks.addFallback(0, "REFLECTION");
  582. }
  583. if (this._defines.REFLECTIVITY) {
  584. fallbacks.addFallback(0, "REFLECTIVITY");
  585. }
  586. if (this._defines.BUMP) {
  587. fallbacks.addFallback(0, "BUMP");
  588. }
  589. if (this._defines.SPECULAROVERALPHA) {
  590. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  591. }
  592. if (this._defines.FOG) {
  593. fallbacks.addFallback(1, "FOG");
  594. }
  595. if (this._defines.POINTSIZE) {
  596. fallbacks.addFallback(0, "POINTSIZE");
  597. }
  598. if (this._defines.LOGARITHMICDEPTH) {
  599. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  600. }
  601. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  602. if (!this._defines["LIGHT" + lightIndex]) {
  603. continue;
  604. }
  605. if (lightIndex > 0) {
  606. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  607. }
  608. if (this._defines["SHADOW" + lightIndex]) {
  609. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  610. }
  611. if (this._defines["SHADOWPCF" + lightIndex]) {
  612. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  613. }
  614. if (this._defines["SHADOWVSM" + lightIndex]) {
  615. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  616. }
  617. }
  618. if (this._defines.SPECULARTERM) {
  619. fallbacks.addFallback(0, "SPECULARTERM");
  620. }
  621. if (this._defines.OPACITYFRESNEL) {
  622. fallbacks.addFallback(1, "OPACITYFRESNEL");
  623. }
  624. if (this._defines.EMISSIVEFRESNEL) {
  625. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  626. }
  627. if (this._defines.FRESNEL) {
  628. fallbacks.addFallback(3, "FRESNEL");
  629. }
  630. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  631. fallbacks.addCPUSkinningFallback(0, mesh);
  632. }
  633. //Attributes
  634. var attribs = [BABYLON.VertexBuffer.PositionKind];
  635. if (this._defines.NORMAL) {
  636. attribs.push(BABYLON.VertexBuffer.NormalKind);
  637. }
  638. if (this._defines.UV1) {
  639. attribs.push(BABYLON.VertexBuffer.UVKind);
  640. }
  641. if (this._defines.UV2) {
  642. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  643. }
  644. if (this._defines.VERTEXCOLOR) {
  645. attribs.push(BABYLON.VertexBuffer.ColorKind);
  646. }
  647. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  650. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  653. }
  654. }
  655. if (this._defines.INSTANCES) {
  656. attribs.push("world0");
  657. attribs.push("world1");
  658. attribs.push("world2");
  659. attribs.push("world3");
  660. }
  661. // Legacy browser patch
  662. var shaderName = "pbr";
  663. if (!scene.getEngine().getCaps().standardDerivatives) {
  664. shaderName = "legacypbr";
  665. }
  666. var join = this._defines.toString();
  667. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  668. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  669. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  670. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  671. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  672. "vFogInfos", "vFogColor", "pointSize",
  673. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  674. "mBones",
  675. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  676. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  677. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  678. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  679. "logarithmicDepthConstant",
  680. "vSphericalX", "vSphericalY", "vSphericalZ",
  681. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  682. "vSphericalXY", "vSphericalYZ", "vSphericalZX"
  683. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  684. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  685. ], join, fallbacks, this.onCompiled, this.onError);
  686. }
  687. if (!this._effect.isReady()) {
  688. return false;
  689. }
  690. this._renderId = scene.getRenderId();
  691. this._wasPreviouslyReady = true;
  692. if (mesh) {
  693. if (!mesh._materialDefines) {
  694. mesh._materialDefines = new PBRMaterialDefines();
  695. }
  696. this._defines.cloneTo(mesh._materialDefines);
  697. }
  698. return true;
  699. };
  700. PBRMaterial.prototype.unbind = function () {
  701. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  702. this._effect.setTexture("reflection2DSampler", null);
  703. }
  704. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  705. this._effect.setTexture("refraction2DSampler", null);
  706. }
  707. _super.prototype.unbind.call(this);
  708. };
  709. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  710. this._effect.setMatrix("world", world);
  711. };
  712. PBRMaterial.prototype.bind = function (world, mesh) {
  713. this._myScene = this.getScene();
  714. // Matrices
  715. this.bindOnlyWorldMatrix(world);
  716. // Bones
  717. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  718. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  719. }
  720. if (this._myScene.getCachedMaterial() !== this) {
  721. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  722. if (BABYLON.StandardMaterial.FresnelEnabled) {
  723. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  724. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  725. }
  726. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  727. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  728. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  729. }
  730. }
  731. // Textures
  732. if (this._myScene.texturesEnabled) {
  733. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  734. this._effect.setTexture("albedoSampler", this.albedoTexture);
  735. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  736. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  737. }
  738. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  739. this._effect.setTexture("ambientSampler", this.ambientTexture);
  740. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  741. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  742. }
  743. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  744. this._effect.setTexture("opacitySampler", this.opacityTexture);
  745. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  746. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  747. }
  748. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  749. if (this.reflectionTexture.isCube) {
  750. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  751. }
  752. else {
  753. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  754. }
  755. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  756. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  757. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  758. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  759. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  760. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  761. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  762. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  763. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  764. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  765. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  766. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  767. }
  768. }
  769. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  770. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  771. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  772. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  773. }
  774. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  775. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  776. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  777. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  778. }
  779. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  780. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  781. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  782. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  783. }
  784. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  785. this._effect.setTexture("bumpSampler", this.bumpTexture);
  786. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  787. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  788. }
  789. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  790. var depth = 1.0;
  791. if (this.refractionTexture.isCube) {
  792. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  793. }
  794. else {
  795. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  796. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  797. if (this.refractionTexture.depth) {
  798. depth = this.refractionTexture.depth;
  799. }
  800. }
  801. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  802. }
  803. }
  804. // Clip plane
  805. if (this._myScene.clipPlane) {
  806. this._effect.setFloat4("vClipPlane", this._myScene.clipPlane.normal.x, this._myScene.clipPlane.normal.y, this._myScene.clipPlane.normal.z, this._myScene.clipPlane.d);
  807. }
  808. // Point size
  809. if (this.pointsCloud) {
  810. this._effect.setFloat("pointSize", this.pointSize);
  811. }
  812. // Colors
  813. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  814. // GAMMA CORRECTION.
  815. this.reflectivityColor.toLinearSpaceToRef(PBRMaterial._scaledReflectivity);
  816. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  817. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  818. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  819. // GAMMA CORRECTION.
  820. this.emissiveColor.toLinearSpaceToRef(PBRMaterial._scaledEmissive);
  821. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  822. // GAMMA CORRECTION.
  823. this.reflectionColor.toLinearSpaceToRef(PBRMaterial._scaledReflection);
  824. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  825. }
  826. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  827. // GAMMA CORRECTION.
  828. this.albedoColor.toLinearSpaceToRef(PBRMaterial._scaledAlbedo);
  829. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  830. // Lights
  831. if (this._myScene.lightsEnabled && !this.disableLighting) {
  832. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines);
  833. }
  834. // View
  835. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  836. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  837. }
  838. // Fog
  839. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  840. this._effect.setFloat4("vFogInfos", this._myScene.fogMode, this._myScene.fogStart, this._myScene.fogEnd, this._myScene.fogDensity);
  841. this._effect.setColor3("vFogColor", this._myScene.fogColor);
  842. }
  843. this._lightingInfos.x = this.directIntensity;
  844. this._lightingInfos.y = this.emissiveIntensity;
  845. this._lightingInfos.z = this.environmentIntensity;
  846. this._lightingInfos.w = this.specularIntensity;
  847. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  848. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  849. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  850. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  851. this._cameraInfos.x = this.cameraExposure;
  852. this._cameraInfos.y = this.cameraContrast;
  853. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  854. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  855. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  856. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  857. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  858. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  859. this.overloadedAmbient.toLinearSpaceToRef(this._tempColor);
  860. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  861. this.overloadedAlbedo.toLinearSpaceToRef(this._tempColor);
  862. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  863. this.overloadedReflectivity.toLinearSpaceToRef(this._tempColor);
  864. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  865. this.overloadedEmissive.toLinearSpaceToRef(this._tempColor);
  866. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  867. this.overloadedReflection.toLinearSpaceToRef(this._tempColor);
  868. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  869. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  870. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  871. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  872. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  873. // Log. depth
  874. if (this._defines.LOGARITHMICDEPTH) {
  875. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(this._myScene.activeCamera.maxZ + 1.0) / Math.LN2));
  876. }
  877. }
  878. _super.prototype.bind.call(this, world, mesh);
  879. this._myScene = null;
  880. };
  881. PBRMaterial.prototype.getAnimatables = function () {
  882. var results = [];
  883. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  884. results.push(this.albedoTexture);
  885. }
  886. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  887. results.push(this.ambientTexture);
  888. }
  889. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  890. results.push(this.opacityTexture);
  891. }
  892. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  893. results.push(this.reflectionTexture);
  894. }
  895. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  896. results.push(this.emissiveTexture);
  897. }
  898. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  899. results.push(this.reflectivityTexture);
  900. }
  901. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  902. results.push(this.bumpTexture);
  903. }
  904. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  905. results.push(this.lightmapTexture);
  906. }
  907. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  908. results.push(this.refractionTexture);
  909. }
  910. return results;
  911. };
  912. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  913. if (this.albedoTexture) {
  914. this.albedoTexture.dispose();
  915. }
  916. if (this.ambientTexture) {
  917. this.ambientTexture.dispose();
  918. }
  919. if (this.opacityTexture) {
  920. this.opacityTexture.dispose();
  921. }
  922. if (this.reflectionTexture) {
  923. this.reflectionTexture.dispose();
  924. }
  925. if (this.emissiveTexture) {
  926. this.emissiveTexture.dispose();
  927. }
  928. if (this.reflectivityTexture) {
  929. this.reflectivityTexture.dispose();
  930. }
  931. if (this.bumpTexture) {
  932. this.bumpTexture.dispose();
  933. }
  934. if (this.lightmapTexture) {
  935. this.lightmapTexture.dispose();
  936. }
  937. if (this.refractionTexture) {
  938. this.refractionTexture.dispose();
  939. }
  940. _super.prototype.dispose.call(this, forceDisposeEffect);
  941. };
  942. PBRMaterial.prototype.clone = function (name) {
  943. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  944. // Base material
  945. this.copyTo(newPBRMaterial);
  946. newPBRMaterial.directIntensity = this.directIntensity;
  947. newPBRMaterial.emissiveIntensity = this.emissiveIntensity;
  948. newPBRMaterial.environmentIntensity = this.environmentIntensity;
  949. newPBRMaterial.specularIntensity = this.specularIntensity;
  950. newPBRMaterial.cameraExposure = this.cameraExposure;
  951. newPBRMaterial.cameraContrast = this.cameraContrast;
  952. newPBRMaterial.overloadedShadowIntensity = this.overloadedShadowIntensity;
  953. newPBRMaterial.overloadedShadeIntensity = this.overloadedShadeIntensity;
  954. newPBRMaterial.overloadedAmbientIntensity = this.overloadedAmbientIntensity;
  955. newPBRMaterial.overloadedAlbedoIntensity = this.overloadedAlbedoIntensity;
  956. newPBRMaterial.overloadedReflectivityIntensity = this.overloadedReflectivityIntensity;
  957. newPBRMaterial.overloadedEmissiveIntensity = this.overloadedEmissiveIntensity;
  958. newPBRMaterial.overloadedAmbient = this.overloadedAmbient;
  959. newPBRMaterial.overloadedAlbedo = this.overloadedAlbedo;
  960. newPBRMaterial.overloadedReflectivity = this.overloadedReflectivity;
  961. newPBRMaterial.overloadedEmissive = this.overloadedEmissive;
  962. newPBRMaterial.overloadedReflection = this.overloadedReflection;
  963. newPBRMaterial.overloadedMicroSurface = this.overloadedMicroSurface;
  964. newPBRMaterial.overloadedMicroSurfaceIntensity = this.overloadedMicroSurfaceIntensity;
  965. newPBRMaterial.overloadedReflectionIntensity = this.overloadedReflectionIntensity;
  966. newPBRMaterial.disableBumpMap = this.disableBumpMap;
  967. // Standard material
  968. if (this.albedoTexture && this.albedoTexture.clone) {
  969. newPBRMaterial.albedoTexture = this.albedoTexture.clone();
  970. }
  971. if (this.ambientTexture && this.ambientTexture.clone) {
  972. newPBRMaterial.ambientTexture = this.ambientTexture.clone();
  973. }
  974. if (this.opacityTexture && this.opacityTexture.clone) {
  975. newPBRMaterial.opacityTexture = this.opacityTexture.clone();
  976. }
  977. if (this.reflectionTexture && this.reflectionTexture.clone) {
  978. newPBRMaterial.reflectionTexture = this.reflectionTexture.clone();
  979. }
  980. if (this.emissiveTexture && this.emissiveTexture.clone) {
  981. newPBRMaterial.emissiveTexture = this.emissiveTexture.clone();
  982. }
  983. if (this.reflectivityTexture && this.reflectivityTexture.clone) {
  984. newPBRMaterial.reflectivityTexture = this.reflectivityTexture.clone();
  985. }
  986. if (this.bumpTexture && this.bumpTexture.clone) {
  987. newPBRMaterial.bumpTexture = this.bumpTexture.clone();
  988. }
  989. if (this.lightmapTexture && this.lightmapTexture.clone) {
  990. newPBRMaterial.lightmapTexture = this.lightmapTexture.clone();
  991. newPBRMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  992. }
  993. if (this.refractionTexture && this.refractionTexture.clone) {
  994. newPBRMaterial.refractionTexture = this.refractionTexture.clone();
  995. newPBRMaterial.linkRefractionWithTransparency = this.linkRefractionWithTransparency;
  996. }
  997. newPBRMaterial.ambientColor = this.ambientColor.clone();
  998. newPBRMaterial.albedoColor = this.albedoColor.clone();
  999. newPBRMaterial.reflectivityColor = this.reflectivityColor.clone();
  1000. newPBRMaterial.reflectionColor = this.reflectionColor.clone();
  1001. newPBRMaterial.microSurface = this.microSurface;
  1002. newPBRMaterial.emissiveColor = this.emissiveColor.clone();
  1003. newPBRMaterial.useAlphaFromAlbedoTexture = this.useAlphaFromAlbedoTexture;
  1004. newPBRMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  1005. newPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha = this.useMicroSurfaceFromReflectivityMapAlpha;
  1006. newPBRMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  1007. newPBRMaterial.indexOfRefraction = this.indexOfRefraction;
  1008. newPBRMaterial.invertRefractionY = this.invertRefractionY;
  1009. newPBRMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  1010. newPBRMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  1011. return newPBRMaterial;
  1012. };
  1013. PBRMaterial.prototype.serialize = function () {
  1014. var serializationObject = _super.prototype.serialize.call(this);
  1015. serializationObject.customType = "BABYLON.PBRMaterial";
  1016. serializationObject.directIntensity = this.directIntensity;
  1017. serializationObject.emissiveIntensity = this.emissiveIntensity;
  1018. serializationObject.environmentIntensity = this.environmentIntensity;
  1019. serializationObject.specularIntensity = this.specularIntensity;
  1020. serializationObject.cameraExposure = this.cameraExposure;
  1021. serializationObject.cameraContrast = this.cameraContrast;
  1022. serializationObject.overloadedShadowIntensity = this.overloadedShadowIntensity;
  1023. serializationObject.overloadedShadeIntensity = this.overloadedShadeIntensity;
  1024. serializationObject.overloadedAmbientIntensity = this.overloadedAmbientIntensity;
  1025. serializationObject.overloadedAlbedoIntensity = this.overloadedAlbedoIntensity;
  1026. serializationObject.overloadedReflectivityIntensity = this.overloadedReflectivityIntensity;
  1027. serializationObject.overloadedEmissiveIntensity = this.overloadedEmissiveIntensity;
  1028. serializationObject.overloadedAmbient = this.overloadedAmbient.asArray();
  1029. serializationObject.overloadedAlbedo = this.overloadedAlbedo.asArray();
  1030. serializationObject.overloadedReflectivity = this.overloadedReflectivity.asArray();
  1031. serializationObject.overloadedEmissive = this.overloadedEmissive.asArray();
  1032. serializationObject.overloadedReflection = this.overloadedReflection.asArray();
  1033. serializationObject.overloadedMicroSurface = this.overloadedMicroSurface;
  1034. serializationObject.overloadedMicroSurfaceIntensity = this.overloadedMicroSurfaceIntensity;
  1035. serializationObject.overloadedReflectionIntensity = this.overloadedReflectionIntensity;
  1036. serializationObject.disableBumpMap = this.disableBumpMap;
  1037. // Standard material
  1038. if (this.albedoTexture) {
  1039. serializationObject.albedoTexture = this.albedoTexture.serialize();
  1040. }
  1041. if (this.ambientTexture) {
  1042. serializationObject.ambientTexture = this.ambientTexture.serialize();
  1043. }
  1044. if (this.opacityTexture) {
  1045. serializationObject.opacityTexture = this.opacityTexture.serialize();
  1046. }
  1047. if (this.reflectionTexture) {
  1048. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  1049. }
  1050. if (this.emissiveTexture) {
  1051. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  1052. }
  1053. if (this.reflectivityTexture) {
  1054. serializationObject.reflectivityTexture = this.reflectivityTexture.serialize();
  1055. }
  1056. if (this.bumpTexture) {
  1057. serializationObject.bumpTexture = this.bumpTexture.serialize();
  1058. }
  1059. if (this.lightmapTexture) {
  1060. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  1061. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  1062. }
  1063. if (this.refractionTexture) {
  1064. serializationObject.refractionTexture = this.refractionTexture;
  1065. serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;
  1066. }
  1067. serializationObject.ambientColor = this.ambientColor.asArray();
  1068. serializationObject.albedoColor = this.albedoColor.asArray();
  1069. serializationObject.reflectivityColor = this.reflectivityColor.asArray();
  1070. serializationObject.reflectionColor = this.reflectionColor.asArray();
  1071. serializationObject.microSurface = this.microSurface;
  1072. serializationObject.emissiveColor = this.emissiveColor.asArray();
  1073. serializationObject.useAlphaFromAlbedoTexture = this.useAlphaFromAlbedoTexture;
  1074. serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  1075. serializationObject.useMicroSurfaceFromReflectivityMapAlpha = this.useMicroSurfaceFromReflectivityMapAlpha;
  1076. serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;
  1077. serializationObject.indexOfRefraction = this.indexOfRefraction;
  1078. serializationObject.invertRefractionY = this.invertRefractionY;
  1079. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  1080. serializationObject.opacityFresnelParameters = this.opacityFresnelParameters.serialize();
  1081. return serializationObject;
  1082. };
  1083. PBRMaterial.Parse = function (source, scene, rootUrl) {
  1084. var material = new PBRMaterial(source.name, scene);
  1085. material.alpha = source.alpha;
  1086. material.id = source.id;
  1087. if (source.disableDepthWrite) {
  1088. material.disableDepthWrite = source.disableDepthWrite;
  1089. }
  1090. if (source.checkReadyOnlyOnce) {
  1091. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  1092. }
  1093. BABYLON.Tags.AddTagsTo(material, source.tags);
  1094. material.backFaceCulling = source.backFaceCulling;
  1095. material.wireframe = source.wireframe;
  1096. material.directIntensity = source.directIntensity;
  1097. material.emissiveIntensity = source.emissiveIntensity;
  1098. material.environmentIntensity = source.environmentIntensity;
  1099. material.specularIntensity = source.specularIntensity;
  1100. material.cameraExposure = source.cameraExposure;
  1101. material.cameraContrast = source.cameraContrast;
  1102. material.overloadedShadowIntensity = source.overloadedShadowIntensity;
  1103. material.overloadedShadeIntensity = source.overloadedShadeIntensity;
  1104. material.overloadedAmbientIntensity = source.overloadedAmbientIntensity;
  1105. material.overloadedAlbedoIntensity = source.overloadedAlbedoIntensity;
  1106. material.overloadedReflectivityIntensity = source.overloadedReflectivityIntensity;
  1107. material.overloadedEmissiveIntensity = source.overloadedEmissiveIntensity;
  1108. material.overloadedAmbient = BABYLON.Color3.FromArray(source.overloadedAmbient);
  1109. material.overloadedAlbedo = BABYLON.Color3.FromArray(source.overloadedAlbedo);
  1110. material.overloadedReflectivity = BABYLON.Color3.FromArray(source.overloadedReflectivity);
  1111. material.overloadedEmissive = BABYLON.Color3.FromArray(source.overloadedEmissive);
  1112. material.overloadedReflection = BABYLON.Color3.FromArray(source.overloadedReflection);
  1113. material.overloadedMicroSurface = source.overloadedMicroSurface;
  1114. material.overloadedMicroSurfaceIntensity = source.overloadedMicroSurfaceIntensity;
  1115. material.overloadedReflectionIntensity = source.overloadedReflectionIntensity;
  1116. material.disableBumpMap = source.disableBumpMap;
  1117. // Standard material
  1118. if (source.albedoTexture) {
  1119. material.albedoTexture = BABYLON.Texture.Parse(source.albedoTexture, scene, rootUrl);
  1120. }
  1121. if (source.ambientTexture) {
  1122. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  1123. }
  1124. if (source.opacityTexture) {
  1125. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  1126. }
  1127. if (source.reflectionTexture) {
  1128. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  1129. }
  1130. if (source.emissiveTexture) {
  1131. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  1132. }
  1133. if (source.reflectivityTexture) {
  1134. material.reflectivityTexture = BABYLON.Texture.Parse(source.reflectivityTexture, scene, rootUrl);
  1135. }
  1136. if (source.bumpTexture) {
  1137. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  1138. }
  1139. if (source.lightmapTexture) {
  1140. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  1141. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  1142. }
  1143. if (source.refractionTexture) {
  1144. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  1145. material.linkRefractionWithTransparency = source.linkRefractionWithTransparency;
  1146. }
  1147. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  1148. material.albedoColor = BABYLON.Color3.FromArray(source.albedo);
  1149. material.reflectivityColor = BABYLON.Color3.FromArray(source.reflectivity);
  1150. material.reflectionColor = BABYLON.Color3.FromArray(source.reflectionColor);
  1151. material.microSurface = source.microSurface;
  1152. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  1153. material.useAlphaFromAlbedoTexture = source.useAlphaFromAlbedoTexture;
  1154. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  1155. material.useMicroSurfaceFromReflectivityMapAlpha = source.useMicroSurfaceFromReflectivityMapAlpha;
  1156. material.useSpecularOverAlpha = source.useSpecularOverAlpha;
  1157. material.indexOfRefraction = source.indexOfRefraction;
  1158. material.invertRefractionY = source.invertRefractionY;
  1159. material.emissiveFresnelParameters = BABYLON.FresnelParameters.Parse(source.emissiveFresnelParameters);
  1160. material.opacityFresnelParameters = BABYLON.FresnelParameters.Parse(source.opacityFresnelParameters);
  1161. return material;
  1162. };
  1163. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  1164. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  1165. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  1166. PBRMaterial._scaledReflection = new BABYLON.Color3();
  1167. return PBRMaterial;
  1168. })(BABYLON.Material);
  1169. BABYLON.PBRMaterial = PBRMaterial;
  1170. })(BABYLON || (BABYLON = {}));
  1171. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1172. var BABYLON;
  1173. (function (BABYLON) {
  1174. var SphericalHarmonics = (function () {
  1175. function SphericalHarmonics() {
  1176. this.L00 = BABYLON.Vector3.Zero();
  1177. this.L1_1 = BABYLON.Vector3.Zero();
  1178. this.L10 = BABYLON.Vector3.Zero();
  1179. this.L11 = BABYLON.Vector3.Zero();
  1180. this.L2_2 = BABYLON.Vector3.Zero();
  1181. this.L2_1 = BABYLON.Vector3.Zero();
  1182. this.L20 = BABYLON.Vector3.Zero();
  1183. this.L21 = BABYLON.Vector3.Zero();
  1184. this.L22 = BABYLON.Vector3.Zero();
  1185. }
  1186. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  1187. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  1188. var c = colorVector.scale(deltaSolidAngle);
  1189. this.L00 = this.L00.add(c.scale(0.282095));
  1190. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  1191. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  1192. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  1193. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  1194. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  1195. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  1196. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  1197. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  1198. };
  1199. SphericalHarmonics.prototype.scale = function (scale) {
  1200. this.L00 = this.L00.scale(scale);
  1201. this.L1_1 = this.L1_1.scale(scale);
  1202. this.L10 = this.L10.scale(scale);
  1203. this.L11 = this.L11.scale(scale);
  1204. this.L2_2 = this.L2_2.scale(scale);
  1205. this.L2_1 = this.L2_1.scale(scale);
  1206. this.L20 = this.L20.scale(scale);
  1207. this.L21 = this.L21.scale(scale);
  1208. this.L22 = this.L22.scale(scale);
  1209. };
  1210. return SphericalHarmonics;
  1211. })();
  1212. BABYLON.SphericalHarmonics = SphericalHarmonics;
  1213. })(BABYLON || (BABYLON = {}));
  1214. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1215. var BABYLON;
  1216. (function (BABYLON) {
  1217. var SphericalPolynomial = (function () {
  1218. function SphericalPolynomial() {
  1219. this.x = BABYLON.Vector3.Zero();
  1220. this.y = BABYLON.Vector3.Zero();
  1221. this.z = BABYLON.Vector3.Zero();
  1222. this.xx = BABYLON.Vector3.Zero();
  1223. this.yy = BABYLON.Vector3.Zero();
  1224. this.zz = BABYLON.Vector3.Zero();
  1225. this.xy = BABYLON.Vector3.Zero();
  1226. this.yz = BABYLON.Vector3.Zero();
  1227. this.zx = BABYLON.Vector3.Zero();
  1228. }
  1229. SphericalPolynomial.prototype.addAmbient = function (color) {
  1230. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  1231. this.xx = this.xx.add(colorVector);
  1232. this.yy = this.yy.add(colorVector);
  1233. this.zz = this.zz.add(colorVector);
  1234. };
  1235. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  1236. var result = new SphericalPolynomial();
  1237. result.x = harmonics.L11.scale(1.02333);
  1238. result.y = harmonics.L1_1.scale(1.02333);
  1239. result.z = harmonics.L10.scale(1.02333);
  1240. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  1241. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  1242. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  1243. result.yz = harmonics.L2_1.scale(0.858086);
  1244. result.zx = harmonics.L21.scale(0.858086);
  1245. result.xy = harmonics.L2_2.scale(0.858086);
  1246. return result;
  1247. };
  1248. return SphericalPolynomial;
  1249. })();
  1250. BABYLON.SphericalPolynomial = SphericalPolynomial;
  1251. })(BABYLON || (BABYLON = {}));
  1252. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1253. var BABYLON;
  1254. (function (BABYLON) {
  1255. var Internals;
  1256. (function (Internals) {
  1257. var PanoramaToCubeMapTools = (function () {
  1258. function PanoramaToCubeMapTools() {
  1259. }
  1260. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  1261. if (!float32Array) {
  1262. throw "ConvertPanoramaToCubemap: input cannot be null";
  1263. }
  1264. if (float32Array.length != inputWidth * inputHeight * 3) {
  1265. throw "ConvertPanoramaToCubemap: input size is wrong";
  1266. }
  1267. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  1268. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  1269. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  1270. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  1271. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  1272. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  1273. return {
  1274. front: textureFront,
  1275. back: textureBack,
  1276. left: textureLeft,
  1277. right: textureRight,
  1278. up: textureUp,
  1279. down: textureDown,
  1280. size: size
  1281. };
  1282. };
  1283. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  1284. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  1285. var textureArray = new Float32Array(buffer);
  1286. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  1287. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  1288. var dy = 1 / texSize;
  1289. var fy = 0;
  1290. for (var y = 0; y < texSize; y++) {
  1291. var xv1 = faceData[0];
  1292. var xv2 = faceData[2];
  1293. for (var x = 0; x < texSize; x++) {
  1294. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  1295. v.normalize();
  1296. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  1297. // 3 channels per pixels
  1298. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  1299. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  1300. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  1301. xv1 = xv1.add(rotDX1);
  1302. xv2 = xv2.add(rotDX2);
  1303. }
  1304. fy += dy;
  1305. }
  1306. return textureArray;
  1307. };
  1308. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  1309. var theta = Math.atan2(vDir.z, vDir.x);
  1310. var phi = Math.acos(vDir.y);
  1311. while (theta < -Math.PI)
  1312. theta += 2 * Math.PI;
  1313. while (theta > Math.PI)
  1314. theta -= 2 * Math.PI;
  1315. var dx = theta / Math.PI;
  1316. var dy = phi / Math.PI;
  1317. // recenter.
  1318. dx = dx * 0.5 + 0.5;
  1319. var px = Math.round(dx * inputWidth);
  1320. if (px < 0)
  1321. px = 0;
  1322. else if (px >= inputWidth)
  1323. px = inputWidth - 1;
  1324. var py = Math.round(dy * inputHeight);
  1325. if (py < 0)
  1326. py = 0;
  1327. else if (py >= inputHeight)
  1328. py = inputHeight - 1;
  1329. var inputY = (inputHeight - py - 1);
  1330. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  1331. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  1332. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  1333. return {
  1334. r: r,
  1335. g: g,
  1336. b: b
  1337. };
  1338. };
  1339. PanoramaToCubeMapTools.FACE_FRONT = [
  1340. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  1341. new BABYLON.Vector3(1.0, -1.0, -1.0),
  1342. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  1343. new BABYLON.Vector3(1.0, 1.0, -1.0)
  1344. ];
  1345. PanoramaToCubeMapTools.FACE_BACK = [
  1346. new BABYLON.Vector3(1.0, -1.0, 1.0),
  1347. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  1348. new BABYLON.Vector3(1.0, 1.0, 1.0),
  1349. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  1350. ];
  1351. PanoramaToCubeMapTools.FACE_LEFT = [
  1352. new BABYLON.Vector3(1.0, -1.0, -1.0),
  1353. new BABYLON.Vector3(1.0, -1.0, 1.0),
  1354. new BABYLON.Vector3(1.0, 1.0, -1.0),
  1355. new BABYLON.Vector3(1.0, 1.0, 1.0)
  1356. ];
  1357. PanoramaToCubeMapTools.FACE_RIGHT = [
  1358. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  1359. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  1360. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  1361. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  1362. ];
  1363. PanoramaToCubeMapTools.FACE_UP = [
  1364. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  1365. new BABYLON.Vector3(1.0, 1.0, -1.0),
  1366. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  1367. new BABYLON.Vector3(1.0, 1.0, 1.0)
  1368. ];
  1369. PanoramaToCubeMapTools.FACE_DOWN = [
  1370. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  1371. new BABYLON.Vector3(1.0, -1.0, 1.0),
  1372. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  1373. new BABYLON.Vector3(1.0, -1.0, -1.0)
  1374. ];
  1375. return PanoramaToCubeMapTools;
  1376. })();
  1377. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  1378. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  1379. })(BABYLON || (BABYLON = {}));
  1380. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1381. var BABYLON;
  1382. (function (BABYLON) {
  1383. var Internals;
  1384. (function (Internals) {
  1385. var FileFaceOrientation = (function () {
  1386. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  1387. this.name = name;
  1388. this.worldAxisForNormal = worldAxisForNormal;
  1389. this.worldAxisForFileX = worldAxisForFileX;
  1390. this.worldAxisForFileY = worldAxisForFileY;
  1391. }
  1392. return FileFaceOrientation;
  1393. })();
  1394. ;
  1395. var CubeMapToSphericalPolynomialTools = (function () {
  1396. function CubeMapToSphericalPolynomialTools() {
  1397. }
  1398. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  1399. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  1400. var totalSolidAngle = 0.0;
  1401. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  1402. var du = 2.0 / cubeInfo.size;
  1403. var dv = du;
  1404. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  1405. var minUV = du * 0.5 - 1.0;
  1406. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  1407. var fileFace = this.FileFaces[faceIndex];
  1408. var dataArray = cubeInfo[fileFace.name];
  1409. var v = minUV;
  1410. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  1411. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  1412. // Because SP is still linear, so summation is fine in that basis.
  1413. for (var y = 0; y < cubeInfo.size; y++) {
  1414. var u = minUV;
  1415. for (var x = 0; x < cubeInfo.size; x++) {
  1416. // World direction (not normalised)
  1417. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  1418. worldDirection.normalize();
  1419. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  1420. if (1) {
  1421. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  1422. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  1423. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  1424. var color = new BABYLON.Color3(r, g, b);
  1425. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  1426. }
  1427. else {
  1428. if (faceIndex == 0) {
  1429. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  1430. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  1431. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  1432. }
  1433. else if (faceIndex == 1) {
  1434. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  1435. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  1436. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  1437. }
  1438. else if (faceIndex == 2) {
  1439. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  1440. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  1441. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  1442. }
  1443. else if (faceIndex == 3) {
  1444. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  1445. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  1446. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  1447. }
  1448. else if (faceIndex == 4) {
  1449. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  1450. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  1451. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  1452. }
  1453. else if (faceIndex == 5) {
  1454. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  1455. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  1456. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  1457. }
  1458. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  1459. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  1460. }
  1461. totalSolidAngle += deltaSolidAngle;
  1462. u += du;
  1463. }
  1464. v += dv;
  1465. }
  1466. }
  1467. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  1468. var correction = correctSolidAngle / totalSolidAngle;
  1469. sphericalHarmonics.scale(correction);
  1470. // Additionally scale by pi -- audit needed
  1471. sphericalHarmonics.scale(1.0 / Math.PI);
  1472. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  1473. };
  1474. CubeMapToSphericalPolynomialTools.FileFaces = [
  1475. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  1476. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  1477. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  1478. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  1479. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  1480. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  1481. ];
  1482. return CubeMapToSphericalPolynomialTools;
  1483. })();
  1484. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  1485. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  1486. })(BABYLON || (BABYLON = {}));
  1487. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1488. var BABYLON;
  1489. (function (BABYLON) {
  1490. var Internals;
  1491. (function (Internals) {
  1492. ;
  1493. var HDRTools = (function () {
  1494. function HDRTools() {
  1495. }
  1496. HDRTools.Ldexp = function (mantissa, exponent) {
  1497. if (exponent > 1023) {
  1498. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  1499. }
  1500. if (exponent < -1074) {
  1501. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  1502. }
  1503. return mantissa * Math.pow(2, exponent);
  1504. };
  1505. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  1506. if (exponent > 0) {
  1507. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  1508. float32array[index + 0] = red * exponent;
  1509. float32array[index + 1] = green * exponent;
  1510. float32array[index + 2] = blue * exponent;
  1511. }
  1512. else {
  1513. float32array[index + 0] = 0;
  1514. float32array[index + 1] = 0;
  1515. float32array[index + 2] = 0;
  1516. }
  1517. };
  1518. HDRTools.readStringLine = function (uint8array, startIndex) {
  1519. var line = "";
  1520. var character = "";
  1521. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  1522. character = String.fromCharCode(uint8array[i]);
  1523. if (character == "\n") {
  1524. break;
  1525. }
  1526. line += character;
  1527. }
  1528. return line;
  1529. };
  1530. /* minimal header reading. modify if you want to parse more information */
  1531. HDRTools.RGBE_ReadHeader = function (uint8array) {
  1532. var height = 0;
  1533. var width = 0;
  1534. var line = this.readStringLine(uint8array, 0);
  1535. if (line[0] != '#' || line[1] != '?') {
  1536. throw "Bad HDR Format.";
  1537. }
  1538. var endOfHeader = false;
  1539. var findFormat = false;
  1540. var lineIndex = 0;
  1541. do {
  1542. lineIndex += (line.length + 1);
  1543. line = this.readStringLine(uint8array, lineIndex);
  1544. if (line == "FORMAT=32-bit_rle_rgbe") {
  1545. findFormat = true;
  1546. }
  1547. else if (line.length == 0) {
  1548. endOfHeader = true;
  1549. }
  1550. } while (!endOfHeader);
  1551. if (!findFormat) {
  1552. throw "HDR Bad header format, unsupported FORMAT";
  1553. }
  1554. lineIndex += (line.length + 1);
  1555. line = this.readStringLine(uint8array, lineIndex);
  1556. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  1557. var match = sizeRegexp.exec(line);
  1558. // TODO. Support +Y and -X if needed.
  1559. if (match.length < 3) {
  1560. throw "HDR Bad header format, no size";
  1561. }
  1562. width = parseInt(match[2]);
  1563. height = parseInt(match[1]);
  1564. if (width < 8 || width > 0x7fff) {
  1565. throw "HDR Bad header format, unsupported size";
  1566. }
  1567. lineIndex += (line.length + 1);
  1568. return {
  1569. height: height,
  1570. width: width,
  1571. dataPosition: lineIndex
  1572. };
  1573. };
  1574. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  1575. var uint8array = new Uint8Array(buffer);
  1576. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  1577. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  1578. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  1579. return cubeMapData;
  1580. };
  1581. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  1582. // Keep for multi format supports.
  1583. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  1584. };
  1585. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  1586. var num_scanlines = hdrInfo.height;
  1587. var scanline_width = hdrInfo.width;
  1588. var a, b, c, d, count;
  1589. var dataIndex = hdrInfo.dataPosition;
  1590. var index = 0, endIndex = 0, i = 0;
  1591. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  1592. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  1593. // 3 channels of 4 bytes per pixel in float.
  1594. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  1595. var resultArray = new Float32Array(resultBuffer);
  1596. // read in each successive scanline
  1597. while (num_scanlines > 0) {
  1598. a = uint8array[dataIndex++];
  1599. b = uint8array[dataIndex++];
  1600. c = uint8array[dataIndex++];
  1601. d = uint8array[dataIndex++];
  1602. if (a != 2 || b != 2 || (c & 0x80)) {
  1603. // this file is not run length encoded
  1604. throw "HDR Bad header format, not RLE";
  1605. }
  1606. if (((c << 8) | d) != scanline_width) {
  1607. throw "HDR Bad header format, wrong scan line width";
  1608. }
  1609. index = 0;
  1610. // read each of the four channels for the scanline into the buffer
  1611. for (i = 0; i < 4; i++) {
  1612. endIndex = (i + 1) * scanline_width;
  1613. while (index < endIndex) {
  1614. a = uint8array[dataIndex++];
  1615. b = uint8array[dataIndex++];
  1616. if (a > 128) {
  1617. // a run of the same value
  1618. count = a - 128;
  1619. if ((count == 0) || (count > endIndex - index)) {
  1620. throw "HDR Bad Format, bad scanline data (run)";
  1621. }
  1622. while (count-- > 0) {
  1623. scanLineArray[index++] = b;
  1624. }
  1625. }
  1626. else {
  1627. // a non-run
  1628. count = a;
  1629. if ((count == 0) || (count > endIndex - index)) {
  1630. throw "HDR Bad Format, bad scanline data (non-run)";
  1631. }
  1632. scanLineArray[index++] = b;
  1633. if (--count > 0) {
  1634. for (var j = 0; j < count; j++) {
  1635. scanLineArray[index++] = uint8array[dataIndex++];
  1636. }
  1637. }
  1638. }
  1639. }
  1640. }
  1641. // now convert data from buffer into floats
  1642. for (i = 0; i < scanline_width; i++) {
  1643. a = scanLineArray[i];
  1644. b = scanLineArray[i + scanline_width];
  1645. c = scanLineArray[i + 2 * scanline_width];
  1646. d = scanLineArray[i + 3 * scanline_width];
  1647. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  1648. }
  1649. num_scanlines--;
  1650. }
  1651. return resultArray;
  1652. };
  1653. return HDRTools;
  1654. })();
  1655. Internals.HDRTools = HDRTools;
  1656. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  1657. })(BABYLON || (BABYLON = {}));
  1658. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1659. var BABYLON;
  1660. (function (BABYLON) {
  1661. var HDRCubeTexture = (function (_super) {
  1662. __extends(HDRCubeTexture, _super);
  1663. function HDRCubeTexture(url, scene, size, noMipmap) {
  1664. _super.call(this, scene);
  1665. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  1666. this.sphericalPolynomial = null;
  1667. this.name = url;
  1668. this.url = url;
  1669. this._noMipmap = noMipmap;
  1670. this.hasAlpha = false;
  1671. this._size = size;
  1672. if (!url) {
  1673. return;
  1674. }
  1675. this._texture = this._getFromCache(url, noMipmap);
  1676. if (!this._texture) {
  1677. if (!scene.useDelayedTextureLoading) {
  1678. this.loadTexture();
  1679. }
  1680. else {
  1681. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  1682. }
  1683. }
  1684. this.isCube = true;
  1685. this._textureMatrix = BABYLON.Matrix.Identity();
  1686. }
  1687. HDRCubeTexture.prototype.loadTexture = function () {
  1688. var _this = this;
  1689. var callback = function (buffer) {
  1690. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  1691. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  1692. var mapping = [
  1693. "left",
  1694. "down",
  1695. "front",
  1696. "right",
  1697. "up",
  1698. "back"
  1699. ];
  1700. var results = [];
  1701. for (var j = 0; j < 6; j++) {
  1702. var dataFace = data[mapping[j]];
  1703. // TODO. Support Int Textures...
  1704. // // 3 channels of 1 bytes per pixel in bytes.
  1705. // var byteBuffer = new ArrayBuffer(this._size * this._size * 3);
  1706. // var byteArray = new Uint8Array(byteBuffer);
  1707. //
  1708. // /* now convert data from buffer into bytes */
  1709. // for(var i = 0; i < this._size * this._size; i++) {
  1710. // byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  1711. // byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  1712. // byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  1713. // }
  1714. results.push(dataFace);
  1715. }
  1716. return results;
  1717. };
  1718. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  1719. };
  1720. HDRCubeTexture.prototype.clone = function () {
  1721. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap);
  1722. // Base texture
  1723. newTexture.level = this.level;
  1724. newTexture.wrapU = this.wrapU;
  1725. newTexture.wrapV = this.wrapV;
  1726. newTexture.coordinatesIndex = this.coordinatesIndex;
  1727. newTexture.coordinatesMode = this.coordinatesMode;
  1728. return newTexture;
  1729. };
  1730. // Methods
  1731. HDRCubeTexture.prototype.delayLoad = function () {
  1732. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  1733. return;
  1734. }
  1735. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  1736. this._texture = this._getFromCache(this.url, this._noMipmap);
  1737. if (!this._texture) {
  1738. this.loadTexture();
  1739. }
  1740. };
  1741. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  1742. return this._textureMatrix;
  1743. };
  1744. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  1745. var texture = null;
  1746. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  1747. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size);
  1748. texture.name = parsedTexture.name;
  1749. texture.hasAlpha = parsedTexture.hasAlpha;
  1750. texture.level = parsedTexture.level;
  1751. texture.coordinatesMode = parsedTexture.coordinatesMode;
  1752. }
  1753. return texture;
  1754. };
  1755. HDRCubeTexture.prototype.serialize = function () {
  1756. if (!this.name) {
  1757. return null;
  1758. }
  1759. var serializationObject = {};
  1760. serializationObject.name = this.name;
  1761. serializationObject.hasAlpha = this.hasAlpha;
  1762. serializationObject.isCube = true;
  1763. serializationObject.level = this.level;
  1764. serializationObject.size = this._size;
  1765. serializationObject.coordinatesMode = this.coordinatesMode;
  1766. return serializationObject;
  1767. };
  1768. return HDRCubeTexture;
  1769. })(BABYLON.BaseTexture);
  1770. BABYLON.HDRCubeTexture = HDRCubeTexture;
  1771. })(BABYLON || (BABYLON = {}));
  1772. BABYLON.Effect.ShadersStore['pbrVertexShader'] = "precision highp float;\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\n#if NUM_BONE_INFLUENCERS > 0\n uniform mat4 mBones[BonesPerMesh];\n\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #if NUM_BONE_INFLUENCERS > 4\n attribute vec4 matricesIndicesExtra;\n attribute vec4 matricesWeightsExtra;\n #endif\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n\n#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif\n\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#if NUM_BONE_INFLUENCERS > 0\n mat4 influence;\n influence = mBones[int(matricesIndices[0])] * matricesWeights[0];\n\n#if NUM_BONE_INFLUENCERS > 1\n influence += mBones[int(matricesIndices[1])] * matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS > 2\n influence += mBones[int(matricesIndices[2])] * matricesWeights[2];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 3\n influence += mBones[int(matricesIndices[3])] * matricesWeights[3];\n#endif\t\n\n#if NUM_BONE_INFLUENCERS > 4\n influence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS > 5\n influence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 6\n influence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 7\n influence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\n#endif\t\n\n finalWorld = finalWorld * influence;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\n vDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\n#endif\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef ALBEDO\n if (vAlbedoInfos.x == 0.)\n {\n vAlbedoUV = vec2(albedoMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAlbedoUV = vec2(albedoMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef LIGHTMAP\n if (vLightmapInfos.x == 0.)\n {\n vLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#if defined(REFLECTIVITY)\n if (vReflectivityInfos.x == 0.)\n {\n vReflectivityUV = vec2(reflectivityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vReflectivityUV = vec2(reflectivityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n\n // Log. depth\n#ifdef LOGARITHMICDEPTH\n vFragmentDepth = 1.0 + gl_Position.w;\n gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n#endif\n}";
  1773. BABYLON.Effect.ShadersStore['pbrPixelShader'] = "#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\nprecision highp float;\n\n// Constants\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\n// CUSTOM CONTROLS\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n\n#ifdef OVERLOADEDVALUES\n uniform vec4 vOverloadedIntensity;\n uniform vec3 vOverloadedAmbient;\n uniform vec3 vOverloadedAlbedo;\n uniform vec3 vOverloadedReflectivity;\n uniform vec3 vOverloadedEmissive;\n uniform vec3 vOverloadedReflection;\n uniform vec3 vOverloadedMicroSurface;\n#endif\n\n#ifdef OVERLOADEDSHADOWVALUES\n uniform vec4 vOverloadedShadowIntensity;\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n uniform vec3 vSphericalX;\n uniform vec3 vSphericalY;\n uniform vec3 vSphericalZ;\n uniform vec3 vSphericalXX;\n uniform vec3 vSphericalYY;\n uniform vec3 vSphericalZZ;\n uniform vec3 vSphericalXY;\n uniform vec3 vSphericalYZ;\n uniform vec3 vSphericalZX;\n\n vec3 EnvironmentIrradiance(vec3 normal)\n {\n // Note: 'normal' is assumed to be normalised (or near normalised)\n // This isn't as critical as it is with other calculations (e.g. specular highlight), but the result will be incorrect nonetheless.\n\n // TODO: switch to optimal implementation\n vec3 result =\n vSphericalX * normal.x +\n vSphericalY * normal.y +\n vSphericalZ * normal.z +\n vSphericalXX * normal.x * normal.x +\n vSphericalYY * normal.y * normal.y +\n vSphericalZZ * normal.z * normal.z +\n vSphericalYZ * normal.y * normal.z +\n vSphericalZX * normal.z * normal.x +\n vSphericalXY * normal.x * normal.y;\n\n return result.rgb;\n }\n#endif\n\n// PBR CUSTOM CONSTANTS\nconst float kPi = 3.1415926535897932384626433832795;\n\n#ifdef PoissonSamplingEnvironment\n const int poissonSphereSamplersCount = 32;\n vec3 poissonSphereSamplers[poissonSphereSamplersCount];\n\n void initSamplers()\n {\n poissonSphereSamplers[0] = vec3( -0.552198926093, 0.801049753814, -0.0322487480415 );\n poissonSphereSamplers[1] = vec3( 0.344874796559, -0.650989584719, 0.283038477033 ); \n poissonSphereSamplers[2] = vec3( -0.0710183703467, 0.163770497767, -0.95022416734 ); \n poissonSphereSamplers[3] = vec3( 0.422221832073, 0.576613638193, 0.519157625948 ); \n poissonSphereSamplers[4] = vec3( -0.561872200916, -0.665581249881, -0.131630473211 ); \n poissonSphereSamplers[5] = vec3( -0.409905973809, 0.0250731510778, 0.674676954809 ); \n poissonSphereSamplers[6] = vec3( 0.206829570551, -0.190199352704, 0.919073906156 ); \n poissonSphereSamplers[7] = vec3( -0.857514664463, 0.0274425010091, -0.475068738967 ); \n poissonSphereSamplers[8] = vec3( -0.816275009951, -0.0432916479141, 0.40394579291 ); \n poissonSphereSamplers[9] = vec3( 0.397976181928, -0.633227519667, -0.617794410447 ); \n poissonSphereSamplers[10] = vec3( -0.181484199014, 0.0155418272003, -0.34675720703 ); \n poissonSphereSamplers[11] = vec3( 0.591734926919, 0.489930882201, -0.51675303188 ); \n poissonSphereSamplers[12] = vec3( -0.264514973057, 0.834248662136, 0.464624235985 ); \n poissonSphereSamplers[13] = vec3( -0.125845223505, 0.812029586099, -0.46213797731 ); \n poissonSphereSamplers[14] = vec3( 0.0345715424639, 0.349983742938, 0.855109899027 ); \n poissonSphereSamplers[15] = vec3( 0.694340492749, -0.281052190209, -0.379600605543 ); \n poissonSphereSamplers[16] = vec3( -0.241055518078, -0.580199280578, 0.435381168431 );\n poissonSphereSamplers[17] = vec3( 0.126313722289, 0.715113642744, 0.124385788055 ); \n poissonSphereSamplers[18] = vec3( 0.752862552387, 0.277075021888, 0.275059597549 );\n poissonSphereSamplers[19] = vec3( -0.400896300918, -0.309374534321, -0.74285782627 ); \n poissonSphereSamplers[20] = vec3( 0.121843331941, -0.00381197918195, 0.322441835258 ); \n poissonSphereSamplers[21] = vec3( 0.741656771351, -0.472083016745, 0.14589173819 ); \n poissonSphereSamplers[22] = vec3( -0.120347565985, -0.397252703556, -0.00153836114051 ); \n poissonSphereSamplers[23] = vec3( -0.846258835203, -0.433763808754, 0.168732209784 ); \n poissonSphereSamplers[24] = vec3( 0.257765618362, -0.546470581239, -0.242234375624 ); \n poissonSphereSamplers[25] = vec3( -0.640343473361, 0.51920903395, 0.549310644325 ); \n poissonSphereSamplers[26] = vec3( -0.894309984621, 0.297394061018, 0.0884583225292 ); \n poissonSphereSamplers[27] = vec3( -0.126241933628, -0.535151016335, -0.440093659672 ); \n poissonSphereSamplers[28] = vec3( -0.158176440297, -0.393125021578, 0.890727226039 ); \n poissonSphereSamplers[29] = vec3( 0.896024272938, 0.203068725821, -0.11198597748 ); \n poissonSphereSamplers[30] = vec3( 0.568671758933, -0.314144243629, 0.509070768816 ); \n poissonSphereSamplers[31] = vec3( 0.289665332178, 0.104356977462, -0.348379247171 );\n }\n\n vec3 environmentSampler(samplerCube cubeMapSampler, vec3 centralDirection, float microsurfaceAverageSlope)\n {\n vec3 result = vec3(0., 0., 0.);\n for(int i = 0; i < poissonSphereSamplersCount; i++)\n {\n vec3 offset = poissonSphereSamplers[i];\n vec3 direction = centralDirection + microsurfaceAverageSlope * offset;\n result += textureCube(cubeMapSampler, direction, 0.).rgb;\n }\n\n result /= 32.0;\n return result;\n }\n\n#endif\n\n// PBR HELPER METHODS\nfloat Square(float value)\n{\n return value * value;\n}\n\nfloat getLuminance(vec3 color)\n{\n return clamp(dot(color, vec3(0.2126, 0.7152, 0.0722)), 0., 1.);\n}\n\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n // Calculate AlphaG as square of roughness; add epsilon to avoid numerical issues\n const float kMinimumVariance = 0.0005;\n float alphaG = Square(roughness) + kMinimumVariance;\n return alphaG;\n}\n\n// From Microfacet Models for Refraction through Rough Surfaces, Walter et al. 2007\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot, float alphaG)\n{\n float tanSquared = (1.0 - dot * dot) / (dot * dot);\n return 2.0 / (1.0 + sqrt(1.0 + alphaG * alphaG * tanSquared));\n}\n\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL, float NdotV, float alphaG)\n{\n return smithVisibilityG1_TrowbridgeReitzGGX(NdotL, alphaG) * smithVisibilityG1_TrowbridgeReitzGGX(NdotV, alphaG);\n}\n\n// Trowbridge-Reitz (GGX)\n// Generalised Trowbridge-Reitz with gamma power=2.0\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH, float alphaG)\n{\n // Note: alphaG is average slope (gradient) of the normals in slope-space.\n // It is also the (trigonometric) tangent of the median distribution value, i.e. 50% of normals have\n // a tangent (gradient) closer to the macrosurface than this slope.\n float a2 = Square(alphaG);\n float d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n return a2 / (kPi * d * d);\n}\n\nvec3 fresnelSchlickGGX(float VdotH, vec3 reflectance0, vec3 reflectance90)\n{\n return reflectance0 + (reflectance90 - reflectance0) * pow(clamp(1.0 - VdotH, 0., 1.), 5.0);\n}\n\nvec3 FresnelSchlickEnvironmentGGX(float VdotN, vec3 reflectance0, vec3 reflectance90, float smoothness)\n{\n // Schlick fresnel approximation, extended with basic smoothness term so that rough surfaces do not approach reflectance90 at grazing angle\n float weight = mix(FRESNEL_MAXIMUM_ON_ROUGH, 1.0, smoothness);\n return reflectance0 + weight * (reflectance90 - reflectance0) * pow(clamp(1.0 - VdotN, 0., 1.), 5.0);\n}\n\n// Cook Torance Specular computation.\nvec3 computeSpecularTerm(float NdotH, float NdotL, float NdotV, float VdotH, float roughness, vec3 specularColor)\n{\n float alphaG = convertRoughnessToAverageSlope(roughness);\n float distribution = normalDistributionFunction_TrowbridgeReitzGGX(NdotH, alphaG);\n float visibility = smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL, NdotV, alphaG);\n visibility /= (4.0 * NdotL * NdotV); // Cook Torance Denominator integated in viibility to avoid issues when visibility function changes.\n\n vec3 fresnel = fresnelSchlickGGX(VdotH, specularColor, vec3(1., 1., 1.));\n\n float specTerm = max(0., visibility * distribution) * NdotL;\n return fresnel * specTerm * kPi; // TODO: audit pi constants\n}\n\nfloat computeDiffuseTerm(float NdotL, float NdotV, float VdotH, float roughness)\n{\n // Diffuse fresnel falloff as per Disney principled BRDF, and in the spirit of\n // of general coupled diffuse/specular models e.g. Ashikhmin Shirley.\n float diffuseFresnelNV = pow(clamp(1.0 - NdotL, 0.000001, 1.), 5.0);\n float diffuseFresnelNL = pow(clamp(1.0 - NdotV, 0.000001, 1.), 5.0);\n float diffuseFresnel90 = 0.5 + 2.0 * VdotH * VdotH * roughness;\n float diffuseFresnelTerm =\n (1.0 + (diffuseFresnel90 - 1.0) * diffuseFresnelNL) *\n (1.0 + (diffuseFresnel90 - 1.0) * diffuseFresnelNV);\n\n\n return diffuseFresnelTerm * NdotL;\n // PI Test\n // diffuseFresnelTerm /= kPi;\n}\n\nfloat computeDefaultMicroSurface(float microSurface, vec3 reflectivityColor)\n{\n float kReflectivityNoAlphaWorkflow_SmoothnessMax = 0.95;\n\n float reflectivityLuminance = getLuminance(reflectivityColor);\n float reflectivityLuma = sqrt(reflectivityLuminance);\n microSurface = reflectivityLuma * kReflectivityNoAlphaWorkflow_SmoothnessMax;\n\n return microSurface;\n}\n\nvec3 toLinearSpace(vec3 color)\n{\n return vec3(pow(color.r, 2.2), pow(color.g, 2.2), pow(color.b, 2.2));\n}\n\nvec3 toGammaSpace(vec3 color)\n{\n return vec3(pow(color.r, 1.0 / 2.2), pow(color.g, 1.0 / 2.2), pow(color.b, 1.0 / 2.2));\n}\n\n#ifdef CAMERATONEMAP\n vec3 toneMaps(vec3 color)\n {\n color = max(color, 0.0);\n\n // TONE MAPPING / EXPOSURE\n color.rgb = color.rgb * vCameraInfos.x;\n\n float tuning = 1.5; // TODO: sync up so e.g. 18% greys are matched to exposure appropriately\n // PI Test\n // tuning *= kPi;\n vec3 tonemapped = 1.0 - exp2(-color.rgb * tuning); // simple local photographic tonemapper\n color.rgb = mix(color.rgb, tonemapped, 1.0);\n return color;\n }\n#endif\n\n#ifdef CAMERACONTRAST\n vec4 contrasts(vec4 color)\n {\n color = clamp(color, 0.0, 1.0);\n\n vec3 resultHighContrast = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb);\n float contrast = vCameraInfos.y;\n if (contrast < 1.0)\n {\n // Decrease contrast: interpolate towards zero-contrast image (flat grey)\n color.rgb = mix(vec3(0.5, 0.5, 0.5), color.rgb, contrast);\n }\n else\n {\n // Increase contrast: apply simple shoulder-toe high contrast curve\n color.rgb = mix(color.rgb, resultHighContrast, contrast - 1.0);\n }\n\n return color;\n }\n#endif\n// END PBR HELPER METHODS\n\n uniform vec4 vReflectivityColor;\n uniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular0;\n#endif\n#ifdef SHADOW0\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#else\nuniform samplerCube shadowSampler0;\n#endif\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular1;\n#endif\n#ifdef SHADOW1\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#else\nuniform samplerCube shadowSampler1;\n#endif\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular2;\n#endif\n#ifdef SHADOW2\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#else\nuniform samplerCube shadowSampler2;\n#endif\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular3;\n#endif\n#ifdef SHADOW3\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#else\nuniform samplerCube shadowSampler3;\n#endif\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\t\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Refraction Reflection\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\n uniform mat4 view;\n#endif\n\n// Refraction\n#ifdef REFRACTION\n uniform vec4 vRefractionInfos;\n\n #ifdef REFRACTIONMAP_3D\n uniform samplerCube refractionCubeSampler;\n #else\n uniform sampler2D refraction2DSampler;\n uniform mat4 refractionMatrix;\n #endif\n#endif\n\n// Reflection\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n #ifdef REFLECTIONMAP_EQUIRECTANGULAR\n varying vec3 vDirectionW;\n #endif\n\n #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\n uniform mat4 reflectionMatrix;\n #endif\n#endif\n\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\n vec3 direction = normalize(vDirectionW);\n\n float t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\n float s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\n\n return vec3(s, t, 0);\n#endif\n\n#ifdef REFLECTIONMAP_SPHERICAL\n vec3 viewDir = normalize(vec3(view * worldPos));\n vec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\n\n vec3 r = reflect(viewDir, viewNormal);\n r.z = r.z - 1.0;\n\n float m = 2.0 * length(r);\n\n return vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\n#endif\n\n#ifdef REFLECTIONMAP_PLANAR\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n#endif\n\n#ifdef REFLECTIONMAP_CUBIC\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n#ifdef INVERTCUBICMAP\n coords.y = 1.0 - coords.y;\n#endif\n return vec3(reflectionMatrix * vec4(coords, 0));\n#endif\n\n#ifdef REFLECTIONMAP_PROJECTION\n return vec3(reflectionMatrix * (view * worldPos));\n#endif\n\n#ifdef REFLECTIONMAP_SKYBOX\n return vPositionUVW;\n#endif\n\n#ifdef REFLECTIONMAP_EXPLICIT\n return vec3(0, 0, 0);\n#endif\n}\n\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\n\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\n{\n\tvec3 directionToLight = vPositionW - lightPosition;\n\tfloat depth = length(directionToLight);\n\tdepth = clamp(depth, 0., 1.0);\n\n\tdirectionToLight = normalize(directionToLight);\n\tdirectionToLight.y = - directionToLight.y;\n\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\n\n if (depth > shadow)\n {\n#ifdef OVERLOADEDSHADOWVALUES\n return mix(1.0, darkness, vOverloadedShadowIntensity.x);\n#else\n return darkness;\n#endif\n }\n return 1.0;\n}\n\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\n{\n\tvec3 directionToLight = vPositionW - lightPosition;\n\tfloat depth = length(directionToLight);\n\n\tdepth = clamp(depth, 0., 1.0);\n\tfloat diskScale = 2.0 / mapSize;\n\n\tdirectionToLight = normalize(directionToLight);\n\tdirectionToLight.y = -directionToLight.y;\n\n float visibility = 1.;\n\n vec3 poissonDisk[4];\n poissonDisk[0] = vec3(-1.0, 1.0, -1.0);\n poissonDisk[1] = vec3(1.0, -1.0, -1.0);\n poissonDisk[2] = vec3(-1.0, -1.0, -1.0);\n poissonDisk[3] = vec3(1.0, -1.0, 1.0);\n\n // Poisson Sampling\n float biasedDepth = depth - bias;\n\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\n\n#ifdef OVERLOADEDSHADOWVALUES\n return min(1.0, mix(1.0, visibility + darkness, vOverloadedShadowIntensity.x));\n#else\n return min(1.0, visibility + darkness);\n#endif\n}\n#endif\n\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\n if (depth.z > shadow)\n {\n#ifdef OVERLOADEDSHADOWVALUES\n return mix(1.0, darkness, vOverloadedShadowIntensity.x);\n#else\n return darkness;\n#endif\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n float biasedDepth = depth.z - bias;\n\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\n#ifdef OVERLOADEDSHADOWVALUES\n return min(1.0, mix(1.0, visibility + darkness, vOverloadedShadowIntensity.x));\n#else\n return min(1.0, visibility + darkness);\n#endif\n}\n\n// Thanks to http://devmaster.net/\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat linstep(float low, float high, float v) {\n return clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\n float p = smoothstep(compare - bias, compare, moments.x);\n float variance = max(moments.y - moments.x * moments.x, 0.02);\n float d = compare - moments.x;\n float p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\n return clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\n return min(1.0, mix(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness, vOverloadedShadowIntensity.x));\n#else\n return min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\n#endif\n}\n#endif\n\n#endif\n\n// Bump\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n#ifdef SPECULARTERM\n vec3 specular;\n#endif\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n vec3 H = normalize(viewDirectionW + lightVectorW);\n float NdotL = max(0.00000000001, dot(vNormal, lightVectorW));\n float VdotH = clamp(0.00000000001, 1.0, dot(viewDirectionW, H));\n\n float diffuseTerm = computeDiffuseTerm(NdotL, NdotV, VdotH, roughness);\n result.diffuse = diffuseTerm * diffuseColor * attenuation;\n\n#ifdef SPECULARTERM\n // Specular\n float NdotH = max(0.00000000001, dot(vNormal, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm * attenuation;\n#endif\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0.0000001, dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n vec3 H = normalize(viewDirectionW - lightDirection.xyz);\n float NdotL = max(0.00000000001, dot(vNormal, -lightDirection.xyz));\n float VdotH = clamp(dot(viewDirectionW, H), 0.00000000001, 1.0);\n\n float diffuseTerm = computeDiffuseTerm(NdotL, NdotV, VdotH, roughness);\n result.diffuse = diffuseTerm * diffuseColor * attenuation * spotAtten;\n\n#ifdef SPECULARTERM\n // Specular\n float NdotH = max(0.00000000001, dot(vNormal, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm * attenuation * spotAtten;\n#endif\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n#ifdef SPECULARTERM\n result.specular = vec3(0.);\n#endif\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 lightVectorW = normalize(lightData.xyz);\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n\n#ifdef SPECULARTERM\n // Specular\n vec3 H = normalize(viewDirectionW + lightVectorW);\n float NdotH = max(0.00000000001, dot(vNormal, H));\n float NdotL = max(0.00000000001, ndl);\n float VdotH = clamp(0.00000000001, 1.0, dot(viewDirectionW, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm;\n#endif\n\n return result;\n}\n\nvoid main(void) {\n #ifdef PoissonSamplingEnvironment\n initSamplers();\n #endif\n\n // Clip plane\n #ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n #endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Albedo\n vec4 surfaceAlbedo = vec4(1., 1., 1., 1.);\n vec3 surfaceAlbedoContribution = vAlbedoColor.rgb;\n \n // Alpha\n float alpha = vAlbedoColor.a;\n\n #ifdef ALBEDO\n surfaceAlbedo = texture2D(albedoSampler, vAlbedoUV);\n surfaceAlbedo = vec4(toLinearSpace(surfaceAlbedo.rgb), surfaceAlbedo.a);\n\n #ifndef LINKREFRACTIONTOTRANSPARENCY\n #ifdef ALPHATEST\n if (surfaceAlbedo.a < 0.4)\n discard;\n #endif\n #endif\n\n #ifdef ALPHAFROMALBEDO\n alpha *= surfaceAlbedo.a;\n #endif\n\n surfaceAlbedo.rgb *= vAlbedoInfos.y;\n #endif\n\n #ifdef VERTEXCOLOR\n surfaceAlbedo.rgb *= vColor.rgb;\n #endif\n\n #ifdef OVERLOADEDVALUES\n surfaceAlbedo.rgb = mix(surfaceAlbedo.rgb, vOverloadedAlbedo, vOverloadedIntensity.y);\n #endif\n\n // Bump\n #ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n #else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n #endif\n\n\n #ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n #endif\n\n // Ambient color\n vec3 ambientColor = vec3(1., 1., 1.);\n\n #ifdef AMBIENT\n ambientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n \n #ifdef OVERLOADEDVALUES\n ambientColor.rgb = mix(ambientColor.rgb, vOverloadedAmbient, vOverloadedIntensity.x);\n #endif\n #endif\n\n // Specular map\n float microSurface = vReflectivityColor.a;\n vec3 surfaceReflectivityColor = vReflectivityColor.rgb;\n \n #ifdef OVERLOADEDVALUES\n surfaceReflectivityColor.rgb = mix(surfaceReflectivityColor.rgb, vOverloadedReflectivity, vOverloadedIntensity.z);\n #endif\n\n #ifdef REFLECTIVITY\n vec4 surfaceReflectivityColorMap = texture2D(reflectivitySampler, vReflectivityUV);\n surfaceReflectivityColor = surfaceReflectivityColorMap.rgb;\n surfaceReflectivityColor = toLinearSpace(surfaceReflectivityColor);\n\n #ifdef OVERLOADEDVALUES\n surfaceReflectivityColor = mix(surfaceReflectivityColor, vOverloadedReflectivity, vOverloadedIntensity.z);\n #endif\n\n #ifdef MICROSURFACEFROMREFLECTIVITYMAP\n microSurface = surfaceReflectivityColorMap.a;\n #else\n microSurface = computeDefaultMicroSurface(microSurface, surfaceReflectivityColor);\n #endif\n #endif\n\n #ifdef OVERLOADEDVALUES\n microSurface = mix(microSurface, vOverloadedMicroSurface.x, vOverloadedMicroSurface.y);\n #endif\n\n // Apply Energy Conservation taking in account the environment level only if the environment is present.\n float reflectance = max(max(surfaceReflectivityColor.r, surfaceReflectivityColor.g), surfaceReflectivityColor.b);\n surfaceAlbedo.rgb = (1. - reflectance) * surfaceAlbedo.rgb;\n\n // Compute Specular Fresnel + Reflectance.\n float NdotV = max(0.00000000001, dot(normalW, viewDirectionW));\n\n // Adapt microSurface.\n microSurface = clamp(microSurface, 0., 1.) * 0.98;\n\n // Call rough to not conflict with previous one.\n float rough = clamp(1. - microSurface, 0.000001, 1.0);\n\n // Lighting\n vec3 lightDiffuseContribution = vec3(0., 0., 0.);\n \n#ifdef OVERLOADEDSHADOWVALUES\n vec3 shadowedOnlyLightDiffuseContribution = vec3(1., 1., 1.);\n#endif\n\n#ifdef SPECULARTERM\n vec3 lightSpecularContribution= vec3(0., 0., 0.);\n#endif\n float notShadowLevel = 1.; // 1 - shadowLevel\n\n#ifdef LIGHT0\n#ifndef SPECULARTERM\n vec3 vLightSpecular0 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, rough, NdotV);\n#endif\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, rough, NdotV);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n notShadowLevel = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\n#else\n#ifdef SHADOWPCF0\n#if defined(POINTLIGHT0)\n notShadowLevel = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\n#else\n notShadowLevel = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\n#endif\n#else\n#if defined(POINTLIGHT0)\n notShadowLevel = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#else\n notShadowLevel = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#endif\n#else\n notShadowLevel = 1.;\n#endif\n lightDiffuseContribution += info.diffuse * notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution *= notShadowLevel;\n#endif\n\n#ifdef SPECULARTERM\n lightSpecularContribution += info.specular * notShadowLevel;\n#endif\n#endif\n\n#ifdef LIGHT1\n#ifndef SPECULARTERM\n vec3 vLightSpecular1 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, rough, NdotV);\n#endif\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, rough, NdotV);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n notShadowLevel = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\n#else\n#ifdef SHADOWPCF1\n#if defined(POINTLIGHT1)\n notShadowLevel = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\n#else\n notShadowLevel = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\n#endif\n#else\n#if defined(POINTLIGHT1)\n notShadowLevel = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#else\n notShadowLevel = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#endif\n#else\n notShadowLevel = 1.;\n#endif\n\n lightDiffuseContribution += info.diffuse * notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution *= notShadowLevel;\n#endif\n\n#ifdef SPECULARTERM\n lightSpecularContribution += info.specular * notShadowLevel;\n#endif\n#endif\n\n#ifdef LIGHT2\n#ifndef SPECULARTERM\n vec3 vLightSpecular2 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, rough, NdotV);\n#endif\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, rough, NdotV);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n notShadowLevel = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\n#else\n#ifdef SHADOWPCF2\n#if defined(POINTLIGHT2)\n notShadowLevel = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\n#else\n notShadowLevel = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\n#endif\n#else\n#if defined(POINTLIGHT2)\n notShadowLevel = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#else\n notShadowLevel = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\t\n#endif\t\n#else\n notShadowLevel = 1.;\n#endif\n\n lightDiffuseContribution += info.diffuse * notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution *= notShadowLevel;\n#endif\n\n#ifdef SPECULARTERM\n lightSpecularContribution += info.specular * notShadowLevel;\n#endif\n#endif\n\n#ifdef LIGHT3\n#ifndef SPECULARTERM\n vec3 vLightSpecular3 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, rough, NdotV);\n#endif\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, rough, NdotV);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n notShadowLevel = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\n#else\n#ifdef SHADOWPCF3\n#if defined(POINTLIGHT3)\n notShadowLevel = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\n#else\n notShadowLevel = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\n#endif\n#else\n#if defined(POINTLIGHT3)\n notShadowLevel = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#else\n notShadowLevel = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\t\n#endif\t\n#else\n notShadowLevel = 1.;\n#endif\n\n lightDiffuseContribution += info.diffuse * notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution *= notShadowLevel;\n#endif\n\n#ifdef SPECULARTERM\n lightSpecularContribution += info.specular * notShadowLevel;\n#endif\n#endif\n\n#ifdef SPECULARTERM\n lightSpecularContribution *= vLightingIntensity.w;\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n #ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n #else\n alpha *= opacityMap.a * vOpacityInfos.y;\n #endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n// Refraction\nvec3 surfaceRefractionColor = vec3(0., 0., 0.);\n\n// Go mat -> blurry reflexion according to microSurface\nfloat bias = 20. * (1.0 - microSurface);\n \n#ifdef REFRACTION\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\n \n #ifdef REFRACTIONMAP_3D\n refractionVector.y = refractionVector.y * vRefractionInfos.w;\n\n if (dot(refractionVector, viewDirectionW) < 1.0)\n {\n surfaceRefractionColor = textureCube(refractionCubeSampler, refractionVector, bias).rgb * vRefractionInfos.x;\n }\n \n #ifndef REFRACTIONMAPINLINEARSPACE\n surfaceRefractionColor = toLinearSpace(surfaceRefractionColor.rgb); \n #endif\n #else\n vec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\n\n vec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\n\n refractionCoords.y = 1.0 - refractionCoords.y;\n\n surfaceRefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\n surfaceRefractionColor = toLinearSpace(surfaceRefractionColor.rgb); \n #endif \n#endif\n\n// Reflection\nvec3 environmentRadiance = vReflectionColor.rgb;\nvec3 environmentIrradiance = vReflectionColor.rgb;\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\n\n #ifdef REFLECTIONMAP_3D\n environmentRadiance = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\n \n #ifdef PoissonSamplingEnvironment\n float alphaG = convertRoughnessToAverageSlope(rough);\n environmentRadiance = environmentSampler(reflectionCubeSampler, vReflectionUVW, alphaG) * vReflectionInfos.x;\n #endif\n\n #ifdef USESPHERICALFROMREFLECTIONMAP\n vec3 normalEnvironmentSpace = (reflectionMatrix * vec4(normalW, 1)).xyz;\n environmentIrradiance = EnvironmentIrradiance(normalEnvironmentSpace);\n #else\n environmentRadiance = toLinearSpace(environmentRadiance.rgb);\n \n environmentIrradiance = textureCube(reflectionCubeSampler, normalW, 20.).rgb * vReflectionInfos.x;\n environmentIrradiance = toLinearSpace(environmentIrradiance.rgb);\n environmentIrradiance *= 0.2; // Hack in case of no hdr cube map use for environment.\n #endif\n #else\n vec2 coords = vReflectionUVW.xy;\n\n #ifdef REFLECTIONMAP_PROJECTION\n coords /= vReflectionUVW.z;\n #endif\n\n coords.y = 1.0 - coords.y;\n\n environmentRadiance = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\n environmentRadiance = toLinearSpace(environmentRadiance.rgb);\n\n environmentIrradiance = texture2D(reflection2DSampler, coords, 20.).rgb * vReflectionInfos.x;\n environmentIrradiance = toLinearSpace(environmentIrradiance.rgb);\n #endif\n#endif\n\n#ifdef OVERLOADEDVALUES\n environmentIrradiance = mix(environmentIrradiance, vOverloadedReflection, vOverloadedMicroSurface.z);\n environmentRadiance = mix(environmentRadiance, vOverloadedReflection, vOverloadedMicroSurface.z);\n#endif\n\nenvironmentRadiance *= vLightingIntensity.z;\nenvironmentIrradiance *= vLightingIntensity.z;\n\n// Compute reflection specular fresnel\nvec3 specularEnvironmentR0 = surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0);\nvec3 specularEnvironmentReflectance = FresnelSchlickEnvironmentGGX(clamp(NdotV, 0., 1.), specularEnvironmentR0, specularEnvironmentR90, sqrt(microSurface));\n\n// Compute refractance\nvec3 refractance = vec3(0.0 , 0.0, 0.0);\n#ifdef REFRACTION\n vec3 transmission = vec3(1.0 , 1.0, 1.0);\n #ifdef LINKREFRACTIONTOTRANSPARENCY\n transmission *= (1.0 - alpha);\n surfaceAlbedoContribution *= alpha;\n \n // Tint the material with diffuse.\n // TODO. Double Check.\n float maxChannel = max(max(surfaceAlbedoContribution.r, surfaceAlbedoContribution.g), surfaceAlbedoContribution.b);\n vec3 tint = transmission + clamp(surfaceAlbedoContribution.rgb - maxChannel, 0.0, 1.0);\n surfaceRefractionColor *= tint;\n \n // Put alpha back to 1;\n alpha = 1.0;\n #endif\n \n // Add Multiple internal bounces.\n specularEnvironmentReflectance = (2.0 * specularEnvironmentReflectance) / (1.0 + specularEnvironmentReflectance);\n \n // In theory T = 1 - R.\n transmission *= 1.0 - specularEnvironmentReflectance;\n \n // Should baked in diffuse.\n refractance = surfaceRefractionColor * transmission;\n#endif\n\nrefractance *= vLightingIntensity.z;\nenvironmentRadiance *= specularEnvironmentReflectance;\n\n// Emissive\nvec3 surfaceEmissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n vec3 emissiveColorTex = texture2D(emissiveSampler, vEmissiveUV).rgb;\n surfaceEmissiveColor = toLinearSpace(emissiveColorTex.rgb) * surfaceEmissiveColor * vEmissiveInfos.y;\n#endif\n\n#ifdef OVERLOADEDVALUES\n surfaceEmissiveColor = mix(surfaceEmissiveColor, vOverloadedEmissive, vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n surfaceEmissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n// Composition\n#ifdef EMISSIVEASILLUMINATION\n vec3 finalDiffuse = max(lightDiffuseContribution * surfaceAlbedoContribution + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n \n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution = max(shadowedOnlyLightDiffuseContribution * surfaceAlbedoContribution + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n #endif\n#else\n #ifdef LINKEMISSIVEWITHALBEDO\n vec3 finalDiffuse = max((lightDiffuseContribution + surfaceEmissiveColor) * surfaceAlbedoContribution + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n\n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution = max((shadowedOnlyLightDiffuseContribution + surfaceEmissiveColor) * surfaceAlbedoContribution + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n #endif\n #else\n vec3 finalDiffuse = max(lightDiffuseContribution * surfaceAlbedoContribution + surfaceEmissiveColor + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n\n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyLightDiffuseContribution = max(shadowedOnlyLightDiffuseContribution * surfaceAlbedoContribution + surfaceEmissiveColor + vAmbientColor, 0.0) * surfaceAlbedo.rgb;\n #endif\n #endif\n#endif\n\n#ifdef OVERLOADEDSHADOWVALUES\n finalDiffuse = mix(finalDiffuse, shadowedOnlyLightDiffuseContribution, (1.0 - vOverloadedShadowIntensity.y));\n#endif\n\n#ifdef SPECULARTERM\n vec3 finalSpecular = lightSpecularContribution * surfaceReflectivityColor;\n#else\n vec3 finalSpecular = vec3(0.0);\n#endif\n\n#ifdef OVERLOADEDSHADOWVALUES\n finalSpecular = mix(finalSpecular, vec3(0.0), (1.0 - vOverloadedShadowIntensity.y));\n#endif\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n// Composition\n// Reflection already includes the environment intensity.\n#ifdef EMISSIVEASILLUMINATION\n vec4 finalColor = vec4(finalDiffuse * ambientColor * vLightingIntensity.x + surfaceAlbedo.rgb * environmentIrradiance + finalSpecular * vLightingIntensity.x + environmentRadiance + surfaceEmissiveColor * vLightingIntensity.y + refractance, alpha);\n#else\n vec4 finalColor = vec4(finalDiffuse * ambientColor * vLightingIntensity.x + surfaceAlbedo.rgb * environmentIrradiance + finalSpecular * vLightingIntensity.x + environmentRadiance + refractance, alpha);\n#endif\n\n#ifdef LIGHTMAP\n vec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\n\n #ifdef USELIGHTMAPASSHADOWMAP\n finalColor.rgb *= lightmapColor;\n #else\n finalColor.rgb += lightmapColor;\n #endif\n#endif\n\n#ifdef FOG\n float fog = CalcFogFactor();\n finalColor.rgb = fog * finalColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n finalColor = max(finalColor, 0.0);\n\n#ifdef CAMERATONEMAP\n finalColor.rgb = toneMaps(finalColor.rgb);\n#endif\n\n finalColor.rgb = toGammaSpace(finalColor.rgb);\n\n#ifdef CAMERACONTRAST\n finalColor = contrasts(finalColor);\n#endif\n\n // Normal Display.\n // gl_FragColor = vec4(normalW * 0.5 + 0.5, 1.0);\n\n // Ambient reflection color.\n // gl_FragColor = vec4(ambientReflectionColor, 1.0);\n\n // Reflection color.\n // gl_FragColor = vec4(reflectionColor, 1.0);\n\n // Base color.\n // gl_FragColor = vec4(surfaceAlbedo.rgb, 1.0);\n\n // Specular color.\n // gl_FragColor = vec4(surfaceReflectivityColor.rgb, 1.0);\n\n // MicroSurface color.\n // gl_FragColor = vec4(microSurface, microSurface, microSurface, 1.0);\n\n // Specular Map\n // gl_FragColor = vec4(reflectivityMapColor.rgb, 1.0);\n \n // Refractance\n // gl_FragColor = vec4(refractance.rgb, 1.0);\n\n //// Emissive Color\n //vec2 test = vEmissiveUV * 0.5 + 0.5;\n //gl_FragColor = vec4(test.x, test.y, 1.0, 1.0);\n\n gl_FragColor = finalColor;\n}";
  1774. BABYLON.Effect.ShadersStore['legacypbrVertexShader'] = "precision mediump float;\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\n#if NUM_BONE_INFLUENCERS > 0\nuniform mat4 mBones[BonesPerMesh];\n\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS > 4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n mat4 finalWorld = world;\n\n#if NUM_BONE_INFLUENCERS > 0\n mat4 influence;\n influence = mBones[int(matricesIndices[0])] * matricesWeights[0];\n\n#if NUM_BONE_INFLUENCERS > 1\n influence += mBones[int(matricesIndices[1])] * matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS > 2\n influence += mBones[int(matricesIndices[2])] * matricesWeights[2];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 3\n influence += mBones[int(matricesIndices[3])] * matricesWeights[3];\n#endif\t\n\n#if NUM_BONE_INFLUENCERS > 4\n influence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS > 5\n influence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 6\n influence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\n#endif\t\n#if NUM_BONE_INFLUENCERS > 7\n influence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\n#endif\t\n\n finalWorld = finalWorld * influence;\n#endif\n\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\n\tvPositionW = vec3(worldPos);\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n\t// Texture coordinates\n#ifndef UV1\n\tvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n\tvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef ALBEDO\n\tif (vAlbedoInfos.x == 0.)\n\t{\n\t\tvAlbedoUV = vec2(albedoMatrix * vec4(uv, 1.0, 0.0));\n\t}\n\telse\n\t{\n\t\tvAlbedoUV = vec2(albedoMatrix * vec4(uv2, 1.0, 0.0));\n\t}\n#endif\n\n#ifdef AMBIENT\n\tif (vAmbientInfos.x == 0.)\n\t{\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n\t}\n\telse\n\t{\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n\t}\n#endif\n\n#ifdef OPACITY\n\tif (vOpacityInfos.x == 0.)\n\t{\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n\t}\n\telse\n\t{\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n\t}\n#endif\n\n#ifdef EMISSIVE\n\tif (vEmissiveInfos.x == 0.)\n\t{\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n\t}\n\telse\n\t{\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n\t}\n#endif\n\n#if defined(REFLECTIVITY)\n\tif (vReflectivityInfos.x == 0.)\n\t{\n\t\tvReflectivityUV = vec2(reflectivityMatrix * vec4(uv, 1.0, 0.0));\n\t}\n\telse\n\t{\n\t\tvReflectivityUV = vec2(reflectivityMatrix * vec4(uv2, 1.0, 0.0));\n\t}\n#endif\n\n\t// Clip plane\n#ifdef CLIPPLANE\n\tfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n\t// Vertex color\n#ifdef VERTEXCOLOR\n\tvColor = color;\n#endif\n}";
  1775. BABYLON.Effect.ShadersStore['legacypbrPixelShader'] = "precision mediump float;\n\n// Constants\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\n// CUSTOM CONTROLS\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n\n// PBR CUSTOM CONSTANTS\nconst float kPi = 3.1415926535897932384626433832795;\n\n// PBR HELPER METHODS\nfloat Square(float value)\n{\n return value * value;\n}\n\nfloat getLuminance(vec3 color)\n{\n return clamp(dot(color, vec3(0.2126, 0.7152, 0.0722)), 0., 1.);\n}\n\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n // Calculate AlphaG as square of roughness; add epsilon to avoid numerical issues\n const float kMinimumVariance = 0.0005;\n float alphaG = Square(roughness) + kMinimumVariance;\n return alphaG;\n}\n\n// From Microfacet Models for Refraction through Rough Surfaces, Walter et al. 2007\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot, float alphaG)\n{\n float tanSquared = (1.0 - dot * dot) / (dot * dot);\n return 2.0 / (1.0 + sqrt(1.0 + alphaG * alphaG * tanSquared));\n}\n\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL, float NdotV, float alphaG)\n{\n return smithVisibilityG1_TrowbridgeReitzGGX(NdotL, alphaG) * smithVisibilityG1_TrowbridgeReitzGGX(NdotV, alphaG);\n}\n\n// Trowbridge-Reitz (GGX)\n// Generalised Trowbridge-Reitz with gamma power=2.0\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH, float alphaG)\n{\n // Note: alphaG is average slope (gradient) of the normals in slope-space.\n // It is also the (trigonometric) tangent of the median distribution value, i.e. 50% of normals have\n // a tangent (gradient) closer to the macrosurface than this slope.\n float a2 = Square(alphaG);\n float d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n return a2 / (kPi * d * d);\n}\n\nvec3 fresnelSchlickGGX(float VdotH, vec3 reflectance0, vec3 reflectance90)\n{\n return reflectance0 + (reflectance90 - reflectance0) * pow(clamp(1.0 - VdotH, 0., 1.), 5.0);\n}\n\nvec3 FresnelSchlickEnvironmentGGX(float VdotN, vec3 reflectance0, vec3 reflectance90, float smoothness)\n{\n // Schlick fresnel approximation, extended with basic smoothness term so that rough surfaces do not approach reflectance90 at grazing angle\n float weight = mix(FRESNEL_MAXIMUM_ON_ROUGH, 1.0, smoothness);\n return reflectance0 + weight * (reflectance90 - reflectance0) * pow(clamp(1.0 - VdotN, 0., 1.), 5.0);\n}\n\n// Cook Torance Specular computation.\nvec3 computeSpecularTerm(float NdotH, float NdotL, float NdotV, float VdotH, float roughness, vec3 specularColor)\n{\n float alphaG = convertRoughnessToAverageSlope(roughness);\n float distribution = normalDistributionFunction_TrowbridgeReitzGGX(NdotH, alphaG);\n float visibility = smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL, NdotV, alphaG);\n visibility /= (4.0 * NdotL * NdotV); // Cook Torance Denominator integated in viibility to avoid issues when visibility function changes.\n\n vec3 fresnel = fresnelSchlickGGX(VdotH, specularColor, vec3(1., 1., 1.));\n\n float specTerm = max(0., visibility * distribution) * NdotL;\n return fresnel * specTerm;\n}\n\nfloat computeDiffuseTerm(float NdotL, float NdotV, float VdotH, float roughness)\n{\n // Diffuse fresnel falloff as per Disney principled BRDF, and in the spirit of\n // of general coupled diffuse/specular models e.g. Ashikhmin Shirley.\n float diffuseFresnelNV = pow(clamp(1.0 - NdotL, 0.000001, 1.), 5.0);\n float diffuseFresnelNL = pow(clamp(1.0 - NdotV, 0.000001, 1.), 5.0);\n float diffuseFresnel90 = 0.5 + 2.0 * VdotH * VdotH * roughness;\n float diffuseFresnelTerm =\n (1.0 + (diffuseFresnel90 - 1.0) * diffuseFresnelNL) *\n (1.0 + (diffuseFresnel90 - 1.0) * diffuseFresnelNV);\n\n return diffuseFresnelTerm * NdotL;\n}\n\nfloat computeDefaultMicroSurface(float microSurface, vec3 reflectivityColor)\n{\n if (microSurface == 0.)\n {\n float kReflectivityNoAlphaWorkflow_SmoothnessMax = 0.95;\n\n float reflectivityLuminance = getLuminance(reflectivityColor);\n float reflectivityLuma = sqrt(reflectivityLuminance);\n microSurface = reflectivityLuma * kReflectivityNoAlphaWorkflow_SmoothnessMax;\n }\n return microSurface;\n}\n\nvec3 toLinearSpace(vec3 color)\n{\n return vec3(pow(color.r, 2.2), pow(color.g, 2.2), pow(color.b, 2.2));\n}\n\nvec3 toGammaSpace(vec3 color)\n{\n return vec3(pow(color.r, 1.0 / 2.2), pow(color.g, 1.0 / 2.2), pow(color.b, 1.0 / 2.2));\n}\n\n#ifdef CAMERATONEMAP\n vec3 toneMaps(vec3 color)\n {\n color = max(color, 0.0);\n\n // TONE MAPPING / EXPOSURE\n color.rgb = color.rgb * vCameraInfos.x;\n\n float tuning = 1.5; // TODO: sync up so e.g. 18% greys are matched to exposure appropriately\n vec3 tonemapped = 1.0 - exp2(-color.rgb * tuning); // simple local photographic tonemapper\n color.rgb = mix(color.rgb, tonemapped, 1.0);\n return color;\n }\n#endif\n\n#ifdef CAMERACONTRAST\n vec4 contrasts(vec4 color)\n {\n color = clamp(color, 0.0, 1.0);\n\n vec3 resultHighContrast = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb);\n float contrast = vCameraInfos.y;\n if (contrast < 1.0)\n {\n // Decrease contrast: interpolate towards zero-contrast image (flat grey)\n color.rgb = mix(vec3(0.5, 0.5, 0.5), color.rgb, contrast);\n }\n else\n {\n // Increase contrast: apply simple shoulder-toe high contrast curve\n color.rgb = mix(color.rgb, resultHighContrast, contrast - 1.0);\n }\n\n return color;\n }\n#endif\n// END PBR HELPER METHODS\n\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular0;\n#endif\n#ifdef SHADOW0\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#else\nuniform samplerCube shadowSampler0;\n#endif\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular1;\n#endif\n#ifdef SHADOW1\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#else\nuniform samplerCube shadowSampler1;\n#endif\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular2;\n#endif\n#ifdef SHADOW2\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#else\nuniform samplerCube shadowSampler2;\n#endif\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular3;\n#endif\n#ifdef SHADOW3\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#else\nuniform samplerCube shadowSampler3;\n#endif\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\t\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n#ifdef SPECULARTERM\n vec3 specular;\n#endif\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n vec3 H = normalize(viewDirectionW + lightVectorW);\n float NdotL = max(0.00000000001, dot(vNormal, lightVectorW));\n float VdotH = clamp(0.00000000001, 1.0, dot(viewDirectionW, H));\n\n float diffuseTerm = computeDiffuseTerm(NdotL, NdotV, VdotH, roughness);\n result.diffuse = diffuseTerm * diffuseColor * attenuation;\n\n#ifdef SPECULARTERM\n // Specular\n float NdotH = max(0.00000000001, dot(vNormal, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm * specularColor * attenuation;\n#endif\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0.0000001, dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n vec3 H = normalize(viewDirectionW - lightDirection.xyz);\n float NdotL = max(0.00000000001, dot(vNormal, -lightDirection.xyz));\n float VdotH = clamp(dot(viewDirectionW, H), 0.00000000001, 1.0);\n\n float diffuseTerm = computeDiffuseTerm(NdotL, NdotV, VdotH, roughness);\n result.diffuse = diffuseTerm * diffuseColor * attenuation * spotAtten;\n\n#ifdef SPECULARTERM\n // Specular\n float NdotH = max(0.00000000001, dot(vNormal, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm * specularColor * attenuation * spotAtten;\n#endif\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n#ifdef SPECULARTERM\n result.specular = vec3(0.);\n#endif\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float roughness, float NdotV) {\n lightingInfo result;\n\n vec3 lightVectorW = normalize(lightData.xyz);\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n\n#ifdef SPECULARTERM\n // Specular\n vec3 H = normalize(viewDirectionW + lightVectorW);\n float NdotH = max(0.00000000001, dot(vNormal, H));\n float NdotL = max(0.00000000001, ndl);\n float VdotH = clamp(0.00000000001, 1.0, dot(viewDirectionW, H));\n\n vec3 specTerm = computeSpecularTerm(NdotH, NdotL, NdotV, VdotH, roughness, specularColor);\n result.specular = specTerm * specularColor;\n#endif\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vAlbedoColor.rgb;\n \n // Alpha\n float alpha = vAlbedoColor.a;\n\n#ifdef ALBEDO\n baseColor = texture2D(diffuseSampler, vAlbedoUV);\n baseColor = vec4(toLinearSpace(baseColor.rgb), baseColor.a);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMALBEDO\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vAlbedoInfos.y;\n#endif\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef OVERLOADEDVALUES\n baseColor.rgb = mix(baseColor.rgb, vOverloadedAlbedo, vOverloadedIntensity.y);\n albedoColor.rgb = mix(albedoColor.rgb, vOverloadedAlbedo, vOverloadedIntensity.y);\n#endif\n\n // Bump\n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n #ifdef OVERLOADEDVALUES\n baseAmbientColor.rgb = mix(baseAmbientColor.rgb, vOverloadedAmbient, vOverloadedIntensity.x);\n #endif\n#endif\n\n // Reflectivity map\n float microSurface = vReflectivityColor.a;\n vec3 reflectivityColor = vReflectivityColor.rgb;\n\n #ifdef OVERLOADEDVALUES\n reflectivityColor.rgb = mix(reflectivityColor.rgb, vOverloadedReflectivity, vOverloadedIntensity.z);\n #endif\n\n #ifdef REFLECTIVITY\n vec4 reflectivityMapColor = texture2D(reflectivitySampler, vReflectivityUV);\n reflectivityColor = toLinearSpace(reflectivityMapColor.rgb);\n\n #ifdef OVERLOADEDVALUES\n reflectivityColor.rgb = mix(reflectivityColor.rgb, vOverloadedReflectivity, vOverloadedIntensity.z);\n #endif\n\n #ifdef MICROSURFACEFROMREFLECTIVITYMAP\n microSurface = reflectivityMapColor.a;\n #else\n microSurface = computeDefaultMicroSurface(microSurface, reflectivityColor);\n #endif\n #endif\n\n #ifdef OVERLOADEDVALUES\n microSurface = mix(microSurface, vOverloadedMicroSurface.x, vOverloadedMicroSurface.y);\n #endif\n\n // Apply Energy Conservation taking in account the environment level only if the environment is present.\n float reflectance = max(max(reflectivityColor.r, reflectivityColor.g), reflectivityColor.b);\n baseColor.rgb = (1. - reflectance) * baseColor.rgb;\n\n // Compute Specular Fresnel + Reflectance.\n float NdotV = max(0.00000000001, dot(normalW, viewDirectionW));\n\n // Adapt microSurface.\n microSurface = clamp(microSurface, 0., 1.) * 0.98;\n\n // Call rough to not conflict with previous one.\n float rough = clamp(1. - microSurface, 0.000001, 1.0);\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n\n#ifdef OVERLOADEDSHADOWVALUES\n vec3 shadowedOnlyDiffuseBase = vec3(1., 1., 1.);\n#endif\n\n#ifdef SPECULARTERM\n vec3 specularBase = vec3(0., 0., 0.);\n#endif\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifndef SPECULARTERM\n vec3 vLightSpecular0 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, rough, NdotV);\n#endif\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, rough, NdotV);\n#endif\n\n shadow = 1.;\n diffuseBase += info.diffuse * shadow;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase *= shadow;\n#endif\n\n#ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n#endif\n#endif\n\n#ifdef LIGHT1\n#ifndef SPECULARTERM\n vec3 vLightSpecular1 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, rough, NdotV);\n#endif\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, rough, NdotV);\n#endif\n\n shadow = 1.;\n diffuseBase += info.diffuse * shadow;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase *= shadow;\n#endif\n\n#ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n#endif\n#endif\n\n#ifdef LIGHT2\n#ifndef SPECULARTERM\n vec3 vLightSpecular2 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, rough, NdotV);\n#endif\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, rough, NdotV);\n#endif\n\n shadow = 1.;\n diffuseBase += info.diffuse * shadow;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase *= shadow;\n#endif\n\n#ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n#endif\n#endif\n\n#ifdef LIGHT3\n#ifndef SPECULARTERM\n vec3 vLightSpecular3 = vec3(0.0);\n#endif\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, rough, NdotV);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, rough, NdotV);\n#endif\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, rough, NdotV);\n#endif\n\n shadow = 1.;\n diffuseBase += info.diffuse * shadow;\n#ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase *= shadow;\n#endif\n\n#ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n#endif\n#endif\n\n// Reflection\nvec3 reflectionColor = vReflectionColor.rgb;\nvec3 ambientReflectionColor = vReflectionColor.rgb;\n\nreflectionColor *= vLightingIntensity.z;\nambientReflectionColor *= vLightingIntensity.z;\n\n// Compute reflection reflectivity fresnel\nvec3 reflectivityEnvironmentR0 = reflectivityColor.rgb;\nvec3 reflectivityEnvironmentR90 = vec3(1.0, 1.0, 1.0);\nvec3 reflectivityEnvironmentReflectanceViewer = FresnelSchlickEnvironmentGGX(clamp(NdotV, 0., 1.), reflectivityEnvironmentR0, reflectivityEnvironmentR90, sqrt(microSurface));\nreflectionColor *= reflectivityEnvironmentReflectanceViewer;\n\n#ifdef OVERLOADEDVALUES\n ambientReflectionColor = mix(ambientReflectionColor, vOverloadedReflection, vOverloadedMicroSurface.z);\n reflectionColor = mix(reflectionColor, vOverloadedReflection, vOverloadedMicroSurface.z);\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n vec3 emissiveColorTex = texture2D(emissiveSampler, vEmissiveUV).rgb;\n emissiveColor = toLinearSpace(emissiveColorTex.rgb) * emissiveColor * vEmissiveInfos.y;\n#endif\n\n#ifdef OVERLOADEDVALUES\n emissiveColor = mix(emissiveColor, vOverloadedEmissive, vOverloadedIntensity.w);\n#endif\n\n // Composition\n#ifdef EMISSIVEASILLUMINATION\n vec3 finalDiffuse = max(diffuseBase * albedoColor + vAmbientColor, 0.0) * baseColor.rgb;\n\n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase = max(shadowedOnlyDiffuseBase * albedoColor + vAmbientColor, 0.0) * baseColor.rgb;\n #endif\n#else\n #ifdef LINKEMISSIVEWITHALBEDO\n vec3 finalDiffuse = max((diffuseBase + emissiveColor) * albedoColor + vAmbientColor, 0.0) * baseColor.rgb;\n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase = max((shadowedOnlyDiffuseBase + emissiveColor) * albedoColor + vAmbientColor, 0.0) * baseColor.rgb;\n #endif\n #else\n vec3 finalDiffuse = max(diffuseBase * albedoColor + emissiveColor + vAmbientColor, 0.0) * baseColor.rgb;\n #ifdef OVERLOADEDSHADOWVALUES\n shadowedOnlyDiffuseBase = max(shadowedOnlyDiffuseBase * albedoColor + emissiveColor + vAmbientColor, 0.0) * baseColor.rgb;\n #endif\n #endif\n#endif\n\n#ifdef OVERLOADEDSHADOWVALUES\n finalDiffuse = mix(finalDiffuse, shadowedOnlyDiffuseBase, (1.0 - vOverloadedShadowIntensity.y));\n#endif\n\n// diffuse lighting from environment 0.2 replaces Harmonic...\n// Ambient Reflection already includes the environment intensity.\nfinalDiffuse += baseColor.rgb * ambientReflectionColor * 0.2;\n\n#ifdef SPECULARTERM\n vec3 finalSpecular = specularBase * reflectivityColor * vLightingIntensity.w;\n#else\n vec3 finalSpecular = vec3(0.0);\n#endif\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n// Composition\n// Reflection already includes the environment intensity.\n#ifdef EMISSIVEASILLUMINATION\n vec4 color = vec4(finalDiffuse * baseAmbientColor * vLightingIntensity.x + finalSpecular * vLightingIntensity.x + reflectionColor + emissiveColor * vLightingIntensity.y, alpha);\n#else\n vec4 color = vec4(finalDiffuse * baseAmbientColor * vLightingIntensity.x + finalSpecular * vLightingIntensity.x + reflectionColor, alpha);\n#endif\n\n color = max(color, 0.0);\n\n#ifdef CAMERATONEMAP\n color.rgb = toneMaps(color.rgb);\n#endif\n\n color.rgb = toGammaSpace(color.rgb);\n\n#ifdef CAMERACONTRAST\n color = contrasts(color);\n#endif\n\n gl_FragColor = color;\n}";