💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

383 lines
13 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "ecs/systems/astronomy-system.hpp"
  20. #include "astro/apparent-size.hpp"
  21. #include "ecs/components/orbit-component.hpp"
  22. #include "ecs/components/blackbody-component.hpp"
  23. #include "ecs/components/atmosphere-component.hpp"
  24. #include "ecs/components/transform-component.hpp"
  25. #include "geom/intersection.hpp"
  26. #include "color/color.hpp"
  27. #include "physics/orbit/orbit.hpp"
  28. #include "physics/time/ut1.hpp"
  29. #include "physics/light/blackbody.hpp"
  30. #include "physics/light/photometry.hpp"
  31. #include "physics/light/luminosity.hpp"
  32. #include "geom/cartesian.hpp"
  33. #include <iostream>
  34. namespace ecs {
  35. /**
  36. * Approximates the density of exponentially-distributed atmospheric particles between two points using the trapezoidal rule.
  37. *
  38. * @param a Start point.
  39. * @param b End point.
  40. * @param r Radius of the planet.
  41. * @param sh Scale height of the atmospheric particles.
  42. * @param n Number of samples.
  43. */
  44. template <class T>
  45. T optical_depth(const math::vector3<T>& a, const math::vector3<T>& b, T r, T sh, std::size_t n)
  46. {
  47. T inverse_sh = T(-1) / sh;
  48. T h = math::length(b - a) / T(n);
  49. math::vector3<T> dy = (b - a) / T(n);
  50. math::vector3<T> y = a + dy;
  51. T f_x = std::exp((length(a) - r) * inverse_sh);
  52. T f_y = std::exp((length(y) - r) * inverse_sh);
  53. T sum = (f_x + f_y);
  54. for (std::size_t i = 1; i < n; ++i)
  55. {
  56. f_x = f_y;
  57. y += dy;
  58. f_y = std::exp((length(y) - r) * inverse_sh);
  59. sum += (f_x + f_y);
  60. }
  61. return sum / T(2) * h;
  62. }
  63. template <class T>
  64. math::vector3<T> transmittance(T depth_r, T depth_m, T depth_o, const math::vector3<T>& beta_r, const math::vector3<T>& beta_m)
  65. {
  66. math::vector3<T> transmittance_r = beta_r * depth_r;
  67. math::vector3<T> transmittance_m = beta_m * depth_m;
  68. math::vector3<T> transmittance_o = {0, 0, 0};
  69. math::vector3<T> t = transmittance_r + transmittance_m + transmittance_o;
  70. t.x = std::exp(-t.x);
  71. t.y = std::exp(-t.y);
  72. t.z = std::exp(-t.z);
  73. return t;
  74. }
  75. double calc_beta_r(double wavelength, double ior, double density)
  76. {
  77. double wavelength2 = wavelength * wavelength;
  78. double ior2m1 = ior * ior - 1.0;
  79. double num = 8.0 * (math::pi<double> * math::pi<double> * math::pi<double>) * ior2m1 * ior2m1;
  80. double den = 3.0 * density * (wavelength2 * wavelength2);
  81. return num / den;
  82. }
  83. astronomy_system::astronomy_system(ecs::registry& registry):
  84. entity_system(registry),
  85. universal_time(0.0),
  86. time_scale(1.0),
  87. reference_body(entt::null),
  88. reference_body_axial_tilt(0.0),
  89. reference_body_axial_rotation(0.0),
  90. sun_light(nullptr),
  91. sky_pass(nullptr)
  92. {
  93. registry.on_construct<ecs::blackbody_component>().connect<&astronomy_system::on_blackbody_construct>(this);
  94. registry.on_replace<ecs::blackbody_component>().connect<&astronomy_system::on_blackbody_replace>(this);
  95. registry.on_construct<ecs::atmosphere_component>().connect<&astronomy_system::on_atmosphere_construct>(this);
  96. registry.on_replace<ecs::atmosphere_component>().connect<&astronomy_system::on_atmosphere_replace>(this);
  97. }
  98. void astronomy_system::update(double t, double dt)
  99. {
  100. // Add scaled timestep to current time
  101. set_universal_time(universal_time + dt * time_scale);
  102. // Abort if reference body has not been set
  103. if (reference_body == entt::null)
  104. return;
  105. // Abort if reference body has no orbit component
  106. if (!registry.has<ecs::orbit_component>(reference_body))
  107. return;
  108. // Update axial rotation of reference body
  109. reference_body_axial_rotation = physics::time::ut1::era(universal_time);
  110. // Get orbit component of reference body
  111. const auto& reference_orbit = registry.get<ecs::orbit_component>(reference_body);
  112. /// Construct reference frame which transforms coordinates from inertial space to reference body BCBF space
  113. inertial_to_bcbf = physics::orbit::inertial::to_bcbf
  114. (
  115. reference_orbit.state.r,
  116. reference_orbit.elements.i,
  117. reference_body_axial_tilt,
  118. reference_body_axial_rotation
  119. );
  120. /// Construct reference frame which transforms coordinates from inertial space to reference body topocentric space
  121. inertial_to_topocentric = inertial_to_bcbf * bcbf_to_topocentric;
  122. // Set the transform component translations of orbiting bodies to their topocentric positions
  123. registry.view<orbit_component, transform_component>().each(
  124. [&](ecs::entity entity, auto& orbit, auto& transform)
  125. {
  126. // Transform Cartesian position vector (r) from inertial space to topocentric space
  127. const math::vector3<double> r_topocentric = inertial_to_topocentric * orbit.state.r;
  128. // Update local transform
  129. transform.local.translation = math::type_cast<float>(r_topocentric);
  130. });
  131. // Update blackbody lighting
  132. registry.view<blackbody_component, orbit_component>().each(
  133. [&](ecs::entity entity, auto& blackbody, auto& orbit)
  134. {
  135. // Calculate blackbody inertial basis
  136. double3 blackbody_forward_inertial = math::normalize(reference_orbit.state.r - orbit.state.r);
  137. double3 blackbody_up_inertial = {0, 0, 1};
  138. // Transform blackbody inertial position and basis into topocentric space
  139. double3 blackbody_position_topocentric = inertial_to_topocentric * orbit.state.r;
  140. double3 blackbody_forward_topocentric = inertial_to_topocentric.rotation * blackbody_forward_inertial;
  141. double3 blackbody_up_topocentric = inertial_to_topocentric.rotation * blackbody_up_inertial;
  142. // Calculate distance from observer to blackbody
  143. const double meters_per_au = 1.496e+11;
  144. double blackbody_distance = math::length(blackbody_position_topocentric) * meters_per_au;
  145. // Calculate blackbody illuminance according to distance
  146. double blackbody_illuminance = blackbody.luminous_intensity / (blackbody_distance * blackbody_distance);
  147. // Get blackbody color
  148. double3 blackbody_color = blackbody.color;
  149. // Get atmosphere component of reference body, if any
  150. if (this->registry.has<ecs::atmosphere_component>(reference_body))
  151. {
  152. const ecs::atmosphere_component& atmosphere = this->registry.get<ecs::atmosphere_component>(reference_body);
  153. const double earth_radius_au = 4.26352e-5;
  154. const double earth_radius_m = earth_radius_au * meters_per_au;
  155. // Altitude of observer in meters
  156. geom::ray<double> sample_ray;
  157. sample_ray.origin = {0, observer_location[0] * meters_per_au, 0};
  158. sample_ray.direction = math::normalize(blackbody_position_topocentric);
  159. geom::sphere<double> exosphere;
  160. exosphere.center = {0, 0, 0};
  161. exosphere.radius = earth_radius_m + atmosphere.exosphere_altitude;
  162. auto intersection_result = geom::ray_sphere_intersection(sample_ray, exosphere);
  163. if (std::get<0>(intersection_result))
  164. {
  165. double3 sample_start = sample_ray.origin;
  166. double3 sample_end = sample_ray.extrapolate(std::get<2>(intersection_result));
  167. double optical_depth_r = optical_depth(sample_start, sample_end, earth_radius_m, atmosphere.rayleigh_scale_height, 32);
  168. double optical_depth_k = optical_depth(sample_start, sample_end, earth_radius_m, atmosphere.mie_scale_height, 32);
  169. double optical_depth_o = 0.0;
  170. double3 attenuation = transmittance(optical_depth_r, optical_depth_k, optical_depth_o, atmosphere.rayleigh_scattering_coefficients, atmosphere.mie_scattering_coefficients);
  171. // Attenuate blackbody color
  172. blackbody_color *= attenuation;
  173. }
  174. }
  175. if (sun_light != nullptr)
  176. {
  177. // Update blackbody light transform
  178. sun_light->set_translation(math::type_cast<float>(blackbody_position_topocentric));
  179. sun_light->set_rotation
  180. (
  181. math::look_rotation
  182. (
  183. math::type_cast<float>(blackbody_forward_topocentric),
  184. math::type_cast<float>(blackbody_up_topocentric)
  185. )
  186. );
  187. // Update blackbody light color and intensity
  188. sun_light->set_color(math::type_cast<float>(blackbody_color));
  189. sun_light->set_intensity(static_cast<float>(blackbody_illuminance));
  190. // Pass blackbody params to sky pas
  191. if (this->sky_pass)
  192. {
  193. this->sky_pass->set_sun_object(sun_light);
  194. this->sky_pass->set_sun_color(math::type_cast<float>(blackbody.color * blackbody_illuminance));
  195. }
  196. }
  197. });
  198. // Update sky pass topocentric frame
  199. if (sky_pass != nullptr)
  200. {
  201. sky_pass->set_topocentric_frame
  202. (
  203. physics::frame<float>
  204. {
  205. math::type_cast<float>(inertial_to_topocentric.translation),
  206. math::type_cast<float>(inertial_to_topocentric.rotation)
  207. }
  208. );
  209. }
  210. }
  211. void astronomy_system::set_universal_time(double time)
  212. {
  213. universal_time = time;
  214. }
  215. void astronomy_system::set_time_scale(double scale)
  216. {
  217. time_scale = scale;
  218. }
  219. void astronomy_system::set_reference_body(ecs::entity entity)
  220. {
  221. reference_body = entity;
  222. }
  223. void astronomy_system::set_reference_body_axial_tilt(double angle)
  224. {
  225. reference_body_axial_tilt = angle;
  226. }
  227. void astronomy_system::set_observer_location(const double3& location)
  228. {
  229. observer_location = location;
  230. // Construct reference frame which transforms coordinates from SEZ to EZS
  231. sez_to_ezs = physics::frame<double>
  232. {
  233. {0, 0, 0},
  234. math::normalize
  235. (
  236. math::quaternion<double>::rotate_x(-math::half_pi<double>) *
  237. math::quaternion<double>::rotate_z(-math::half_pi<double>)
  238. )
  239. };
  240. // Construct reference frame which transforms coordinates from EZS to SEZ
  241. ezs_to_sez = sez_to_ezs.inverse();
  242. // Construct reference frame which transforms coordinates from BCBF space to topocentric space
  243. bcbf_to_topocentric = physics::orbit::bcbf::to_topocentric
  244. (
  245. observer_location[0], // Radial distance
  246. observer_location[1], // Latitude
  247. observer_location[2] // Longitude
  248. ) * sez_to_ezs;
  249. }
  250. void astronomy_system::set_sun_light(scene::directional_light* light)
  251. {
  252. sun_light = light;
  253. }
  254. void astronomy_system::set_sky_pass(::sky_pass* pass)
  255. {
  256. this->sky_pass = pass;
  257. }
  258. void astronomy_system::on_blackbody_construct(ecs::registry& registry, ecs::entity entity, ecs::blackbody_component& blackbody)
  259. {
  260. on_blackbody_replace(registry, entity, blackbody);
  261. }
  262. void astronomy_system::on_blackbody_replace(ecs::registry& registry, ecs::entity entity, ecs::blackbody_component& blackbody)
  263. {
  264. // Calculate surface area of spherical blackbody
  265. const double surface_area = double(4) * math::pi<double> * blackbody.radius * blackbody.radius;
  266. // Calculate radiant flux
  267. blackbody.radiant_flux = physics::light::blackbody::radiant_flux(blackbody.temperature, surface_area);
  268. // Blackbody spectral power distribution function
  269. auto spd = [blackbody](double x) -> double
  270. {
  271. // Convert nanometers to meters
  272. x *= double(1e-9);
  273. return physics::light::blackbody::spectral_radiance<double>(blackbody.temperature, x, physics::constants::speed_of_light<double>);
  274. };
  275. // Luminous efficiency function (photopic)
  276. auto lef = [](double x) -> double
  277. {
  278. return physics::light::luminosity::photopic<double>(x);
  279. };
  280. // Construct range of spectral sample points
  281. std::vector<double> samples(10000);
  282. std::iota(samples.begin(), samples.end(), 10);
  283. // Calculate luminous efficiency
  284. const double efficiency = physics::light::luminous_efficiency<double>(spd, lef, samples.begin(), samples.end());
  285. // Convert radiant flux to luminous flux
  286. blackbody.luminous_flux = physics::light::watts_to_lumens<double>(blackbody.radiant_flux, efficiency);
  287. // Calculate luminous intensity from luminous flux
  288. blackbody.luminous_intensity = blackbody.luminous_flux / (4.0 * math::pi<double>);
  289. // Calculate blackbody color from temperature
  290. double3 color_xyz = color::cct::to_xyz(blackbody.temperature);
  291. blackbody.color = color::xyz::to_acescg(color_xyz);
  292. }
  293. void astronomy_system::on_atmosphere_construct(ecs::registry& registry, ecs::entity entity, ecs::atmosphere_component& atmosphere)
  294. {
  295. on_atmosphere_replace(registry, entity, atmosphere);
  296. }
  297. void astronomy_system::on_atmosphere_replace(ecs::registry& registry, ecs::entity entity, ecs::atmosphere_component& atmosphere)
  298. {
  299. // ACEScg wavelengths determined by matching wavelengths to XYZ, transforming XYZ to ACEScg, then selecting the max wavelengths for R, G, and B.
  300. const double3 acescg_wavelengths_nm = {600.0, 540.0, 450.0};
  301. const double3 acescg_wavelengths_m = acescg_wavelengths_nm * 1.0e-9;
  302. // Calculate Rayleigh scattering coefficients
  303. const double air_ior = 1.0003;
  304. const double molecular_density = 2.545e25;
  305. double3 beta_r;
  306. atmosphere.rayleigh_scattering_coefficients =
  307. {
  308. calc_beta_r(acescg_wavelengths_m.x, air_ior, molecular_density),
  309. calc_beta_r(acescg_wavelengths_m.y, air_ior, molecular_density),
  310. calc_beta_r(acescg_wavelengths_m.z, air_ior, molecular_density)
  311. };
  312. // Calculate Mie scattering coefficients
  313. atmosphere.mie_scattering_coefficients = {2.0e-6, 2.0e-6, 2.0e-6};
  314. }
  315. } // namespace ecs