Sky.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import {
  2. BackSide,
  3. BoxGeometry,
  4. Mesh,
  5. ShaderMaterial,
  6. UniformsUtils,
  7. Vector3
  8. } from 'three';
  9. /**
  10. * Represents a skydome for scene backgrounds. Based on [A Practical Analytic Model for Daylight](https://www.researchgate.net/publication/220720443_A_Practical_Analytic_Model_for_Daylight)
  11. * aka The Preetham Model, the de facto standard for analytical skydomes.
  12. *
  13. * Note that this class can only be used with {@link WebGLRenderer}.
  14. * When using {@link WebGPURenderer}, use {@link SkyMesh}.
  15. *
  16. * More references:
  17. *
  18. * - {@link http://simonwallner.at/project/atmospheric-scattering/}
  19. * - {@link http://blenderartists.org/forum/showthread.php?245954-preethams-sky-impementation-HDR}
  20. *
  21. *
  22. * ```js
  23. * const sky = new Sky();
  24. * sky.scale.setScalar( 10000 );
  25. * scene.add( sky );
  26. * ```
  27. *
  28. * It can be useful to hide the sun disc when generating an environment map to avoid artifacts
  29. *
  30. * ```js
  31. * // disable before rendering environment map
  32. * sky.material.uniforms.showSunDisc.value = false;
  33. * // ...
  34. * // re-enable before scene sky box rendering
  35. * sky.material.uniforms.showSunDisc.value = true;
  36. * ```
  37. *
  38. * @augments Mesh
  39. * @three_import import { Sky } from 'three/addons/objects/Sky.js';
  40. */
  41. class Sky extends Mesh {
  42. /**
  43. * Constructs a new skydome.
  44. */
  45. constructor() {
  46. const shader = Sky.SkyShader;
  47. const material = new ShaderMaterial( {
  48. name: shader.name,
  49. uniforms: UniformsUtils.clone( shader.uniforms ),
  50. vertexShader: shader.vertexShader,
  51. fragmentShader: shader.fragmentShader,
  52. side: BackSide,
  53. depthWrite: false
  54. } );
  55. super( new BoxGeometry( 1, 1, 1 ), material );
  56. /**
  57. * This flag can be used for type testing.
  58. *
  59. * @type {boolean}
  60. * @readonly
  61. * @default true
  62. */
  63. this.isSky = true;
  64. }
  65. }
  66. Sky.SkyShader = {
  67. name: 'SkyShader',
  68. uniforms: {
  69. 'turbidity': { value: 2 },
  70. 'rayleigh': { value: 1 },
  71. 'mieCoefficient': { value: 0.005 },
  72. 'mieDirectionalG': { value: 0.8 },
  73. 'sunPosition': { value: new Vector3() },
  74. 'up': { value: new Vector3( 0, 1, 0 ) },
  75. 'cloudScale': { value: 0.0002 },
  76. 'cloudSpeed': { value: 0.0001 },
  77. 'cloudCoverage': { value: 0.4 },
  78. 'cloudDensity': { value: 0.4 },
  79. 'cloudElevation': { value: 0.5 },
  80. 'showSunDisc': { value: 1 },
  81. 'time': { value: 0.0 }
  82. },
  83. vertexShader: /* glsl */`
  84. uniform vec3 sunPosition;
  85. uniform float rayleigh;
  86. uniform float turbidity;
  87. uniform float mieCoefficient;
  88. uniform vec3 up;
  89. varying vec3 vWorldPosition;
  90. varying vec3 vSunDirection;
  91. varying float vSunfade;
  92. varying vec3 vBetaR;
  93. varying vec3 vBetaM;
  94. varying float vSunE;
  95. // constants for atmospheric scattering
  96. const float e = 2.71828182845904523536028747135266249775724709369995957;
  97. const float pi = 3.141592653589793238462643383279502884197169;
  98. // wavelength of used primaries, according to preetham
  99. const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );
  100. // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function:
  101. // (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))
  102. const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );
  103. // mie stuff
  104. // K coefficient for the primaries
  105. const float v = 4.0;
  106. const vec3 K = vec3( 0.686, 0.678, 0.666 );
  107. // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
  108. const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );
  109. // earth shadow hack
  110. // cutoffAngle = pi / 1.95;
  111. const float cutoffAngle = 1.6110731556870734;
  112. const float steepness = 1.5;
  113. const float EE = 1000.0;
  114. float sunIntensity( float zenithAngleCos ) {
  115. zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );
  116. return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );
  117. }
  118. vec3 totalMie( float T ) {
  119. float c = ( 0.2 * T ) * 10E-18;
  120. return 0.434 * c * MieConst;
  121. }
  122. void main() {
  123. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  124. vWorldPosition = worldPosition.xyz;
  125. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  126. gl_Position.z = gl_Position.w; // set z to camera.far
  127. vSunDirection = normalize( sunPosition );
  128. vSunE = sunIntensity( dot( vSunDirection, up ) );
  129. vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );
  130. float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );
  131. // extinction (absorption + out scattering)
  132. // rayleigh coefficients
  133. vBetaR = totalRayleigh * rayleighCoefficient;
  134. // mie coefficients
  135. vBetaM = totalMie( turbidity ) * mieCoefficient;
  136. }`,
  137. fragmentShader: /* glsl */`
  138. varying vec3 vWorldPosition;
  139. varying vec3 vSunDirection;
  140. varying vec3 vBetaR;
  141. varying vec3 vBetaM;
  142. varying float vSunE;
  143. uniform float mieDirectionalG;
  144. uniform vec3 up;
  145. uniform float cloudScale;
  146. uniform float cloudSpeed;
  147. uniform float cloudCoverage;
  148. uniform float cloudDensity;
  149. uniform float cloudElevation;
  150. uniform float showSunDisc;
  151. uniform float time;
  152. // gradient at a lattice corner; sinless hash so every GPU produces the same clouds
  153. vec2 gradient( vec2 i ) {
  154. vec3 p = fract( i.xyx * vec3( 0.1031, 0.1030, 0.0973 ) );
  155. p += dot( p, p.yzx + 33.33 );
  156. return fract( ( p.xx + p.yz ) * p.zy ) * 2.0 - 1.0;
  157. }
  158. // 2D gradient noise: isotropic lobes like Perlin at value-noise cost
  159. float noise( vec2 p ) {
  160. vec2 i = floor( p );
  161. vec2 f = fract( p );
  162. vec2 u = f * f * f * ( f * ( f * 6.0 - 15.0 ) + 10.0 ); // quintic fade
  163. float a = dot( gradient( i ), f );
  164. float b = dot( gradient( i + vec2( 1.0, 0.0 ) ), f - vec2( 1.0, 0.0 ) );
  165. float c = dot( gradient( i + vec2( 0.0, 1.0 ) ), f - vec2( 0.0, 1.0 ) );
  166. float d = dot( gradient( i + vec2( 1.0, 1.0 ) ), f - vec2( 1.0, 1.0 ) );
  167. return mix( mix( a, b, u.x ), mix( c, d, u.x ), u.y ) * 1.6; // ~[-1,1]
  168. }
  169. // fbm; per-octave drift makes clouds billow instead of scrolling as a rigid stamp
  170. float fbm( vec2 p, float drift ) {
  171. float result = 0.0;
  172. float amplitude = 1.0;
  173. for ( int i = 0; i < 4; i ++ ) {
  174. result += amplitude * noise( p );
  175. amplitude *= 0.5;
  176. p = p * 2.0 + drift;
  177. }
  178. return result;
  179. }
  180. // constants for atmospheric scattering
  181. const float pi = 3.141592653589793238462643383279502884197169;
  182. const float n = 1.0003; // refractive index of air
  183. const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius)
  184. // optical length at zenith for molecules
  185. const float rayleighZenithLength = 8.4E3;
  186. const float mieZenithLength = 1.25E3;
  187. // 66 arc seconds -> degrees, and the cosine of that
  188. const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;
  189. // 3.0 / ( 16.0 * pi )
  190. const float THREE_OVER_SIXTEENPI = 0.05968310365946075;
  191. // 1.0 / ( 4.0 * pi )
  192. const float ONE_OVER_FOURPI = 0.07957747154594767;
  193. float rayleighPhase( float cosTheta ) {
  194. return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );
  195. }
  196. float hgPhase( float cosTheta, float g ) {
  197. float g2 = pow( g, 2.0 );
  198. float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );
  199. return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );
  200. }
  201. void main() {
  202. vec3 direction = normalize( vWorldPosition - cameraPosition );
  203. // optical length
  204. // cutoff angle at 90 to avoid singularity in next formula.
  205. float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );
  206. float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );
  207. float sR = rayleighZenithLength * inverse;
  208. float sM = mieZenithLength * inverse;
  209. // combined extinction factor
  210. vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );
  211. // in scattering
  212. float cosTheta = dot( direction, vSunDirection );
  213. float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );
  214. vec3 betaRTheta = vBetaR * rPhase;
  215. float mPhase = hgPhase( cosTheta, mieDirectionalG );
  216. vec3 betaMTheta = vBetaM * mPhase;
  217. vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );
  218. Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );
  219. // nightsky
  220. float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]
  221. float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]
  222. vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );
  223. vec3 L0 = vec3( 0.1 ) * Fex;
  224. // composition + solar disc
  225. float sundisc = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ) * showSunDisc;
  226. L0 += ( vSunE * 19000.0 * Fex ) * sundisc;
  227. vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );
  228. // Clouds
  229. if ( direction.y > 0.0 && cloudCoverage > 0.0 ) {
  230. // Project to cloud plane (higher elevation = clouds appear lower/closer)
  231. float elevation = mix( 1.0, 0.1, cloudElevation );
  232. vec2 cloudUV = direction.xz / ( direction.y * elevation );
  233. cloudUV *= cloudScale;
  234. cloudUV += time * cloudSpeed;
  235. // Cloud density field
  236. float evolve = time * cloudSpeed * 300.0;
  237. float cloudNoise = clamp( fbm( cloudUV * 1000.0, evolve ) * 0.7 + 0.5, 0.0, 1.0 );
  238. // Large-scale coverage variation: clear gaps next to dense banks
  239. float region = noise( cloudUV * 300.0 ) * 0.37 + 0.5;
  240. float cov = clamp( cloudCoverage + ( region - 0.5 ) * 0.6, 0.0, 1.0 );
  241. // Carve clouds where noise rises above the coverage level
  242. float threshold = 1.0 - cov;
  243. float cloudMask = smoothstep( threshold, threshold + 0.3, cloudNoise );
  244. // Fade clouds near horizon (adjusted by elevation)
  245. float horizonFade = smoothstep( 0.0, 0.03 + 0.06 * cloudElevation, direction.y );
  246. cloudMask *= horizonFade;
  247. // Cloud lighting from the sky's own radiance
  248. float dayFactor = smoothstep( -0.08, 0.3, vSunDirection.y );
  249. vec3 sunColor = vSunE * Fex * 0.22 * 0.04; // 0.22 ~ albedo/pi, 0.04 = exposure; the aerial composite adds the eye-leg extinction
  250. vec3 skyAmbient = Lin * 0.04 + vec3( 0.0, 0.0003, 0.00075 );
  251. // Beer-powder self-shadow from the sampled density
  252. float depth = max( 0.0, cloudNoise - threshold );
  253. float beer = exp( depth * -4.0 );
  254. float powder = 1.0 - beer * beer; // beer*beer == exp(-8*depth)
  255. float shade = mix( 0.45, 1.0, clamp( beer * powder * 2.6, 0.0, 1.0 ) ); // 2.6 = 1/0.385, normalizes beer*powder peak to 1
  256. // Henyey-Greenstein forward lobe ( g = 0.7 ): silver lining on rims toward the sun
  257. float silver = clamp( 0.51 / pow( 1.49 - cosTheta * 1.4, 1.5 ), 0.0, 3.0 ); // 0.51=1-g^2, 1.49=1+g^2, 1.4=2g
  258. float edge = cloudMask * ( 1.0 - cloudMask ) * 4.0;
  259. vec3 cloudColor = skyAmbient + sunColor * shade;
  260. cloudColor += sunColor * silver * edge * 0.6;
  261. cloudColor *= max( dayFactor, 0.03 );
  262. // Cloud opacity via Beer's law: density sets how solid the clouds get
  263. float alpha = ( 1.0 - exp( depth * cloudDensity * -12.0 ) ) * horizonFade;
  264. // Occlude the sun disc/glow behind opaque cloud
  265. texColor -= L0 * 0.04 * alpha;
  266. // Composite through the atmosphere so distant clouds dissolve into haze
  267. vec3 cloudAerial = mix( texColor, cloudColor, Fex );
  268. texColor = mix( texColor, cloudAerial, alpha );
  269. }
  270. gl_FragColor = vec4( texColor, 1.0 );
  271. #include <tonemapping_fragment>
  272. #include <colorspace_fragment>
  273. }`
  274. };
  275. export { Sky };
粤ICP备19079148号