skyMaterial.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { Nullable } from "babylonjs/types";
  2. import { serializeAsVector3, serialize, SerializationHelper } from "babylonjs/Misc/decorators";
  3. import { Vector3, Matrix } from "babylonjs/Maths/math.vector";
  4. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  5. import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture";
  6. import { EffectFallbacks } from "babylonjs/Materials/effect";
  7. import { MaterialDefines } from "babylonjs/Materials/materialDefines";
  8. import { MaterialHelper } from "babylonjs/Materials/materialHelper";
  9. import { PushMaterial } from "babylonjs/Materials/pushMaterial";
  10. import { VertexBuffer } from "babylonjs/Meshes/buffer";
  11. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  12. import { SubMesh } from "babylonjs/Meshes/subMesh";
  13. import { Mesh } from "babylonjs/Meshes/mesh";
  14. import { Scene } from "babylonjs/scene";
  15. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  16. import "./sky.fragment";
  17. import "./sky.vertex";
  18. /** @hidden */
  19. class SkyMaterialDefines extends MaterialDefines {
  20. public CLIPPLANE = false;
  21. public CLIPPLANE2 = false;
  22. public CLIPPLANE3 = false;
  23. public CLIPPLANE4 = false;
  24. public POINTSIZE = false;
  25. public FOG = false;
  26. public VERTEXCOLOR = false;
  27. public VERTEXALPHA = false;
  28. constructor() {
  29. super();
  30. this.rebuild();
  31. }
  32. }
  33. /**
  34. * This is the sky material which allows to create dynamic and texture free effects for skyboxes.
  35. * @see https://doc.babylonjs.com/extensions/sky
  36. */
  37. export class SkyMaterial extends PushMaterial {
  38. /**
  39. * Defines the overall luminance of sky in interval ]0, 1[.
  40. */
  41. @serialize()
  42. public luminance: number = 1.0;
  43. /**
  44. * Defines the amount (scattering) of haze as opposed to molecules in atmosphere.
  45. */
  46. @serialize()
  47. public turbidity: number = 10.0;
  48. /**
  49. * Defines the sky appearance (light intensity).
  50. */
  51. @serialize()
  52. public rayleigh: number = 2.0;
  53. /**
  54. * Defines the mieCoefficient in interval [0, 0.1] which affects the property .mieDirectionalG.
  55. */
  56. @serialize()
  57. public mieCoefficient: number = 0.005;
  58. /**
  59. * Defines the amount of haze particles following the Mie scattering theory.
  60. */
  61. @serialize()
  62. public mieDirectionalG: number = 0.8;
  63. /**
  64. * Defines the distance of the sun according to the active scene camera.
  65. */
  66. @serialize()
  67. public distance: number = 500;
  68. /**
  69. * Defines the sun inclination, in interval [-0.5, 0.5]. When the inclination is not 0, the sun is said
  70. * "inclined".
  71. */
  72. @serialize()
  73. public inclination: number = 0.49;
  74. /**
  75. * Defines the solar azimuth in interval [0, 1]. The azimuth is the angle in the horizontal plan between
  76. * an object direction and a reference direction.
  77. */
  78. @serialize()
  79. public azimuth: number = 0.25;
  80. /**
  81. * Defines the sun position in the sky on (x,y,z). If the property .useSunPosition is set to false, then
  82. * the property is overriden by the inclination and the azimuth and can be read at any moment.
  83. */
  84. @serializeAsVector3()
  85. public sunPosition: Vector3 = new Vector3(0, 100, 0);
  86. /**
  87. * Defines if the sun position should be computed (inclination and azimuth) according to the given
  88. * .sunPosition property.
  89. */
  90. @serialize()
  91. public useSunPosition: boolean = false;
  92. /**
  93. * Defines an offset vector used to get a horizon offset.
  94. * @example skyMaterial.cameraOffset.y = camera.globalPosition.y // Set horizon relative to 0 on the Y axis
  95. */
  96. @serialize()
  97. public cameraOffset: Vector3 = Vector3.Zero();
  98. // Private members
  99. private _cameraPosition: Vector3 = Vector3.Zero();
  100. private _renderId: number;
  101. /**
  102. * Instantiates a new sky material.
  103. * This material allows to create dynamic and texture free
  104. * effects for skyboxes by taking care of the atmosphere state.
  105. * @see https://doc.babylonjs.com/extensions/sky
  106. * @param name Define the name of the material in the scene
  107. * @param scene Define the scene the material belong to
  108. */
  109. constructor(name: string, scene: Scene) {
  110. super(name, scene);
  111. }
  112. /**
  113. * Specifies if the material will require alpha blending
  114. * @returns a boolean specifying if alpha blending is needed
  115. */
  116. public needAlphaBlending(): boolean {
  117. return (this.alpha < 1.0);
  118. }
  119. /**
  120. * Specifies if this material should be rendered in alpha test mode
  121. * @returns false as the sky material doesn't need alpha testing.
  122. */
  123. public needAlphaTesting(): boolean {
  124. return false;
  125. }
  126. /**
  127. * Get the texture used for alpha test purpose.
  128. * @returns null as the sky material has no texture.
  129. */
  130. public getAlphaTestTexture(): Nullable<BaseTexture> {
  131. return null;
  132. }
  133. /**
  134. * Get if the submesh is ready to be used and all its information available.
  135. * Child classes can use it to update shaders
  136. * @param mesh defines the mesh to check
  137. * @param subMesh defines which submesh to check
  138. * @param useInstances specifies that instances should be used
  139. * @returns a boolean indicating that the submesh is ready or not
  140. */
  141. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  142. if (this.isFrozen) {
  143. if (this._wasPreviouslyReady && subMesh.effect) {
  144. return true;
  145. }
  146. }
  147. if (!subMesh._materialDefines) {
  148. subMesh._materialDefines = new SkyMaterialDefines();
  149. }
  150. var defines = <SkyMaterialDefines>subMesh._materialDefines;
  151. var scene = this.getScene();
  152. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  153. if (this._renderId === scene.getRenderId()) {
  154. return true;
  155. }
  156. }
  157. MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, false, defines);
  158. // Attribs
  159. MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, false);
  160. // Get correct effect
  161. if (defines.isDirty) {
  162. defines.markAsProcessed();
  163. scene.resetCachedMaterial();
  164. // Fallbacks
  165. var fallbacks = new EffectFallbacks();
  166. if (defines.FOG) {
  167. fallbacks.addFallback(1, "FOG");
  168. }
  169. //Attributes
  170. var attribs = [VertexBuffer.PositionKind];
  171. if (defines.VERTEXCOLOR) {
  172. attribs.push(VertexBuffer.ColorKind);
  173. }
  174. var shaderName = "sky";
  175. var join = defines.toString();
  176. subMesh.setEffect(scene.getEngine().createEffect(shaderName,
  177. attribs,
  178. ["world", "viewProjection", "view",
  179. "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4",
  180. "luminance", "turbidity", "rayleigh", "mieCoefficient", "mieDirectionalG", "sunPosition",
  181. "cameraPosition", "cameraOffset"
  182. ],
  183. [],
  184. join, fallbacks, this.onCompiled, this.onError), defines);
  185. }
  186. if (!subMesh.effect || !subMesh.effect.isReady()) {
  187. return false;
  188. }
  189. this._renderId = scene.getRenderId();
  190. this._wasPreviouslyReady = true;
  191. return true;
  192. }
  193. /**
  194. * Binds the submesh to this material by preparing the effect and shader to draw
  195. * @param world defines the world transformation matrix
  196. * @param mesh defines the mesh containing the submesh
  197. * @param subMesh defines the submesh to bind the material to
  198. */
  199. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  200. var scene = this.getScene();
  201. var defines = <SkyMaterialDefines>subMesh._materialDefines;
  202. if (!defines) {
  203. return;
  204. }
  205. var effect = subMesh.effect;
  206. if (!effect) {
  207. return;
  208. }
  209. this._activeEffect = effect;
  210. // Matrices
  211. this.bindOnlyWorldMatrix(world);
  212. this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  213. if (this._mustRebind(scene, effect)) {
  214. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  215. // Point size
  216. if (this.pointsCloud) {
  217. this._activeEffect.setFloat("pointSize", this.pointSize);
  218. }
  219. }
  220. // View
  221. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  222. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  223. }
  224. // Fog
  225. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  226. // Sky
  227. var camera = scene.activeCamera;
  228. if (camera) {
  229. var cameraWorldMatrix = camera.getWorldMatrix();
  230. this._cameraPosition.x = cameraWorldMatrix.m[12];
  231. this._cameraPosition.y = cameraWorldMatrix.m[13];
  232. this._cameraPosition.z = cameraWorldMatrix.m[14];
  233. this._activeEffect.setVector3("cameraPosition", this._cameraPosition);
  234. }
  235. this._activeEffect.setVector3("cameraOffset", this.cameraOffset);
  236. if (this.luminance > 0) {
  237. this._activeEffect.setFloat("luminance", this.luminance);
  238. }
  239. this._activeEffect.setFloat("turbidity", this.turbidity);
  240. this._activeEffect.setFloat("rayleigh", this.rayleigh);
  241. this._activeEffect.setFloat("mieCoefficient", this.mieCoefficient);
  242. this._activeEffect.setFloat("mieDirectionalG", this.mieDirectionalG);
  243. if (!this.useSunPosition) {
  244. var theta = Math.PI * (this.inclination - 0.5);
  245. var phi = 2 * Math.PI * (this.azimuth - 0.5);
  246. this.sunPosition.x = this.distance * Math.cos(phi);
  247. this.sunPosition.y = this.distance * Math.sin(phi) * Math.sin(theta);
  248. this.sunPosition.z = this.distance * Math.sin(phi) * Math.cos(theta);
  249. }
  250. this._activeEffect.setVector3("sunPosition", this.sunPosition);
  251. this._afterBind(mesh, this._activeEffect);
  252. }
  253. /**
  254. * Get the list of animatables in the material.
  255. * @returns the list of animatables object used in the material
  256. */
  257. public getAnimatables(): IAnimatable[] {
  258. return [];
  259. }
  260. /**
  261. * Disposes the material
  262. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  263. */
  264. public dispose(forceDisposeEffect?: boolean): void {
  265. super.dispose(forceDisposeEffect);
  266. }
  267. /**
  268. * Makes a duplicate of the material, and gives it a new name
  269. * @param name defines the new name for the duplicated material
  270. * @returns the cloned material
  271. */
  272. public clone(name: string): SkyMaterial {
  273. return SerializationHelper.Clone<SkyMaterial>(() => new SkyMaterial(name, this.getScene()), this);
  274. }
  275. /**
  276. * Serializes this material in a JSON representation
  277. * @returns the serialized material object
  278. */
  279. public serialize(): any {
  280. var serializationObject = SerializationHelper.Serialize(this);
  281. serializationObject.customType = "BABYLON.SkyMaterial";
  282. return serializationObject;
  283. }
  284. /**
  285. * Gets the current class name of the material e.g. "SkyMaterial"
  286. * Mainly use in serialization.
  287. * @returns the class name
  288. */
  289. public getClassName(): string {
  290. return "SkyMaterial";
  291. }
  292. /**
  293. * Creates a sky material from parsed material data
  294. * @param source defines the JSON representation of the material
  295. * @param scene defines the hosting scene
  296. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  297. * @returns a new sky material
  298. */
  299. public static Parse(source: any, scene: Scene, rootUrl: string): SkyMaterial {
  300. return SerializationHelper.Parse(() => new SkyMaterial(source.name, scene), source, scene, rootUrl);
  301. }
  302. }
  303. _TypeStore.RegisteredTypes["BABYLON.SkyMaterial"] = SkyMaterial;