babylon.skyMaterial.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var __extends = (this && this.__extends) || (function () {
  3. var extendStatics = function (d, b) {
  4. extendStatics = Object.setPrototypeOf ||
  5. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  7. return extendStatics(d, b);
  8. }
  9. return function (d, b) {
  10. extendStatics(d, b);
  11. function __() { this.constructor = d; }
  12. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13. };
  14. })();
  15. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20. };
  21. var BABYLON;
  22. (function (BABYLON) {
  23. /** @hidden */
  24. var SkyMaterialDefines = /** @class */ (function (_super) {
  25. __extends(SkyMaterialDefines, _super);
  26. function SkyMaterialDefines() {
  27. var _this = _super.call(this) || this;
  28. _this.CLIPPLANE = false;
  29. _this.CLIPPLANE2 = false;
  30. _this.CLIPPLANE3 = false;
  31. _this.CLIPPLANE4 = false;
  32. _this.POINTSIZE = false;
  33. _this.FOG = false;
  34. _this.VERTEXCOLOR = false;
  35. _this.VERTEXALPHA = false;
  36. _this.rebuild();
  37. return _this;
  38. }
  39. return SkyMaterialDefines;
  40. }(BABYLON.MaterialDefines));
  41. /**
  42. * This is the sky material which allows to create dynamic and texture free effects for skyboxes.
  43. * @see https://doc.babylonjs.com/extensions/sky
  44. */
  45. var SkyMaterial = /** @class */ (function (_super) {
  46. __extends(SkyMaterial, _super);
  47. /**
  48. * Instantiates a new sky material.
  49. * This material allows to create dynamic and texture free
  50. * effects for skyboxes by taking care of the atmosphere state.
  51. * @see https://doc.babylonjs.com/extensions/sky
  52. * @param name Define the name of the material in the scene
  53. * @param scene Define the scene the material belong to
  54. */
  55. function SkyMaterial(name, scene) {
  56. var _this = _super.call(this, name, scene) || this;
  57. /**
  58. * Defines the overall luminance of sky in interval ]0, 1[.
  59. */
  60. _this.luminance = 1.0;
  61. /**
  62. * Defines the amount (scattering) of haze as opposed to molecules in atmosphere.
  63. */
  64. _this.turbidity = 10.0;
  65. /**
  66. * Defines the sky appearance (light intensity).
  67. */
  68. _this.rayleigh = 2.0;
  69. /**
  70. * Defines the mieCoefficient in interval [0, 0.1] which affects the property .mieDirectionalG.
  71. */
  72. _this.mieCoefficient = 0.005;
  73. /**
  74. * Defines the amount of haze particles following the Mie scattering theory.
  75. */
  76. _this.mieDirectionalG = 0.8;
  77. /**
  78. * Defines the distance of the sun according to the active scene camera.
  79. */
  80. _this.distance = 500;
  81. /**
  82. * Defines the sun inclination, in interval [-0.5, 0.5]. When the inclination is not 0, the sun is said
  83. * "inclined".
  84. */
  85. _this.inclination = 0.49;
  86. /**
  87. * Defines the solar azimuth in interval [0, 1]. The azimuth is the angle in the horizontal plan between
  88. * an object direction and a reference direction.
  89. */
  90. _this.azimuth = 0.25;
  91. /**
  92. * Defines the sun position in the sky on (x,y,z). If the property .useSunPosition is set to false, then
  93. * the property is overriden by the inclination and the azimuth and can be read at any moment.
  94. */
  95. _this.sunPosition = new BABYLON.Vector3(0, 100, 0);
  96. /**
  97. * Defines if the sun position should be computed (inclination and azimuth) according to the given
  98. * .sunPosition property.
  99. */
  100. _this.useSunPosition = false;
  101. /**
  102. * Defines an offset vector used to get a horizon offset.
  103. * @example skyMaterial.cameraOffset.y = camera.globalPosition.y // Set horizon relative to 0 on the Y axis
  104. */
  105. _this.cameraOffset = BABYLON.Vector3.Zero();
  106. _this._cameraPosition = BABYLON.Vector3.Zero();
  107. return _this;
  108. }
  109. /**
  110. * Specifies if the material will require alpha blending
  111. * @returns a boolean specifying if alpha blending is needed
  112. */
  113. SkyMaterial.prototype.needAlphaBlending = function () {
  114. return (this.alpha < 1.0);
  115. };
  116. /**
  117. * Specifies if this material should be rendered in alpha test mode
  118. * @returns false as the sky material doesn't need alpha testing.
  119. */
  120. SkyMaterial.prototype.needAlphaTesting = function () {
  121. return false;
  122. };
  123. /**
  124. * Get the texture used for alpha test purpose.
  125. * @returns null as the sky material has no texture.
  126. */
  127. SkyMaterial.prototype.getAlphaTestTexture = function () {
  128. return null;
  129. };
  130. /**
  131. * Get if the submesh is ready to be used and all its information available.
  132. * Child classes can use it to update shaders
  133. * @param mesh defines the mesh to check
  134. * @param subMesh defines which submesh to check
  135. * @param useInstances specifies that instances should be used
  136. * @returns a boolean indicating that the submesh is ready or not
  137. */
  138. SkyMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  139. if (this.isFrozen) {
  140. if (this._wasPreviouslyReady && subMesh.effect) {
  141. return true;
  142. }
  143. }
  144. if (!subMesh._materialDefines) {
  145. subMesh._materialDefines = new SkyMaterialDefines();
  146. }
  147. var defines = subMesh._materialDefines;
  148. var scene = this.getScene();
  149. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  150. if (this._renderId === scene.getRenderId()) {
  151. return true;
  152. }
  153. }
  154. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, false, defines);
  155. // Attribs
  156. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, false);
  157. // Get correct effect
  158. if (defines.isDirty) {
  159. defines.markAsProcessed();
  160. scene.resetCachedMaterial();
  161. // Fallbacks
  162. var fallbacks = new BABYLON.EffectFallbacks();
  163. if (defines.FOG) {
  164. fallbacks.addFallback(1, "FOG");
  165. }
  166. //Attributes
  167. var attribs = [BABYLON.VertexBuffer.PositionKind];
  168. if (defines.VERTEXCOLOR) {
  169. attribs.push(BABYLON.VertexBuffer.ColorKind);
  170. }
  171. var shaderName = "sky";
  172. var join = defines.toString();
  173. subMesh.setEffect(scene.getEngine().createEffect(shaderName, attribs, ["world", "viewProjection", "view",
  174. "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4",
  175. "luminance", "turbidity", "rayleigh", "mieCoefficient", "mieDirectionalG", "sunPosition",
  176. "cameraPosition", "cameraOffset"
  177. ], [], join, fallbacks, this.onCompiled, this.onError), defines);
  178. }
  179. if (!subMesh.effect || !subMesh.effect.isReady()) {
  180. return false;
  181. }
  182. this._renderId = scene.getRenderId();
  183. this._wasPreviouslyReady = true;
  184. return true;
  185. };
  186. /**
  187. * Binds the submesh to this material by preparing the effect and shader to draw
  188. * @param world defines the world transformation matrix
  189. * @param mesh defines the mesh containing the submesh
  190. * @param subMesh defines the submesh to bind the material to
  191. */
  192. SkyMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  193. var scene = this.getScene();
  194. var defines = subMesh._materialDefines;
  195. if (!defines) {
  196. return;
  197. }
  198. var effect = subMesh.effect;
  199. if (!effect) {
  200. return;
  201. }
  202. this._activeEffect = effect;
  203. // Matrices
  204. this.bindOnlyWorldMatrix(world);
  205. this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  206. if (this._mustRebind(scene, effect)) {
  207. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  208. // Point size
  209. if (this.pointsCloud) {
  210. this._activeEffect.setFloat("pointSize", this.pointSize);
  211. }
  212. }
  213. // View
  214. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  215. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  216. }
  217. // Fog
  218. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  219. // Sky
  220. var camera = scene.activeCamera;
  221. if (camera) {
  222. var cameraWorldMatrix = camera.getWorldMatrix();
  223. this._cameraPosition.x = cameraWorldMatrix.m[12];
  224. this._cameraPosition.y = cameraWorldMatrix.m[13];
  225. this._cameraPosition.z = cameraWorldMatrix.m[14];
  226. this._activeEffect.setVector3("cameraPosition", this._cameraPosition);
  227. }
  228. this._activeEffect.setVector3("cameraOffset", this.cameraOffset);
  229. if (this.luminance > 0) {
  230. this._activeEffect.setFloat("luminance", this.luminance);
  231. }
  232. this._activeEffect.setFloat("turbidity", this.turbidity);
  233. this._activeEffect.setFloat("rayleigh", this.rayleigh);
  234. this._activeEffect.setFloat("mieCoefficient", this.mieCoefficient);
  235. this._activeEffect.setFloat("mieDirectionalG", this.mieDirectionalG);
  236. if (!this.useSunPosition) {
  237. var theta = Math.PI * (this.inclination - 0.5);
  238. var phi = 2 * Math.PI * (this.azimuth - 0.5);
  239. this.sunPosition.x = this.distance * Math.cos(phi);
  240. this.sunPosition.y = this.distance * Math.sin(phi) * Math.sin(theta);
  241. this.sunPosition.z = this.distance * Math.sin(phi) * Math.cos(theta);
  242. }
  243. this._activeEffect.setVector3("sunPosition", this.sunPosition);
  244. this._afterBind(mesh, this._activeEffect);
  245. };
  246. /**
  247. * Get the list of animatables in the material.
  248. * @returns the list of animatables object used in the material
  249. */
  250. SkyMaterial.prototype.getAnimatables = function () {
  251. return [];
  252. };
  253. /**
  254. * Disposes the material
  255. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  256. */
  257. SkyMaterial.prototype.dispose = function (forceDisposeEffect) {
  258. _super.prototype.dispose.call(this, forceDisposeEffect);
  259. };
  260. /**
  261. * Makes a duplicate of the material, and gives it a new name
  262. * @param name defines the new name for the duplicated material
  263. * @returns the cloned material
  264. */
  265. SkyMaterial.prototype.clone = function (name) {
  266. var _this = this;
  267. return BABYLON.SerializationHelper.Clone(function () { return new SkyMaterial(name, _this.getScene()); }, this);
  268. };
  269. /**
  270. * Serializes this material in a JSON representation
  271. * @returns the serialized material object
  272. */
  273. SkyMaterial.prototype.serialize = function () {
  274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  275. serializationObject.customType = "BABYLON.SkyMaterial";
  276. return serializationObject;
  277. };
  278. /**
  279. * Gets the current class name of the material e.g. "SkyMaterial"
  280. * Mainly use in serialization.
  281. * @returns the class name
  282. */
  283. SkyMaterial.prototype.getClassName = function () {
  284. return "SkyMaterial";
  285. };
  286. /**
  287. * Creates a sky material from parsed material data
  288. * @param source defines the JSON representation of the material
  289. * @param scene defines the hosting scene
  290. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  291. * @returns a new sky material
  292. */
  293. SkyMaterial.Parse = function (source, scene, rootUrl) {
  294. return BABYLON.SerializationHelper.Parse(function () { return new SkyMaterial(source.name, scene); }, source, scene, rootUrl);
  295. };
  296. __decorate([
  297. BABYLON.serialize()
  298. ], SkyMaterial.prototype, "luminance", void 0);
  299. __decorate([
  300. BABYLON.serialize()
  301. ], SkyMaterial.prototype, "turbidity", void 0);
  302. __decorate([
  303. BABYLON.serialize()
  304. ], SkyMaterial.prototype, "rayleigh", void 0);
  305. __decorate([
  306. BABYLON.serialize()
  307. ], SkyMaterial.prototype, "mieCoefficient", void 0);
  308. __decorate([
  309. BABYLON.serialize()
  310. ], SkyMaterial.prototype, "mieDirectionalG", void 0);
  311. __decorate([
  312. BABYLON.serialize()
  313. ], SkyMaterial.prototype, "distance", void 0);
  314. __decorate([
  315. BABYLON.serialize()
  316. ], SkyMaterial.prototype, "inclination", void 0);
  317. __decorate([
  318. BABYLON.serialize()
  319. ], SkyMaterial.prototype, "azimuth", void 0);
  320. __decorate([
  321. BABYLON.serializeAsVector3()
  322. ], SkyMaterial.prototype, "sunPosition", void 0);
  323. __decorate([
  324. BABYLON.serialize()
  325. ], SkyMaterial.prototype, "useSunPosition", void 0);
  326. __decorate([
  327. BABYLON.serialize()
  328. ], SkyMaterial.prototype, "cameraOffset", void 0);
  329. return SkyMaterial;
  330. }(BABYLON.PushMaterial));
  331. BABYLON.SkyMaterial = SkyMaterial;
  332. })(BABYLON || (BABYLON = {}));
  333. //# sourceMappingURL=babylon.skyMaterial.js.map
  334. BABYLON.Effect.ShadersStore['skyVertexShader'] = "precision highp float;\n\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nvoid main(void) {\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";
  335. BABYLON.Effect.ShadersStore['skyPixelShader'] = "precision highp float;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\nuniform vec3 cameraPosition;\nuniform vec3 cameraOffset;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n\n#include<fogFragmentDeclaration>\n\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst vec3 up=vec3(0.0,1.0,0.0);\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\n\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0);\ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\n\n\n\nvec3 retColor=curr*whiteScale;\n\n\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n\n#include<fogFragment>\ngl_FragColor=color;\n}\n";