SkyAtmosphereCommon.glsl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * @license
  3. * Copyright (c) 2000-2005, Sean O'Neil (s_p_oneil@hotmail.com)
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * * Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. * * Neither the name of the project nor the names of its contributors may be
  16. * used to endorse or promote products derived from this software without
  17. * specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  26. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  27. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. * Modifications made by Cesium GS, Inc.
  31. */
  32. // Code: http://sponeil.net/
  33. // GPU Gems 2 Article: https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter16.html
  34. const float Kr = 0.0025;
  35. const float Kr4PI = Kr * 4.0 * czm_pi;
  36. const float Km = 0.0015;
  37. const float Km4PI = Km * 4.0 * czm_pi;
  38. const float ESun = 15.0;
  39. const float KmESun = Km * ESun;
  40. const float KrESun = Kr * ESun;
  41. const vec3 InvWavelength = vec3(
  42. 5.60204474633241, // Red = 1.0 / Math.pow(0.650, 4.0)
  43. 9.473284437923038, // Green = 1.0 / Math.pow(0.570, 4.0)
  44. 19.643802610477206); // Blue = 1.0 / Math.pow(0.475, 4.0)
  45. const float rayleighScaleDepth = 0.25;
  46. const int nSamples = 2;
  47. const float fSamples = 2.0;
  48. const float g = -0.95;
  49. const float g2 = g * g;
  50. #ifdef COLOR_CORRECT
  51. uniform vec3 u_hsbShift; // Hue, saturation, brightness
  52. #endif
  53. uniform vec3 u_radiiAndDynamicAtmosphereColor; // outer radius, inner radius, dynamic atmosphere color flag
  54. float scale(float cosAngle)
  55. {
  56. float x = 1.0 - cosAngle;
  57. return rayleighScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));
  58. }
  59. vec3 getLightDirection(vec3 positionWC)
  60. {
  61. float lightEnum = u_radiiAndDynamicAtmosphereColor.z;
  62. vec3 lightDirection =
  63. positionWC * float(lightEnum == 0.0) +
  64. czm_lightDirectionWC * float(lightEnum == 1.0) +
  65. czm_sunDirectionWC * float(lightEnum == 2.0);
  66. return normalize(lightDirection);
  67. }
  68. void calculateRayScatteringFromSpace(in vec3 positionWC, in vec3 ray, in float innerRadius, in float outerRadius, inout float far, out vec3 start, out float startOffset)
  69. {
  70. // Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere)
  71. float cameraHeight = length(positionWC);
  72. float B = 2.0 * dot(positionWC, ray);
  73. float C = cameraHeight * cameraHeight - outerRadius * outerRadius;
  74. float det = max(0.0, B * B - 4.0 * C);
  75. float near = 0.5 * (-B - sqrt(det));
  76. // Calculate the ray's starting position, then calculate its scattering offset
  77. start = positionWC + ray * near;
  78. far -= near;
  79. float startAngle = dot(ray, start) / outerRadius;
  80. float startDepth = exp(-1.0 / rayleighScaleDepth);
  81. startOffset = startDepth * scale(startAngle);
  82. }
  83. void calculateRayScatteringFromGround(in vec3 positionWC, in vec3 ray, in float atmosphereScale, in float innerRadius, out vec3 start, out float startOffset)
  84. {
  85. // Calculate the ray's starting position, then calculate its scattering offset
  86. float cameraHeight = length(positionWC);
  87. start = positionWC;
  88. float height = length(start);
  89. float depth = exp((atmosphereScale / rayleighScaleDepth ) * (innerRadius - cameraHeight));
  90. float startAngle = dot(ray, start) / height;
  91. startOffset = depth*scale(startAngle);
  92. }
  93. czm_raySegment rayEllipsoidIntersection(czm_ray ray, vec3 inverseRadii)
  94. {
  95. vec3 o = inverseRadii * (czm_inverseView * vec4(ray.origin, 1.0)).xyz;
  96. vec3 d = inverseRadii * (czm_inverseView * vec4(ray.direction, 0.0)).xyz;
  97. float a = dot(d, d);
  98. float b = dot(d, o);
  99. float c = dot(o, o) - 1.0;
  100. float discriminant = b * b - a * c;
  101. if (discriminant < 0.0)
  102. {
  103. return czm_emptyRaySegment;
  104. }
  105. discriminant = sqrt(discriminant);
  106. float t1 = (-b - discriminant) / a;
  107. float t2 = (-b + discriminant) / a;
  108. if (t1 < 0.0 && t2 < 0.0)
  109. {
  110. return czm_emptyRaySegment;
  111. }
  112. if (t1 < 0.0 && t2 >= 0.0)
  113. {
  114. t1 = 0.0;
  115. }
  116. return czm_raySegment(t1, t2);
  117. }
  118. vec3 getAdjustedPosition(vec3 positionWC, float innerRadius)
  119. {
  120. // Adjust the camera position so that atmosphere color looks the same wherever the eye height is the same
  121. float cameraHeight = czm_eyeHeight + innerRadius;
  122. return normalize(positionWC) * cameraHeight;
  123. }
  124. vec3 getTranslucentPosition(vec3 positionWC, vec3 outerPositionWC, float innerRadius, out bool intersectsEllipsoid)
  125. {
  126. vec3 directionWC = normalize(outerPositionWC - positionWC);
  127. vec3 directionEC = czm_viewRotation * directionWC;
  128. czm_ray viewRay = czm_ray(vec3(0.0), directionEC);
  129. czm_raySegment raySegment = rayEllipsoidIntersection(viewRay, czm_ellipsoidInverseRadii);
  130. intersectsEllipsoid = raySegment.start >= 0.0;
  131. if (intersectsEllipsoid)
  132. {
  133. return positionWC + raySegment.stop * directionWC;
  134. }
  135. return getAdjustedPosition(positionWC, innerRadius);
  136. }
  137. void calculateMieColorAndRayleighColor(vec3 outerPositionWC, out vec3 mieColor, out vec3 rayleighColor)
  138. {
  139. // Unpack attributes
  140. float outerRadius = u_radiiAndDynamicAtmosphereColor.x;
  141. float innerRadius = u_radiiAndDynamicAtmosphereColor.y;
  142. #ifdef GLOBE_TRANSLUCENT
  143. bool intersectsEllipsoid = false;
  144. vec3 startPositionWC = getTranslucentPosition(czm_viewerPositionWC, outerPositionWC, innerRadius, intersectsEllipsoid);
  145. #else
  146. vec3 startPositionWC = getAdjustedPosition(czm_viewerPositionWC, innerRadius);
  147. #endif
  148. vec3 lightDirection = getLightDirection(startPositionWC);
  149. // Get the ray from the start position to the outer position and its length (which is the far point of the ray passing through the atmosphere)
  150. vec3 ray = outerPositionWC - startPositionWC;
  151. float far = length(ray);
  152. ray /= far;
  153. float atmosphereScale = 1.0 / (outerRadius - innerRadius);
  154. vec3 start;
  155. float startOffset;
  156. #ifdef SKY_FROM_SPACE
  157. #ifdef GLOBE_TRANSLUCENT
  158. if (intersectsEllipsoid)
  159. {
  160. calculateRayScatteringFromGround(startPositionWC, ray, atmosphereScale, innerRadius, start, startOffset);
  161. }
  162. else
  163. {
  164. calculateRayScatteringFromSpace(startPositionWC, ray, innerRadius, outerRadius, far, start, startOffset);
  165. }
  166. #else
  167. calculateRayScatteringFromSpace(startPositionWC, ray, innerRadius, outerRadius, far, start, startOffset);
  168. #endif
  169. #else
  170. calculateRayScatteringFromGround(startPositionWC, ray, atmosphereScale, innerRadius, start, startOffset);
  171. #endif
  172. // Initialize the scattering loop variables
  173. float sampleLength = far / fSamples;
  174. float scaledLength = sampleLength * atmosphereScale;
  175. vec3 sampleRay = ray * sampleLength;
  176. vec3 samplePoint = start + sampleRay * 0.5;
  177. // Now loop through the sample rays
  178. vec3 frontColor = vec3(0.0, 0.0, 0.0);
  179. for (int i = 0; i<nSamples; i++)
  180. {
  181. float height = length(samplePoint);
  182. float depth = exp((atmosphereScale / rayleighScaleDepth ) * (innerRadius - height));
  183. float fLightAngle = dot(lightDirection, samplePoint) / height;
  184. float fCameraAngle = dot(ray, samplePoint) / height;
  185. float fScatter = (startOffset + depth*(scale(fLightAngle) - scale(fCameraAngle)));
  186. vec3 attenuate = exp(-fScatter * (InvWavelength * Kr4PI + Km4PI));
  187. frontColor += attenuate * (depth * scaledLength);
  188. samplePoint += sampleRay;
  189. }
  190. // Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader
  191. mieColor = frontColor * KmESun;
  192. rayleighColor = frontColor * (InvWavelength * KrESun);
  193. // Cap mie and rayleigh colors to prevent NaNs when vertex interpolation happens
  194. mieColor = min(mieColor, vec3(10000000.0));
  195. rayleighColor = min(rayleighColor, vec3(10000000.0));
  196. }
  197. vec4 calculateFinalColor(vec3 positionWC, vec3 toCamera, vec3 lightDirection, vec3 mieColor, vec3 rayleighColor)
  198. {
  199. // Extra normalize added for Android
  200. float cosAngle = dot(lightDirection, normalize(toCamera)) / length(toCamera);
  201. float rayleighPhase = 0.75 * (1.0 + cosAngle * cosAngle);
  202. float miePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + cosAngle * cosAngle) / pow(1.0 + g2 - 2.0 * g * cosAngle, 1.5);
  203. vec3 rgb = rayleighPhase * rayleighColor + miePhase * mieColor;
  204. const float exposure = 2.0;
  205. vec3 rgbExposure = vec3(1.0) - exp(-exposure * rgb);
  206. #ifndef HDR
  207. rgb = rgbExposure;
  208. #endif
  209. #ifdef COLOR_CORRECT
  210. // Convert rgb color to hsb
  211. vec3 hsb = czm_RGBToHSB(rgb);
  212. // Perform hsb shift
  213. hsb.x += u_hsbShift.x; // hue
  214. hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0); // saturation
  215. hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0; // brightness
  216. // Convert shifted hsb back to rgb
  217. rgb = czm_HSBToRGB(hsb);
  218. #endif
  219. float outerRadius = u_radiiAndDynamicAtmosphereColor.x;
  220. float innerRadius = u_radiiAndDynamicAtmosphereColor.y;
  221. float lightEnum = u_radiiAndDynamicAtmosphereColor.z;
  222. float cameraHeight = czm_eyeHeight + innerRadius;
  223. // Alter alpha based on how close the viewer is to the ground (1.0 = on ground, 0.0 = at edge of atmosphere)
  224. float atmosphereAlpha = clamp((outerRadius - cameraHeight) / (outerRadius - innerRadius), 0.0, 1.0);
  225. // Alter alpha based on time of day (0.0 = night , 1.0 = day)
  226. float nightAlpha = (lightEnum != 0.0) ? clamp(dot(normalize(positionWC), lightDirection), 0.0, 1.0) : 1.0;
  227. atmosphereAlpha *= pow(nightAlpha, 0.5);
  228. vec4 finalColor = vec4(rgb, mix(clamp(rgbExposure.b, 0.0, 1.0), 1.0, atmosphereAlpha) * smoothstep(0.0, 1.0, czm_morphTime));
  229. if (mieColor.b > 1.0)
  230. {
  231. // Fade atmosphere below the ellipsoid. As the camera zooms further away from the ellipsoid draw
  232. // a larger atmosphere ring to cover empty space of lower LOD globe tiles.
  233. float strength = mieColor.b;
  234. float minDistance = outerRadius;
  235. float maxDistance = outerRadius * 3.0;
  236. float maxStrengthLerp = 1.0 - clamp((maxDistance - cameraHeight) / (maxDistance - minDistance), 0.0, 1.0);
  237. float maxStrength = mix(100.0, 10000.0, maxStrengthLerp);
  238. strength = min(strength, maxStrength);
  239. float alpha = 1.0 - (strength / maxStrength);
  240. finalColor.a = alpha;
  241. }
  242. return finalColor;
  243. }