|
R/ |
154 | 80 | 0 | 80 | 0.0 | 0.00% |
|
src/ |
150 | 55 | 0 | 55 | 0.0 | 0.00% |
|
R/ |
96 | 33 | 0 | 33 | 0.0 | 0.00% |
|
src/ |
148 | 19 | 0 | 19 | 0.0 | 0.00% |
|
src/ |
107 | 4 | 0 | 4 | 0.0 | 0.00% |
|
src/ |
143 | 1 | 0 | 1 | 0.0 | 0.00% |
|
src/ |
122 | 1 | 0 | 1 | 0.0 | 0.00% |
|
src/ |
66 | 1 | 0 | 1 | 0.0 | 0.00% |
|
inst/ |
194 | 1 | 0 | 1 | 0.0 | 0.00% |
|
src/ |
1550 | 655 | 21 | 634 | <0.1 | 3.21% |
|
src/ |
534 | 34 | 7 | 27 | 0.5 | 20.59% |
|
src/ |
181 | 113 | 35 | 78 | 0.7 | 30.97% |
|
src/ |
12 | 3 | 1 | 2 | 2.0 | 33.33% |
|
src/ |
208 | 73 | 26 | 47 | 25.8 | 35.62% |
|
src/ |
1028 | 590 | 224 | 366 | 3241254.8 | 37.97% |
|
src/ |
365 | 84 | 40 | 44 | 562.5 | 47.62% |
|
R/ |
8 | 4 | 2 | 2 | 1.5 | 50.00% |
|
R/ |
869 | 325 | 171 | 154 | 3.4 | 52.62% |
|
R/ |
106 | 61 | 35 | 26 | 2.7 | 57.38% |
|
src/ |
82 | 51 | 33 | 18 | 5807.7 | 64.71% |
|
src/ |
831 | 254 | 174 | 80 | 12211455.5 | 68.50% |
|
R/ |
18 | 10 | 7 | 3 | 3740.2 | 70.00% |
|
R/ |
370 | 192 | 138 | 54 | 12.9 | 71.88% |
|
src/ |
310 | 44 | 32 | 12 | 2445.0 | 72.73% |
|
R/ |
126 | 53 | 39 | 14 | 15.0 | 73.58% |
|
R/ |
98 | 47 | 37 | 10 | 2.8 | 78.72% |
|
src/ |
265 | 179 | 154 | 25 | 12.2 | 86.03% |
|
R/ |
104 | 37 | 32 | 5 | 0.9 | 86.49% |
|
R/ |
120 | 60 | 53 | 7 | 391.0 | 88.33% |
|
R/ |
206 | 70 | 64 | 6 | 3634.6 | 91.43% |
|
R/ |
413 | 243 | 223 | 20 | 5152.8 | 91.77% |
|
R/ |
136 | 74 | 68 | 6 | 1.2 | 91.89% |
|
src/ |
368 | 226 | 218 | 8 | 157160.5 | 96.46% |
|
R/ |
464 | 249 | 241 | 8 | 16.3 | 96.79% |
|
R/ |
582 | 298 | 293 | 5 | 41.2 | 98.32% |
| Total | 10534 | 4224 | 2368 | 1856 | 1195930.9 | 56.06% |
| 1 | #' Generate Sun and Moon Disk Radiance Images | |
| 2 | #' | |
| 3 | #' Generate a celestial disk directly at texture resolution, independently of | |
| 4 | #' an environment map. The Sun supports Prague and Hosek radiance profiles. The Moon | |
| 5 | #' uses the existing lunar surface texture, topocentric phase orientation, | |
| 6 | #' earthshine, photometry, and atmospheric extinction. | |
| 7 | #' | |
| 8 | #' @param datetime A single `POSIXct` instant. Its time zone is respected. | |
| 9 | #' @param lat Observer latitude in degrees, between -90 and 90. | |
| 10 | #' @param lon Observer longitude in degrees, between -180 and 180. | |
| 11 | #' @param altitude Default `0`. Observer altitude in meters, from 0 to 15000. | |
| 12 | #' @param resolution Default `256` for the Sun and `1024` for the Moon. Target | |
| 13 | #' disk width and height in pixels, an integer of at least 16. The Moon is | |
| 14 | #' cropped from a padded raster without resampling; edge coverage can add a | |
| 15 | #' few pixels to the returned dimensions. | |
| 16 | #' @param visibility Default `50`. Prague visibility in kilometers, from 20 to | |
| 17 | #' 131.8. | |
| 18 | #' @param albedo Default `0.5`. Ground albedo, from 0 to 1. | |
| 19 | #' @param number_cores Default `1`. Positive integer number of worker threads. | |
| 20 | #' @param wide_spectrum Default `FALSE`. Use the extended Prague spectral data. | |
| 21 | #' @param prague_rgb_correction Default `TRUE`. RGB correction passed to | |
| 22 | #' [calculate_sky_values()]. | |
| 23 | #' @param prague_rgb_correction_strength Default `1`. Nonnegative correction | |
| 24 | #' strength passed to [calculate_sky_values()]. | |
| 25 | #' @param prague_rgb_correction_gain Default `"auto"`. Automatic correction or | |
| 26 | #' three positive RGB gains, as in [calculate_sky_values()]. | |
| 27 | #' @param earthshine Default `TRUE`. Include Earth-reflected light on the Moon. | |
| 28 | #' @param earthshine_albedo Default `0.19`. Nonnegative Earth albedo used for | |
| 29 | #' earthshine. | |
| 30 | #' @param solar_irradiance_w_m2 Default `1300`. Positive solar irradiance in | |
| 31 | #' watts per square meter used to illuminate the lunar surface. | |
| 32 | #' @param hosek Default `FALSE`. Use the Hosek solar radiance profile without | |
| 33 | #' Prague data. Only supported for Sun disks with atmospheric attenuation. | |
| 34 | #' @param turbidity Default `3`. Hosek atmospheric turbidity, from 1.7 to 10. | |
| 35 | #' @param elevation Default `NULL`. Optional Sun elevation in degrees, from -90 | |
| 36 | #' to 90. Supply with `azimuth` to override ephemeris placement and attenuation. | |
| 37 | #' @param azimuth Default `NULL`. Optional Sun azimuth in degrees, from 0 to 360, | |
| 38 | #' clockwise from north. Apparent diameter still comes from the ephemeris. | |
| 39 | #' @param atmospheric_attenuation Default `TRUE`. Include atmospheric extinction | |
| 40 | #' and tint for the specified observer. Set `FALSE` to return radiance before | |
| 41 | #' it enters Earth's atmosphere; the consuming renderer must apply atmospheric | |
| 42 | #' transport and horizon visibility. Lunar phase, surface detail, and earthshine | |
| 43 | #' are retained. `moon_extinction_kV` is ignored when this is `FALSE`. | |
| 44 | #' @param moon_extinction_kV Default `0.172`. Nonnegative lunar atmospheric | |
| 45 | #' extinction coefficient in magnitudes per airmass. | |
| 46 | #' | |
| 47 | #' @return A list containing: | |
| 48 | #' * `image`: a numeric array with dimensions `c(height, width, 3)` containing | |
| 49 | #' linear sRGB radiance, with no exposure, tone mapping, or alpha channel. | |
| 50 | #' Antialiased lunar coverage is already applied: do not multiply by alpha. | |
| 51 | #' Out-of-gamut solar RGB values may be negative and should be preserved. | |
| 52 | #' * `azimuth_deg`: disk-center azimuth, clockwise from true north, in [0, 360). | |
| 53 | #' * `elevation_deg`: disk-center elevation above the local horizon, in degrees. | |
| 54 | #' * `angular_diameter_deg`: topocentric apparent angular diameter in degrees. | |
| 55 | #' * `atmospheric_attenuation`: whether atmospheric filtering is included. | |
| 56 | #' * `projection`: `"rectilinear"`, using the disk mapping described below. | |
| 57 | #' | |
| 58 | #' @details | |
| 59 | #' Prague disks require data installed with [download_sky_data()]. Hosek Sun | |
| 60 | #' disks (`hosek = TRUE`) need no external data. They include fixed-observer | |
| 61 | #' atmospheric attenuation and support finite values at zenith. The atmosphere is | |
| 62 | #' evaluated for one observer altitude and time when `atmospheric_attenuation` | |
| 63 | #' is `TRUE`. With `FALSE`, solar radiance comes from the model's intrinsic | |
| 64 | #' solar spectrum and lunar radiance uses unattenuated photometry without the | |
| 65 | #' atmospheric tint. Solar texture values are then independent of altitude and | |
| 66 | #' solar elevation; ephemeris placement and lunar phase still use the requested | |
| 67 | #' location and time. Neither mode clips the texture to a geometric horizon. | |
| 68 | #' Pair these images with an atmosphere-only sky and disable the corresponding | |
| 69 | #' rasterized celestial bodies in that sky to avoid counting their light twice. | |
| 70 | #' | |
| 71 | #' The disk is inscribed in the image rectangle. For column `j`, row `i`, width | |
| 72 | #' `w`, and height `h`, pixel centers have coordinates | |
| 73 | #' `x = 2 * (j - 0.5) / w - 1` and `y = 1 - 2 * (i - 0.5) / h`. | |
| 74 | #' Sample only within `x^2 + y^2 <= 1`. The corresponding ray direction is | |
| 75 | #' `normalize(forward + tan(radius) * (x * right + y * up))`, where | |
| 76 | #' `radius = angular_diameter_deg * pi / 360`. Image-up is the projection of | |
| 77 | #' local vertical into the disk plane; image-right points toward increasing | |
| 78 | #' azimuth. At the zenith or nadir, north replaces the vertical reference axis. | |
| 79 | #' There is no image reprojection or implicit rotation in the return value. | |
| 80 | #' | |
| 81 | #' The solar model has a fixed angular profile, mapped here to the apparent | |
| 82 | #' ephemeris diameter without changing radiance. Lunar radiance is normalized | |
| 83 | #' over disk solid angle to the existing phase-dependent irradiance, with the | |
| 84 | #' solar spectral RGB distribution. With `atmospheric_attenuation = TRUE`, | |
| 85 | #' lunar attenuation and Prague tint are evaluated at the disk center. At or | |
| 86 | #' below zero center elevation, their finite horizon values are retained so the | |
| 87 | #' upper limb does not disappear prematurely. This continuation preserves a full | |
| 88 | #' disk texture; it is not a model of below-horizon visibility or horizon | |
| 89 | #' depression at altitude. Geometric horizon clipping is the consumer's | |
| 90 | #' responsibility; sample the full disk and discard directions below the | |
| 91 | #' horizon when appropriate. | |
| 92 | #' | |
| 93 | #' To save an EXR without changing radiance, tag `image` with | |
| 94 | #' `rayimage::ray_read_image(image, normalize = FALSE, source_linear = TRUE, | |
| 95 | #' assume_colorspace = rayimage::CS_SRGB)` and write with `clamp = FALSE`. | |
| 96 | #' | |
| 97 | #' @export | |
| 98 | #' @examplesIf interactive() | |
| 99 | #' time = as.POSIXct("2026-01-28 21:00:00", tz = "Pacific/Auckland") | |
| 100 | #' moon = generate_moon_disk(time, lat = -36.87593, lon = 174.7647) | |
| 101 | #' moon[c("azimuth_deg", "elevation_deg", "angular_diameter_deg")] | |
| 102 | #' # Let a renderer evaluate Earth's atmosphere at each interaction instead. | |
| 103 | #' intrinsic_moon = generate_moon_disk(time, lat = -36.87593, lon = 174.7647, | |
| 104 | #' atmospheric_attenuation = FALSE) | |
| 105 | generate_sun_disk = function( | |
| 106 | datetime, | |
| 107 | lat, | |
| 108 | lon, | |
| 109 | altitude = 0, | |
| 110 | resolution = 256, | |
| 111 | visibility = 50, | |
| 112 | albedo = 0.5, | |
| 113 | number_cores = 1, | |
| 114 | wide_spectrum = FALSE, | |
| 115 | prague_rgb_correction = TRUE, | |
| 116 | prague_rgb_correction_strength = 1, | |
| 117 | prague_rgb_correction_gain = "auto", | |
| 118 | atmospheric_attenuation = TRUE, | |
| 119 | hosek = FALSE, | |
| 120 | turbidity = 3, | |
| 121 | elevation = NULL, | |
| 122 | azimuth = NULL | |
| 123 | ) { | |
| 124 | 79x | validate_disk_logical(atmospheric_attenuation, "atmospheric_attenuation") |
| 125 | 75x | validate_disk_logical(hosek, "hosek") |
| 126 | 75x | validate_disk_scalar(turbidity, "turbidity", 1.7, 10) |
| 127 | 74x | if (hosek && !atmospheric_attenuation) { |
| 128 | 1x | stop( |
| 129 | 1x | "Hosek solar disks require atmospheric_attenuation = TRUE.", |
| 130 | 1x | call. = FALSE |
| 131 | ) | |
| 132 | } | |
| 133 | 73x | manual = !is.null(elevation) || !is.null(azimuth) |
| 134 | 73x | if (manual) { |
| 135 | 18x | validate_disk_scalar(elevation, "elevation", -90, 90) |
| 136 | 16x | validate_disk_scalar(azimuth, "azimuth", 0, 360) |
| 137 | } | |
| 138 | 70x | settings = celestial_disk_settings( |
| 139 | 70x | datetime, |
| 140 | 70x | lat, |
| 141 | 70x | lon, |
| 142 | 70x | altitude, |
| 143 | 70x | resolution, |
| 144 | 70x | visibility, |
| 145 | 70x | albedo, |
| 146 | 70x | number_cores, |
| 147 | 70x | wide_spectrum, |
| 148 | 70x | prague_rgb_correction, |
| 149 | 70x | prague_rgb_correction_strength, |
| 150 | 70x | prague_rgb_correction_gain |
| 151 | ) | |
| 152 | 18x | ephemeris = swe_dirs_topo_moon_sun(datetime, lat, lon, elev_m = altitude) |
| 153 | 18x | d = ephemeris$sun_dir_topo |
| 154 | 18x | if (manual) { |
| 155 | # Convert the editor's north-to-east azimuth to Swiss Ephemeris coordinates. | |
| 156 | 15x | e = elevation * pi / 180 |
| 157 | 15x | a = azimuth * pi / 180 |
| 158 | 15x | d = c(-sin(a) * cos(e), -cos(a) * cos(e), sin(e)) |
| 159 | } | |
| 160 | 18x | position = celestial_disk_result( |
| 161 | 18x | array(0, c(1, 1, 3)), |
| 162 | 18x | d, |
| 163 | 18x | ephemeris$sun_diameter_degrees |
| 164 | ) | |
| 165 | 18x | image = if (hosek) { |
| 166 | 15x | hosek_sun_disk_rcpp( |
| 167 | 15x | position$elevation_deg, |
| 168 | 15x | position$azimuth_deg, |
| 169 | 15x | albedo, |
| 170 | 15x | turbidity, |
| 171 | 15x | resolution, |
| 172 | 15x | number_cores |
| 173 | ) | |
| 174 | } else { | |
| 175 | 3x | celestial_sun_pixels( |
| 176 | 3x | c(d[1], d[3], -d[2]), |
| 177 | 3x | resolution, |
| 178 | 3x | settings, |
| 179 | 3x | atmospheric_attenuation |
| 180 | ) | |
| 181 | } | |
| 182 | 18x | result = celestial_disk_result(image, d, ephemeris$sun_diameter_degrees) |
| 183 | 18x | result$atmospheric_attenuation = atmospheric_attenuation |
| 184 | 18x | result |
| 185 | } | |
| 186 | ||
| 187 | #' @rdname generate_sun_disk | |
| 188 | #' @export | |
| 189 | generate_moon_disk = function( | |
| 190 | datetime, | |
| 191 | lat, | |
| 192 | lon, | |
| 193 | altitude = 0, | |
| 194 | resolution = 1024, | |
| 195 | visibility = 50, | |
| 196 | albedo = 0.5, | |
| 197 | number_cores = 1, | |
| 198 | wide_spectrum = FALSE, | |
| 199 | prague_rgb_correction = TRUE, | |
| 200 | prague_rgb_correction_strength = 1, | |
| 201 | prague_rgb_correction_gain = "auto", | |
| 202 | earthshine = TRUE, | |
| 203 | earthshine_albedo = 0.19, | |
| 204 | solar_irradiance_w_m2 = 1300, | |
| 205 | moon_extinction_kV = 0.172, | |
| 206 | atmospheric_attenuation = TRUE | |
| 207 | ) { | |
| 208 | 69x | validate_disk_logical(atmospheric_attenuation, "atmospheric_attenuation") |
| 209 | 65x | settings = celestial_disk_settings( |
| 210 | 65x | datetime, |
| 211 | 65x | lat, |
| 212 | 65x | lon, |
| 213 | 65x | altitude, |
| 214 | 65x | resolution, |
| 215 | 65x | visibility, |
| 216 | 65x | albedo, |
| 217 | 65x | number_cores, |
| 218 | 65x | wide_spectrum, |
| 219 | 65x | prague_rgb_correction, |
| 220 | 65x | prague_rgb_correction_strength, |
| 221 | 65x | prague_rgb_correction_gain |
| 222 | ) | |
| 223 | 13x | validate_disk_logical(earthshine, "earthshine") |
| 224 | 12x | validate_disk_scalar(earthshine_albedo, "earthshine_albedo", 0, Inf) |
| 225 | 11x | validate_disk_scalar(solar_irradiance_w_m2, "solar_irradiance_w_m2", 0, Inf) |
| 226 | 11x | if (solar_irradiance_w_m2 == 0) { |
| 227 | 1x | stop("solar_irradiance_w_m2 must be positive.", call. = FALSE) |
| 228 | } | |
| 229 | 10x | validate_disk_scalar(moon_extinction_kV, "moon_extinction_kV", 0, Inf) |
| 230 | 9x | args = list( |
| 231 | 9x | earthshine = earthshine, |
| 232 | 9x | earthshine_albedo = earthshine_albedo, |
| 233 | 9x | solar_irradiance_w_m2 = solar_irradiance_w_m2, |
| 234 | 9x | moon_extinction_kV = moon_extinction_kV |
| 235 | ) | |
| 236 | 9x | ephemeris = swe_dirs_topo_moon_sun( |
| 237 | 9x | datetime, |
| 238 | 9x | lat, |
| 239 | 9x | lon, |
| 240 | 9x | elev_m = altitude, |
| 241 | 9x | moon_extinction_kV = moon_extinction_kV |
| 242 | ) | |
| 243 | 9x | image = celestial_moon_pixels( |
| 244 | 9x | datetime, |
| 245 | 9x | lat, |
| 246 | 9x | lon, |
| 247 | 9x | resolution, |
| 248 | 9x | args, |
| 249 | 9x | ephemeris, |
| 250 | 9x | settings, |
| 251 | 9x | atmospheric_attenuation |
| 252 | ) | |
| 253 | 8x | result = celestial_disk_result( |
| 254 | 8x | image, |
| 255 | 8x | ephemeris$moon_dir_topo, |
| 256 | 8x | ephemeris$moon_diameter_degrees |
| 257 | ) | |
| 258 | 8x | result$atmospheric_attenuation = atmospheric_attenuation |
| 259 | 8x | result |
| 260 | } | |
| 261 | ||
| 262 | #' @keywords internal | |
| 263 | validate_disk_scalar = function(value, name, lower, upper, integer = FALSE) { | |
| 264 | if ( | |
| 265 | 815x | !is.numeric(value) || |
| 266 | 815x | length(value) != 1L || |
| 267 | 815x | !is.finite(value) || |
| 268 | 815x | value < lower || |
| 269 | 815x | value > upper || |
| 270 | 815x | (integer && value != floor(value)) |
| 271 | ) { | |
| 272 | 92x | stop( |
| 273 | 92x | name, |
| 274 | 92x | " must be a finite ", |
| 275 | 26x | if (integer) "integer" else "number", |
| 276 | 92x | " between ", |
| 277 | 92x | lower, |
| 278 | 92x | " and ", |
| 279 | 92x | upper, |
| 280 | ".", | |
| 281 | 92x | call. = FALSE |
| 282 | ) | |
| 283 | } | |
| 284 | } | |
| 285 | ||
| 286 | #' @keywords internal | |
| 287 | validate_disk_logical = function(value, name) { | |
| 288 | 283x | if (!is.logical(value) || length(value) != 1L || is.na(value)) { |
| 289 | 11x | stop(name, " must be TRUE or FALSE.", call. = FALSE) |
| 290 | } | |
| 291 | } | |
| 292 | ||
| 293 | #' @keywords internal | |
| 294 | celestial_disk_settings = function( | |
| 295 | datetime, | |
| 296 | lat, | |
| 297 | lon, | |
| 298 | altitude, | |
| 299 | resolution, | |
| 300 | visibility, | |
| 301 | albedo, | |
| 302 | number_cores, | |
| 303 | wide_spectrum, | |
| 304 | prague_rgb_correction, | |
| 305 | prague_rgb_correction_strength, | |
| 306 | prague_rgb_correction_gain | |
| 307 | ) { | |
| 308 | if ( | |
| 309 | 135x | !inherits(datetime, "POSIXct") || |
| 310 | 135x | length(datetime) != 1L || |
| 311 | 135x | !is.finite(as.numeric(datetime)) |
| 312 | ) { | |
| 313 | 2x | stop("datetime must be a single finite POSIXct instant.", call. = FALSE) |
| 314 | } | |
| 315 | 133x | validate_disk_scalar(lat, "lat", -90, 90) |
| 316 | 121x | validate_disk_scalar(lon, "lon", -180, 180) |
| 317 | 109x | validate_disk_scalar(altitude, "altitude", 0, 15000) |
| 318 | 97x | validate_disk_scalar( |
| 319 | 97x | resolution, |
| 320 | 97x | "resolution", |
| 321 | 97x | 16, |
| 322 | 97x | .Machine$integer.max / 2, |
| 323 | 97x | TRUE |
| 324 | ) | |
| 325 | 83x | validate_disk_scalar(visibility, "visibility", 20, 131.8) |
| 326 | 71x | validate_disk_scalar(albedo, "albedo", 0, 1) |
| 327 | 59x | validate_disk_scalar( |
| 328 | 59x | number_cores, |
| 329 | 59x | "number_cores", |
| 330 | 59x | 1, |
| 331 | 59x | .Machine$integer.max, |
| 332 | 59x | TRUE |
| 333 | ) | |
| 334 | 47x | validate_disk_logical(wide_spectrum, "wide_spectrum") |
| 335 | 45x | normalize_prague_rgb_correction(prague_rgb_correction) |
| 336 | 43x | prepare_prague_rgb_gain( |
| 337 | 43x | prague_rgb_correction_gain, |
| 338 | 43x | prague_rgb_correction_strength |
| 339 | ) | |
| 340 | 31x | list( |
| 341 | 31x | altitude = altitude, |
| 342 | 31x | visibility = visibility, |
| 343 | 31x | albedo = albedo, |
| 344 | 31x | number_cores = number_cores, |
| 345 | 31x | wide_spectrum = wide_spectrum, |
| 346 | 31x | prague_rgb_correction = prague_rgb_correction, |
| 347 | 31x | prague_rgb_correction_strength = prague_rgb_correction_strength, |
| 348 | 31x | prague_rgb_correction_gain = prague_rgb_correction_gain |
| 349 | ) | |
| 350 | } | |
| 351 | ||
| 352 | #' @keywords internal | |
| 353 | celestial_disk_result = function(image, direction, diameter) { | |
| 354 | 44x | if (any(!is.finite(image))) { |
| 355 | ! | stop( |
| 356 | ! | "Nonfinite celestial radiance returned by the sky model.", |
| 357 | ! | call. = FALSE |
| 358 | ) | |
| 359 | } | |
| 360 | # swe_dirs_topo_moon_sun retains Swiss Ephemeris's south-to-west azimuth | |
| 361 | # convention. Convert to the public north-to-east convention used by the sky. | |
| 362 | 44x | list( |
| 363 | 44x | image = image, |
| 364 | 44x | azimuth_deg = (180 + atan2(direction[1], direction[2]) * 180 / pi) %% 360, |
| 365 | 44x | elevation_deg = asin(pmax(-1, pmin(1, direction[3]))) * 180 / pi, |
| 366 | 44x | angular_diameter_deg = diameter, |
| 367 | 44x | projection = "rectilinear" |
| 368 | ) | |
| 369 | } | |
| 370 | ||
| 371 | #' @keywords internal | |
| 372 | celestial_frame = function(direction) { | |
| 373 | 2x | forward = direction / sqrt(sum(direction^2)) |
| 374 | 2x | vertical = if (abs(forward[2]) < 0.999999) c(0, 1, 0) else c(0, 0, 1) |
| 375 | 2x | right = c( |
| 376 | 2x | forward[2] * vertical[3] - forward[3] * vertical[2], |
| 377 | 2x | forward[3] * vertical[1] - forward[1] * vertical[3], |
| 378 | 2x | forward[1] * vertical[2] - forward[2] * vertical[1] |
| 379 | ) | |
| 380 | 2x | right = right / sqrt(sum(right^2)) |
| 381 | 2x | up = c( |
| 382 | 2x | right[2] * forward[3] - right[3] * forward[2], |
| 383 | 2x | right[3] * forward[1] - right[1] * forward[3], |
| 384 | 2x | right[1] * forward[2] - right[2] * forward[1] |
| 385 | ) | |
| 386 | 2x | list(forward = forward, right = right, up = up) |
| 387 | } | |
| 388 | ||
| 389 | #' @keywords internal | |
| 390 | celestial_sun_pixels = function( | |
| 391 | direction, | |
| 392 | n, | |
| 393 | settings, | |
| 394 | atmospheric_attenuation = TRUE | |
| 395 | ) { | |
| 396 | # The intrinsic solar disk is independent of the terrestrial horizon. Query | |
| 397 | # its angular profile at the zenith even when the actual Sun is below it. | |
| 398 | 3x | if (!atmospheric_attenuation) { |
| 399 | 1x | direction = c(0, 1, 0) |
| 400 | } | |
| 401 | 3x | elevation = asin(direction[2]) * 180 / pi |
| 402 | 3x | if (elevation < -4.2) { |
| 403 | 1x | return(array(0, c(n, n, 3))) |
| 404 | } | |
| 405 | 2x | azimuth = (atan2(-direction[1], direction[3]) * 180 / pi) %% 360 |
| 406 | 2x | frame = celestial_frame(direction) |
| 407 | 2x | grid = expand.grid( |
| 408 | 2x | y = 1 - 2 * ((seq_len(n) - 0.5) / n), |
| 409 | 2x | x = 2 * ((seq_len(n) - 0.5) / n) - 1 |
| 410 | ) | |
| 411 | # SUN_RADIUS in src/PragueSkyModel/PragueSkyModel.cpp. Sample its profile | |
| 412 | # here; consumers map the resulting image to the ephemeris angular diameter. | |
| 413 | 2x | radius = 0.004654793 |
| 414 | 2x | dirs = outer(grid$x * tan(radius), frame$right) + |
| 415 | 2x | outer(grid$y * tan(radius), frame$up) + |
| 416 | 2x | matrix(frame$forward, n * n, 3, byrow = TRUE) |
| 417 | 2x | dirs = dirs / sqrt(rowSums(dirs^2)) |
| 418 | 2x | phi = (atan2(-dirs[, 1], dirs[, 3]) * 180 / pi) %% 360 |
| 419 | 2x | theta = asin(pmax(-1, pmin(1, dirs[, 2]))) * 180 / pi |
| 420 | 2x | values = if (atmospheric_attenuation) { |
| 421 | 1x | do.call( |
| 422 | 1x | calculate_sky_values, |
| 423 | 1x | c( |
| 424 | 1x | list( |
| 425 | 1x | phi = phi, |
| 426 | 1x | theta = theta, |
| 427 | 1x | elevation = elevation, |
| 428 | 1x | azimuth = azimuth, |
| 429 | 1x | render_mode = "sun" |
| 430 | ), | |
| 431 | 1x | settings |
| 432 | ) | |
| 433 | ) | |
| 434 | } else { | |
| 435 | 1x | filename = resolve_prague_coef_file( |
| 436 | 1x | altitude = 0, |
| 437 | 1x | wide_spectrum = settings$wide_spectrum, |
| 438 | 1x | allow_download = FALSE |
| 439 | ) | |
| 440 | 1x | count = length(phi) |
| 441 | 1x | values = calculate_raw_prague( |
| 442 | 1x | phi, |
| 443 | 1x | theta, |
| 444 | 1x | rep(elevation, count), |
| 445 | 1x | rep(settings$albedo, count), |
| 446 | 1x | rep(0, count), |
| 447 | 1x | rep(settings$visibility, count), |
| 448 | 1x | rep(azimuth, count), |
| 449 | 1x | settings$number_cores, |
| 450 | 1x | filename, |
| 451 | 1x | "sun", |
| 452 | 1x | atmospheric_attenuation = FALSE |
| 453 | ) | |
| 454 | 2x | if ( |
| 455 | 1x | normalize_prague_rgb_correction(settings$prague_rgb_correction) == |
| 456 | 1x | "constant" |
| 457 | ) { | |
| 458 | 1x | values = apply_prague_rgb_gain( |
| 459 | 1x | values, |
| 460 | 1x | prepare_prague_rgb_gain( |
| 461 | 1x | settings$prague_rgb_correction_gain, |
| 462 | 1x | settings$prague_rgb_correction_strength |
| 463 | ) | |
| 464 | ) | |
| 465 | } | |
| 466 | 1x | values |
| 467 | } | |
| 468 | 2x | array(as.numeric(values), c(n, n, 3)) |
| 469 | } | |
| 470 | ||
| 471 | #' @keywords internal | |
| 472 | celestial_moon_pixels = function( | |
| 473 | datetime, | |
| 474 | lat, | |
| 475 | lon, | |
| 476 | resolution, | |
| 477 | args, | |
| 478 | ephemeris, | |
| 479 | settings, | |
| 480 | atmospheric_attenuation = TRUE | |
| 481 | ) { | |
| 482 | # skymodelr rasterizes a padded patch using rayvertex. Scope its thread count; | |
| 483 | # preparation happens before the path tracer's worker pool starts. | |
| 484 | 9x | old_options = options(cores = settings$number_cores) |
| 485 | 9x | on.exit(options(old_options), add = TRUE) |
| 486 | 9x | patch = do.call( |
| 487 | 9x | generate_moon_image_latlong, |
| 488 | 9x | c( |
| 489 | 9x | list( |
| 490 | 9x | datetime = datetime, |
| 491 | 9x | lat = lat, |
| 492 | 9x | lon = lon, |
| 493 | 9x | elev_m = settings$altitude, |
| 494 | 9x | width = 2 * resolution, |
| 495 | 9x | height = 2 * resolution |
| 496 | ), | |
| 497 | 9x | args |
| 498 | ) | |
| 499 | 9x | )$moon_luminance_array |
| 500 | 8x | mask = patch[,, 4] > 0 |
| 501 | 8x | indices = which(mask, arr.ind = TRUE) |
| 502 | 8x | if (!nrow(indices)) { |
| 503 | ! | stop("skymodelr returned an empty Moon texture.", call. = FALSE) |
| 504 | } | |
| 505 | 8x | rows = seq(min(indices[, 1]), max(indices[, 1])) |
| 506 | 8x | cols = seq(min(indices[, 2]), max(indices[, 2])) |
| 507 | 8x | patch = patch[rows, cols, , drop = FALSE] |
| 508 | 8x | pixels = patch[,, 1:3, drop = FALSE] |
| 509 | # The rasterizer's reconstruction filter can undershoot at the silhouette. | |
| 510 | # Remove negative coverage/radiance before the physical normalization. | |
| 511 | 8x | coverage = pmax(0, pmin(1, patch[,, 4])) |
| 512 | 8x | for (c in 1:3) { |
| 513 | 24x | pixels[,, c] = pmax(0, pixels[,, c]) * coverage |
| 514 | } | |
| 515 | ||
| 516 | 8x | direction = c( |
| 517 | 8x | ephemeris$moon_dir_topo[1], |
| 518 | 8x | ephemeris$moon_dir_topo[3], |
| 519 | 8x | -ephemeris$moon_dir_topo[2] |
| 520 | ) | |
| 521 | 8x | elevation = asin(pmax(-1, pmin(1, direction[2]))) * 180 / pi |
| 522 | # Calibrate a complete disk. Its center may be below zero while the upper | |
| 523 | # limb remains visible; horizon visibility belongs to the consuming renderer. | |
| 524 | 8x | illuminance = if (atmospheric_attenuation) { |
| 525 | 6x | apply_airmass_extinction( |
| 526 | 6x | ephemeris$moon_brightness_lux_unattenuated, |
| 527 | 6x | elevation, |
| 528 | 6x | kV = args$moon_extinction_kV, |
| 529 | 6x | clip_horizon = FALSE |
| 530 | ) | |
| 531 | } else { | |
| 532 | 2x | ephemeris$moon_brightness_lux_unattenuated |
| 533 | } | |
| 534 | 8x | irradiance = lux_to_radiometric_irradiance( |
| 535 | 8x | illuminance, |
| 536 | 8x | compute_K_eff("BB5778") |
| 537 | ) | |
| 538 | 8x | rgb = compute_spd_rgb_unit("BB5778") |
| 539 | # Use the same finite horizon limit for color, avoiding a tint discontinuity | |
| 540 | # when the center crosses zero. This remains a disk-wide approximation. | |
| 541 | 8x | tint_elevation = max(0, elevation) |
| 542 | 8x | azimuth = (atan2(-direction[1], direction[3]) * 180 / pi) %% 360 |
| 543 | 8x | if (atmospheric_attenuation) { |
| 544 | 6x | tint = do.call( |
| 545 | 6x | calculate_sky_values, |
| 546 | 6x | c( |
| 547 | 6x | list( |
| 548 | 6x | phi = azimuth, |
| 549 | 6x | theta = tint_elevation, |
| 550 | 6x | elevation = tint_elevation, |
| 551 | 6x | azimuth = azimuth, |
| 552 | 6x | render_mode = "sun" |
| 553 | ), | |
| 554 | 6x | settings |
| 555 | ) | |
| 556 | ) | |
| 557 | 6x | if (all(is.finite(tint)) && sum(tint) > 0) { |
| 558 | 6x | rgb = rgb * pmax(as.numeric(tint), 0) |
| 559 | } | |
| 560 | } | |
| 561 | 8x | rgb = rgb / sum(rgb) |
| 562 | 8x | n = dim(pixels) |
| 563 | 8x | xx = matrix( |
| 564 | 8x | rep(2 * ((seq_len(n[2]) - 0.5) / n[2]) - 1, each = n[1]), |
| 565 | 8x | n[1], |
| 566 | 8x | n[2] |
| 567 | ) | |
| 568 | 8x | yy = matrix(rep(2 * ((seq_len(n[1]) - 0.5) / n[1]) - 1, n[2]), n[1], n[2]) |
| 569 | 8x | r2 = xx^2 + yy^2 |
| 570 | 8x | t2 = tan(ephemeris$moon_diameter_degrees * pi / 360)^2 |
| 571 | 8x | domega = 4 * t2 / (1 + t2 * r2)^1.5 / (n[1] * n[2]) |
| 572 | 8x | domega[r2 > 1] = 0 |
| 573 | 8x | for (c in 1:3) { |
| 574 | 24x | integral = sum(pixels[,, c] * domega) |
| 575 | 24x | pixels[,, c] = if (integral > 0) { |
| 576 | 24x | pixels[,, c] * irradiance * rgb[c] / integral |
| 577 | } else { | |
| 578 | ! | 0 |
| 579 | } | |
| 580 | } | |
| 581 | 8x | pixels |
| 582 | } |
| 1 | sun_solid_angle_sr = function(diameter_deg = 0.533) { | |
| 2 | 3x | r = (diameter_deg * 0.5) * pi / 180 |
| 3 | 3x | 2 * pi * (1 - cos(r)) |
| 4 | } | |
| 5 | ||
| 6 | #' Generate the atmosphere with the moon | |
| 7 | #' | |
| 8 | #' @description Note that this is just a scaled version of `generate_sky()`, scaled down by the luminance | |
| 9 | #' of the moon as compared to the sun. This function takes the phase of the moon into account, | |
| 10 | #' along with the increase in luminosity around a full moon (known as opposition surge). Moonlight | |
| 11 | #' attenuation uses the Rozenberg/Krisciunas-Schaefer airmass approximation with configurable `moon_extinction_kV`. | |
| 12 | #' | |
| 13 | #' @details The complete lunar disk is calibrated before directions below the | |
| 14 | #' horizontal horizon are clipped. The upper limb remains visible after the | |
| 15 | #' center sets, with the finite horizon attenuation and tint retained below zero | |
| 16 | #' center elevation. The visible segment is not renormalized to the full Moon's | |
| 17 | #' brightness. Finite sky-map resolution limits how finely this edge is resolved. | |
| 18 | #' | |
| 19 | #' Disk visibility is independent of the atmospheric model's elevation domain: | |
| 20 | #' the optional atmospheric component requires center elevation at least zero | |
| 21 | #' for Hosek or -4.2 degrees for Prague. Below that domain it is omitted, while | |
| 22 | #' any visible lunar limb is still drawn. Horizon depression and refraction are | |
| 23 | #' not modeled. | |
| 24 | #' | |
| 25 | #' @param datetime POSIX-compatible date-time. | |
| 26 | #' @param lat Observer latitude (degrees N). | |
| 27 | #' @param lon Observer longitude (degrees E; west < 0). | |
| 28 | #' @param filename Default `NA`. Path to the image file to write. | |
| 29 | #' @param albedo Default `0.5`. Ground albedo, range 0 to 1. | |
| 30 | #' @param turbidity Default `3`. Atmospheric turbidity, range | |
| 31 | #' 1.7 to 10 (*Hosek only*). | |
| 32 | #' @param altitude Default `0`. Observer altitude (m), range | |
| 33 | #' 0 to 15000 (*Prague only*). | |
| 34 | #' @param resolution Default `2048`. Image height in pixels (width = 2 * height). | |
| 35 | #' @param number_cores Default `1`. CPU threads to use. | |
| 36 | #' @param moon_atmosphere Default `FALSE`. If `TRUE`, this generates atmospheric scattering from light from the moon. | |
| 37 | #' @param earthshine Default `TRUE`. If `FALSE`, disable earthshine contribution on the moon. | |
| 38 | #' @param earthshine_albedo Default `0.19`. Effective Earth albedo term used | |
| 39 | #' in the earthshine irradiance approximation. | |
| 40 | #' @param solar_irradiance_w_m2 Default `1300`. Reference solar irradiance at | |
| 41 | #' 1 AU (W/m^2) used to normalize earthshine emission intensity. | |
| 42 | #' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction | |
| 43 | #' coefficient for direct moonlight attenuation. | |
| 44 | #' @param hosek Default `TRUE`. `FALSE` selects the Prague model. | |
| 45 | #' @param wide_spectrum Default `FALSE`. 55-channel Prague coefficients (altitude = 0m only). | |
| 46 | #' @param visibility Default `50`. Meteorological range (km); *Prague only*. | |
| 47 | #' @param moon_texture_width Default `801`. Internal moon-texture render width. | |
| 48 | #' @param moon_texture_height Default `801`. Internal moon-texture render height. | |
| 49 | #' @param verbose Default `FALSE`. Whether to print progress bars/diagnostic info. | |
| 50 | #' | |
| 51 | #' @return Either the image array, or the array is invisibly returned if a file | |
| 52 | #' is written. The array has dimensions `(resolution, 2 * resolution, 4)`. | |
| 53 | #' @note Writing to non-EXR formats will introduce precision loss because HDR | |
| 54 | #' data are quantised to the destination format, and low dynamic range outputs like PNG | |
| 55 | #' and JPEG files will not represent the true luminosity values encoded in the array. | |
| 56 | #' @export | |
| 57 | #' | |
| 58 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 59 | #' # Moonlit sky (Hosek), mid-evening in DC | |
| 60 | #' generate_moon_latlong( | |
| 61 | #' datetime = as.POSIXct("2025-09-05 19:30:00", tz = "America/New_York"), | |
| 62 | #' lat = 38.9072, | |
| 63 | #' lon = -77.0369, | |
| 64 | #' resolution = 400, | |
| 65 | #' turbidity = 3, | |
| 66 | #' verbose = TRUE | |
| 67 | #' ) |> | |
| 68 | #' rayimage::render_exposure(15) |> | |
| 69 | #' rayimage::plot_image() | |
| 70 | generate_moon_latlong = function( | |
| 71 | datetime, | |
| 72 | lat, | |
| 73 | lon, | |
| 74 | filename = NA, | |
| 75 | albedo = 0.5, | |
| 76 | turbidity = 3, | |
| 77 | altitude = 0, | |
| 78 | resolution = 2048, | |
| 79 | number_cores = 1, | |
| 80 | moon_atmosphere = FALSE, | |
| 81 | earthshine = TRUE, | |
| 82 | earthshine_albedo = 0.19, | |
| 83 | solar_irradiance_w_m2 = 1300, | |
| 84 | moon_extinction_kV = 0.172, | |
| 85 | hosek = TRUE, | |
| 86 | wide_spectrum = FALSE, | |
| 87 | visibility = 50, | |
| 88 | moon_texture_width = 801, | |
| 89 | moon_texture_height = 801, | |
| 90 | verbose = FALSE | |
| 91 | ) { | |
| 92 | 17x | moon_sun_data = swe_dirs_topo_moon_sun( |
| 93 | 17x | datetime = datetime, |
| 94 | 17x | lat = lat, |
| 95 | 17x | lon = lon, |
| 96 | 17x | elev_m = altitude, |
| 97 | 17x | moon_extinction_kV = moon_extinction_kV |
| 98 | ) | |
| 99 | 17x | moon_dir = moon_sun_data$moon_dir_topo |
| 100 | 17x | moon_elevation = asin(moon_dir[3]) * 180 / pi |
| 101 | 17x | moon_azimuth = (180 + atan2(moon_dir[1], moon_dir[2]) * 180 / pi + 360) %% |
| 102 | 17x | 360 |
| 103 | # Sample sun colour so the moon inherits the same atmospheric tint. | |
| 104 | 17x | sun_rgb_ratio = c(1, 1, 1) |
| 105 | # Disk visibility is evaluated per direction below. Keep a finite tint for | |
| 106 | # the visible upper limb even after the center passes the horizon. | |
| 107 | 17x | tint_elevation = max(0, moon_elevation) |
| 108 | 17x | if (is.finite(moon_elevation)) { |
| 109 | 17x | sample_resolution = max(256, min(1024, resolution)) |
| 110 | 17x | sun_sample = tryCatch( |
| 111 | { | |
| 112 | 17x | generate_sky( |
| 113 | 17x | albedo = albedo, |
| 114 | 17x | turbidity = turbidity, |
| 115 | 17x | altitude = altitude, |
| 116 | 17x | elevation = tint_elevation, |
| 117 | 17x | visibility = visibility, |
| 118 | 17x | azimuth = moon_azimuth, |
| 119 | 17x | resolution = sample_resolution, |
| 120 | 17x | number_cores = number_cores, |
| 121 | 17x | hosek = hosek, |
| 122 | 17x | wide_spectrum = wide_spectrum, |
| 123 | 17x | render_mode = "sun", |
| 124 | 17x | verbose = FALSE |
| 125 | ) | |
| 126 | }, | |
| 127 | 17x | error = function(e) { |
| 128 | ! | NULL |
| 129 | } | |
| 130 | ) | |
| 131 | 17x | if (!is.null(sun_sample)) { |
| 132 | 17x | sun_lum = sun_sample[,, 1] + sun_sample[,, 2] + sun_sample[,, 3] |
| 133 | 17x | peak_idx = which.max(sun_lum) |
| 134 | 17x | sun_rgb = c( |
| 135 | 17x | sun_sample[,, 1][peak_idx], |
| 136 | 17x | sun_sample[,, 2][peak_idx], |
| 137 | 17x | sun_sample[,, 3][peak_idx] |
| 138 | ) | |
| 139 | 17x | sun_mean = mean(sun_rgb) |
| 140 | 17x | if (all(is.finite(sun_rgb)) && sun_mean > 0) { |
| 141 | 17x | sun_rgb_ratio = sun_rgb / sun_mean |
| 142 | } | |
| 143 | } | |
| 144 | } | |
| 145 | ||
| 146 | 17x | moon_lux = moon_sun_data$moon_brightness_lux |
| 147 | 17x | moon_phase = moon_sun_data$moon_phase |
| 148 | 17x | spd_type = "BB5778" |
| 149 | 17x | rgb_unit = compute_spd_rgb_unit(spd_type) |
| 150 | 17x | K_eff = compute_K_eff(spd_type) |
| 151 | 17x | moon_irradiance = lux_to_radiometric_irradiance(moon_lux, K_eff) |
| 152 | 17x | if (!is.finite(moon_irradiance)) { |
| 153 | ! | moon_irradiance = 0 |
| 154 | } | |
| 155 | ||
| 156 | 17x | old_options = options(cores = number_cores) |
| 157 | 17x | on.exit(options(old_options), add = TRUE) |
| 158 | 17x | moon_info_list = generate_moon_image_latlong( |
| 159 | 17x | datetime = datetime, |
| 160 | 17x | lat = lat, |
| 161 | 17x | lon = lon, |
| 162 | 17x | elev_m = altitude, |
| 163 | 17x | width = moon_texture_width, |
| 164 | 17x | height = moon_texture_height, |
| 165 | 17x | earthshine = earthshine, |
| 166 | 17x | earthshine_albedo = earthshine_albedo, |
| 167 | 17x | solar_irradiance_w_m2 = solar_irradiance_w_m2, |
| 168 | 17x | moon_extinction_kV = moon_extinction_kV, |
| 169 | 17x | verbose = verbose |
| 170 | ) | |
| 171 | 17x | moon_luminance_array = moon_info_list$moon_luminance_array |
| 172 | 17x | moon_angular_diameter_deg = moon_info_list$moon_angular_diameter_deg |
| 173 | 17x | moon_angular_diameter_rad = moon_angular_diameter_deg * pi / 180 |
| 174 | ||
| 175 | 17x | if (verbose) { |
| 176 | ! | message(sprintf( |
| 177 | ! | "Moon: %0.1f elevation, %0.1f azimuth, %0.3f phase, %f lux", |
| 178 | ! | moon_elevation, |
| 179 | ! | moon_azimuth, |
| 180 | ! | moon_phase, |
| 181 | ! | moon_lux |
| 182 | )) | |
| 183 | } | |
| 184 | # The atmospheric component still follows its model's supported domain; | |
| 185 | # this must not determine whether the independent lunar disk is rendered. | |
| 186 | 17x | atmosphere_min_elevation = if (hosek) 0 else -4.2 |
| 187 | 17x | if (moon_atmosphere && moon_elevation >= atmosphere_min_elevation) { |
| 188 | 3x | coef_file = "" |
| 189 | 3x | stopifnot(all(altitude >= 0 & altitude <= 15000)) |
| 190 | 3x | if (!hosek) { |
| 191 | 2x | coef_file = resolve_prague_coef_file( |
| 192 | 2x | altitude = altitude, |
| 193 | 2x | wide_spectrum = wide_spectrum, |
| 194 | 2x | model = "Prague moon-atmosphere model" |
| 195 | ) | |
| 196 | } | |
| 197 | 3x | moon_array = generate_sky( |
| 198 | 3x | albedo = albedo, |
| 199 | 3x | turbidity = turbidity, |
| 200 | 3x | altitude = altitude, |
| 201 | 3x | elevation = moon_elevation, |
| 202 | 3x | azimuth = moon_azimuth, |
| 203 | 3x | resolution = resolution, |
| 204 | 3x | number_cores = number_cores, |
| 205 | 3x | hosek = hosek, |
| 206 | 3x | wide_spectrum = wide_spectrum, |
| 207 | 3x | visibility = visibility, |
| 208 | 3x | verbose = verbose, |
| 209 | 3x | render_mode = "atmosphere" |
| 210 | ) | |
| 211 | 3x | lambda_values = seq(360, 720, by = 40) |
| 212 | 3x | model = if (hosek) "hosek" else "prague" |
| 213 | 3x | E_unit = calculate_sun_radiance_band_rcpp( |
| 214 | 3x | albedo = albedo, |
| 215 | 3x | turbidity = turbidity, |
| 216 | 3x | elevation = moon_elevation, |
| 217 | 3x | azimuth_deg = moon_azimuth, |
| 218 | 3x | model = model, |
| 219 | 3x | prg_dataset = coef_file, |
| 220 | 3x | altitude = altitude, |
| 221 | 3x | visibility = visibility, |
| 222 | 3x | lambda_nm = if (hosek) lambda_values else NULL |
| 223 | ) * | |
| 224 | 3x | sun_solid_angle_sr(0.533) |
| 225 | 3x | scale_sun_to_moon = if (is.finite(E_unit) && E_unit > 0) { |
| 226 | 3x | moon_irradiance / E_unit |
| 227 | } else { | |
| 228 | ! | 0 |
| 229 | } | |
| 230 | # Apply radiometric scaling and atmospheric tint | |
| 231 | 3x | moon_array[,, 1:3] = sweep( |
| 232 | 3x | moon_array[,, 1:3] * scale_sun_to_moon, |
| 233 | 3x | 3, |
| 234 | 3x | sun_rgb_ratio, |
| 235 | "*" | |
| 236 | ) | |
| 237 | } else { | |
| 238 | 14x | moon_array = array( |
| 239 | 14x | 0, |
| 240 | 14x | dim = c(resolution, resolution * 2, 4) |
| 241 | ) | |
| 242 | 14x | moon_array[,, 4] = 1 |
| 243 | } | |
| 244 | ||
| 245 | 17x | moon_dir_vec = c( |
| 246 | 17x | cospi(moon_azimuth / 180) * cospi(moon_elevation / 180), |
| 247 | 17x | sinpi(moon_elevation / 180), |
| 248 | 17x | sinpi(moon_azimuth / 180) * cospi(moon_elevation / 180) |
| 249 | ) | |
| 250 | ||
| 251 | 17x | moon_diameter_pixels = resolution / 180 * moon_angular_diameter_deg |
| 252 | 17x | resize_moon_dim = ceiling(moon_diameter_pixels) |
| 253 | 17x | if (resize_moon_dim %% 2 == 0) { |
| 254 | 17x | resize_moon_dim = resize_moon_dim + 1 |
| 255 | } | |
| 256 | 17x | resized_moon_luminance_array = rayimage::render_resized( |
| 257 | 17x | moon_luminance_array, |
| 258 | 17x | dims = c(resize_moon_dim, resize_moon_dim), |
| 259 | 17x | method = "box" |
| 260 | ) | |
| 261 | 17x | patch_mask = resized_moon_luminance_array[,, 4] > 0 |
| 262 | 17x | if (!any(patch_mask)) { |
| 263 | ! | patch_mask[,] = TRUE |
| 264 | } | |
| 265 | 17x | alpha_mask = resized_moon_luminance_array[,, 4] > 0 |
| 266 | 17x | if (any(alpha_mask)) { |
| 267 | 17x | alpha_inds = which(alpha_mask, arr.ind = TRUE) |
| 268 | 17x | min_row = min(alpha_inds[, 1]) |
| 269 | 17x | max_row = max(alpha_inds[, 1]) |
| 270 | 17x | min_col = min(alpha_inds[, 2]) |
| 271 | 17x | max_col = max(alpha_inds[, 2]) |
| 272 | 17x | center_x = (min_col + max_col) / 2 |
| 273 | 17x | center_y = (min_row + max_row) / 2 |
| 274 | 17x | radius_x = max(1, (max_col - min_col + 1) / 2) |
| 275 | 17x | radius_y = max(1, (max_row - min_row + 1) / 2) |
| 276 | } else { | |
| 277 | ! | half_dim = (resize_moon_dim - 1) / 2 |
| 278 | ! | center_x = half_dim + 1 |
| 279 | ! | center_y = half_dim + 1 |
| 280 | ! | radius_x = half_dim |
| 281 | ! | radius_y = half_dim |
| 282 | } | |
| 283 | 17x | rgb_target = rgb_unit * sun_rgb_ratio |
| 284 | 17x | if (sum(rgb_target) > 0) { |
| 285 | 17x | rgb_target = rgb_target / sum(rgb_target) |
| 286 | } else { | |
| 287 | ! | rgb_target = rgb_unit |
| 288 | } | |
| 289 | 17x | mean_rgb = c( |
| 290 | 17x | mean(resized_moon_luminance_array[,, 1][patch_mask], na.rm = TRUE), |
| 291 | 17x | mean(resized_moon_luminance_array[,, 2][patch_mask], na.rm = TRUE), |
| 292 | 17x | mean(resized_moon_luminance_array[,, 3][patch_mask], na.rm = TRUE) |
| 293 | ) | |
| 294 | 17x | mean_rgb[!is.finite(mean_rgb)] = 0 |
| 295 | 17x | rgb_scale = ifelse(mean_rgb > 0, rgb_target / mean_rgb, 0) |
| 296 | 17x | resized_moon_luminance_array[,, 1:3] = sweep( |
| 297 | 17x | resized_moon_luminance_array[,, 1:3], |
| 298 | 17x | 3, |
| 299 | 17x | rgb_scale, |
| 300 | "*" | |
| 301 | ) | |
| 302 | 17x | mean_sum = mean( |
| 303 | 17x | rowSums(resized_moon_luminance_array[,, 1:3])[patch_mask], |
| 304 | 17x | na.rm = TRUE |
| 305 | ) | |
| 306 | 17x | if (is.finite(mean_sum) && mean_sum > 0) { |
| 307 | 16x | resized_moon_luminance_array[,, 1:3] = |
| 308 | 16x | resized_moon_luminance_array[,, 1:3] / mean_sum |
| 309 | } | |
| 310 | ||
| 311 | 17x | nTheta = resolution |
| 312 | 17x | nPhi = 2 * resolution |
| 313 | 17x | disk_mask = matrix(FALSE, nrow = nTheta, ncol = nPhi) |
| 314 | ||
| 315 | 17x | r = moon_angular_diameter_rad / 2 |
| 316 | 17x | cos_r = cos(r) |
| 317 | ||
| 318 | 17x | phi_c = moon_elevation * pi / 180 |
| 319 | 17x | j_min = max(1, floor(((pi / 2) - (phi_c + r)) / pi * (nTheta - 1)) + 1) |
| 320 | 17x | j_max = min( |
| 321 | 17x | nTheta, |
| 322 | 17x | ceiling(((pi / 2) - (phi_c - r)) / pi * (nTheta - 1)) + 1 |
| 323 | ) | |
| 324 | ||
| 325 | 17x | thetas = seq(pi / 2, -pi / 2, length.out = nTheta) |
| 326 | 17x | phis = seq(0, 2 * pi, length.out = nPhi) |
| 327 | ||
| 328 | 17x | cos_phi = cos(phis) |
| 329 | 17x | sin_phi = sin(phis) |
| 330 | 17x | cos_theta = cos(thetas) |
| 331 | 17x | sin_theta = sin(thetas) |
| 332 | ||
| 333 | # Tangent frame at moon center (z = moon_dir_vec) | |
| 334 | 17x | lam_c = moon_azimuth * pi / 180 |
| 335 | 17x | z_hat = moon_dir_vec |
| 336 | 17x | e_hat = c(-sin(lam_c), 0, cos(lam_c)) |
| 337 | 17x | e_hat = e_hat / sqrt(sum(e_hat * e_hat)) # local east |
| 338 | 17x | n_hat = c( |
| 339 | 17x | z_hat[2] * e_hat[3] - z_hat[3] * e_hat[2], |
| 340 | 17x | z_hat[3] * e_hat[1] - z_hat[1] * e_hat[3], |
| 341 | 17x | z_hat[1] * e_hat[2] - z_hat[2] * e_hat[1] |
| 342 | ) | |
| 343 | 17x | n_hat = n_hat / sqrt(sum(n_hat * n_hat)) # local north |
| 344 | ||
| 345 | 17x | tan_r = tan(r) # r = moon_angular_diameter_rad/2 |
| 346 | # Normalize the full projected disk, including its hidden portion. Using only | |
| 347 | # visible texels would concentrate the entire Moon's power into its last limb. | |
| 348 | 17x | dphi = 2 * pi / nPhi |
| 349 | 17x | dtheta = pi / nTheta |
| 350 | 17x | full_disk_integral = 0 |
| 351 | ||
| 352 | 17x | for (j in seq(j_min, j_max)) { |
| 353 | 357x | for (i in seq_len(nPhi)) { |
| 354 | 146720x | sample_dir_vec = c( |
| 355 | 146720x | cos_phi[i] * cos_theta[j], |
| 356 | 146720x | sin_theta[j], |
| 357 | 146720x | sin_phi[i] * cos_theta[j] |
| 358 | ) | |
| 359 | 146720x | dot = sum(moon_dir_vec * sample_dir_vec) |
| 360 | 146720x | if (dot < cos_r) { |
| 361 | 128026x | next |
| 362 | } | |
| 363 | ||
| 364 | # Camera (tangent) components of the sample direction | |
| 365 | 18694x | vx = sum(sample_dir_vec * e_hat) |
| 366 | 18694x | vy = sum(sample_dir_vec * n_hat) |
| 367 | 18694x | vz = sum(sample_dir_vec * z_hat) # == dot |
| 368 | ||
| 369 | # Inverse rectilinear mapping (square FOV 2*r): | |
| 370 | 18694x | u_px = center_x + radius_x * (vx / (tan_r * vz)) |
| 371 | 18694x | v_px = center_y + radius_y * (vy / (tan_r * vz)) |
| 372 | ||
| 373 | 18694x | u_i = clamp_value(round(u_px), 1, resize_moon_dim) |
| 374 | 18694x | v_i = clamp_value(round(v_px), 1, resize_moon_dim) |
| 375 | ||
| 376 | 18694x | pixel = resized_moon_luminance_array[v_i, u_i, 1:3] |
| 377 | 18694x | full_disk_integral = full_disk_integral + |
| 378 | 18694x | sum(pixel) * dphi * dtheta * cos_theta[j] |
| 379 | 18694x | if (sample_dir_vec[2] < 0) { |
| 380 | 2436x | next |
| 381 | } | |
| 382 | 16258x | disk_mask[j, i] = TRUE |
| 383 | 16258x | moon_array[j, i, 1:3] = pixel |
| 384 | } | |
| 385 | } | |
| 386 | ||
| 387 | 17x | disk_scale = if (is.finite(full_disk_integral) && full_disk_integral > 0) { |
| 388 | 17x | moon_irradiance / full_disk_integral |
| 389 | } else { | |
| 390 | ! | 0 |
| 391 | } | |
| 392 | 17x | for (channel in 1:3) { |
| 393 | 51x | moon_array[,, channel][disk_mask] = moon_array[,, channel][disk_mask] * |
| 394 | 51x | disk_scale |
| 395 | } | |
| 396 | 17x | moon_band = attr(moon_array, "L_band") |
| 397 | 17x | if (is.null(moon_band)) { |
| 398 | 14x | moon_band = moon_array[,, 1] + moon_array[,, 2] + moon_array[,, 3] |
| 399 | 3x | } else if (any(disk_mask)) { |
| 400 | 3x | moon_band[disk_mask] = moon_array[,, 1][disk_mask] + |
| 401 | 3x | moon_array[,, 2][disk_mask] + |
| 402 | 3x | moon_array[,, 3][disk_mask] |
| 403 | } | |
| 404 | 17x | moon_array = as_sky_image(moon_array) |
| 405 | 17x | attr(moon_array, "L_band") = moon_band |
| 406 | 17x | if (!is.na(filename)) { |
| 407 | ! | warn_precision_loss(filename) |
| 408 | ! | write_sky_image(moon_array, filename, clamp = FALSE) |
| 409 | ! | return(invisible(moon_array)) |
| 410 | } else { | |
| 411 | 17x | return(moon_array) |
| 412 | } | |
| 413 | } |
| 1 | #' Convert B-V color index to blackbody temperature | |
| 2 | #' | |
| 3 | #' @param bv Numeric vector of B-V values. | |
| 4 | #' @return Numeric vector of temperatures in Kelvin. | |
| 5 | #' @keywords internal | |
| 6 | bv_to_temperature_K = function(bv) { | |
| 7 | 1x | bv = pmax(pmin(bv, 2.0), -0.4) |
| 8 | 1x | temp = 4600 * (1 / (0.92 * bv + 1.7) + 1 / (0.92 * bv + 0.62)) |
| 9 | 1x | temp[!is.finite(temp)] = NA_real_ |
| 10 | 1x | pmax(pmin(temp, 40000), 1000) |
| 11 | } | |
| 12 | ||
| 13 | #' Convert V magnitude to illuminance in lux | |
| 14 | #' | |
| 15 | #' @param mV Numeric vector of V magnitudes. | |
| 16 | #' @param zero_point Optional scalar multiplier for catalog scaling. | |
| 17 | #' @return Numeric vector of photometric illuminance in lux. | |
| 18 | #' @keywords internal | |
| 19 | vmag_to_ev_lux = function(mV, zero_point = 1) { | |
| 20 | 1x | zero_point * 10^((-14.18 - mV) / 2.5) |
| 21 | } | |
| 22 | ||
| 23 | #' Compute luminous efficacy for a blackbody SPD | |
| 24 | #' | |
| 25 | #' @param temperature_K Numeric vector of blackbody temperatures in Kelvin. | |
| 26 | #' @param wavelengths_nm Optional wavelength grid in nm. | |
| 27 | #' @param V_lambda Optional photopic V(lambda) samples matching the grid. | |
| 28 | #' @return Numeric vector of K_eff values in lm/W. | |
| 29 | #' @keywords internal | |
| 30 | luminous_efficacy_blackbody = function( | |
| 31 | temperature_K, | |
| 32 | wavelengths_nm = NULL, | |
| 33 | V_lambda = NULL | |
| 34 | ) { | |
| 35 | 2x | if (is.null(wavelengths_nm) || is.null(V_lambda)) { |
| 36 | 1x | cie = cie_1931_2deg() |
| 37 | 1x | wavelengths_nm = cie$lambda_nm |
| 38 | 1x | V_lambda = cie$y_bar |
| 39 | } | |
| 40 | 2x | if (length(wavelengths_nm) != length(V_lambda)) { |
| 41 | ! | stop("wavelengths_nm and V_lambda must have the same length.") |
| 42 | } | |
| 43 | 2x | w = trapezoid_weights(wavelengths_nm) |
| 44 | 2x | c2 = 1.4387769e-2 |
| 45 | 2x | blackbody_spd = function(T) { |
| 46 | 2x | lambda_m = wavelengths_nm * 1e-9 |
| 47 | 2x | denom = exp(c2 / (lambda_m * T)) - 1 |
| 48 | 2x | spd = 1 / (lambda_m^5 * denom) |
| 49 | 2x | spd[!is.finite(spd)] = 0 |
| 50 | 2x | spd |
| 51 | } | |
| 52 | 2x | vapply( |
| 53 | 2x | temperature_K, |
| 54 | 2x | function(T) { |
| 55 | 2x | if (!is.finite(T) || T <= 0) { |
| 56 | ! | return(NA_real_) |
| 57 | } | |
| 58 | 2x | spd = blackbody_spd(T) |
| 59 | 2x | num = sum(spd * V_lambda * w) |
| 60 | 2x | den = sum(spd * w) |
| 61 | 2x | if (!is.finite(num) || !is.finite(den) || den <= 0) { |
| 62 | ! | return(NA_real_) |
| 63 | } | |
| 64 | 2x | 683 * num / den |
| 65 | }, | |
| 66 | 2x | numeric(1) |
| 67 | ) | |
| 68 | } | |
| 69 | ||
| 70 | #' Compute radiometric star amplitude and RGB unit vector | |
| 71 | #' | |
| 72 | #' @param mV Numeric vector of V magnitudes. | |
| 73 | #' @param bv Numeric vector of B-V values. | |
| 74 | #' @param wavelengths_nm Optional wavelength grid in nm. | |
| 75 | #' @param V_lambda Optional photopic V(lambda) samples matching the grid. | |
| 76 | #' @return List with E_v (lux), E_e (W/m^2), K_eff (lm/W), and rgb_unit. | |
| 77 | #' @keywords internal | |
| 78 | star_radiometric_amplitude = function( | |
| 79 | mV, | |
| 80 | bv, | |
| 81 | wavelengths_nm = NULL, | |
| 82 | V_lambda = NULL | |
| 83 | ) { | |
| 84 | 1x | if (length(mV) != length(bv)) { |
| 85 | ! | stop("mV and bv must have the same length.") |
| 86 | } | |
| 87 | 1x | cie = cie_1931_2deg() |
| 88 | 1x | if (is.null(wavelengths_nm)) { |
| 89 | 1x | wavelengths_nm = cie$lambda_nm |
| 90 | } | |
| 91 | 1x | if (is.null(V_lambda)) { |
| 92 | 1x | V_lambda = cie$y_bar |
| 93 | } | |
| 94 | 1x | if (length(wavelengths_nm) != length(V_lambda)) { |
| 95 | ! | stop("wavelengths_nm and V_lambda must have the same length.") |
| 96 | } | |
| 97 | 1x | w = trapezoid_weights(wavelengths_nm) |
| 98 | 1x | c2 = 1.4387769e-2 |
| 99 | 1x | blackbody_spd = function(T) { |
| 100 | 1x | lambda_m = wavelengths_nm * 1e-9 |
| 101 | 1x | denom = exp(c2 / (lambda_m * T)) - 1 |
| 102 | 1x | spd = 1 / (lambda_m^5 * denom) |
| 103 | 1x | spd[!is.finite(spd)] = 0 |
| 104 | 1x | spd |
| 105 | } | |
| 106 | 1x | out = mapply( |
| 107 | 1x | function(m, b) { |
| 108 | 1x | T = bv_to_temperature_K(b) |
| 109 | 1x | E_v = vmag_to_ev_lux(m) |
| 110 | 1x | K_eff = luminous_efficacy_blackbody(T, wavelengths_nm, V_lambda) |
| 111 | 1x | E_e = E_v / K_eff |
| 112 | 1x | spd = blackbody_spd(T) |
| 113 | 1x | X = sum(spd * cie$x_bar * w) |
| 114 | 1x | Y = sum(spd * cie$y_bar * w) |
| 115 | 1x | Z = sum(spd * cie$z_bar * w) |
| 116 | 1x | rgb = xyz_to_srgb(c(X, Y, Z)) |
| 117 | 1x | rgb[!is.finite(rgb)] = 0 |
| 118 | 1x | rgb = pmax(rgb, 0) |
| 119 | 1x | sum_rgb = sum(rgb) |
| 120 | 1x | if (!is.finite(sum_rgb) || sum_rgb <= 0) { |
| 121 | ! | rgb = c(1, 1, 1) / 3 |
| 122 | } else { | |
| 123 | 1x | rgb = rgb / sum_rgb |
| 124 | } | |
| 125 | 1x | list(E_v = E_v, E_e = E_e, K_eff = K_eff, rgb_unit = rgb) |
| 126 | }, | |
| 127 | 1x | mV, |
| 128 | 1x | bv, |
| 129 | 1x | SIMPLIFY = FALSE |
| 130 | ) | |
| 131 | 1x | E_v = vapply(out, function(x) x$E_v, numeric(1)) |
| 132 | 1x | E_e = vapply(out, function(x) x$E_e, numeric(1)) |
| 133 | 1x | K_eff = vapply(out, function(x) x$K_eff, numeric(1)) |
| 134 | 1x | rgb_unit = do.call(rbind, lapply(out, function(x) x$rgb_unit)) |
| 135 | 1x | list(E_v = E_v, E_e = E_e, K_eff = K_eff, rgb_unit = rgb_unit) |
| 136 | } |
| 1 | normalize_render_mode = function(render_mode) { | |
| 2 | 28x | if (is.logical(render_mode)) { |
| 3 | ! | stopifnot(length(render_mode) == 1) |
| 4 | ! | return(if (render_mode) "all" else "atmosphere") |
| 5 | } | |
| 6 | 28x | render_mode = tolower(as.character(render_mode)) |
| 7 | 28x | match.arg(render_mode, c("all", "atmosphere", "sun")) |
| 8 | } | |
| 9 | ||
| 10 | #' Generate a Hosek-Wilkie sky dome array | |
| 11 | #' | |
| 12 | #' @description Evaluate either the Hosek-Wilkie or Prague analytic sky models | |
| 13 | #' and return a high-dynamic-range image array for the given solar | |
| 14 | #' configuration. An image file is written only when `filename` is supplied. | |
| 15 | #' | |
| 16 | #' @param filename Default `NA`. Path to an image file to write. If not given, the array is returned instead. | |
| 17 | #' @param albedo Default `0.1`. 0.0-1.0 ground albedo. Grass has an albedo of about 0.09, while a landscape covered in | |
| 18 | #' snow will have an albedo of 1.0. | |
| 19 | #' @param turbidity Default `3`. 1.7-10 atmospheric turbidity. Only valid for Hosek model. | |
| 20 | #' @param elevation Default `10`. Solar elevation above the horizon (degrees). | |
| 21 | #' @param azimuth Default `90`, sun directly east. Solar azimuth (degrees). The left edge of the image faces north and the middle faces south. | |
| 22 | #' @param altitude Default `0`. Altitude of the viewer in meters. Valid range: 0 to 15000. Only valid for the Prague model. | |
| 23 | #' @param resolution Default `2048`. Height of the image. Width is twice this number. | |
| 24 | #' @param number_cores Default `1`. Number of threads to use in computation. | |
| 25 | #' @param hosek Default `TRUE`. Set to `FALSE` to enable the Prague 2021-22 spectral sky model. | |
| 26 | #' @param wide_spectrum Default `FALSE`. Use the 55-channel Prague coefficients (sea level only). | |
| 27 | #' @param visibility Default `50`. Meteorological range in kilometres for Prague model. | |
| 28 | #' @param verbose Default `FALSE`. Whether to print progress bars/diagnostic info. | |
| 29 | #' @param render_mode Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`. | |
| 30 | #' Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only. | |
| 31 | #' @param below_horizon Default `TRUE`. Whether to sample atmospheric scattering below the horizon, which is non-zero when altitude > 0. | |
| 32 | #' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB | |
| 33 | #' tint correction. This correction is only applied when `hosek = FALSE`. Use | |
| 34 | #' `FALSE` for raw Prague RGB output. | |
| 35 | #' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB | |
| 36 | #' tint correction. Use `0` for no correction and `1` for the calibrated | |
| 37 | #' correction. | |
| 38 | #' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB | |
| 39 | #' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated | |
| 40 | #' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`. | |
| 41 | #' @param exr_adopted_white Default `"D60"`. Adopted neutral white to write to | |
| 42 | #' EXR metadata for generated sky maps. Currently supports `"D60"`, `"D65"`, | |
| 43 | #' or a numeric XYZ white with Y = 1. This tags the EXR `adoptedNeutral` | |
| 44 | #' metadata and does not change pixel values. | |
| 45 | #' @param exr_metadata Default `TRUE`. Whether to attach skymodelr EXR metadata | |
| 46 | #' before writing EXR output. Metadata includes sRGB/Rec.709 chromaticities and | |
| 47 | #' the selected adopted neutral white. | |
| 48 | #' | |
| 49 | #' @details | |
| 50 | #' For Prague RGB output, `prague_rgb_correction = TRUE` applies a fixed linear | |
| 51 | #' RGB gain to reduce the small magenta / negative-green tint observed in the | |
| 52 | #' RGB projection of Prague sky maps. Set `prague_rgb_correction = FALSE` to | |
| 53 | #' recover raw Prague RGB output. The correction is not a white balance and is | |
| 54 | #' not applied to wavelength-specific spectral radiance. | |
| 55 | #' | |
| 56 | #' EXR metadata: Generated sky maps are linear RGB. When `exr_metadata = TRUE`, | |
| 57 | #' skymodelr tags the image with sRGB/Rec.709 chromaticities and an EXR | |
| 58 | #' `adoptedNeutral` white. The default adopted neutral is D60. This metadata | |
| 59 | #' does not convert pixel values; it informs downstream readers how to treat the | |
| 60 | #' scene neutral. Use `exr_adopted_white = "D65"` for D65 adopted neutral, or | |
| 61 | #' `exr_metadata = FALSE` to omit skymodelr EXR metadata. The RGB encoding | |
| 62 | #' remains linear sRGB / Rec.709 even when the adopted neutral is D60. | |
| 63 | #' | |
| 64 | #' @return Either the image array, or the array is invisibly returned if a file | |
| 65 | #' is written. The array has dimensions `(resolution, 2 * resolution, 4)`. | |
| 66 | #' @note Writing to non-EXR formats will introduce precision loss because HDR | |
| 67 | #' data are quantised to the destination format, and low dynamic range outputs like PNG | |
| 68 | #' and JPEG files will not represent the true luminosity values encoded in the array. | |
| 69 | #' @export | |
| 70 | #' @examples | |
| 71 | #' sky = generate_sky( | |
| 72 | #' resolution = 8, | |
| 73 | #' elevation = 30, | |
| 74 | #' azimuth = 135, | |
| 75 | #' render_mode = "atmosphere" | |
| 76 | #' ) | |
| 77 | #' dim(sky) | |
| 78 | #' | |
| 79 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 80 | #' # Hosek model (default): clear morning, Sun SE, with solar disk | |
| 81 | #' generate_sky( | |
| 82 | #' resolution = 400, | |
| 83 | #' elevation = 15, | |
| 84 | #' azimuth = 135, | |
| 85 | #' turbidity = 3, | |
| 86 | #' render_mode = "all" | |
| 87 | #' ) |> | |
| 88 | #' rayimage::plot_image() | |
| 89 | #' | |
| 90 | #' # Same view but hazier and without the solar disk | |
| 91 | #' generate_sky( | |
| 92 | #' resolution = 400, | |
| 93 | #' elevation = 15, | |
| 94 | #' azimuth = 135, | |
| 95 | #' turbidity = 6, | |
| 96 | #' render_mode = "atmosphere" | |
| 97 | #' ) |> | |
| 98 | #' rayimage::plot_image() | |
| 99 | #' | |
| 100 | #' # Prague model (requires downloaded coefficients) | |
| 101 | #' generate_sky( | |
| 102 | #' resolution = 400, | |
| 103 | #' hosek = FALSE, | |
| 104 | #' altitude = 0, | |
| 105 | #' visibility = 80, | |
| 106 | #' albedo = 0.2, | |
| 107 | #' elevation = 5, | |
| 108 | #' azimuth = 220, | |
| 109 | #' number_cores = 2 | |
| 110 | #' ) |> | |
| 111 | #' rayimage::plot_image() | |
| 112 | #' | |
| 113 | #' generate_sky( | |
| 114 | #' "raw_prague.exr", | |
| 115 | #' elevation = 60, | |
| 116 | #' azimuth = 315, | |
| 117 | #' hosek = FALSE, | |
| 118 | #' prague_rgb_correction = FALSE | |
| 119 | #' ) | |
| 120 | generate_sky = function( | |
| 121 | filename = NA, | |
| 122 | albedo = 0.1, | |
| 123 | turbidity = 3, | |
| 124 | elevation = 10, | |
| 125 | azimuth = 90, | |
| 126 | altitude = 0, | |
| 127 | resolution = 2048, | |
| 128 | number_cores = 1, | |
| 129 | hosek = TRUE, | |
| 130 | wide_spectrum = FALSE, | |
| 131 | visibility = 50, | |
| 132 | verbose = FALSE, | |
| 133 | render_mode = "all", | |
| 134 | below_horizon = TRUE, | |
| 135 | prague_rgb_correction = TRUE, | |
| 136 | prague_rgb_correction_strength = 1, | |
| 137 | prague_rgb_correction_gain = "auto", | |
| 138 | exr_adopted_white = "D60", | |
| 139 | exr_metadata = TRUE | |
| 140 | ) { | |
| 141 | 12x | render_mode = normalize_render_mode(render_mode) |
| 142 | 12x | coef_file = "" |
| 143 | 12x | if (!hosek) { |
| 144 | ! | stopifnot(altitude >= 0 && altitude <= 15000) |
| 145 | ! | model = "prague" |
| 146 | ! | coef_file = resolve_prague_coef_file( |
| 147 | ! | altitude = altitude, |
| 148 | ! | wide_spectrum = wide_spectrum |
| 149 | ) | |
| 150 | } else { | |
| 151 | 12x | model = "hosek" |
| 152 | } | |
| 153 | #If sun below valid region, write black image | |
| 154 | 12x | if (model == "hosek") { |
| 155 | 12x | if (elevation < 0.0) { |
| 156 | 2x | if (verbose) { |
| 157 | ! | message( |
| 158 | ! | "Drawing black image as Hosek model does not produce valid output for elevation < 0." |
| 159 | ) | |
| 160 | } | |
| 161 | 2x | black_sky = array(0, dim = c(resolution, resolution * 2, 4)) |
| 162 | 2x | black_sky[,, 4] = 1 |
| 163 | 2x | black_sky = as_sky_image(black_sky) |
| 164 | 2x | black_sky = tag_generated_sky_exr_metadata( |
| 165 | 2x | black_sky, |
| 166 | 2x | hosek = hosek, |
| 167 | 2x | exr_metadata = exr_metadata, |
| 168 | 2x | exr_adopted_white = exr_adopted_white |
| 169 | ) | |
| 170 | 2x | if (!is.na(filename)) { |
| 171 | 1x | warn_precision_loss(filename) |
| 172 | 1x | write_sky_image(black_sky, filename) |
| 173 | 1x | return(invisible(black_sky)) |
| 174 | } else { | |
| 175 | 1x | return(black_sky) |
| 176 | } | |
| 177 | } | |
| 178 | } else { | |
| 179 | ! | if (elevation < -4.2) { |
| 180 | ! | if (verbose) { |
| 181 | ! | message( |
| 182 | ! | "Drawing black image as Prague model does not produce valid output for elevation < -4.2." |
| 183 | ) | |
| 184 | } | |
| 185 | ! | black_sky = array(0, dim = c(resolution, resolution * 2, 4)) |
| 186 | ! | black_sky[,, 4] = 1 |
| 187 | ! | black_sky = as_sky_image(black_sky) |
| 188 | ! | black_sky = tag_generated_sky_exr_metadata( |
| 189 | ! | black_sky, |
| 190 | ! | hosek = hosek, |
| 191 | ! | exr_metadata = exr_metadata, |
| 192 | ! | exr_adopted_white = exr_adopted_white |
| 193 | ) | |
| 194 | ! | if (!is.na(filename)) { |
| 195 | ! | warn_precision_loss(filename) |
| 196 | ! | write_sky_image(black_sky, filename) |
| 197 | ! | return(invisible(black_sky)) |
| 198 | } else { | |
| 199 | ! | return(black_sky) |
| 200 | } | |
| 201 | } | |
| 202 | } | |
| 203 | ||
| 204 | 10x | lambda_values = seq(360, 720, by = 40) |
| 205 | ||
| 206 | 10x | generated_rgb = makesky_rcpp( |
| 207 | 10x | albedo = albedo, |
| 208 | 10x | turbidity = turbidity, |
| 209 | 10x | elevation = elevation, |
| 210 | 10x | azimuth_deg = azimuth, |
| 211 | 10x | resolution = resolution, |
| 212 | 10x | number_cores = number_cores, |
| 213 | 10x | model = model, |
| 214 | 10x | prg_dataset = coef_file, |
| 215 | 10x | altitude = altitude, |
| 216 | 10x | visibility = visibility, |
| 217 | 10x | render_mode = render_mode, |
| 218 | 10x | lambda_nm = lambda_values, |
| 219 | 10x | below_horizon = below_horizon |
| 220 | ) | |
| 221 | 10x | band = attr(generated_rgb, "L_band") |
| 222 | ||
| 223 | 10x | applied_prague_rgb_gain = NULL |
| 224 | ||
| 225 | 10x | if (!hosek) { |
| 226 | ! | prague_rgb_correction = normalize_prague_rgb_correction( |
| 227 | ! | prague_rgb_correction |
| 228 | ) | |
| 229 | } | |
| 230 | ||
| 231 | 10x | if (!hosek && prague_rgb_correction == "constant") { |
| 232 | ! | applied_prague_rgb_gain = prepare_prague_rgb_gain( |
| 233 | ! | gain = prague_rgb_correction_gain, |
| 234 | ! | strength = prague_rgb_correction_strength |
| 235 | ) | |
| 236 | ||
| 237 | ! | generated_rgb = apply_prague_rgb_gain( |
| 238 | ! | generated_rgb, |
| 239 | ! | gain = applied_prague_rgb_gain |
| 240 | ) | |
| 241 | } | |
| 242 | ||
| 243 | 10x | generated_sky = array(0, dim = c(resolution, resolution * 2, 4)) |
| 244 | 10x | generated_sky[,, 1:3] = generated_rgb |
| 245 | 10x | generated_sky[,, 4] = 1 |
| 246 | 10x | if (!is.null(band)) { |
| 247 | 10x | attr(generated_sky, "L_band") = band |
| 248 | } | |
| 249 | 10x | generated_sky = as_sky_image(generated_sky) |
| 250 | 10x | if (!is.null(applied_prague_rgb_gain)) { |
| 251 | ! | attr(generated_sky, "prague_rgb_correction") = "constant" |
| 252 | ! | attr(generated_sky, "prague_rgb_correction_gain") = applied_prague_rgb_gain |
| 253 | ! | attr(generated_sky, "prague_rgb_correction_strength") = |
| 254 | ! | prague_rgb_correction_strength |
| 255 | } | |
| 256 | 10x | generated_sky = tag_generated_sky_exr_metadata( |
| 257 | 10x | generated_sky, |
| 258 | 10x | hosek = hosek, |
| 259 | 10x | exr_metadata = exr_metadata, |
| 260 | 10x | exr_adopted_white = exr_adopted_white |
| 261 | ) | |
| 262 | ||
| 263 | 10x | if (!is.na(filename)) { |
| 264 | 1x | warn_precision_loss(filename) |
| 265 | 1x | write_sky_image(generated_sky, filename) |
| 266 | 1x | return(invisible(generated_sky)) |
| 267 | } else { | |
| 268 | 9x | return(generated_sky) |
| 269 | } | |
| 270 | } | |
| 271 | ||
| 272 | #' Generate a location and time-specific sky dome (optionally with stars) | |
| 273 | #' | |
| 274 | #' @description Convenience wrapper around [generate_sky()] that: | |
| 275 | #' 1. Computes the Sun's apparent position for `datetime`, `lat`, and `lon` | |
| 276 | #' (via Swiss Ephemeris / **swephR**). | |
| 277 | #' 2. Renders the corresponding sky model. | |
| 278 | #' 3. Optionally overlays a star field using [generate_stars()] or moon with [generate_moon_latlong()]. | |
| 279 | #' | |
| 280 | #' @param datetime POSIX-compatible date-time. | |
| 281 | #' @param lat Observer latitude (degrees N). | |
| 282 | #' @param lon Observer longitude (degrees E; west < 0). | |
| 283 | #' @param filename Default `NA`. Path to the `.exr` file to write. | |
| 284 | #' @param albedo Default `0.5`. Ground albedo, range 0 to 1. | |
| 285 | #' @param turbidity Default `3`. Atmospheric turbidity, range | |
| 286 | #' 1.7 to 10 (*Hosek only*). | |
| 287 | #' @param altitude Default `0`. Observer altitude (m), range | |
| 288 | #' 0 to 15000 (*Prague only*). | |
| 289 | #' @param resolution Default `2048`. Image height in pixels (width = 2 * height). | |
| 290 | #' @param number_cores Default `1`. CPU threads to use. | |
| 291 | #' @param hosek Default `TRUE`. `FALSE` selects the Prague model. | |
| 292 | #' @param wide_spectrum Default `FALSE`. 55-channel Prague coefficients (altitude = 0m only). | |
| 293 | #' @param visibility Default `50`. Meteorological range (km); *Prague only*. | |
| 294 | #' @param stars Default `FALSE`. If `TRUE`, composite a star field | |
| 295 | #' using [generate_stars()]. Automatically falls back to a pure star render | |
| 296 | #' when the black-sky condition is met (see *Details*). | |
| 297 | #' @param star_width Default `1`. Passed to [generate_stars()] to control stellar point-spread size. | |
| 298 | #' @param planets Default `FALSE`. If `TRUE`, composite bright planets via [generate_planets()]. | |
| 299 | #' @param moon Default `FALSE`. If `TRUE`, overlay a moon render from [generate_moon_latlong()]. | |
| 300 | #' @param moon_atmosphere Default `FALSE`. If `TRUE`, this generates atmospheric scattering from light from the moon. | |
| 301 | #' @param moon_hosek Default `TRUE`. Whether to use the faster (but less accurate) Hosek model for atmospheric scattering from the moon. Note | |
| 302 | #' that the light scattered from the moon is much less intense than the sun, and thus small inaccuracies are much less likely to be noticable. | |
| 303 | #' @param render_mode Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`. | |
| 304 | #' Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only. | |
| 305 | #' @param below_horizon Default `TRUE`. Whether to sample atmospheric scattering below the horizon, which is non-zero when altitude > 0. | |
| 306 | #' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB | |
| 307 | #' tint correction. This correction is only applied when `hosek = FALSE`. Use | |
| 308 | #' `FALSE` for raw Prague RGB output. | |
| 309 | #' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB | |
| 310 | #' tint correction. Use `0` for no correction and `1` for the calibrated | |
| 311 | #' correction. | |
| 312 | #' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB | |
| 313 | #' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated | |
| 314 | #' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`. | |
| 315 | #' @param exr_adopted_white Default `"D60"`. Adopted neutral white to write to | |
| 316 | #' EXR metadata for generated sky maps. Currently supports `"D60"`, `"D65"`, | |
| 317 | #' or a numeric XYZ white with Y = 1. This tags the EXR `adoptedNeutral` | |
| 318 | #' metadata and does not change pixel values. | |
| 319 | #' @param exr_metadata Default `TRUE`. Whether to attach skymodelr EXR metadata | |
| 320 | #' before writing EXR output. Metadata includes sRGB/Rec.709 chromaticities and | |
| 321 | #' the selected adopted neutral white. | |
| 322 | #' @param stars_exposure Default `0`. Increases star exposure by `2^exposure`. Non-physical, this just controls adjustments for artistic effect. | |
| 323 | #' @param verbose Default `FALSE`. Whether to print progress bars/diagnostic info. | |
| 324 | #' @param ... Additional **named** arguments forwarded to [generate_stars()], and when enabled, [generate_planets()] and [generate_moon_latlong()]. | |
| 325 | #' Unmatched names are ignored. | |
| 326 | #' | |
| 327 | #' @details | |
| 328 | #' *Solar angles* - altitude (degrees above the horizon) and azimuth (degrees clockwise from | |
| 329 | #' east, so 90 degrees = south) - are derived internally; you never have to supply | |
| 330 | #' them directly. | |
| 331 | #' | |
| 332 | #' *Black-sky rule* - With the Prague model the sky radiance is defined only | |
| 333 | #' down to -4.2 degrees, and with the Hosek model it is defined only about 0 degrees. | |
| 334 | #' Below that the function skips the sky render and writes **only stars** when `stars = TRUE`. | |
| 335 | #' | |
| 336 | #' @return Either the raw data, or the data is invisibly returned if filename is given. The EXR is written to `filename`. | |
| 337 | #' @export | |
| 338 | #' | |
| 339 | #' @examples | |
| 340 | #' sky = generate_sky_latlong( | |
| 341 | #' datetime = as.POSIXct("2025-03-21 12:00:00", tz = "America/New_York"), | |
| 342 | #' lat = 38.9072, | |
| 343 | #' lon = -77.0369, | |
| 344 | #' resolution = 8 | |
| 345 | #' ) | |
| 346 | #' dim(sky) | |
| 347 | #' | |
| 348 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 349 | #' # Morning sunrise on spring solstice over Washington, DC with Prague model | |
| 350 | #' generate_sky_latlong( | |
| 351 | #' datetime = as.POSIXct("2025-03-21 06:15:00", tz = "America/New_York"), | |
| 352 | #' lat = 38.9072, | |
| 353 | #' lon = -77.0369, | |
| 354 | #' number_cores = 2, | |
| 355 | #' hosek = FALSE | |
| 356 | #' ) |> | |
| 357 | #' rayimage::plot_image() | |
| 358 | #' | |
| 359 | #' generate_sky_latlong( | |
| 360 | #' datetime = as.POSIXct("2025-03-21 12:00:00", tz = "America/New_York"), | |
| 361 | #' lat = 38.9072, | |
| 362 | #' lon = -77.0369, | |
| 363 | #' number_cores = 2 | |
| 364 | #' ) |> | |
| 365 | #' rayimage::plot_image() | |
| 366 | #' | |
| 367 | #' generate_sky_latlong( | |
| 368 | #' datetime = as.POSIXct("2025-03-21 18:00:00", tz = "America/New_York"), | |
| 369 | #' lat = 38.9072, | |
| 370 | #' lon = -77.0369, | |
| 371 | #' number_cores = 2 | |
| 372 | #' ) |> | |
| 373 | #' rayimage::plot_image() | |
| 374 | #' | |
| 375 | #' generate_sky_latlong( | |
| 376 | #' datetime = as.POSIXct("2025-03-21 18:30:00", tz = "America/New_York"), | |
| 377 | #' lat = 38.9072, | |
| 378 | #' lon = -77.0369, | |
| 379 | #' number_cores = 2, | |
| 380 | #' hosek = FALSE, | |
| 381 | #' verbose = TRUE | |
| 382 | #' ) |> | |
| 383 | #' rayimage::render_exposure(exposure = 2) |> | |
| 384 | #' rayimage::plot_image() | |
| 385 | generate_sky_latlong = function( | |
| 386 | datetime, | |
| 387 | lat, | |
| 388 | lon, | |
| 389 | filename = NA, | |
| 390 | albedo = 0.5, | |
| 391 | turbidity = 3, | |
| 392 | altitude = 0, | |
| 393 | resolution = 2048, | |
| 394 | number_cores = 1, | |
| 395 | hosek = TRUE, | |
| 396 | wide_spectrum = FALSE, | |
| 397 | visibility = 50, | |
| 398 | stars = FALSE, | |
| 399 | star_width = 1.0, | |
| 400 | planets = FALSE, | |
| 401 | moon = FALSE, | |
| 402 | moon_atmosphere = FALSE, | |
| 403 | moon_hosek = TRUE, | |
| 404 | render_mode = "all", | |
| 405 | below_horizon = TRUE, | |
| 406 | prague_rgb_correction = TRUE, | |
| 407 | prague_rgb_correction_strength = 1, | |
| 408 | prague_rgb_correction_gain = "auto", | |
| 409 | exr_adopted_white = "D60", | |
| 410 | exr_metadata = TRUE, | |
| 411 | verbose = FALSE, | |
| 412 | stars_exposure = 0, | |
| 413 | ... | |
| 414 | ) { | |
| 415 | 6x | render_mode = normalize_render_mode(render_mode) |
| 416 | 6x | extra_args = list(...) |
| 417 | 6x | filter_extra_args = function(fun, args) { |
| 418 | 18x | arg_names = names(args) |
| 419 | 18x | if (length(arg_names) == 0) { |
| 420 | 12x | return(list()) |
| 421 | } | |
| 422 | 6x | valid = names(formals(fun)) |
| 423 | 6x | keep = !is.null(arg_names) & nzchar(arg_names) & (arg_names %in% valid) |
| 424 | 6x | args[keep] |
| 425 | } | |
| 426 | 6x | merge_call_args = function(base_args, extra_args) { |
| 427 | 2x | if (length(extra_args) == 0) { |
| 428 | ! | return(base_args) |
| 429 | } | |
| 430 | 2x | extra_args = extra_args[!(names(extra_args) %in% names(base_args))] |
| 431 | 2x | c(base_args, extra_args) |
| 432 | } | |
| 433 | 6x | moon_extra = filter_extra_args(generate_moon_latlong, extra_args) |
| 434 | 6x | stars_extra = filter_extra_args(generate_stars, extra_args) |
| 435 | 6x | planets_extra = filter_extra_args(generate_planets, extra_args) |
| 436 | ||
| 437 | 6x | sunmoon_data = swe_dirs_topo_moon_sun( |
| 438 | 6x | datetime = datetime, |
| 439 | 6x | lat = lat, |
| 440 | 6x | lon = lon, |
| 441 | 6x | elev_m = altitude |
| 442 | ) | |
| 443 | 6x | sun_dir = sunmoon_data$sun_dir_topo |
| 444 | 6x | elevation = asin(sun_dir[3]) * 180 / pi |
| 445 | 6x | azimuth = (180 + atan2(sun_dir[1], sun_dir[2]) * 180 / pi + 360) %% 360 |
| 446 | ||
| 447 | 6x | if (verbose) { |
| 448 | ! | message(sprintf( |
| 449 | ! | "Sun: %0.1f elevation, %0.1f azimuth", |
| 450 | ! | elevation, |
| 451 | ! | azimuth |
| 452 | )) | |
| 453 | } | |
| 454 | # Just add up all three | |
| 455 | 6x | sky_array = generate_sky( |
| 456 | 6x | albedo = albedo, |
| 457 | 6x | turbidity = turbidity, |
| 458 | 6x | altitude = altitude, |
| 459 | 6x | elevation = elevation, |
| 460 | 6x | azimuth = azimuth, |
| 461 | 6x | resolution = resolution, |
| 462 | 6x | number_cores = number_cores, |
| 463 | 6x | hosek = hosek, |
| 464 | 6x | wide_spectrum = wide_spectrum, |
| 465 | 6x | visibility = visibility, |
| 466 | 6x | verbose = verbose, |
| 467 | 6x | render_mode = render_mode, |
| 468 | 6x | below_horizon = below_horizon, |
| 469 | 6x | prague_rgb_correction = prague_rgb_correction, |
| 470 | 6x | prague_rgb_correction_strength = prague_rgb_correction_strength, |
| 471 | 6x | prague_rgb_correction_gain = prague_rgb_correction_gain, |
| 472 | 6x | exr_adopted_white = exr_adopted_white, |
| 473 | 6x | exr_metadata = exr_metadata |
| 474 | ) | |
| 475 | ||
| 476 | 6x | if (moon) { |
| 477 | 2x | moon_call_args = merge_call_args( |
| 478 | 2x | base_args = list( |
| 479 | 2x | filename = filename, |
| 480 | 2x | datetime = datetime, |
| 481 | 2x | lat = lat, |
| 482 | 2x | lon = lon, |
| 483 | 2x | albedo = albedo, |
| 484 | 2x | turbidity = turbidity, |
| 485 | 2x | altitude = altitude, |
| 486 | 2x | resolution = resolution, |
| 487 | 2x | number_cores = number_cores, |
| 488 | 2x | hosek = moon_hosek, |
| 489 | 2x | moon_atmosphere = moon_atmosphere, |
| 490 | 2x | wide_spectrum = wide_spectrum, |
| 491 | 2x | visibility = visibility, |
| 492 | 2x | verbose = verbose |
| 493 | ), | |
| 494 | 2x | extra_args = moon_extra |
| 495 | ) | |
| 496 | 2x | moon_array = do.call(generate_moon_latlong, moon_call_args) |
| 497 | 2x | sky_band = attr(sky_array, "L_band") |
| 498 | 2x | moon_band = attr(moon_array, "L_band") |
| 499 | 2x | sky_array = sky_array + moon_array |
| 500 | 2x | if (!is.null(sky_band) && !is.null(moon_band)) { |
| 501 | 2x | attr(sky_array, "L_band") = sky_band + moon_band |
| 502 | } | |
| 503 | } | |
| 504 | 6x | if (stars) { |
| 505 | ! | stars_call_args = merge_call_args( |
| 506 | ! | base_args = list( |
| 507 | ! | resolution = resolution, |
| 508 | ! | lon = lon, |
| 509 | ! | lat = lat, |
| 510 | ! | datetime = as.POSIXct(datetime), |
| 511 | ! | turbidity = turbidity, |
| 512 | ! | altitude = altitude, |
| 513 | ! | number_cores = number_cores, |
| 514 | ! | star_width = star_width |
| 515 | ), | |
| 516 | ! | extra_args = stars_extra |
| 517 | ) | |
| 518 | ! | stars_array = do.call(generate_stars, stars_call_args) * |
| 519 | ! | (2^stars_exposure) |
| 520 | ! | sky_array = sky_array + stars_array |
| 521 | } | |
| 522 | 6x | if (planets) { |
| 523 | ! | planets_call_args = merge_call_args( |
| 524 | ! | base_args = list( |
| 525 | ! | resolution = resolution, |
| 526 | ! | datetime = as.POSIXct(datetime), |
| 527 | ! | lon = lon, |
| 528 | ! | lat = lat, |
| 529 | ! | turbidity = turbidity, |
| 530 | ! | altitude = altitude, |
| 531 | ! | number_cores = number_cores, |
| 532 | ! | planet_width = star_width, |
| 533 | ! | verbose = verbose |
| 534 | ), | |
| 535 | ! | extra_args = planets_extra |
| 536 | ) | |
| 537 | ! | planets_array = do.call(generate_planets, planets_call_args) |
| 538 | ! | sky_array = sky_array + planets_array |
| 539 | } | |
| 540 | 6x | sky_array[,, 4] = 1 |
| 541 | 6x | sky_array = as_sky_image(sky_array) |
| 542 | 6x | sky_array = tag_generated_sky_exr_metadata( |
| 543 | 6x | sky_array, |
| 544 | 6x | hosek = hosek, |
| 545 | 6x | exr_metadata = exr_metadata, |
| 546 | 6x | exr_adopted_white = exr_adopted_white |
| 547 | ) | |
| 548 | 6x | if (!is.na(filename)) { |
| 549 | 1x | warn_precision_loss(filename) |
| 550 | 1x | write_sky_image(sky_array, filename, clamp = FALSE) |
| 551 | 1x | return(invisible(sky_array)) |
| 552 | } else { | |
| 553 | 5x | return(sky_array) |
| 554 | } | |
| 555 | } | |
| 556 | ||
| 557 | #' Sample a direction from the Prague model. | |
| 558 | #' | |
| 559 | #' @description Evaluate the Prague spectral sky model at arbitrary spherical | |
| 560 | #' directions without writing an image, returning radiance-only samples. | |
| 561 | #' | |
| 562 | #' @param phi Horizontal angle of the sample, degrees. Vectorized. Range 0 to 360. | |
| 563 | #' @param theta Vertical angle of the sample, degrees. Vectorized. Range -90 to 90. | |
| 564 | #' @param altitude Default `0`, vectorized. Altitude of the viewer in meters. Range 0 to 15000. | |
| 565 | #' @param elevation Default `10`, vectorized. Solar elevation angle above/below the horizon (degrees). Range -4.2 to 90. | |
| 566 | #' @param visibility Default `50`, vectorized. Range 20 to 131.8. Meteorological range in kilometers for Prague model. | |
| 567 | #' @param albedo Default `0.5`, vectorized. Range 0 to 1. Ground albedo. | |
| 568 | #' @param azimuth Default `90`, single value. Solar azimuth (degrees). Defaults South. | |
| 569 | #' @param number_cores Default `1`. Number of threads to use in computation. | |
| 570 | #' @param wide_spectrum Default `FALSE`. Whether to use the wide-spectrum (55-channel, polarised) coefficients. | |
| 571 | #' @param render_mode Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`. | |
| 572 | #' Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only. | |
| 573 | #' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB | |
| 574 | #' tint correction to returned RGB values. This correction is only applied to | |
| 575 | #' Prague RGB output. | |
| 576 | #' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB | |
| 577 | #' tint correction. Use `0` for no correction and `1` for the calibrated | |
| 578 | #' correction. | |
| 579 | #' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB | |
| 580 | #' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated | |
| 581 | #' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`. | |
| 582 | #' | |
| 583 | #' @return 3-column RGB matrix. | |
| 584 | #' @export | |
| 585 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 586 | #' # Generate a basic atmosphere with the Prague model | |
| 587 | #' value_grid = expand.grid( | |
| 588 | #' phi = seq(0, 360, by = 30), | |
| 589 | #' theta = seq(0, 90, by = 10), | |
| 590 | #' altitude = c(0, 10000) | |
| 591 | #' ) | |
| 592 | #' vals = calculate_sky_values( | |
| 593 | #' phi = value_grid$phi, | |
| 594 | #' theta = value_grid$theta, | |
| 595 | #' altitude = value_grid$altitude, | |
| 596 | #' elevation = 45, | |
| 597 | #' visibility = 120, | |
| 598 | #' albedo = 0 | |
| 599 | #' ) | |
| 600 | #' cbind(value_grid, vals) | |
| 601 | calculate_sky_values = function( | |
| 602 | phi, | |
| 603 | theta, | |
| 604 | altitude = 0, | |
| 605 | elevation = 10, | |
| 606 | visibility = 50, | |
| 607 | albedo = 0.5, | |
| 608 | azimuth = 90, | |
| 609 | number_cores = 1, | |
| 610 | wide_spectrum = FALSE, | |
| 611 | render_mode = "all", | |
| 612 | prague_rgb_correction = TRUE, | |
| 613 | prague_rgb_correction_strength = 1, | |
| 614 | prague_rgb_correction_gain = "auto" | |
| 615 | ) { | |
| 616 | ! | render_mode = normalize_render_mode(render_mode) |
| 617 | ! | stopifnot(all(phi <= 360 & phi >= 0)) |
| 618 | ! | stopifnot(all(theta <= 90 & theta >= -90)) |
| 619 | ! | stopifnot(all(altitude <= 15000 & altitude >= 0)) |
| 620 | ! | stopifnot(all(visibility >= 20 & visibility <= 131.8)) |
| 621 | ! | stopifnot(all(albedo >= 0 & albedo <= 1)) |
| 622 | ! | df_values = as.list(data.frame( |
| 623 | ! | phi = phi, |
| 624 | ! | theta = theta, |
| 625 | ! | altitude = altitude, |
| 626 | ! | elevation = elevation, |
| 627 | ! | visibility = visibility, |
| 628 | ! | albedo = albedo, |
| 629 | ! | azimuth = azimuth |
| 630 | )) | |
| 631 | ! | stopifnot(all(altitude >= 0 & altitude <= 15000)) |
| 632 | ! | coef_file = resolve_prague_coef_file( |
| 633 | ! | altitude = altitude, |
| 634 | ! | wide_spectrum = wide_spectrum |
| 635 | ) | |
| 636 | ! | vals = calculate_raw_prague( |
| 637 | ! | df_values$phi, |
| 638 | ! | df_values$theta, |
| 639 | ! | df_values$elevation, |
| 640 | ! | df_values$albedo, |
| 641 | ! | df_values$altitude, |
| 642 | ! | df_values$visibility, |
| 643 | ! | df_values$azimuth, |
| 644 | ! | number_cores, |
| 645 | ! | coef_file, |
| 646 | ! | render_mode |
| 647 | ) | |
| 648 | ! | colnames(vals) = c("r", "g", "b") |
| 649 | ! | prague_rgb_correction = normalize_prague_rgb_correction( |
| 650 | ! | prague_rgb_correction |
| 651 | ) | |
| 652 | ||
| 653 | ! | if (prague_rgb_correction == "constant") { |
| 654 | ! | applied_prague_rgb_gain = prepare_prague_rgb_gain( |
| 655 | ! | gain = prague_rgb_correction_gain, |
| 656 | ! | strength = prague_rgb_correction_strength |
| 657 | ) | |
| 658 | ||
| 659 | ! | vals = apply_prague_rgb_gain( |
| 660 | ! | vals, |
| 661 | ! | gain = applied_prague_rgb_gain |
| 662 | ) | |
| 663 | ||
| 664 | ! | attr(vals, "prague_rgb_correction") = "constant" |
| 665 | ! | attr(vals, "prague_rgb_correction_gain") = applied_prague_rgb_gain |
| 666 | ! | attr(vals, "prague_rgb_correction_strength") = |
| 667 | ! | prague_rgb_correction_strength |
| 668 | } | |
| 669 | ! | return(vals) |
| 670 | } | |
| 671 | ||
| 672 | #' Sample Prague sky radiance over directions and wavelengths | |
| 673 | #' | |
| 674 | #' @description Evaluate the Prague spectral sky model at arbitrary spherical | |
| 675 | #' directions and wavelengths, including grids of atmospheric conditions. Use | |
| 676 | #' `render_mode = "all"` for atmosphere + solar disk, `"atmosphere"` for | |
| 677 | #' atmospheric radiance only, or `"sun"` for the solar disk only. | |
| 678 | #' | |
| 679 | #' @param phi Azimuthal angle of the sample, degrees. Vectorized. Range 0 to 360. | |
| 680 | #' @param theta Vertical angle of the sample, degrees. Vectorized. Range -90 to 90. | |
| 681 | #' @param lambda_nm Wavelength in nanometers. Vectorized. Must lie within the loaded Prague dataset range. | |
| 682 | #' @param altitude Default `0`. Vectorized altitude of the viewer in meters. Range 0 to 15000. | |
| 683 | #' @param elevation Default `10`. Vectorized solar elevation angle above/below the horizon (degrees). Range -4.2 to 90. | |
| 684 | #' @param visibility Default `50`. Vectorized meteorological range in kilometers. Range 20 to 131.8. | |
| 685 | #' @param albedo Default `0.5`. Vectorized ground albedo. Range 0 to 1. | |
| 686 | #' @param azimuth Default `90`. Vectorized solar azimuth (degrees). Defaults South. | |
| 687 | #' @param number_cores Default `1`. Number of CPU threads. Ignored with `backend = "gpu"`. | |
| 688 | #' @param wide_spectrum Default `FALSE`. Whether to use the wide-spectrum (55-channel, polarised) coefficients. | |
| 689 | #' @param render_mode Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`. | |
| 690 | #' Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only. | |
| 691 | #' @param backend Default `"cpu"`. Use `"cpu"` for CPU evaluation or `"gpu"` | |
| 692 | #' for batch evaluation on a macOS Metal device. | |
| 693 | #' | |
| 694 | #' @return Numeric vector of spectral radiance values in W m^-2 sr^-1 nm^-1, | |
| 695 | #' in input row order. | |
| 696 | #' @export | |
| 697 | #' @details Inputs are paired element by element, with shorter vectors recycled | |
| 698 | #' by [data.frame()]. Use [expand.grid()] to form all combinations, then pass | |
| 699 | #' its columns as the corresponding arguments. The function does not create a | |
| 700 | #' Cartesian product automatically. | |
| 701 | #' | |
| 702 | #' The GPU backend evaluates geometry, atmospheric radiance, and solar radiance | |
| 703 | #' using the same Prague coefficients as the CPU backend. It uses single | |
| 704 | #' precision, so results can differ slightly, especially near the solar limb. | |
| 705 | #' Coefficients and compiled shaders are cached across calls; changing datasets | |
| 706 | #' replaces the cached GPU coefficients. Large inputs are processed in bounded | |
| 707 | #' batches. The initial upload and shader compilation can outweigh the benefit | |
| 708 | #' for small inputs. An unavailable Metal device or a GPU failure raises an | |
| 709 | #' error; use `backend = "cpu"` to evaluate on the CPU. | |
| 710 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 711 | #' # Compare the same direction and wavelength at two observer altitudes. | |
| 712 | #' lambda_vals = calculate_sky_radiance( | |
| 713 | #' phi = c(90, 90), | |
| 714 | #' theta = c(45, 45), | |
| 715 | #' lambda_nm = 550, | |
| 716 | #' altitude = c(0, 10000), | |
| 717 | #' elevation = 20, | |
| 718 | #' visibility = 80, | |
| 719 | #' albedo = 0.1 | |
| 720 | #' ) | |
| 721 | #' cbind(altitude = c(0, 10000), radiance = lambda_vals) | |
| 722 | #' | |
| 723 | #' # Form a direction-by-wavelength grid and preserve its row ordering. | |
| 724 | #' # On a Mac with Metal, add backend = "gpu" to evaluate the grid on the GPU. | |
| 725 | #' grid = expand.grid( | |
| 726 | #' phi = seq(0, 350, by = 10), | |
| 727 | #' theta = seq(0, 90, by = 10), | |
| 728 | #' lambda_nm = seq(380, 740, by = 20) | |
| 729 | #' ) | |
| 730 | #' grid$radiance = calculate_sky_radiance( | |
| 731 | #' phi = grid$phi, | |
| 732 | #' theta = grid$theta, | |
| 733 | #' lambda_nm = grid$lambda_nm, | |
| 734 | #' render_mode = "atmosphere" | |
| 735 | #' ) | |
| 736 | calculate_sky_radiance = function( | |
| 737 | phi, | |
| 738 | theta, | |
| 739 | lambda_nm, | |
| 740 | altitude = 0, | |
| 741 | elevation = 10, | |
| 742 | visibility = 50, | |
| 743 | albedo = 0.5, | |
| 744 | azimuth = 90, | |
| 745 | number_cores = 1, | |
| 746 | wide_spectrum = FALSE, | |
| 747 | render_mode = "all", | |
| 748 | backend = "cpu" | |
| 749 | ) { | |
| 750 | 11x | backend = match.arg(backend, c("cpu", "gpu")) |
| 751 | 10x | render_mode = normalize_render_mode(render_mode) |
| 752 | 10x | inputs = list( |
| 753 | 10x | phi = phi, |
| 754 | 10x | theta = theta, |
| 755 | 10x | lambda_nm = lambda_nm, |
| 756 | 10x | altitude = altitude, |
| 757 | 10x | elevation = elevation, |
| 758 | 10x | visibility = visibility, |
| 759 | 10x | albedo = albedo, |
| 760 | 10x | azimuth = azimuth |
| 761 | ) | |
| 762 | 10x | for (name in names(inputs)) { |
| 763 | 45x | if (!is.numeric(inputs[[name]]) || any(!is.finite(inputs[[name]]))) { |
| 764 | 9x | stop( |
| 765 | 9x | sprintf("`%s` must contain finite numeric values.", name), |
| 766 | 9x | call. = FALSE |
| 767 | ) | |
| 768 | } | |
| 769 | } | |
| 770 | 1x | stopifnot(all(phi <= 360 & phi >= 0)) |
| 771 | 1x | stopifnot(all(theta <= 90 & theta >= -90)) |
| 772 | 1x | stopifnot(all(altitude <= 15000 & altitude >= 0)) |
| 773 | 1x | stopifnot(all(visibility >= 20 & visibility <= 131.8)) |
| 774 | 1x | stopifnot(all(albedo >= 0 & albedo <= 1)) |
| 775 | 1x | df_values = as.list(data.frame( |
| 776 | 1x | phi = phi, |
| 777 | 1x | theta = theta, |
| 778 | 1x | lambda_nm = lambda_nm, |
| 779 | 1x | altitude = altitude, |
| 780 | 1x | elevation = elevation, |
| 781 | 1x | visibility = visibility, |
| 782 | 1x | albedo = albedo, |
| 783 | 1x | azimuth = azimuth |
| 784 | )) | |
| 785 | ! | coef_file = resolve_prague_coef_file( |
| 786 | ! | altitude = altitude, |
| 787 | ! | wide_spectrum = wide_spectrum |
| 788 | ) | |
| 789 | ! | calculate_raw_prague_radiance( |
| 790 | ! | df_values$phi, |
| 791 | ! | df_values$theta, |
| 792 | ! | df_values$lambda_nm, |
| 793 | ! | df_values$elevation, |
| 794 | ! | df_values$albedo, |
| 795 | ! | df_values$altitude, |
| 796 | ! | df_values$visibility, |
| 797 | ! | df_values$azimuth, |
| 798 | ! | number_cores, |
| 799 | ! | coef_file, |
| 800 | ! | render_mode, |
| 801 | ! | backend |
| 802 | ) | |
| 803 | } | |
| 804 | ||
| 805 | #' Sample sun luminance at the disk center. | |
| 806 | #' | |
| 807 | #' @description Evaluate the Prague or Hosek sky model at the sun center and | |
| 808 | #' integrate against the CIE Y curve to return a luminance value. This is | |
| 809 | #' useful for relative attenuation (e.g., comparing zenith sun to a low sun). | |
| 810 | #' | |
| 811 | #' @param elevation Default `10`. Solar elevation angle above/below | |
| 812 | #' the horizon (degrees). Range `[-4.2, 90]` for Prague, `[0, 90]` for Hosek. | |
| 813 | #' @param azimuth Default `90`. Solar azimuth (degrees). | |
| 814 | #' @param albedo Default `0.5`. Ground albedo, range 0 to 1. | |
| 815 | #' @param turbidity Default `3`. Atmospheric turbidity, range 1.7 to 10 | |
| 816 | #' (*Hosek only*). | |
| 817 | #' @param altitude Default `0`. Observer altitude (m), range 0 to 15000 | |
| 818 | #' (*Prague only*). | |
| 819 | #' @param visibility Default `50`. Meteorological range (km); *Prague only*. | |
| 820 | #' @param hosek Default `TRUE`. `FALSE` selects the Prague model. | |
| 821 | #' @param wide_spectrum Default `FALSE`. Use wide-spectrum (55-channel) | |
| 822 | #' coefficients for Prague at sea level only. | |
| 823 | #' @param lambda_nm Optional vector of wavelengths for Hosek sampling. | |
| 824 | #' | |
| 825 | #' @return Numeric scalar of sun luminance (CIE Y, relative scale). | |
| 826 | #' @export | |
| 827 | #' @examples | |
| 828 | #' calculate_sun_brightness(elevation = 45, hosek = TRUE) | |
| 829 | calculate_sun_brightness = function( | |
| 830 | elevation = 10, | |
| 831 | azimuth = 90, | |
| 832 | albedo = 0.5, | |
| 833 | turbidity = 3, | |
| 834 | altitude = 0, | |
| 835 | visibility = 50, | |
| 836 | hosek = TRUE, | |
| 837 | wide_spectrum = FALSE, | |
| 838 | lambda_nm = NULL | |
| 839 | ) { | |
| 840 | ! | stopifnot(length(elevation) == 1) |
| 841 | ! | stopifnot(length(azimuth) == 1) |
| 842 | ! | stopifnot(length(albedo) == 1) |
| 843 | ! | stopifnot(length(turbidity) == 1) |
| 844 | ! | stopifnot(length(altitude) == 1) |
| 845 | ! | stopifnot(length(visibility) == 1) |
| 846 | ! | stopifnot(altitude >= 0) |
| 847 | ||
| 848 | ! | model = if (hosek) "hosek" else "prague" |
| 849 | ! | coef_file = "" |
| 850 | ||
| 851 | ! | if (!hosek) { |
| 852 | ! | coef_file = resolve_prague_coef_file( |
| 853 | ! | altitude = altitude, |
| 854 | ! | wide_spectrum = wide_spectrum |
| 855 | ) | |
| 856 | } | |
| 857 | ||
| 858 | ! | calculate_sun_brightness_rcpp( |
| 859 | ! | albedo = albedo, |
| 860 | ! | turbidity = turbidity, |
| 861 | ! | elevation = elevation, |
| 862 | ! | azimuth_deg = azimuth, |
| 863 | ! | model = model, |
| 864 | ! | prg_dataset = coef_file, |
| 865 | ! | altitude = altitude, |
| 866 | ! | visibility = visibility, |
| 867 | ! | lambda_nm = if (hosek) lambda_nm else NULL |
| 868 | ) | |
| 869 | } |
| 1 | prague_coef_cache_dir = function() { | |
| 2 | 5x | tools::R_user_dir("skymodelr", "data") |
| 3 | } | |
| 4 | ||
| 5 | prague_coef_info = function( | |
| 6 | sea_level = TRUE, | |
| 7 | wide_spectrum = FALSE, | |
| 8 | altitude = NULL | |
| 9 | ) { | |
| 10 | 6x | if (!is.null(altitude)) { |
| 11 | 6x | sea_level = all(altitude == 0) |
| 12 | } | |
| 13 | 6x | if (wide_spectrum && !sea_level) { |
| 14 | ! | stop( |
| 15 | ! | "`wide_spectrum = TRUE` is only valid when `altitude == 0`.", |
| 16 | ! | call. = FALSE |
| 17 | ) | |
| 18 | } | |
| 19 | ||
| 20 | 6x | if (sea_level && wide_spectrum) { |
| 21 | ! | list( |
| 22 | ! | name = "PragueSkyModelDatasetGroundInfra.dat", |
| 23 | ! | url = "https://skydata.tylermw.com/PragueSkyModelDatasetGroundInfra.dat", |
| 24 | ! | md5 = "33b97729ce8cd7fbdfc60317ff2805e7", |
| 25 | ! | size = "574MB", |
| 26 | ! | sea_level = TRUE, |
| 27 | ! | wide_spectrum = TRUE |
| 28 | ) | |
| 29 | 6x | } else if (sea_level) { |
| 30 | 4x | list( |
| 31 | 4x | name = "SkyModelDatasetGround.dat", |
| 32 | 4x | url = "https://skydata.tylermw.com/SkyModelDatasetGround.dat", |
| 33 | 4x | md5 = "953864f62c9434269b7f909cdff6c7cd", |
| 34 | 4x | size = "107MB", |
| 35 | 4x | sea_level = TRUE, |
| 36 | 4x | wide_spectrum = FALSE |
| 37 | ) | |
| 38 | } else { | |
| 39 | 2x | list( |
| 40 | 2x | name = "SkyModelDataset.dat", |
| 41 | 2x | url = "https://skydata.tylermw.com/SkyModelDataset.dat", |
| 42 | 2x | md5 = "dcfa2bd165cf803c1791c469e05d134c", |
| 43 | 2x | size = "2.4GB", |
| 44 | 2x | sea_level = FALSE, |
| 45 | 2x | wide_spectrum = FALSE |
| 46 | ) | |
| 47 | } | |
| 48 | } | |
| 49 | ||
| 50 | prague_download_call = function(info) { | |
| 51 | 6x | sprintf( |
| 52 | 6x | "download_sky_data(sea_level = %s, wide_spectrum = %s)", |
| 53 | 2x | if (info$sea_level) "TRUE" else "FALSE", |
| 54 | ! | if (info$wide_spectrum) "TRUE" else "FALSE" |
| 55 | ) | |
| 56 | } | |
| 57 | ||
| 58 | stop_missing_prague_coef = function(info, model = "Prague sky model") { | |
| 59 | 6x | stop( |
| 60 | 6x | sprintf( |
| 61 | 6x | "The %s coefficient file '%s' is not installed. Run %s explicitly to download it.", |
| 62 | 6x | model, |
| 63 | 6x | info$name, |
| 64 | 6x | prague_download_call(info) |
| 65 | ), | |
| 66 | 6x | call. = FALSE |
| 67 | ) | |
| 68 | } | |
| 69 | ||
| 70 | resolve_prague_coef_file = function( | |
| 71 | altitude = 0, | |
| 72 | wide_spectrum = FALSE, | |
| 73 | allow_download = interactive(), | |
| 74 | model = "Prague sky model" | |
| 75 | ) { | |
| 76 | 6x | info = prague_coef_info(altitude = altitude, wide_spectrum = wide_spectrum) |
| 77 | 6x | coef_file = file.path(prague_coef_cache_dir(), info$name) |
| 78 | 6x | if (file.exists(coef_file)) { |
| 79 | ! | return(coef_file) |
| 80 | } | |
| 81 | ||
| 82 | 6x | if (!allow_download) { |
| 83 | 6x | stop_missing_prague_coef(info, model = model) |
| 84 | } | |
| 85 | ||
| 86 | ! | answer = readline( |
| 87 | ! | prompt = sprintf( |
| 88 | ! | "Coefficient file '%s' for the %s is not installed. This is a large file (%s). Download now? [y/n] ", |
| 89 | ! | info$name, |
| 90 | ! | model, |
| 91 | ! | info$size |
| 92 | ) | |
| 93 | ) | |
| 94 | ! | answer = tolower(trimws(answer)) |
| 95 | ||
| 96 | ! | if (answer %in% c("y", "yes")) { |
| 97 | ! | return(download_sky_data( |
| 98 | ! | sea_level = info$sea_level, |
| 99 | ! | wide_spectrum = info$wide_spectrum |
| 100 | )) | |
| 101 | } | |
| 102 | ! | if (answer %in% c("n", "no")) { |
| 103 | ! | stop_missing_prague_coef(info, model = model) |
| 104 | } | |
| 105 | ! | stop("Input not recognized.", call. = FALSE) |
| 106 | } |
| 1 | .prague_rgb_correction_gain = c( | |
| 2 | R = 0.94438727, | |
| 3 | G = 1.02157200, | |
| 4 | B = 0.95012063 | |
| 5 | ) | |
| 6 | ||
| 7 | #' Normalize Prague RGB correction option | |
| 8 | #' | |
| 9 | #' @param prague_rgb_correction Prague RGB correction option. | |
| 10 | #' @keywords internal | |
| 11 | normalize_prague_rgb_correction = function(prague_rgb_correction) { | |
| 12 | 47x | if (is.logical(prague_rgb_correction)) { |
| 13 | 47x | if (length(prague_rgb_correction) != 1L || is.na(prague_rgb_correction)) { |
| 14 | 3x | stop( |
| 15 | 3x | "prague_rgb_correction must be TRUE, FALSE, \"constant\", or \"none\".", |
| 16 | 3x | call. = FALSE |
| 17 | ) | |
| 18 | } | |
| 19 | ||
| 20 | ! | return(if (isTRUE(prague_rgb_correction)) "constant" else "none") |
| 21 | } | |
| 22 | ||
| 23 | ! | prague_rgb_correction = tolower(as.character(prague_rgb_correction)) |
| 24 | ! | match.arg(prague_rgb_correction, c("none", "constant")) |
| 25 | } | |
| 26 | ||
| 27 | #' Validate Prague RGB correction gain | |
| 28 | #' | |
| 29 | #' @param gain RGB correction gain. | |
| 30 | #' @keywords internal | |
| 31 | validate_prague_rgb_gain = function(gain) { | |
| 32 | 49x | if (!is.numeric(gain) || length(gain) != 3L) { |
| 33 | 1x | stop( |
| 34 | 1x | "prague_rgb_correction_gain must be a numeric vector of length 3.", |
| 35 | 1x | call. = FALSE |
| 36 | ) | |
| 37 | } | |
| 38 | ||
| 39 | 48x | if (is.null(names(gain))) { |
| 40 | 4x | names(gain) = c("R", "G", "B") |
| 41 | } | |
| 42 | ||
| 43 | 48x | if (!all(c("R", "G", "B") %in% names(gain))) { |
| 44 | ! | stop( |
| 45 | ! | "prague_rgb_correction_gain must have names R, G, and B.", |
| 46 | ! | call. = FALSE |
| 47 | ) | |
| 48 | } | |
| 49 | ||
| 50 | 48x | gain = gain[c("R", "G", "B")] |
| 51 | ||
| 52 | 48x | if (any(!is.finite(gain)) || any(gain <= 0)) { |
| 53 | 3x | stop( |
| 54 | 3x | "prague_rgb_correction_gain values must be finite and positive.", |
| 55 | 3x | call. = FALSE |
| 56 | ) | |
| 57 | } | |
| 58 | ||
| 59 | 45x | gain |
| 60 | } | |
| 61 | ||
| 62 | #' Prepare Prague RGB correction gain | |
| 63 | #' | |
| 64 | #' @param gain Default `"auto"`. RGB correction gain. | |
| 65 | #' @param strength Default `1`. Correction strength. | |
| 66 | #' @keywords internal | |
| 67 | prepare_prague_rgb_gain = function( | |
| 68 | gain = "auto", | |
| 69 | strength = 1 | |
| 70 | ) { | |
| 71 | 48x | if (identical(gain, "auto")) { |
| 72 | 42x | gain = .prague_rgb_correction_gain |
| 73 | } | |
| 74 | ||
| 75 | 48x | gain = validate_prague_rgb_gain(gain) |
| 76 | ||
| 77 | if ( | |
| 78 | 44x | !is.numeric(strength) || |
| 79 | 44x | length(strength) != 1L || |
| 80 | 44x | !is.finite(strength) || |
| 81 | 44x | strength < 0 |
| 82 | ) { | |
| 83 | 11x | stop( |
| 84 | 11x | "prague_rgb_correction_strength must be a finite non-negative scalar.", |
| 85 | 11x | call. = FALSE |
| 86 | ) | |
| 87 | } | |
| 88 | ||
| 89 | 33x | exp(log(gain) * strength) |
| 90 | } | |
| 91 | ||
| 92 | #' Apply Prague RGB correction gain | |
| 93 | #' | |
| 94 | #' @param x RGB array or matrix. | |
| 95 | #' @param gain RGB correction gain. | |
| 96 | #' @keywords internal | |
| 97 | apply_prague_rgb_gain = function(x, gain) { | |
| 98 | 1x | gain = validate_prague_rgb_gain(gain) |
| 99 | ||
| 100 | 1x | out = x |
| 101 | 1x | d = dim(out) |
| 102 | ||
| 103 | 1x | if (length(d) == 3L) { |
| 104 | ! | if (d[3] < 3L) { |
| 105 | ! | stop("RGB array must have at least 3 channels.", call. = FALSE) |
| 106 | } | |
| 107 | ||
| 108 | ! | out[,, 1] = out[,, 1] * gain[["R"]] |
| 109 | ! | out[,, 2] = out[,, 2] * gain[["G"]] |
| 110 | ! | out[,, 3] = out[,, 3] * gain[["B"]] |
| 111 | ! | return(out) |
| 112 | } | |
| 113 | ||
| 114 | 1x | if (is.matrix(out)) { |
| 115 | 1x | if (ncol(out) < 3L) { |
| 116 | ! | stop("RGB matrix must have at least 3 columns.", call. = FALSE) |
| 117 | } | |
| 118 | ||
| 119 | 1x | out[, 1] = out[, 1] * gain[["R"]] |
| 120 | 1x | out[, 2] = out[, 2] * gain[["G"]] |
| 121 | 1x | out[, 3] = out[, 3] * gain[["B"]] |
| 122 | 1x | return(out) |
| 123 | } | |
| 124 | ||
| 125 | ! | stop("Expected an RGB array or RGB matrix.", call. = FALSE) |
| 126 | } |
| 1 | #' Normalize a vector to unit length | |
| 2 | #' | |
| 3 | #' @description Scale a numeric vector so it has unit Euclidean length. | |
| 4 | #' @param v Numeric vector to normalise. | |
| 5 | #' @keywords internal | |
| 6 | normalize = function(v) { | |
| 7 | 103x | s = sqrt(sum(v * v)) |
| 8 | 103x | if (s == 0) { |
| 9 | ! | stop("Zero-length vector") |
| 10 | } | |
| 11 | 103x | return(v / s) |
| 12 | } | |
| 13 | ||
| 14 | #' Convert altitude/azimuth to ENU | |
| 15 | #' | |
| 16 | #' @description Map altitude/azimuth angles (north-referenced) to a unit | |
| 17 | #' East-North-Up direction vector. | |
| 18 | #' @param alt_rad Altitude in radians. | |
| 19 | #' @param azN_rad Azimuth in radians measured from north. | |
| 20 | #' @keywords internal | |
| 21 | altaz_to_enu = function(alt_rad, azN_rad) { | |
| 22 | 100x | east = sin(azN_rad) * cos(alt_rad) |
| 23 | 100x | north = cos(azN_rad) * cos(alt_rad) |
| 24 | 100x | up = sin(alt_rad) |
| 25 | 100x | normalize(c(east, north, up)) # (E, N, U) matches engine XYZ |
| 26 | } | |
| 27 | ||
| 28 | ||
| 29 | #' Moon V-band magnitude from phase angle | |
| 30 | #' | |
| 31 | #' @param phase_deg Phase angle psi in degrees (0 = full Moon, 180 = new). | |
| 32 | #' @param dist_km Default `384400`. Current geocentric distance (km). | |
| 33 | #' @param mean_km Default `384400`. Mean distance (km). | |
| 34 | #' @keywords internal | |
| 35 | #' | |
| 36 | #' @return Apparent V magnitude `m`. | |
| 37 | moon_mag = function( | |
| 38 | phase_deg, | |
| 39 | dist_km = 384400, | |
| 40 | mean_km = 384400 | |
| 41 | ) { | |
| 42 | # Allen-1976 magnitude for a disc at mean distance, no surge (phase_deg in degrees): | |
| 43 | 25x | m0 = -12.73 + 0.026 * abs(phase_deg) + 4e-9 * phase_deg^4 |
| 44 | ||
| 45 | # Geometry: inverse-square scaling with distance | |
| 46 | 25x | geom = 5 * log10(dist_km / mean_km) |
| 47 | ||
| 48 | # Opposition surge term (Allen's "extra" brightness near full Moon) | |
| 49 | 25x | S = max(1, 1.35 - 0.05 * abs(phase_deg)) # Allen's empirical fit |
| 50 | 25x | surge_corr = -2.5 * log10(S) |
| 51 | ||
| 52 | 25x | m = m0 + geom + surge_corr |
| 53 | 25x | return(m) |
| 54 | } | |
| 55 | ||
| 56 | ||
| 57 | # Krisciunas & Schaefer (1991) / Rozenberg (1966) airmass approximation: | |
| 58 | # X(Z) = [cos(Z) + 0.025 * exp(-11 * cos(Z))]^(-1) | |
| 59 | # where Z is zenith distance in radians; bounded to ~40 at the horizon. | |
| 60 | airmass_rozenberg1966 = function(zenith_deg) { | |
| 61 | 61x | z = zenith_deg * pi / 180 |
| 62 | 61x | c = cos(z) |
| 63 | 61x | 1 / (c + 0.025 * exp(-11 * c)) |
| 64 | } | |
| 65 | ||
| 66 | #' @keywords internal | |
| 67 | apply_airmass_extinction = function( | |
| 68 | lux_top_atm, | |
| 69 | alt_deg, | |
| 70 | kV = 0.172, | |
| 71 | clip_horizon = FALSE | |
| 72 | ) { | |
| 73 | if ( | |
| 74 | 64x | !is.finite(lux_top_atm) || |
| 75 | 64x | !is.finite(alt_deg) || |
| 76 | 64x | (clip_horizon && alt_deg <= 0) |
| 77 | ) { | |
| 78 | 3x | return(0) |
| 79 | } | |
| 80 | ||
| 81 | # Disk consumers clip individual directions. Continue the finite horizon | |
| 82 | # value below zero instead of switching off an extended source at its center. | |
| 83 | # Rozenberg is only defined over the upper hemisphere. | |
| 84 | 61x | alt_deg = max(0, min(alt_deg, 90)) |
| 85 | 61x | zenith_deg = 90 - alt_deg |
| 86 | ||
| 87 | 61x | X = airmass_rozenberg1966(zenith_deg) |
| 88 | 61x | lux_top_atm * 10^(-0.4 * kV * X) |
| 89 | } | |
| 90 | ||
| 91 | #' Compute topocentric moon/sun directions | |
| 92 | #' | |
| 93 | #' @description Query Swiss Ephemeris for topocentric sun and moon direction | |
| 94 | #' vectors and magnitudes for a given observer location. | |
| 95 | #' @param datetime POSIXct observation time (UTC). | |
| 96 | #' @param lat Latitude in degrees. | |
| 97 | #' @param lon Longitude in degrees. | |
| 98 | #' @param elev_m Observer elevation above sea level in metres. | |
| 99 | #' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction | |
| 100 | #' coefficient used in the Rozenberg/Krisciunas-Schaefer airmass attenuation | |
| 101 | #' model for moonlight. | |
| 102 | #' @keywords internal | |
| 103 | swe_dirs_topo_moon_sun = function( | |
| 104 | datetime, | |
| 105 | lat, | |
| 106 | lon, | |
| 107 | elev_m = 0, | |
| 108 | moon_extinction_kV = 0.172 | |
| 109 | ) { | |
| 110 | 25x | swephR::swe_set_topo(lon, lat, elev_m) |
| 111 | 25x | attr(datetime, "tzone") = "UTC" |
| 112 | 25x | ts = as.POSIXlt(datetime, tz = "UTC") |
| 113 | 25x | jd_ut = swephR::swe_utc_to_jd( |
| 114 | 25x | ts$year + 1900, |
| 115 | 25x | ts$mon + 1, |
| 116 | 25x | ts$mday, |
| 117 | 25x | ts$hour, |
| 118 | 25x | ts$min, |
| 119 | 25x | ts$sec, |
| 120 | 25x | swephR::SE$GREG_CAL |
| 121 | 25x | )$dret[2] # Swiss Ephemeris returns TT first, then UT1. |
| 122 | ||
| 123 | 25x | flg_eq_topo = swephR::SE$FLG_SWIEPH + |
| 124 | 25x | swephR::SE$FLG_EQUATORIAL + |
| 125 | 25x | swephR::SE$FLG_TOPOCTR |
| 126 | 25x | long_rad = lon * pi / 180 |
| 127 | 25x | lat_rad = lat * pi / 180 |
| 128 | ||
| 129 | 25x | enu_to_ecef = matrix( |
| 130 | 25x | c( |
| 131 | 25x | -sin(long_rad), |
| 132 | 25x | cos(long_rad), |
| 133 | 25x | 0, |
| 134 | 25x | -sin(lat_rad) * cos(long_rad), |
| 135 | 25x | -sin(lat_rad) * sin(long_rad), |
| 136 | 25x | cos(lat_rad), |
| 137 | 25x | cos(lat_rad) * cos(long_rad), |
| 138 | 25x | cos(lat_rad) * sin(long_rad), |
| 139 | 25x | sin(lat_rad) |
| 140 | ), | |
| 141 | 25x | ncol = 3, |
| 142 | 25x | nrow = 3, |
| 143 | 25x | byrow = TRUE |
| 144 | ) | |
| 145 | 25x | sun_t = swephR::swe_calc_ut(jd_ut, swephR::SE$SUN, flg_eq_topo)$xx |
| 146 | 25x | moon_t = swephR::swe_calc_ut(jd_ut, swephR::SE$MOON, flg_eq_topo)$xx |
| 147 | 25x | moon_size = swephR::swe_pheno_ut(jd_ut, swephR::SE$MOON, flg_eq_topo)$attr |
| 148 | 25x | sun_size = swephR::swe_pheno_ut(jd_ut, swephR::SE$SUN, flg_eq_topo)$attr |
| 149 | ||
| 150 | 25x | dist_au = moon_t[3] |
| 151 | 25x | moon_distance_km = dist_au * 149597870.7 |
| 152 | ||
| 153 | 25x | moon_phase = moon_size[1] |
| 154 | 25x | moon_diameter_degrees = moon_size[4] |
| 155 | 25x | moon_brightness_magnitude = moon_size[5] |
| 156 | ||
| 157 | 25x | m = moon_mag( |
| 158 | 25x | moon_phase, |
| 159 | 25x | dist_km = moon_distance_km, |
| 160 | 25x | mean_km = 384400 |
| 161 | ) | |
| 162 | ||
| 163 | 25x | ftcnds_to_lux = 10.76 |
| 164 | 25x | moon_brightness_lux_raw = ftcnds_to_lux * 10^(-0.4 * (m + 16.57)) |
| 165 | ||
| 166 | 25x | sun_diameter_degrees = sun_size[4] |
| 167 | 25x | sun_brightness_magnitude = sun_size[5] |
| 168 | 25x | sun_brightness_lux = ftcnds_to_lux * |
| 169 | 25x | 10^(-0.4 * (sun_brightness_magnitude + 16.57)) |
| 170 | ||
| 171 | 25x | to_local_horizontal_coordinates = function(ra_dec) { |
| 172 | 50x | aa = swephR::swe_azalt( |
| 173 | 50x | jd_ut, |
| 174 | 50x | swephR::SE$EQU2HOR, |
| 175 | 50x | c(lon, lat, elev_m), |
| 176 | 50x | 0, |
| 177 | 50x | 0, |
| 178 | 50x | xin = c(ra_dec[1], ra_dec[2], 1) |
| 179 | 50x | )$xaz |
| 180 | 50x | aa |
| 181 | } | |
| 182 | 25x | to_rad = pi / 180 |
| 183 | ||
| 184 | 25x | local_horizon_sun = to_local_horizontal_coordinates(sun_t) * to_rad |
| 185 | 25x | local_horizon_moon = to_local_horizontal_coordinates(moon_t) * to_rad |
| 186 | ||
| 187 | 25x | azN_s = local_horizon_sun[1] |
| 188 | 25x | alt_s = local_horizon_sun[2] |
| 189 | 25x | azN_mt = local_horizon_moon[1] |
| 190 | 25x | alt_mt = local_horizon_moon[2] |
| 191 | ||
| 192 | 25x | moon_elev_deg = alt_mt * 180 / pi |
| 193 | 25x | moon_brightness_lux = apply_airmass_extinction( |
| 194 | 25x | lux_top_atm = moon_brightness_lux_raw, |
| 195 | 25x | alt_deg = moon_elev_deg, |
| 196 | 25x | kV = moon_extinction_kV |
| 197 | ) | |
| 198 | ||
| 199 | 25x | list( |
| 200 | 25x | sun_dir_topo = altaz_to_enu(alt_s, azN_s), |
| 201 | 25x | sun_ecef_geo = enu_to_ecef %*% altaz_to_enu(alt_s, azN_s), |
| 202 | 25x | moon_dir_topo = altaz_to_enu(alt_mt, azN_mt), |
| 203 | 25x | moon_ecef_geo = enu_to_ecef %*% altaz_to_enu(alt_mt, azN_mt), |
| 204 | 25x | local_up_geo = enu_to_ecef %*% c(0, 0, 1), |
| 205 | 25x | moon_diameter_degrees = moon_diameter_degrees, |
| 206 | 25x | moon_brightness_magnitude = moon_brightness_magnitude, |
| 207 | 25x | moon_brightness_lux = moon_brightness_lux, #lux for the complete attenuated disk |
| 208 | 25x | moon_brightness_lux_unattenuated = moon_brightness_lux_raw, #lux, before atmospheric attenuation |
| 209 | 25x | moon_phase = moon_phase, |
| 210 | 25x | sun_diameter_degrees = sun_diameter_degrees, |
| 211 | 25x | sun_brightness_magnitude = sun_brightness_magnitude, |
| 212 | 25x | sun_brightness_lux = sun_brightness_lux #lux |
| 213 | ) |> | |
| 214 | 25x | lapply(as.numeric) |
| 215 | } | |
| 216 | ||
| 217 | ||
| 218 | #' Convert Swiss ephemeris data to a starfield frame | |
| 219 | #' | |
| 220 | #' @description Build a data frame compatible with `make_starfield_rcpp()` from | |
| 221 | #' Swiss Ephemeris results. | |
| 222 | #' @param sweph_info List of planetary info objects. | |
| 223 | #' @keywords internal | |
| 224 | sweph_info_to_stars_df = function(sweph_info) { | |
| 225 | 2x | sweph_info_df = do.call(rbind, lapply(sweph_info, as.data.frame)) |
| 226 | 2x | planets = rownames(sweph_info_df) |
| 227 | 2x | data.frame( |
| 228 | 2x | planet = planets, |
| 229 | 2x | ra_rad = sweph_info_df$ra_rad, |
| 230 | 2x | dec_rad = sweph_info_df$dec_rad, |
| 231 | 2x | ra_deg = sweph_info_df$ra_rad * 180 / pi, |
| 232 | 2x | dec_deg = sweph_info_df$dec_rad * 180 / pi, |
| 233 | 2x | v_mag = sweph_info_df$v_mag, |
| 234 | 2x | r = 1, |
| 235 | 2x | g = 1, |
| 236 | 2x | b = 1 |
| 237 | ) | |
| 238 | } | |
| 239 | ||
| 240 | #' Compute sun/moon positions via Swiss Ephemeris | |
| 241 | #' | |
| 242 | #' @description Produce a data frame of apparent positions and | |
| 243 | #' magnitudes for the observer. | |
| 244 | #' @param datetime POSIXct observation time (UTC). | |
| 245 | #' @param lat Latitude in degrees. | |
| 246 | #' @param lon Longitude in degrees. | |
| 247 | #' @param elev_m Observer elevation above sea level in metres. | |
| 248 | #' @keywords internal | |
| 249 | swe_dirs_topo_sunmoon_df = function(datetime, lat, lon, elev_m = 0) { | |
| 250 | 1x | swephR::swe_set_topo(lon, lat, elev_m) |
| 251 | 1x | attr(datetime, "tzone") = "UTC" |
| 252 | 1x | ts = as.POSIXlt(datetime, tz = "UTC") |
| 253 | 1x | jd_ut = swephR::swe_utc_to_jd( |
| 254 | 1x | ts$year + 1900, |
| 255 | 1x | ts$mon + 1, |
| 256 | 1x | ts$mday, |
| 257 | 1x | ts$hour, |
| 258 | 1x | ts$min, |
| 259 | 1x | ts$sec, |
| 260 | 1x | swephR::SE$GREG_CAL |
| 261 | 1x | )$dret[2] # Swiss Ephemeris returns TT first, then UT1. |
| 262 | ||
| 263 | 1x | flg_eq_topo = swephR::SE$FLG_SWIEPH + |
| 264 | 1x | swephR::SE$FLG_EQUATORIAL + |
| 265 | 1x | swephR::SE$FLG_TOPOCTR |
| 266 | ||
| 267 | 1x | to_rad = pi / 180 |
| 268 | 1x | get_enu_magnitude = function(planet_flag) { |
| 269 | 2x | position_rad = swephR::swe_calc_ut(jd_ut, planet_flag, flg_eq_topo)$xx * |
| 270 | 2x | to_rad |
| 271 | 2x | info = swephR::swe_pheno_ut(jd_ut, planet_flag, flg_eq_topo)$attr |
| 272 | 2x | list(ra_rad = position_rad[1], dec_rad = position_rad[2], v_mag = info[5]) |
| 273 | } | |
| 274 | 1x | info = list( |
| 275 | 1x | sun = get_enu_magnitude(swephR::SE$SUN), |
| 276 | 1x | moon = get_enu_magnitude(swephR::SE$MOON) |
| 277 | ) | |
| 278 | 1x | return(sweph_info_to_stars_df(info)) |
| 279 | } | |
| 280 | ||
| 281 | #' Compute bright-planet positions via Swiss Ephemeris | |
| 282 | #' | |
| 283 | #' @description Produce a data frame of planetary apparent positions and | |
| 284 | #' magnitudes for the observer. | |
| 285 | #' @param datetime POSIXct observation time (UTC). | |
| 286 | #' @param lat Latitude in degrees. | |
| 287 | #' @param lon Longitude in degrees. | |
| 288 | #' @param elev_m Observer elevation above sea level in metres. | |
| 289 | #' @keywords internal | |
| 290 | swe_dirs_topo_planets_df = function(datetime, lat, lon, elev_m = 0) { | |
| 291 | 1x | swephR::swe_set_topo(lon, lat, elev_m) |
| 292 | 1x | attr(datetime, "tzone") = "UTC" |
| 293 | 1x | ts = as.POSIXlt(datetime, tz = "UTC") |
| 294 | 1x | jd_ut = swephR::swe_utc_to_jd( |
| 295 | 1x | ts$year + 1900, |
| 296 | 1x | ts$mon + 1, |
| 297 | 1x | ts$mday, |
| 298 | 1x | ts$hour, |
| 299 | 1x | ts$min, |
| 300 | 1x | ts$sec, |
| 301 | 1x | swephR::SE$GREG_CAL |
| 302 | 1x | )$dret[2] # Swiss Ephemeris returns TT first, then UT1. |
| 303 | ||
| 304 | 1x | flg_eq_topo = swephR::SE$FLG_SWIEPH + |
| 305 | 1x | swephR::SE$FLG_EQUATORIAL + |
| 306 | 1x | swephR::SE$FLG_TOPOCTR |
| 307 | ||
| 308 | 1x | to_rad = pi / 180 |
| 309 | 1x | get_enu_magnitude = function(planet_flag) { |
| 310 | 7x | position_rad = swephR::swe_calc_ut(jd_ut, planet_flag, flg_eq_topo)$xx * |
| 311 | 7x | to_rad |
| 312 | 7x | info = swephR::swe_pheno_ut(jd_ut, planet_flag, flg_eq_topo)$attr |
| 313 | 7x | list(ra_rad = position_rad[1], dec_rad = position_rad[2], v_mag = info[5]) |
| 314 | } | |
| 315 | 1x | planet_info = list( |
| 316 | 1x | mercury = get_enu_magnitude(swephR::SE$MERCURY), |
| 317 | 1x | venus = get_enu_magnitude(swephR::SE$VENUS), |
| 318 | 1x | mars = get_enu_magnitude(swephR::SE$MARS), |
| 319 | 1x | jupiter = get_enu_magnitude(swephR::SE$JUPITER), |
| 320 | 1x | saturn = get_enu_magnitude(swephR::SE$SATURN), |
| 321 | 1x | uranus = get_enu_magnitude(swephR::SE$URANUS), |
| 322 | 1x | neptune = get_enu_magnitude(swephR::SE$NEPTUNE) |
| 323 | ) | |
| 324 | 1x | return(sweph_info_to_stars_df(planet_info)) |
| 325 | } | |
| 326 | ||
| 327 | ||
| 328 | #' Generate the moon into a lat-long image array patch | |
| 329 | #' | |
| 330 | #' @description Produce a rasterised moon texture aligned for composition into | |
| 331 | #' the sky dome. The Earth phase is inferred from the Sun-Moon geometry, and earthshine is | |
| 332 | #' implemented as an emissive term scaled relative to solar irradiance. | |
| 333 | #' | |
| 334 | #' @param datetime POSIXct observation time (UTC). | |
| 335 | #' @param lat Latitude in degrees. | |
| 336 | #' @param lon Longitude in degrees. | |
| 337 | #' @param elev_m Observer elevation above sea level in metres. | |
| 338 | #' @param width Output width in pixels. | |
| 339 | #' @param height Output height in pixels. | |
| 340 | #' @param earthshine Default `TRUE`. If `FALSE`, skip the earthshine emissive term. | |
| 341 | #' @param earthshine_albedo Default `0.19`. Effective Earth albedo term used | |
| 342 | #' in the earthshine irradiance approximation. | |
| 343 | #' @param solar_irradiance_w_m2 Default `1300`. Reference solar irradiance at | |
| 344 | #' 1 AU (W/m^2) used to normalize earthshine emission intensity. | |
| 345 | #' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction | |
| 346 | #' coefficient for direct moonlight attenuation. | |
| 347 | #' @param verbose Default `FALSE`. If `TRUE`, print earthshine diagnostics. | |
| 348 | #' @keywords internal | |
| 349 | generate_moon_image_latlong = function( | |
| 350 | datetime, | |
| 351 | lat, | |
| 352 | lon, | |
| 353 | elev_m = 0, | |
| 354 | width = 800, | |
| 355 | height = 800, | |
| 356 | earthshine = TRUE, | |
| 357 | earthshine_albedo = 0.19, | |
| 358 | solar_irradiance_w_m2 = 1300, | |
| 359 | moon_extinction_kV = 0.172, | |
| 360 | verbose = FALSE | |
| 361 | ) { | |
| 362 | 1x | moon_sun_data = swe_dirs_topo_moon_sun( |
| 363 | 1x | datetime = datetime, |
| 364 | 1x | lat = lat, |
| 365 | 1x | lon = lon, |
| 366 | 1x | elev_m = elev_m, |
| 367 | 1x | moon_extinction_kV = moon_extinction_kV |
| 368 | ) | |
| 369 | 1x | dir_moon = normalize(moon_sun_data$moon_ecef_geo) |
| 370 | 1x | dir_sun = -normalize(moon_sun_data$sun_ecef_geo) |
| 371 | 1x | local_up = normalize(moon_sun_data$local_up_geo) |
| 372 | ||
| 373 | 1x | tex = get_moon_texture() |
| 374 | ||
| 375 | 1x | cot = function(x) { |
| 376 | 1x | 1 / tan(x) |
| 377 | } | |
| 378 | ||
| 379 | 1x | cos_phi = clamp_value(sum(dir_moon * dir_sun), -1, 1) |
| 380 | 1x | phi = acos(cos_phi) |
| 381 | ||
| 382 | 1x | earth_phase = pi - phi |
| 383 | 1x | earth_phase = clamp_value(earth_phase, 1e-6, pi - 1e-6) |
| 384 | ||
| 385 | # Paper-based earthshine irradiance model: | |
| 386 | # E_em = A_e * 0.5 * [1 - sin(phase/2) * tan(phase/2) * ln(cot(phase/4))] | |
| 387 | 1x | E_em = earthshine_albedo * |
| 388 | 1x | 0.5 * |
| 389 | 1x | (1 - |
| 390 | 1x | sin(earth_phase / 2) * |
| 391 | 1x | tan(earth_phase / 2) * |
| 392 | 1x | log(cot(earth_phase / 4))) |
| 393 | ||
| 394 | 1x | if (!is.finite(E_em) || E_em < 0) { |
| 395 | ! | E_em = 0 |
| 396 | } | |
| 397 | ||
| 398 | 1x | earth_emissive_intensity = 0 |
| 399 | if ( | |
| 400 | 1x | earthshine && is.finite(solar_irradiance_w_m2) && solar_irradiance_w_m2 > 0 |
| 401 | ) { | |
| 402 | 1x | earth_emissive_intensity = E_em / solar_irradiance_w_m2 |
| 403 | } | |
| 404 | ||
| 405 | # Build a base mesh transform for the moon pass | |
| 406 | 1x | build_moon_mesh = function(material) { |
| 407 | 1x | rayvertex::sphere_mesh(material = material, radius = 0.5) |> |
| 408 | 1x | rayvertex::subdivide_mesh() |> |
| 409 | 1x | rayvertex::rotate_mesh(c(0, -90, 6.68), order_rotation = c(3, 1, 2)) |> |
| 410 | 1x | rayvertex::transform_mesh(rayvertex::lookat_transform( |
| 411 | 1x | pos = -dir_moon, |
| 412 | 1x | look = c(0, 0, 0), |
| 413 | 1x | up = c(0, 0, 1) |
| 414 | )) |> | |
| 415 | 1x | rayvertex::translate_mesh(dir_moon * 10) |
| 416 | } | |
| 417 | ||
| 418 | # Combined sun + earthshine using emissive intensity | |
| 419 | 1x | moon_material = rayvertex::material_list( |
| 420 | 1x | texture_location = tex, |
| 421 | 1x | emissive_texture_location = tex, |
| 422 | 1x | diffuse = c(1, 1, 1), |
| 423 | 1x | emission = c(1, 1, 1), |
| 424 | 1x | diffuse_intensity = 1, |
| 425 | 1x | emission_intensity = earth_emissive_intensity, |
| 426 | 1x | sigma = 10 |
| 427 | ) | |
| 428 | ||
| 429 | 1x | moon_mesh = build_moon_mesh(moon_material) |
| 430 | ||
| 431 | 1x | moon_image = rayvertex::rasterize_scene( |
| 432 | 1x | moon_mesh, |
| 433 | 1x | lookfrom = c(0, 0, 0), |
| 434 | 1x | lookat = dir_moon * 10, |
| 435 | 1x | camera_up = local_up, |
| 436 | 1x | fov = 0, |
| 437 | 1x | ortho_dimensions = c(2, 2), # Keep edge effects away from the visible disk |
| 438 | 1x | light_info = rayvertex::directional_light( |
| 439 | 1x | direction = -dir_sun, |
| 440 | 1x | intensity = 1 |
| 441 | ), | |
| 442 | 1x | transparent_background = TRUE, |
| 443 | 1x | plot = FALSE, |
| 444 | 1x | width = width, |
| 445 | 1x | height = height |
| 446 | ) | |
| 447 | ||
| 448 | 1x | if (verbose) { |
| 449 | ! | message(sprintf( |
| 450 | ! | "phi=%0.4f, earth_phase=%0.4f, E_em=%0.4g W/m^2, emission_intensity=%0.4g", |
| 451 | ! | phi, |
| 452 | ! | earth_phase, |
| 453 | ! | E_em, |
| 454 | ! | earth_emissive_intensity |
| 455 | )) | |
| 456 | } | |
| 457 | ||
| 458 | 1x | moon_image[,, 4][moon_image[,, 4] > 1] = 1 |
| 459 | ||
| 460 | 1x | list( |
| 461 | 1x | moon_luminance_array = moon_image, |
| 462 | 1x | moon_angular_diameter_deg = moon_sun_data$moon_diameter_degrees |
| 463 | ) | |
| 464 | } |
| 1 | #' Attach skymodelr RGB color metadata | |
| 2 | #' | |
| 3 | #' @param image Image array or rayimage image. | |
| 4 | #' @keywords internal | |
| 5 | as_sky_image = function(image) { | |
| 6 | 35x | l_band = attr(image, "L_band", exact = TRUE) |
| 7 | 35x | exr_metadata = attr(image, "exr", exact = TRUE) |
| 8 | 35x | colorspace = attr(image, "colorspace", exact = TRUE) |
| 9 | 35x | white_current = attr(image, "white_current", exact = TRUE) |
| 10 | 35x | prague_rgb_correction = attr(image, "prague_rgb_correction", exact = TRUE) |
| 11 | 35x | prague_rgb_correction_gain = attr( |
| 12 | 35x | image, |
| 13 | 35x | "prague_rgb_correction_gain", |
| 14 | 35x | exact = TRUE |
| 15 | ) | |
| 16 | 35x | prague_rgb_correction_strength = attr( |
| 17 | 35x | image, |
| 18 | 35x | "prague_rgb_correction_strength", |
| 19 | 35x | exact = TRUE |
| 20 | ) | |
| 21 | 35x | image = rayimage::ray_read_image( |
| 22 | 35x | image, |
| 23 | 35x | normalize = FALSE, |
| 24 | 35x | assume_white = if (is.null(white_current)) "D65" else white_current, |
| 25 | 35x | assume_colorspace = rayimage::CS_SRGB |
| 26 | ) | |
| 27 | 35x | if (!is.null(l_band)) { |
| 28 | 19x | attr(image, "L_band") = l_band |
| 29 | } | |
| 30 | 35x | if (!is.null(colorspace)) { |
| 31 | 6x | attr(image, "colorspace") = colorspace |
| 32 | } | |
| 33 | 35x | if (!is.null(white_current)) { |
| 34 | 6x | attr(image, "white_current") = white_current |
| 35 | } | |
| 36 | 35x | if (!is.null(prague_rgb_correction)) { |
| 37 | ! | attr(image, "prague_rgb_correction") = prague_rgb_correction |
| 38 | } | |
| 39 | 35x | if (!is.null(prague_rgb_correction_gain)) { |
| 40 | ! | attr(image, "prague_rgb_correction_gain") = prague_rgb_correction_gain |
| 41 | } | |
| 42 | 35x | if (!is.null(prague_rgb_correction_strength)) { |
| 43 | ! | attr(image, "prague_rgb_correction_strength") = |
| 44 | ! | prague_rgb_correction_strength |
| 45 | } | |
| 46 | 35x | if (!is.list(exr_metadata)) { |
| 47 | 29x | exr_metadata = list() |
| 48 | } | |
| 49 | 35x | attr(image, "exr") = utils::modifyList( |
| 50 | 35x | exr_metadata, |
| 51 | 35x | list(envmap = "latlong") |
| 52 | ) | |
| 53 | 35x | image |
| 54 | } | |
| 55 | ||
| 56 | .skymodelr_d60_xy = c(0.32168, 0.33767) | |
| 57 | ||
| 58 | .skymodelr_exr_rgb_encoding_label = | |
| 59 | "linear sRGB / Rec.709, D65 chromaticities" | |
| 60 | .skymodelr_exr_adopted_neutral_label = "D60" | |
| 61 | ||
| 62 | #' Convert xy chromaticity to XYZ with Y equal to 1 | |
| 63 | #' | |
| 64 | #' @param xy Finite xy chromaticity vector. | |
| 65 | #' @keywords internal | |
| 66 | xy_to_xyz_y1 = function(xy) { | |
| 67 | 35x | if (!is.numeric(xy) || length(xy) != 2L || any(!is.finite(xy))) { |
| 68 | ! | stop("xy must be a finite numeric vector of length 2.", call. = FALSE) |
| 69 | } | |
| 70 | ||
| 71 | 35x | x = xy[1] |
| 72 | 35x | y = xy[2] |
| 73 | ||
| 74 | 35x | if (y <= 0) { |
| 75 | ! | stop("xy y-coordinate must be positive.", call. = FALSE) |
| 76 | } | |
| 77 | ||
| 78 | 35x | c(X = x / y, Y = 1, Z = (1 - x - y) / y) |
| 79 | } | |
| 80 | ||
| 81 | #' Get skymodelr EXR adopted white | |
| 82 | #' | |
| 83 | #' @param exr_adopted_white Adopted white name or XYZ vector. | |
| 84 | #' @keywords internal | |
| 85 | get_skymodelr_adopted_white = function(exr_adopted_white) { | |
| 86 | 16x | if (is.character(exr_adopted_white) && length(exr_adopted_white) == 1L) { |
| 87 | 16x | white_name = toupper(exr_adopted_white) |
| 88 | ||
| 89 | 16x | if (white_name == "D60") { |
| 90 | 16x | return(list( |
| 91 | 16x | name = "D60", |
| 92 | 16x | xy = .skymodelr_d60_xy, |
| 93 | 16x | xyz = xy_to_xyz_y1(.skymodelr_d60_xy) |
| 94 | )) | |
| 95 | } | |
| 96 | ||
| 97 | ! | if (white_name == "D65") { |
| 98 | ! | xy = c(0.3127, 0.3290) |
| 99 | ! | return(list( |
| 100 | ! | name = "D65", |
| 101 | ! | xy = xy, |
| 102 | ! | xyz = xy_to_xyz_y1(xy) |
| 103 | )) | |
| 104 | } | |
| 105 | ||
| 106 | ! | stop( |
| 107 | ! | "exr_adopted_white must be \"D60\", \"D65\", or numeric XYZ with Y = 1.", |
| 108 | ! | call. = FALSE |
| 109 | ) | |
| 110 | } | |
| 111 | ||
| 112 | ! | if (is.numeric(exr_adopted_white) && length(exr_adopted_white) == 3L) { |
| 113 | ! | if (any(!is.finite(exr_adopted_white)) || exr_adopted_white[2] <= 0) { |
| 114 | ! | stop( |
| 115 | ! | "Numeric exr_adopted_white must be finite XYZ with positive Y.", |
| 116 | ! | call. = FALSE |
| 117 | ) | |
| 118 | } | |
| 119 | ||
| 120 | ! | xyz = as.numeric(exr_adopted_white) |
| 121 | ! | xyz = xyz / xyz[2] |
| 122 | ! | sum_xyz = sum(xyz) |
| 123 | ||
| 124 | ! | if (!is.finite(sum_xyz) || sum_xyz <= 0) { |
| 125 | ! | stop( |
| 126 | ! | "Numeric exr_adopted_white must have positive XYZ sum.", |
| 127 | ! | call. = FALSE |
| 128 | ) | |
| 129 | } | |
| 130 | ||
| 131 | ! | xy = c(xyz[1] / sum_xyz, xyz[2] / sum_xyz) |
| 132 | ||
| 133 | ! | return(list( |
| 134 | ! | name = "custom", |
| 135 | ! | xy = xy, |
| 136 | ! | xyz = xyz |
| 137 | )) | |
| 138 | } | |
| 139 | ||
| 140 | ! | stop( |
| 141 | ! | "exr_adopted_white must be \"D60\", \"D65\", or numeric XYZ with Y = 1.", |
| 142 | ! | call. = FALSE |
| 143 | ) | |
| 144 | } | |
| 145 | ||
| 146 | #' Tag skymodelr EXR metadata | |
| 147 | #' | |
| 148 | #' @param sky Sky image array. | |
| 149 | #' @param adopted_white_xy Default `.skymodelr_d60_xy`. Adopted white xy. | |
| 150 | #' @param adopted_white_name Default `.skymodelr_exr_adopted_neutral_label`. | |
| 151 | #' Adopted white name. | |
| 152 | #' @param rgb_colorspace Default `rayimage::CS_SRGB`. RGB colorspace. | |
| 153 | #' @param model_name Default `NULL`. Sky model name. | |
| 154 | #' @param prague_rgb_correction Default `NULL`. Prague RGB correction label. | |
| 155 | #' @keywords internal | |
| 156 | tag_skymodelr_exr_metadata = function( | |
| 157 | sky, | |
| 158 | adopted_white_xy = .skymodelr_d60_xy, | |
| 159 | adopted_white_name = .skymodelr_exr_adopted_neutral_label, | |
| 160 | rgb_colorspace = rayimage::CS_SRGB, | |
| 161 | model_name = NULL, | |
| 162 | prague_rgb_correction = NULL | |
| 163 | ) { | |
| 164 | 19x | l_band = attr(sky, "L_band", exact = TRUE) |
| 165 | 19x | exr = attr(sky, "exr", exact = TRUE) |
| 166 | 19x | prague_rgb_correction_attr = attr( |
| 167 | 19x | sky, |
| 168 | 19x | "prague_rgb_correction", |
| 169 | 19x | exact = TRUE |
| 170 | ) | |
| 171 | 19x | prague_rgb_correction_gain = attr( |
| 172 | 19x | sky, |
| 173 | 19x | "prague_rgb_correction_gain", |
| 174 | 19x | exact = TRUE |
| 175 | ) | |
| 176 | 19x | prague_rgb_correction_strength = attr( |
| 177 | 19x | sky, |
| 178 | 19x | "prague_rgb_correction_strength", |
| 179 | 19x | exact = TRUE |
| 180 | ) | |
| 181 | ||
| 182 | 19x | out = rayimage::ray_read_image( |
| 183 | 19x | sky, |
| 184 | 19x | normalize = FALSE, |
| 185 | 19x | assume_colorspace = rgb_colorspace, |
| 186 | 19x | assume_white = xy_to_xyz_y1(adopted_white_xy) |
| 187 | ) | |
| 188 | ||
| 189 | 19x | if (!is.null(l_band)) { |
| 190 | 14x | attr(out, "L_band") = l_band |
| 191 | } | |
| 192 | 19x | if (!is.null(prague_rgb_correction_attr)) { |
| 193 | ! | attr(out, "prague_rgb_correction") = prague_rgb_correction_attr |
| 194 | } | |
| 195 | 19x | if (!is.null(prague_rgb_correction_gain)) { |
| 196 | ! | attr(out, "prague_rgb_correction_gain") = prague_rgb_correction_gain |
| 197 | } | |
| 198 | 19x | if (!is.null(prague_rgb_correction_strength)) { |
| 199 | ! | attr(out, "prague_rgb_correction_strength") = |
| 200 | ! | prague_rgb_correction_strength |
| 201 | } | |
| 202 | ||
| 203 | 19x | if (!is.list(exr)) { |
| 204 | 3x | exr = list() |
| 205 | } | |
| 206 | ||
| 207 | 19x | exr$skymodelr_rgb_encoding = .skymodelr_exr_rgb_encoding_label |
| 208 | 19x | exr$skymodelr_adopted_neutral = adopted_white_name |
| 209 | 19x | exr$skymodelr_adopted_neutral_xy = sprintf( |
| 210 | 19x | "%.8f %.8f", |
| 211 | 19x | adopted_white_xy[1], |
| 212 | 19x | adopted_white_xy[2] |
| 213 | ) | |
| 214 | ||
| 215 | 19x | if (!is.null(model_name)) { |
| 216 | 16x | exr$skymodelr_model = as.character(model_name) |
| 217 | } | |
| 218 | ||
| 219 | 19x | if (!is.null(prague_rgb_correction)) { |
| 220 | ! | exr$skymodelr_prague_rgb_correction = |
| 221 | ! | as.character(prague_rgb_correction) |
| 222 | } | |
| 223 | ||
| 224 | 19x | attr(out, "exr") = exr |
| 225 | ||
| 226 | 19x | if (inherits(sky, "sky_image") && !inherits(out, "sky_image")) { |
| 227 | ! | class(out) = unique(c("sky_image", class(out))) |
| 228 | } | |
| 229 | ||
| 230 | 19x | out |
| 231 | } | |
| 232 | ||
| 233 | #' Tag generated sky EXR metadata | |
| 234 | #' | |
| 235 | #' @param sky Sky image array. | |
| 236 | #' @param hosek Whether the Hosek-Wilkie model was used. | |
| 237 | #' @param exr_metadata Whether to attach skymodelr EXR metadata. | |
| 238 | #' @param exr_adopted_white Adopted white name or XYZ vector. | |
| 239 | #' @keywords internal | |
| 240 | tag_generated_sky_exr_metadata = function( | |
| 241 | sky, | |
| 242 | hosek, | |
| 243 | exr_metadata, | |
| 244 | exr_adopted_white | |
| 245 | ) { | |
| 246 | 18x | if (!isTRUE(exr_metadata)) { |
| 247 | 2x | return(sky) |
| 248 | } | |
| 249 | ||
| 250 | 16x | adopted_white = get_skymodelr_adopted_white(exr_adopted_white) |
| 251 | ||
| 252 | 16x | model_name = if (isTRUE(hosek)) { |
| 253 | 16x | "Hosek-Wilkie" |
| 254 | } else { | |
| 255 | ! | "Prague" |
| 256 | } | |
| 257 | ||
| 258 | 16x | prague_correction_label = NULL |
| 259 | ||
| 260 | 16x | if (!isTRUE(hosek)) { |
| 261 | ! | prague_correction_label = attr( |
| 262 | ! | sky, |
| 263 | ! | "prague_rgb_correction", |
| 264 | ! | exact = TRUE |
| 265 | ) | |
| 266 | ||
| 267 | ! | if (is.null(prague_correction_label)) { |
| 268 | ! | prague_correction_label = "none" |
| 269 | } | |
| 270 | } | |
| 271 | ||
| 272 | 16x | tag_skymodelr_exr_metadata( |
| 273 | 16x | sky, |
| 274 | 16x | adopted_white_xy = adopted_white$xy, |
| 275 | 16x | adopted_white_name = adopted_white$name, |
| 276 | 16x | rgb_colorspace = rayimage::CS_SRGB, |
| 277 | 16x | model_name = model_name, |
| 278 | 16x | prague_rgb_correction = prague_correction_label |
| 279 | ) | |
| 280 | } | |
| 281 | ||
| 282 | #' Build EXR metadata for skymodelr RGB output | |
| 283 | #' | |
| 284 | #' @param image Default `NULL`. Image to read colorspace and white metadata from. | |
| 285 | #' @keywords internal | |
| 286 | sky_exr_metadata = function(image = NULL) { | |
| 287 | 6x | colorspace = attr(image, "colorspace", exact = TRUE) |
| 288 | 6x | white_current = attr(image, "white_current", exact = TRUE) |
| 289 | 6x | exr_metadata = attr(image, "exr", exact = TRUE) |
| 290 | ||
| 291 | 6x | if (is.null(colorspace)) { |
| 292 | ! | colorspace = rayimage::CS_SRGB |
| 293 | } | |
| 294 | 6x | if (is.null(white_current)) { |
| 295 | ! | white_current = colorspace$white_xyz |
| 296 | } | |
| 297 | 6x | if (!is.list(exr_metadata)) { |
| 298 | ! | exr_metadata = list() |
| 299 | } | |
| 300 | ||
| 301 | 6x | colorspace_white_xyz = colorspace$white_xyz |
| 302 | 6x | colorspace_white_xy = unname(c( |
| 303 | 6x | colorspace_white_xyz[1] / sum(colorspace_white_xyz), |
| 304 | 6x | colorspace_white_xyz[2] / sum(colorspace_white_xyz) |
| 305 | )) | |
| 306 | 6x | adopted_white_xy = unname(c( |
| 307 | 6x | white_current[1] / sum(white_current), |
| 308 | 6x | white_current[2] / sum(white_current) |
| 309 | )) | |
| 310 | ||
| 311 | 6x | utils::modifyList( |
| 312 | 6x | exr_metadata, |
| 313 | 6x | list( |
| 314 | 6x | chromaticities = list( |
| 315 | 6x | red = unname(colorspace$primaries$r), |
| 316 | 6x | green = unname(colorspace$primaries$g), |
| 317 | 6x | blue = unname(colorspace$primaries$b), |
| 318 | 6x | white = colorspace_white_xy |
| 319 | ), | |
| 320 | 6x | adoptedNeutral = adopted_white_xy, |
| 321 | 6x | envmap = "latlong" |
| 322 | ) | |
| 323 | ) | |
| 324 | } | |
| 325 | ||
| 326 | #' Keep EXR metadata fields supported by libopenexr | |
| 327 | #' | |
| 328 | #' @param metadata EXR metadata list. | |
| 329 | #' @keywords internal | |
| 330 | filter_supported_exr_metadata = function(metadata) { | |
| 331 | 6x | metadata[intersect( |
| 332 | 6x | names(metadata), |
| 333 | 6x | c("chromaticities", "adoptedNeutral", "whiteLuminance", "envmap") |
| 334 | )] | |
| 335 | } | |
| 336 | ||
| 337 | #' Write a skymodelr image with EXR color metadata | |
| 338 | #' | |
| 339 | #' @param image Image array or rayimage image. | |
| 340 | #' @param filename Destination image path. | |
| 341 | #' @param ... Additional arguments passed to [rayimage::ray_write_image()]. | |
| 342 | #' @keywords internal | |
| 343 | write_sky_image = function(image, filename, ...) { | |
| 344 | 3x | dots = list(...) |
| 345 | 3x | image_to_write = image |
| 346 | 3x | if (tolower(tools::file_ext(filename)) == "exr") { |
| 347 | 3x | metadata = dots$metadata |
| 348 | 3x | if (!is.null(metadata) && !is.list(metadata)) { |
| 349 | ! | stop("EXR metadata must be a list.", call. = FALSE) |
| 350 | } | |
| 351 | 3x | dots$metadata = filter_supported_exr_metadata( |
| 352 | 3x | if (is.null(metadata)) { |
| 353 | 3x | sky_exr_metadata(image) |
| 354 | } else { | |
| 355 | ! | utils::modifyList(sky_exr_metadata(image), metadata) |
| 356 | } | |
| 357 | ) | |
| 358 | 3x | attr(image_to_write, "exr") = filter_supported_exr_metadata( |
| 359 | 3x | attr(image_to_write, "exr", exact = TRUE) |
| 360 | ) | |
| 361 | } | |
| 362 | ||
| 363 | 3x | do.call( |
| 364 | 3x | rayimage::ray_write_image, |
| 365 | 3x | c( |
| 366 | 3x | list(image = image_to_write, filename = filename), |
| 367 | 3x | dots |
| 368 | ) | |
| 369 | ) | |
| 370 | } |
| 1 | #' Generate a bright-planet image array | |
| 2 | #' | |
| 3 | #' @description Build a planetary luminance map aligned with the sky dome for | |
| 4 | #' compositing within [generate_sky_latlong()]. | |
| 5 | #' | |
| 6 | #' @param datetime POSIXct timestamp used for ephemerides. | |
| 7 | #' @param lon Observer longitude in degrees (east positive). | |
| 8 | #' @param lat Observer latitude in degrees. | |
| 9 | #' @param filename Default `NA`. Destination image path to write. When `NA`, the | |
| 10 | #' image array is returned without writing. | |
| 11 | #' @param resolution Default `2048`. Map half-width (image is `2 * resolution` by `resolution`). | |
| 12 | #' @param turbidity Atmospheric turbidity for extinction modelling. | |
| 13 | #' @param ozone_du Column ozone (Dobson Units) for colour shifts. | |
| 14 | #' @param altitude Observer altitude in metres. | |
| 15 | #' @param color Render RGB (`TRUE`) stars or monochrome (`FALSE`). | |
| 16 | #' @param planet_width Approximate point-spread size for planets in pixels. | |
| 17 | #' @param upper_hemisphere_only If `TRUE`, mask pixels below the horizon. | |
| 18 | #' @param atmosphere_effects If `TRUE`, apply atmospheric extinction. | |
| 19 | #' @param number_cores CPU threads used for rendering. | |
| 20 | #' @param verbose Emit diagnostic output when `TRUE`. | |
| 21 | #' | |
| 22 | #' @return Either the image array, or the array is invisibly returned if a file | |
| 23 | #' is written. The array has dimensions `(resolution, 2 * resolution, 4)`. | |
| 24 | #' @note Writing to non-EXR formats will introduce precision loss because HDR | |
| 25 | #' data are quantised to the destination format, and low dynamic range outputs like PNG | |
| 26 | #' and JPEG files will not represent the true luminosity values encoded in the array. | |
| 27 | #' | |
| 28 | #' @export | |
| 29 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 30 | #' # Basic star field over Washington, DC at a fixed time | |
| 31 | #' generate_planets( | |
| 32 | #' datetime = as.POSIXct("2025-03-21 02:20:00", tz = "America/New_York"), | |
| 33 | #' lon = -77.0369, | |
| 34 | #' lat = 38.9072, | |
| 35 | #' resolution = 400, | |
| 36 | #' color = TRUE, | |
| 37 | #' planet_width = 1, | |
| 38 | #' atmosphere_effects = TRUE, | |
| 39 | #' upper_hemisphere_only = TRUE, | |
| 40 | #' number_cores = 2 | |
| 41 | #' ) |> | |
| 42 | #' rayimage::plot_image() | |
| 43 | generate_planets = function( | |
| 44 | datetime, | |
| 45 | lon, | |
| 46 | lat, | |
| 47 | filename = NA, | |
| 48 | resolution = 2048, | |
| 49 | turbidity = 3.0, | |
| 50 | ozone_du = 300.0, | |
| 51 | altitude = 0.0, | |
| 52 | color = FALSE, | |
| 53 | planet_width = 1, | |
| 54 | upper_hemisphere_only = TRUE, | |
| 55 | atmosphere_effects = TRUE, | |
| 56 | number_cores = 1, | |
| 57 | verbose = FALSE | |
| 58 | ) { | |
| 59 | 1x | if (!inherits(datetime, "POSIXct")) { |
| 60 | ! | stop("datetime must be POSIXct in UTC") |
| 61 | } | |
| 62 | 1x | attr(datetime, "tzone") = "UTC" |
| 63 | 1x | jd = jd_utc(datetime) |
| 64 | ||
| 65 | 1x | planet_temp = swe_dirs_topo_planets_df( |
| 66 | 1x | datetime = datetime, |
| 67 | 1x | lat = lat, |
| 68 | 1x | lon = lon, |
| 69 | 1x | elev_m = altitude |
| 70 | ) | |
| 71 | 1x | if (verbose) { |
| 72 | ! | print(planet_temp) |
| 73 | } | |
| 74 | 1x | planet_rgb = make_starfield_rcpp( |
| 75 | 1x | stars = planet_temp, |
| 76 | 1x | resolution = resolution, |
| 77 | 1x | lon_deg = lon, |
| 78 | 1x | lat_deg = lat, |
| 79 | 1x | jd = jd, |
| 80 | 1x | use_rgb = color, |
| 81 | 1x | turbidity = turbidity, |
| 82 | 1x | ozone_du = ozone_du, |
| 83 | 1x | altitude = altitude, |
| 84 | 1x | star_width = planet_width, |
| 85 | 1x | atmosphere_effects = atmosphere_effects, |
| 86 | 1x | upper_hemisphere_only = upper_hemisphere_only, |
| 87 | 1x | number_cores = number_cores |
| 88 | ) | |
| 89 | 1x | planet_array = array(0, dim = c(resolution, resolution * 2, 4)) |
| 90 | 1x | planet_array[,, 1:3] = planet_rgb |
| 91 | 1x | planet_array[,, 4] = 1 |
| 92 | 1x | planet_array = rayimage::ray_read_image( |
| 93 | 1x | planet_array, |
| 94 | 1x | assume_white = "D65", |
| 95 | 1x | assume_colorspace = rayimage::CS_SRGB |
| 96 | ) | |
| 97 | 1x | if (!is.na(filename)) { |
| 98 | ! | warn_precision_loss(filename) |
| 99 | ! | write_sky_image(planet_array, filename) |
| 100 | ! | return(invisible(planet_array)) |
| 101 | } else { | |
| 102 | 1x | return(planet_array) |
| 103 | } | |
| 104 | } |
| 1 | # --------------------------------------------------------------------------- | |
| 2 | # Helpers to convert POSIXct to Julian Date (UTC noon 1 Jan 2000 = 2451545). | |
| 3 | #' Convert POSIXct timestamps to Julian Date | |
| 4 | #' | |
| 5 | #' @description Transform a POSIXct time value into an astronomical Julian Date | |
| 6 | #' (days since noon UTC 1 Jan 4713 BCE). | |
| 7 | #' @param time_utc POSIXct vector in UTC. | |
| 8 | #' @keywords internal | |
| 9 | jd_utc = function(time_utc) { | |
| 10 | 2x | unclass(time_utc) / 86400 + 2440587.5 # Unix epoch to JD |
| 11 | } | |
| 12 | ||
| 13 | spec_to_bv = function(spec) { | |
| 14 | 9110x | if (is.na(spec) || !nzchar(spec)) { |
| 15 | ! | return(NA_real_) |
| 16 | } | |
| 17 | 9110x | s = toupper(trimws(spec)) |
| 18 | 9110x | letter = substr(s, 1, 1) |
| 19 | 9110x | base = c( |
| 20 | 9110x | O = -0.33, |
| 21 | 9110x | B = -0.30, |
| 22 | 9110x | A = 0.00, |
| 23 | 9110x | F = 0.30, |
| 24 | 9110x | G = 0.58, |
| 25 | 9110x | K = 0.81, |
| 26 | 9110x | M = 1.40 |
| 27 | ) | |
| 28 | 9110x | if (!letter %in% names(base)) { |
| 29 | 50x | return(NA_real_) |
| 30 | } | |
| 31 | 9060x | digit = suppressWarnings(as.numeric(substr(s, 2, 2))) |
| 32 | 9060x | if (!is.finite(digit)) { |
| 33 | 61x | digit = 0 |
| 34 | } | |
| 35 | 9060x | digit = max(0, min(9, digit)) |
| 36 | 9060x | next_letter = switch( |
| 37 | 9060x | letter, |
| 38 | 9060x | O = "B", |
| 39 | 9060x | B = "A", |
| 40 | 9060x | A = "F", |
| 41 | 9060x | F = "G", |
| 42 | 9060x | G = "K", |
| 43 | 9060x | K = "M", |
| 44 | 9060x | M = NA |
| 45 | ) | |
| 46 | 9060x | next_base = if (!is.na(next_letter)) { |
| 47 | 8551x | base[[next_letter]] |
| 48 | } else { | |
| 49 | 509x | base[["M"]] + 0.35 |
| 50 | } | |
| 51 | 9060x | b_v = base[[letter]] + (digit / 10) * (next_base - base[[letter]]) |
| 52 | 9060x | max(-0.4, min(2.0, b_v)) |
| 53 | } | |
| 54 | ||
| 55 | stars_with_bv = local({ | |
| 56 | cache = NULL | |
| 57 | function() { | |
| 58 | 1x | if (!is.null(cache)) { |
| 59 | ! | return(cache) |
| 60 | } | |
| 61 | 1x | star_df = skymodelr::stars |
| 62 | 1x | if (!("b_v" %in% names(star_df))) { |
| 63 | 1x | star_df$b_v = vapply(star_df$spec, spec_to_bv, numeric(1)) |
| 64 | } | |
| 65 | 1x | cache = star_df |
| 66 | 1x | cache |
| 67 | } | |
| 68 | }) | |
| 69 | ||
| 70 | # --------------------------------------------------------------------------- | |
| 71 | #' Generate a star-field array aligned with `generate_sky()` | |
| 72 | #' | |
| 73 | #' @description Render a star map for a given observer location, time, and atmospheric | |
| 74 | #' conditions so it can be composited with [generate_sky()]. Returns a | |
| 75 | #' `(resolution, 2 * resolution, 4)` array with an opaque alpha channel. An | |
| 76 | #' image file is written only when `filename` is supplied. | |
| 77 | #' | |
| 78 | #' @param datetime `POSIXct` timestamp used to compute local sidereal time. | |
| 79 | #' @param lon Observer longitude in degrees (east positive). | |
| 80 | #' @param lat Observer latitude in degrees. | |
| 81 | #' @param filename Default `NA`. Path to an image file to write. If `NA`, the | |
| 82 | #' image array is returned without writing. | |
| 83 | #' @param resolution Default `2048`. Map half-width; the output image is `2 * resolution` by `resolution`. | |
| 84 | #' @param turbidity Default `3.0`. Atmospheric turbidity controlling aerosol optical depth for extinction/reddening. | |
| 85 | #' @param ozone_du Default `300.0`. Column ozone in Dobson Units used in atmospheric absorption. | |
| 86 | #' @param altitude Default `0.0`. Observer altitude above mean sea level in meters. | |
| 87 | #' @param color Default `TRUE`. If `TRUE`, render RGB star colors; if `FALSE`, render monochrome luminance. | |
| 88 | #' @param star_width Default `1`. Approximate stellar point-spread size in pixels (controls apparent star sharpness). | |
| 89 | #' @param upper_hemisphere_only Default `TRUE`. If `TRUE`, pixels below the local horizon are suppressed to match `generate_sky()`'s visible hemisphere. | |
| 90 | #' @param atmosphere_effects Default `TRUE`. If `TRUE`, apply atmospheric extinction and color shift using `turbidity`, `ozone_du`, and `altitude`. | |
| 91 | #' @param number_cores Default `1`. Number of CPU threads to use. | |
| 92 | #' | |
| 93 | #' @return Either the image array, or the array is invisibly returned if a file | |
| 94 | #' is written. The array has dimensions `(resolution, 2 * resolution, 4)`. | |
| 95 | #' @note Writing to non-EXR formats will introduce precision loss because HDR | |
| 96 | #' data are quantised to the destination format, and low dynamic range outputs like PNG | |
| 97 | #' and JPEG files will not represent the true luminosity values encoded in the array. | |
| 98 | #' | |
| 99 | #' @export | |
| 100 | #' @examples | |
| 101 | #' star_map = generate_stars( | |
| 102 | #' resolution = 8, | |
| 103 | #' lon = -77.0369, | |
| 104 | #' lat = 38.9072, | |
| 105 | #' datetime = as.POSIXct("2025-03-21 02:20:00", tz = "UTC"), | |
| 106 | #' atmosphere_effects = FALSE, | |
| 107 | #' number_cores = 1 | |
| 108 | #' ) | |
| 109 | #' dim(star_map) | |
| 110 | #' | |
| 111 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 112 | #' # Note: exposure has been increased for all examples (via white_point) for | |
| 113 | #' # ease of visibility in documentation | |
| 114 | #' | |
| 115 | #' # Basic star field over Washington, DC at a fixed time | |
| 116 | #' generate_stars( | |
| 117 | #' resolution = 400, | |
| 118 | #' lon = -77.0369, | |
| 119 | #' lat = 38.9072, | |
| 120 | #' datetime = as.POSIXct("2025-03-21 02:20:00", tz = "America/New_York"), | |
| 121 | #' color = TRUE, | |
| 122 | #' star_width = 1, | |
| 123 | #' atmosphere_effects = TRUE, | |
| 124 | #' upper_hemisphere_only = TRUE, | |
| 125 | #' number_cores = 2 | |
| 126 | #' ) |> | |
| 127 | #' rayimage::plot_image() | |
| 128 | #' | |
| 129 | #' # Monochrome stars, no atmospheric extinction/reddening, full sphere | |
| 130 | #' generate_stars( | |
| 131 | #' resolution = 400, | |
| 132 | #' lon = -122.4194, | |
| 133 | #' lat = 37.7749, | |
| 134 | #' datetime = as.POSIXct("2025-06-01 08:00:00", tz = "UTC"), | |
| 135 | #' color = FALSE, | |
| 136 | #' star_width = 1, | |
| 137 | #' upper_hemisphere_only = FALSE, | |
| 138 | #' atmosphere_effects = FALSE | |
| 139 | #' ) |> | |
| 140 | #' rayimage::plot_image() | |
| 141 | #' | |
| 142 | #' # Sharper stars (smaller PSF) with ozone/turbidity and altitude | |
| 143 | #' generate_stars( | |
| 144 | #' resolution = 400, | |
| 145 | #' lon = 10, | |
| 146 | #' lat = 45, | |
| 147 | #' datetime = as.POSIXct("2025-12-01 22:00:00", tz = "UTC"), | |
| 148 | #' star_width = 0.5, | |
| 149 | #' turbidity = 3.5, | |
| 150 | #' ozone_du = 320, | |
| 151 | #' altitude = 1000, | |
| 152 | #' color = TRUE | |
| 153 | #' ) |> | |
| 154 | #' rayimage::plot_image() | |
| 155 | generate_stars = function( | |
| 156 | lon, | |
| 157 | lat, | |
| 158 | datetime, | |
| 159 | filename = NA, | |
| 160 | resolution = 2048, | |
| 161 | turbidity = 3.0, | |
| 162 | ozone_du = 300.0, | |
| 163 | altitude = 0.0, | |
| 164 | color = TRUE, | |
| 165 | star_width = 1, | |
| 166 | upper_hemisphere_only = TRUE, | |
| 167 | atmosphere_effects = TRUE, | |
| 168 | number_cores = 1 | |
| 169 | ) { | |
| 170 | 1x | if (!inherits(datetime, "POSIXct")) { |
| 171 | ! | stop("datetime must be POSIXct in UTC") |
| 172 | } | |
| 173 | 1x | attr(datetime, "tzone") = "UTC" |
| 174 | 1x | jd = jd_utc(datetime) |
| 175 | ||
| 176 | 1x | star_rgb = make_starfield_rcpp( |
| 177 | 1x | stars = stars_with_bv(), |
| 178 | 1x | resolution = resolution, |
| 179 | 1x | lon_deg = lon, |
| 180 | 1x | lat_deg = lat, |
| 181 | 1x | jd = jd, |
| 182 | 1x | use_rgb = color, |
| 183 | 1x | turbidity = turbidity, |
| 184 | 1x | ozone_du = ozone_du, |
| 185 | 1x | altitude = altitude, |
| 186 | 1x | star_width = star_width, |
| 187 | 1x | atmosphere_effects = atmosphere_effects, |
| 188 | 1x | upper_hemisphere_only = upper_hemisphere_only, |
| 189 | 1x | number_cores = number_cores |
| 190 | ) | |
| 191 | 1x | star_array = array(0, dim = c(resolution, resolution * 2, 4)) |
| 192 | 1x | star_array[,, 1:3] = star_rgb |
| 193 | 1x | star_array[,, 4] = 1 |
| 194 | 1x | star_array = rayimage::ray_read_image( |
| 195 | 1x | star_array, |
| 196 | 1x | assume_white = "D65", |
| 197 | 1x | assume_colorspace = rayimage::CS_SRGB |
| 198 | ) | |
| 199 | 1x | if (!is.na(filename)) { |
| 200 | ! | warn_precision_loss(filename) |
| 201 | ! | write_sky_image(star_array, filename) |
| 202 | ! | return(invisible(star_array)) |
| 203 | } else { | |
| 204 | 1x | return(star_array) |
| 205 | } | |
| 206 | } |
| 1 | warn_precision_loss = function(path) { | |
| 2 | 3x | ext = tools::file_ext(path) |
| 3 | 3x | if (nzchar(ext) && tolower(ext) != "exr") { |
| 4 | ! | message( |
| 5 | ! | "Note: writing to non-EXR formats may introduce precision loss and unphysically clamp luminosity values." |
| 6 | ) | |
| 7 | } | |
| 8 | } |
| 1 | #' Moon disk solid angle in steradians | |
| 2 | #' | |
| 3 | #' @param diameter_deg Angular diameter in degrees. | |
| 4 | #' @return Solid angle in steradians. | |
| 5 | #' @keywords internal | |
| 6 | moon_solid_angle_sr = function(diameter_deg = 0.533) { | |
| 7 | ! | r = (diameter_deg * 0.5) * pi / 180 |
| 8 | ! | 2 * pi * (1 - cos(r)) |
| 9 | } | |
| 10 | ||
| 11 | cie_1931_2deg = local({ | |
| 12 | cache = NULL | |
| 13 | function() { | |
| 14 | 46x | if (is.null(cache)) { |
| 15 | 46x | cache = cie_1931_2deg_rcpp() |
| 16 | } | |
| 17 | 46x | cache |
| 18 | } | |
| 19 | }) | |
| 20 | ||
| 21 | trapezoid_weights = function(lambda_nm) { | |
| 22 | 47x | n = length(lambda_nm) |
| 23 | 47x | if (n == 0) { |
| 24 | ! | return(numeric(0)) |
| 25 | } | |
| 26 | 47x | if (n == 1) { |
| 27 | ! | return(1) |
| 28 | } | |
| 29 | 47x | w = numeric(n) |
| 30 | 47x | w[1] = (lambda_nm[2] - lambda_nm[1]) / 2 |
| 31 | 47x | for (i in 2:(n - 1)) { |
| 32 | 22043x | w[i] = (lambda_nm[i + 1] - lambda_nm[i - 1]) / 2 |
| 33 | } | |
| 34 | 47x | w[n] = (lambda_nm[n] - lambda_nm[n - 1]) / 2 |
| 35 | 47x | w |
| 36 | } | |
| 37 | ||
| 38 | xyz_to_srgb = function(XYZ) { | |
| 39 | 23x | M = matrix( |
| 40 | 23x | c( |
| 41 | 23x | 3.2404542, |
| 42 | 23x | -1.5371385, |
| 43 | 23x | -0.4985314, |
| 44 | 23x | -0.9692660, |
| 45 | 23x | 1.8760108, |
| 46 | 23x | 0.0415560, |
| 47 | 23x | 0.0556434, |
| 48 | 23x | -0.2040259, |
| 49 | 23x | 1.0572252 |
| 50 | ), | |
| 51 | 23x | nrow = 3, |
| 52 | 23x | byrow = TRUE |
| 53 | ) | |
| 54 | 23x | as.numeric(M %*% XYZ) |
| 55 | } | |
| 56 | ||
| 57 | #' Compute a unit RGB vector for a chosen SPD | |
| 58 | #' | |
| 59 | #' @param spd_type SPD shape. Either `"D65"` or `"BB5778"`. | |
| 60 | #' @return Numeric vector length 3, normalized so sum equals 1. | |
| 61 | #' @keywords internal | |
| 62 | compute_spd_rgb_unit = function(spd_type = c("D65", "BB5778")) { | |
| 63 | 22x | spd_type = match.arg(spd_type) |
| 64 | 22x | cie = cie_1931_2deg() |
| 65 | 22x | lambda_nm = cie$lambda_nm |
| 66 | 22x | spd = spd_values_rcpp(lambda_nm, spd_type) |
| 67 | 22x | w = trapezoid_weights(lambda_nm) |
| 68 | 22x | X = sum(spd * cie$x_bar * w) |
| 69 | 22x | Y = sum(spd * cie$y_bar * w) |
| 70 | 22x | Z = sum(spd * cie$z_bar * w) |
| 71 | 22x | rgb = xyz_to_srgb(c(X, Y, Z)) |
| 72 | 22x | rgb[!is.finite(rgb)] = 0 |
| 73 | 22x | rgb = pmax(rgb, 0) |
| 74 | 22x | total = sum(rgb) |
| 75 | 22x | if (!is.finite(total) || total <= 0) { |
| 76 | ! | return(c(0, 0, 0)) |
| 77 | } | |
| 78 | 22x | rgb / total |
| 79 | } | |
| 80 | ||
| 81 | #' Compute effective luminous efficacy for a chosen SPD | |
| 82 | #' | |
| 83 | #' @param spd_type SPD shape. Either `"D65"` or `"BB5778"`. | |
| 84 | #' @param wavelength_grid Optional numeric vector of wavelengths (nm). | |
| 85 | #' @param V_lambda Optional numeric vector of photopic V(lambda) samples. | |
| 86 | #' @return Effective luminous efficacy in lm/W. | |
| 87 | #' @keywords internal | |
| 88 | compute_K_eff = function( | |
| 89 | spd_type = c("D65", "BB5778"), | |
| 90 | wavelength_grid = NULL, | |
| 91 | V_lambda = NULL | |
| 92 | ) { | |
| 93 | 22x | spd_type = match.arg(spd_type) |
| 94 | 22x | if (is.null(wavelength_grid) || is.null(V_lambda)) { |
| 95 | 22x | cie = cie_1931_2deg() |
| 96 | 22x | wavelength_grid = cie$lambda_nm |
| 97 | 22x | V_lambda = cie$y_bar |
| 98 | } | |
| 99 | 22x | if (length(wavelength_grid) != length(V_lambda)) { |
| 100 | ! | stop("wavelength_grid and V_lambda must have the same length.") |
| 101 | } | |
| 102 | 22x | spd = spd_values_rcpp(wavelength_grid, spd_type) |
| 103 | 22x | w = trapezoid_weights(wavelength_grid) |
| 104 | 22x | num = sum(spd * V_lambda * w) |
| 105 | 22x | den = sum(spd * w) |
| 106 | 22x | if (!is.finite(num) || !is.finite(den) || den <= 0) { |
| 107 | ! | return(NA_real_) |
| 108 | } | |
| 109 | 22x | 683 * num / den |
| 110 | } | |
| 111 | ||
| 112 | #' Convert photometric illuminance to radiometric irradiance | |
| 113 | #' | |
| 114 | #' @param E_v_lux Illuminance in lux. | |
| 115 | #' @param K_eff Effective luminous efficacy in lm/W. | |
| 116 | #' @return Irradiance in W/m^2. | |
| 117 | #' @keywords internal | |
| 118 | lux_to_radiometric_irradiance = function(E_v_lux, K_eff) { | |
| 119 | 7x | E_v_lux / K_eff |
| 120 | } |
| 1 | #' List cached sky data files | |
| 2 | #' | |
| 3 | #' @description | |
| 4 | #' Lists files cached by [download_sky_data()] under | |
| 5 | #' `tools::R_user_dir("skymodelr", "data")`. | |
| 6 | #' | |
| 7 | #' @returns A data frame with columns `file`, `path`, `size`, and `modified`. | |
| 8 | #' @export | |
| 9 | #' | |
| 10 | #' @examples | |
| 11 | #' list_sky_data() | |
| 12 | list_sky_data = function() { | |
| 13 | 5x | cache_dir = prague_coef_cache_dir() |
| 14 | 5x | empty = data.frame( |
| 15 | 5x | file = character(), |
| 16 | 5x | path = character(), |
| 17 | 5x | size = numeric(), |
| 18 | 5x | modified = as.POSIXct(character()), |
| 19 | 5x | stringsAsFactors = FALSE |
| 20 | ) | |
| 21 | ||
| 22 | 5x | if (!dir.exists(cache_dir)) { |
| 23 | ! | return(empty) |
| 24 | } | |
| 25 | ||
| 26 | 5x | paths = list.files(cache_dir, full.names = TRUE, no.. = TRUE) |
| 27 | 5x | if (!length(paths)) { |
| 28 | 1x | return(empty) |
| 29 | } | |
| 30 | ||
| 31 | 4x | info = file.info(paths) |
| 32 | 4x | keep = !is.na(info$isdir) & !info$isdir |
| 33 | 4x | if (!any(keep)) { |
| 34 | ! | return(empty) |
| 35 | } | |
| 36 | ||
| 37 | 4x | paths = paths[keep] |
| 38 | 4x | info = info[keep, , drop = FALSE] |
| 39 | ||
| 40 | 4x | data.frame( |
| 41 | 4x | file = basename(paths), |
| 42 | 4x | path = normalizePath(paths, winslash = "/", mustWork = FALSE), |
| 43 | 4x | size = info$size, |
| 44 | 4x | modified = info$mtime, |
| 45 | 4x | stringsAsFactors = FALSE, |
| 46 | 4x | row.names = NULL |
| 47 | ) | |
| 48 | } | |
| 49 | ||
| 50 | #' Clear cached sky data files | |
| 51 | #' | |
| 52 | #' @description | |
| 53 | #' Removes files cached by [download_sky_data()] under | |
| 54 | #' `tools::R_user_dir("skymodelr", "data")`. | |
| 55 | #' | |
| 56 | #' @param files Default `NULL`. Character vector of cached file basenames to remove. | |
| 57 | #' @param ask Default `interactive()`. Whether to ask for confirmation before deleting files. | |
| 58 | #' | |
| 59 | #' @returns Invisibly, the paths successfully removed. | |
| 60 | #' @export | |
| 61 | #' | |
| 62 | #' @examplesIf interactive() | |
| 63 | #' clear_sky_data() | |
| 64 | clear_sky_data = function(files = NULL, ask = interactive()) { | |
| 65 | 3x | cache_dir = prague_coef_cache_dir() |
| 66 | 3x | if (!dir.exists(cache_dir)) { |
| 67 | ! | return(invisible(character())) |
| 68 | } | |
| 69 | ||
| 70 | 3x | cached = list_sky_data() |
| 71 | 3x | if (is.null(files)) { |
| 72 | ! | paths = cached$path |
| 73 | } else { | |
| 74 | 3x | requested = unique(basename(files)) |
| 75 | 3x | requested = requested[nzchar(requested) & !requested %in% c(".", "..")] |
| 76 | 3x | paths = cached$path[cached$file %in% requested] |
| 77 | } | |
| 78 | ||
| 79 | 3x | if (!length(paths)) { |
| 80 | 2x | message("No matching cached sky data files found.") |
| 81 | 2x | return(invisible(character())) |
| 82 | } | |
| 83 | ||
| 84 | 1x | if (isTRUE(ask)) { |
| 85 | ! | prompt = sprintf( |
| 86 | ! | "Remove %d cached sky data file%s?", |
| 87 | ! | length(paths), |
| 88 | ! | if (length(paths) == 1) "" else "s" |
| 89 | ) | |
| 90 | ! | if (!isTRUE(utils::askYesNo(prompt, default = FALSE))) { |
| 91 | ! | return(invisible(character())) |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 95 | 1x | unlink(paths) |
| 96 | 1x | removed = paths[!file.exists(paths)] |
| 97 | 1x | invisible(removed) |
| 98 | } |
| 1 | #' Download Prague Sky Model Coefficient Data | |
| 2 | #' | |
| 3 | #' This model which allows for sun angles below the horizon, | |
| 4 | #' wide spectral ranges including infrared, polarization, as well | |
| 5 | #' rendering at altitude) need to download a coefficient file. There are three versions | |
| 6 | #' of this dataset, listed here in order of increasing size: | |
| 7 | #' | |
| 8 | #' | Argument combination | File | Size | | |
| 9 | #' |------------------------------------|--------------------------------------|----------------| | |
| 10 | #' | `sea_level = TRUE, wide_spectrum = FALSE` | `SkyModelDatasetGround.dat` | 107MB | | |
| 11 | #' | `sea_level = TRUE, wide_spectrum = TRUE` | `PragueSkyModelDatasetGroundInfra.dat` | 574MB | | |
| 12 | #' | `sea_level = FALSE` | `SkyModelDataset.dat` | 2.4GB | | |
| 13 | #' | |
| 14 | #' | |
| 15 | #' @param sea_level Default `TRUE`. Download the sea-level-only data. | |
| 16 | #' Set to `FALSE` to download the full-altitude dataset. | |
| 17 | #' @param wide_spectrum Default `FALSE`. If `TRUE`, downloads the | |
| 18 | #' wide-spectrum (55-channel, polarised) version. Valid only when `sea_level = TRUE`. | |
| 19 | #' | |
| 20 | #' @returns Invisibly, the full path to the data file. | |
| 21 | #' @export | |
| 22 | #' | |
| 23 | #' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true") | |
| 24 | #' # Standard (11-channel, sea-level) coefficients | |
| 25 | #' download_sky_data() | |
| 26 | #' | |
| 27 | #' # Wide-spectrum sea-level coefficients | |
| 28 | #' download_sky_data(wide_spectrum = TRUE) | |
| 29 | #' | |
| 30 | #' # Full altitude-range coefficients | |
| 31 | #' download_sky_data(sea_level = FALSE) | |
| 32 | download_sky_data = function(sea_level = TRUE, wide_spectrum = FALSE) { | |
| 33 | ! | if (wide_spectrum && !sea_level) { |
| 34 | ! | stop("`wide_spectrum = TRUE` is only valid when `sea_level = TRUE`.") |
| 35 | } | |
| 36 | ||
| 37 | ! | file_info = prague_coef_info( |
| 38 | ! | sea_level = sea_level, |
| 39 | ! | wide_spectrum = wide_spectrum |
| 40 | ) | |
| 41 | ||
| 42 | ! | cache_dir = prague_coef_cache_dir() |
| 43 | ! | if (!dir.exists(cache_dir)) { |
| 44 | ! | dir.create(cache_dir, recursive = TRUE) |
| 45 | } | |
| 46 | ||
| 47 | ! | tmp_path = tempfile(pattern = paste0(file_info$name, "."), tmpdir = cache_dir) |
| 48 | ! | on.exit(if (file.exists(tmp_path)) unlink(tmp_path), add = TRUE) |
| 49 | ! | final_dest_path = file.path(cache_dir, file_info$name) |
| 50 | ||
| 51 | ! | file_present = FALSE |
| 52 | ! | if (file.exists(final_dest_path)) { |
| 53 | ! | message("File exists, comparing checksum.") |
| 54 | ! | if (identical(unname(tools::md5sum(final_dest_path)), file_info$md5)) { |
| 55 | ! | file_present = TRUE |
| 56 | } else { | |
| 57 | ! | message( |
| 58 | ! | "File exists in cache folder but checksum not correct: removing ", |
| 59 | ! | final_dest_path |
| 60 | ) | |
| 61 | ! | file.remove(final_dest_path) |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | ! | if (file_present) { |
| 66 | ! | message( |
| 67 | ! | "File already present at '", |
| 68 | ! | final_dest_path, |
| 69 | ! | "' with correct checksum." |
| 70 | ) | |
| 71 | } else { | |
| 72 | ! | message("Downloading ", file_info$name) |
| 73 | ! | old_timeout = getOption("timeout") |
| 74 | ! | on.exit(options(timeout = old_timeout), add = TRUE) |
| 75 | ! | options(timeout = 3600) |
| 76 | ! | download_error = new.env(parent = emptyenv()) |
| 77 | ! | status = tryCatch( |
| 78 | ! | utils::download.file( |
| 79 | ! | file_info$url, |
| 80 | ! | destfile = tmp_path, |
| 81 | ! | mode = "wb", |
| 82 | ! | quiet = FALSE |
| 83 | ), | |
| 84 | ! | error = function(e) { |
| 85 | ! | download_error$message = conditionMessage(e) |
| 86 | ! | NA_integer_ |
| 87 | } | |
| 88 | ) | |
| 89 | ||
| 90 | ! | if (!identical(status, 0L) && !identical(status, 0)) { |
| 91 | ! | if (file.exists(tmp_path)) { |
| 92 | ! | unlink(tmp_path) |
| 93 | } | |
| 94 | ! | detail = if ( |
| 95 | ! | exists("message", envir = download_error, inherits = FALSE) |
| 96 | ) { | |
| 97 | ! | paste0(": ", download_error$message) |
| 98 | } else { | |
| 99 | ! | paste0(" with status ", status) |
| 100 | } | |
| 101 | ! | stop( |
| 102 | ! | "Failed to download Prague coefficient file '", |
| 103 | ! | file_info$name, |
| 104 | "'", | |
| 105 | ! | detail, |
| 106 | ".", | |
| 107 | ! | call. = FALSE |
| 108 | ) | |
| 109 | } | |
| 110 | ||
| 111 | ! | if (!file.exists(tmp_path)) { |
| 112 | ! | stop( |
| 113 | ! | "Download reported success but no temporary file was created for '", |
| 114 | ! | file_info$name, |
| 115 | "'.", | |
| 116 | ! | call. = FALSE |
| 117 | ) | |
| 118 | } | |
| 119 | ||
| 120 | ! | if (!identical(unname(tools::md5sum(tmp_path)), file_info$md5)) { |
| 121 | ! | unlink(tmp_path) |
| 122 | ! | stop( |
| 123 | ! | "Checksum mismatch after downloading Prague coefficient file '", |
| 124 | ! | file_info$name, |
| 125 | ! | "'. The partial file was deleted.", |
| 126 | ! | call. = FALSE |
| 127 | ) | |
| 128 | } | |
| 129 | ||
| 130 | ! | if (file.exists(final_dest_path)) { |
| 131 | ! | unlink(final_dest_path) |
| 132 | } | |
| 133 | ! | moved = file.rename(tmp_path, final_dest_path) |
| 134 | ! | if (!moved) { |
| 135 | ! | moved = file.copy(tmp_path, final_dest_path, overwrite = TRUE) |
| 136 | ! | unlink(tmp_path) |
| 137 | } | |
| 138 | ! | if (!moved) { |
| 139 | ! | stop("Failed to move Prague coefficient file into place.", call. = FALSE) |
| 140 | } | |
| 141 | ||
| 142 | ! | if (!identical(unname(tools::md5sum(final_dest_path)), file_info$md5)) { |
| 143 | ! | unlink(final_dest_path) |
| 144 | ! | stop( |
| 145 | ! | "Checksum mismatch after installing Prague coefficient file '", |
| 146 | ! | file_info$name, |
| 147 | ! | "'. The bad file was deleted.", |
| 148 | ! | call. = FALSE |
| 149 | ) | |
| 150 | } | |
| 151 | ! | message("Saved to ", final_dest_path) |
| 152 | } | |
| 153 | ! | invisible(final_dest_path) |
| 154 | } |
| 1 | clamp_value = function(x, min_value = 0, max_value = 1) { | |
| 2 | 37390x | pmin(pmax(x, min_value), max_value) |
| 3 | } | |
| 4 | ||
| 5 | get_moon_texture = function() { | |
| 6 | 2x | texture_file = system.file( |
| 7 | 2x | "textures", |
| 8 | 2x | "lroc_color_poles_1k.jpg", |
| 9 | 2x | package = "skymodelr" |
| 10 | ) | |
| 11 | 2x | if (!nzchar(texture_file)) { |
| 12 | ! | stop( |
| 13 | ! | "Moon texture file 'lroc_color_poles_1k.jpg' was not found in the installed package.", |
| 14 | ! | call. = FALSE |
| 15 | ) | |
| 16 | } | |
| 17 | 2x | texture_file |
| 18 | } |
| 1 | #' Prepare Location and Time Metadata for Native Prague Sky Queries | |
| 2 | #' | |
| 3 | #' Resolve the full-altitude Prague dataset and the Sun's topocentric position | |
| 4 | #' without loading coefficients or generating an image. This lets rendering | |
| 5 | #' libraries evaluate the model natively while using skymodelr's ephemeris and | |
| 6 | #' RGB calibration through a public interface. | |
| 7 | #' | |
| 8 | #' @param datetime A single `POSIXct` instant. Its time zone is respected. | |
| 9 | #' @param lat Observer latitude in degrees, between -90 and 90. | |
| 10 | #' @param lon Observer longitude in degrees, between -180 and 180. | |
| 11 | #' @param altitude Default `0`. Reference altitude in meters, from 0 to 15000. | |
| 12 | #' @param visibility Default `50`. Meteorological visibility in kilometers, | |
| 13 | #' from 20 to 131.8. | |
| 14 | #' @param albedo Default `0.5`. Ground albedo, from 0 to 1. | |
| 15 | #' @param prague_rgb_correction Default `TRUE`. Apply the Prague RGB calibration, | |
| 16 | #' as in [calculate_sky_values()]. | |
| 17 | #' @param prague_rgb_correction_strength Default `1`. Nonnegative calibration | |
| 18 | #' strength. | |
| 19 | #' @param prague_rgb_correction_gain Default `"auto"`. Automatic calibration or | |
| 20 | #' three positive RGB gains, as in [calculate_sky_values()]. | |
| 21 | #' | |
| 22 | #' @return A list with `filename` (the installed full-altitude coefficient file), | |
| 23 | #' `elevation_deg`, `azimuth_deg` (clockwise from north), | |
| 24 | #' `angular_diameter_deg`, `rgb_gain` (the applied R, G, B gains), and the | |
| 25 | #' reference `altitude`, `visibility`, and `albedo`. No native pointers are | |
| 26 | #' included; the result can be serialized. The coefficient path is local to | |
| 27 | #' this computer and should be resolved again on another machine. | |
| 28 | #' | |
| 29 | #' @details Install the data explicitly with | |
| 30 | #' `download_sky_data(sea_level = FALSE)`. This function never downloads files | |
| 31 | #' or prompts. It supports the visible-spectrum, full-altitude dataset and | |
| 32 | #' returns the actual Sun position even below the Prague model's minimum | |
| 33 | #' elevation of -4.2 degrees. Native consumers should use zero solar radiance | |
| 34 | #' below that limit while retaining transmission for other light sources. | |
| 35 | #' This function does not evaluate radiance, attenuation, or atmospheric | |
| 36 | #' refraction. | |
| 37 | #' @export | |
| 38 | #' @examplesIf interactive() | |
| 39 | #' info = get_prague_sky_metadata( | |
| 40 | #' as.POSIXct("2026-06-21 20:00:00", tz = "America/New_York"), | |
| 41 | #' lat = 40.7, lon = -74 | |
| 42 | #' ) | |
| 43 | #' info[c("elevation_deg", "azimuth_deg", "rgb_gain")] | |
| 44 | get_prague_sky_metadata = function( | |
| 45 | datetime, | |
| 46 | lat, | |
| 47 | lon, | |
| 48 | altitude = 0, | |
| 49 | visibility = 50, | |
| 50 | albedo = 0.5, | |
| 51 | prague_rgb_correction = TRUE, | |
| 52 | prague_rgb_correction_strength = 1, | |
| 53 | prague_rgb_correction_gain = "auto" | |
| 54 | ) { | |
| 55 | ! | celestial_disk_settings( |
| 56 | ! | datetime, |
| 57 | ! | lat, |
| 58 | ! | lon, |
| 59 | ! | altitude, |
| 60 | ! | 16, |
| 61 | ! | visibility, |
| 62 | ! | albedo, |
| 63 | ! | 1, |
| 64 | ! | FALSE, |
| 65 | ! | prague_rgb_correction, |
| 66 | ! | prague_rgb_correction_strength, |
| 67 | ! | prague_rgb_correction_gain |
| 68 | ) | |
| 69 | ! | filename = resolve_prague_coef_file(altitude = 1, allow_download = FALSE) |
| 70 | ! | ephemeris = swe_dirs_topo_moon_sun(datetime, lat, lon, elev_m = altitude) |
| 71 | ! | disk = celestial_disk_result( |
| 72 | ! | NULL, |
| 73 | ! | ephemeris$sun_dir_topo, |
| 74 | ! | ephemeris$sun_diameter_degrees |
| 75 | ) | |
| 76 | ! | gain = if ( |
| 77 | ! | normalize_prague_rgb_correction(prague_rgb_correction) == "constant" |
| 78 | ) { | |
| 79 | ! | prepare_prague_rgb_gain( |
| 80 | ! | prague_rgb_correction_gain, |
| 81 | ! | prague_rgb_correction_strength |
| 82 | ) | |
| 83 | } else { | |
| 84 | ! | c(R = 1, G = 1, B = 1) |
| 85 | } | |
| 86 | ! | c( |
| 87 | ! | list(filename = filename), |
| 88 | ! | disk[c("elevation_deg", "azimuth_deg", "angular_diameter_deg")], |
| 89 | ! | list( |
| 90 | ! | rgb_gain = gain, |
| 91 | ! | altitude = altitude, |
| 92 | ! | visibility = visibility, |
| 93 | ! | albedo = albedo |
| 94 | ) | |
| 95 | ) | |
| 96 | } |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /* | |
| 8 | This source is published under the following 3-clause BSD license. | |
| 9 | ||
| 10 | Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie | |
| 11 | All rights reserved. | |
| 12 | ||
| 13 | Redistribution and use in source and binary forms, with or without | |
| 14 | modification, are permitted provided that the following conditions are met: | |
| 15 | ||
| 16 | * Redistributions of source code must retain the above copyright | |
| 17 | notice, this list of conditions and the following disclaimer. | |
| 18 | * Redistributions in binary form must reproduce the above copyright | |
| 19 | notice, this list of conditions and the following disclaimer in the | |
| 20 | documentation and/or other materials provided with the distribution. | |
| 21 | * None of the names of the contributors may be used to endorse or promote | |
| 22 | products derived from this software without specific prior written | |
| 23 | permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
| 26 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
| 27 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY | |
| 29 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
| 30 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
| 31 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
| 32 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| 33 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
| 34 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | ||
| 37 | /* ============================================================================ | |
| 38 | ||
| 39 | This file is part of a sample implementation of the analytical skylight and | |
| 40 | solar radiance models presented in the SIGGRAPH 2012 paper | |
| 41 | ||
| 42 | ||
| 43 | "An Analytic Model for Full Spectral Sky-Dome Radiance" | |
| 44 | ||
| 45 | and the 2013 IEEE CG&A paper | |
| 46 | ||
| 47 | "Adding a Solar Radiance Function to the Hosek Skylight Model" | |
| 48 | ||
| 49 | both by | |
| 50 | ||
| 51 | Lukas Hosek and Alexander Wilkie | |
| 52 | Charles University in Prague, Czech Republic | |
| 53 | ||
| 54 | ||
| 55 | Version: 1.4a, February 22nd, 2013 | |
| 56 | ||
| 57 | Version history: | |
| 58 | ||
| 59 | 1.4a February 22nd, 2013 | |
| 60 | Removed unnecessary and counter-intuitive solar radius parameters | |
| 61 | from the interface of the colourspace sky dome initialisation functions. | |
| 62 | ||
| 63 | 1.4 February 11th, 2013 | |
| 64 | Fixed a bug which caused the relative brightness of the solar disc | |
| 65 | and the sky dome to be off by a factor of about 6. The sun was too | |
| 66 | bright: this affected both normal and alien sun scenarios. The | |
| 67 | coefficients of the solar radiance function were changed to fix this. | |
| 68 | ||
| 69 | 1.3 January 21st, 2013 (not released to the public) | |
| 70 | Added support for solar discs that are not exactly the same size as | |
| 71 | the terrestrial sun. Also added support for suns with a different | |
| 72 | emission spectrum ("Alien World" functionality). | |
| 73 | ||
| 74 | 1.2a December 18th, 2012 | |
| 75 | Fixed a mistake and some inaccuracies in the solar radiance function | |
| 76 | explanations found in ArHosekSkyModel.h. The actual source code is | |
| 77 | unchanged compared to version 1.2. | |
| 78 | ||
| 79 | 1.2 December 17th, 2012 | |
| 80 | Native RGB data and a solar radiance function that matches the turbidity | |
| 81 | conditions were added. | |
| 82 | ||
| 83 | 1.1 September 2012 | |
| 84 | The coefficients of the spectral model are now scaled so that the output | |
| 85 | is given in physical units: W / (m^-2 * sr * nm). Also, the output of the | |
| 86 | XYZ model is now no longer scaled to the range [0...1]. Instead, it is | |
| 87 | the result of a simple conversion from spectral data via the CIE 2 degree | |
| 88 | standard observer matching functions. Therefore, after multiplication | |
| 89 | with 683 lm / W, the Y channel now corresponds to luminance in lm. | |
| 90 | ||
| 91 | 1.0 May 11th, 2012 | |
| 92 | Initial release. | |
| 93 | ||
| 94 | ||
| 95 | Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if | |
| 96 | an updated version of this code has been published! | |
| 97 | ||
| 98 | ============================================================================ */ | |
| 99 | ||
| 100 | /* | |
| 101 | ||
| 102 | All instructions on how to use this code are in the accompanying header file. | |
| 103 | ||
| 104 | */ | |
| 105 | ||
| 106 | #include "ArHosekSkyModel.h" | |
| 107 | #include "ArHosekSkyModelData_Spectral.h" | |
| 108 | #include "ArHosekSkyModelData_CIEXYZ.h" | |
| 109 | #include "ArHosekSkyModelData_RGB.h" | |
| 110 | #include <assert.h> | |
| 111 | #include <stdio.h> | |
| 112 | #include <stdlib.h> | |
| 113 | #include <math.h> | |
| 114 | ||
| 115 | ||
| 116 | #ifdef __cplusplus | |
| 117 | extern "C" { | |
| 118 | #endif | |
| 119 | ||
| 120 | // Some macro definitions that occur elsewhere in ART, and that have to be | |
| 121 | // replicated to make this a stand-alone module. | |
| 122 | ||
| 123 | #ifndef NIL | |
| 124 | #define NIL 0 | |
| 125 | #endif | |
| 126 | ||
| 127 | #ifndef MATH_PI | |
| 128 | #define MATH_PI 3.141592653589793 | |
| 129 | #endif | |
| 130 | ||
| 131 | #ifndef MATH_DEG_TO_RAD | |
| 132 | #define MATH_DEG_TO_RAD ( MATH_PI / 180.0 ) | |
| 133 | #endif | |
| 134 | ||
| 135 | #ifndef MATH_RAD_TO_DEG | |
| 136 | #define MATH_RAD_TO_DEG ( 180.0 / MATH_PI ) | |
| 137 | #endif | |
| 138 | ||
| 139 | #ifndef DEGREES | |
| 140 | #define DEGREES * MATH_DEG_TO_RAD | |
| 141 | #endif | |
| 142 | ||
| 143 | #ifndef TERRESTRIAL_SOLAR_RADIUS | |
| 144 | #define TERRESTRIAL_SOLAR_RADIUS ( ( 0.51 DEGREES ) / 2.0 ) | |
| 145 | #endif | |
| 146 | ||
| 147 | #ifndef ALLOC | |
| 148 | #define ALLOC(_struct) ((_struct *)malloc(sizeof(_struct))) | |
| 149 | #endif | |
| 150 | ||
| 151 | // internal definitions | |
| 152 | ||
| 153 | typedef double *ArHosekSkyModel_Dataset; | |
| 154 | typedef double *ArHosekSkyModel_Radiance_Dataset; | |
| 155 | ||
| 156 | // internal functions | |
| 157 | ||
| 158 | 297x | void ArHosekSkyModel_CookConfiguration( |
| 159 | ArHosekSkyModel_Dataset dataset, | |
| 160 | ArHosekSkyModelConfiguration config, | |
| 161 | double turbidity, | |
| 162 | double albedo, | |
| 163 | double solar_elevation | |
| 164 | ) | |
| 165 | { | |
| 166 | double * elev_matrix; | |
| 167 | ||
| 168 | 297x | int int_turbidity = (int)turbidity; |
| 169 | 297x | double turbidity_rem = turbidity - (double)int_turbidity; |
| 170 | ||
| 171 | 297x | solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0)); |
| 172 | ||
| 173 | // alb 0 low turb | |
| 174 | ||
| 175 | 297x | elev_matrix = dataset + ( 9 * 6 * (int_turbidity-1) ); |
| 176 | ||
| 177 | ||
| 178 | 2970x | for( unsigned int i = 0; i < 9; ++i ) |
| 179 | { | |
| 180 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 181 | 2673x | config[i] = |
| 182 | 2673x | (1.0-albedo) * (1.0 - turbidity_rem) |
| 183 | 2673x | * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + |
| 184 | 2673x | 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + |
| 185 | 2673x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + |
| 186 | 2673x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + |
| 187 | 2673x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + |
| 188 | 2673x | pow(solar_elevation, 5.0) * elev_matrix[i+45]); |
| 189 | } | |
| 190 | ||
| 191 | // alb 1 low turb | |
| 192 | 297x | elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity-1)); |
| 193 | 2970x | for(unsigned int i = 0; i < 9; ++i) |
| 194 | { | |
| 195 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 196 | 2673x | config[i] += |
| 197 | 2673x | (albedo) * (1.0 - turbidity_rem) |
| 198 | 2673x | * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + |
| 199 | 2673x | 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + |
| 200 | 2673x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + |
| 201 | 2673x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + |
| 202 | 2673x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + |
| 203 | 2673x | pow(solar_elevation, 5.0) * elev_matrix[i+45]); |
| 204 | } | |
| 205 | ||
| 206 | 297x | if(int_turbidity == 10) |
| 207 | ! | return; |
| 208 | ||
| 209 | // alb 0 high turb | |
| 210 | 297x | elev_matrix = dataset + (9*6*(int_turbidity)); |
| 211 | 2970x | for(unsigned int i = 0; i < 9; ++i) |
| 212 | { | |
| 213 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 214 | 2673x | config[i] += |
| 215 | 2673x | (1.0-albedo) * (turbidity_rem) |
| 216 | 2673x | * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + |
| 217 | 2673x | 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + |
| 218 | 2673x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + |
| 219 | 2673x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + |
| 220 | 2673x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + |
| 221 | 2673x | pow(solar_elevation, 5.0) * elev_matrix[i+45]); |
| 222 | } | |
| 223 | ||
| 224 | // alb 1 high turb | |
| 225 | 297x | elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity)); |
| 226 | 2970x | for(unsigned int i = 0; i < 9; ++i) |
| 227 | { | |
| 228 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 229 | 2673x | config[i] += |
| 230 | 2673x | (albedo) * (turbidity_rem) |
| 231 | 2673x | * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + |
| 232 | 2673x | 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + |
| 233 | 2673x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + |
| 234 | 2673x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + |
| 235 | 2673x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + |
| 236 | 2673x | pow(solar_elevation, 5.0) * elev_matrix[i+45]); |
| 237 | } | |
| 238 | } | |
| 239 | ||
| 240 | 297x | double ArHosekSkyModel_CookRadianceConfiguration( |
| 241 | ArHosekSkyModel_Radiance_Dataset dataset, | |
| 242 | double turbidity, | |
| 243 | double albedo, | |
| 244 | double solar_elevation | |
| 245 | ) | |
| 246 | { | |
| 247 | double* elev_matrix; | |
| 248 | ||
| 249 | 297x | int int_turbidity = (int)turbidity; |
| 250 | 297x | double turbidity_rem = turbidity - (double)int_turbidity; |
| 251 | double res; | |
| 252 | 297x | solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0)); |
| 253 | ||
| 254 | // alb 0 low turb | |
| 255 | 297x | elev_matrix = dataset + (6*(int_turbidity-1)); |
| 256 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 257 | 297x | res = (1.0-albedo) * (1.0 - turbidity_rem) * |
| 258 | 297x | ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + |
| 259 | 297x | 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + |
| 260 | 297x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + |
| 261 | 297x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + |
| 262 | 297x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + |
| 263 | 297x | pow(solar_elevation, 5.0) * elev_matrix[5]); |
| 264 | ||
| 265 | // alb 1 low turb | |
| 266 | 297x | elev_matrix = dataset + (6*10 + 6*(int_turbidity-1)); |
| 267 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 268 | 297x | res += (albedo) * (1.0 - turbidity_rem) * |
| 269 | 297x | ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + |
| 270 | 297x | 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + |
| 271 | 297x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + |
| 272 | 297x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + |
| 273 | 297x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + |
| 274 | 297x | pow(solar_elevation, 5.0) * elev_matrix[5]); |
| 275 | 297x | if(int_turbidity == 10) |
| 276 | ! | return res; |
| 277 | ||
| 278 | // alb 0 high turb | |
| 279 | 297x | elev_matrix = dataset + (6*(int_turbidity)); |
| 280 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 281 | 297x | res += (1.0-albedo) * (turbidity_rem) * |
| 282 | 297x | ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + |
| 283 | 297x | 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + |
| 284 | 297x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + |
| 285 | 297x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + |
| 286 | 297x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + |
| 287 | 297x | pow(solar_elevation, 5.0) * elev_matrix[5]); |
| 288 | ||
| 289 | // alb 1 high turb | |
| 290 | 297x | elev_matrix = dataset + (6*10 + 6*(int_turbidity)); |
| 291 | //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; | |
| 292 | 297x | res += (albedo) * (turbidity_rem) * |
| 293 | 297x | ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + |
| 294 | 297x | 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + |
| 295 | 297x | 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + |
| 296 | 297x | 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + |
| 297 | 297x | 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + |
| 298 | 297x | pow(solar_elevation, 5.0) * elev_matrix[5]); |
| 299 | 297x | return res; |
| 300 | } | |
| 301 | ||
| 302 | 117655440x | double ArHosekSkyModel_GetRadianceInternal( |
| 303 | ArHosekSkyModelConfiguration configuration, | |
| 304 | double theta, | |
| 305 | double gamma | |
| 306 | ) | |
| 307 | { | |
| 308 | 117655440x | const double expM = exp(configuration[4] * gamma); |
| 309 | 117655440x | const double rayM = cos(gamma)*cos(gamma); |
| 310 | 117655440x | const double mieM = (1.0 + cos(gamma)*cos(gamma)) / pow((1.0 + configuration[8]*configuration[8] - 2.0*configuration[8]*cos(gamma)), 1.5); |
| 311 | 117655440x | const double zenith = sqrt(cos(theta)); |
| 312 | 117655440x | const double cos_factor = (cos(theta) + 0.01); |
| 313 | 117655440x | const double factor1 = (1.0 + configuration[0] * exp(configuration[1] / cos_factor)); |
| 314 | 117655440x | const double factor2 = (configuration[2] + configuration[3] * expM + configuration[5] * rayM + configuration[6] * mieM + configuration[7] * zenith); |
| 315 | ||
| 316 | 117655440x | return factor1 * factor2; |
| 317 | } | |
| 318 | ||
| 319 | // spectral version | |
| 320 | ||
| 321 | 27x | ArHosekSkyModelState * arhosekskymodelstate_alloc_init( |
| 322 | const double solar_elevation, | |
| 323 | const double atmospheric_turbidity, | |
| 324 | const double ground_albedo | |
| 325 | ) | |
| 326 | { | |
| 327 | 27x | ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); |
| 328 | ||
| 329 | 27x | state->solar_radius = ( 0.51 DEGREES ) / 2.0; |
| 330 | 27x | state->turbidity = atmospheric_turbidity; |
| 331 | 27x | state->albedo = ground_albedo; |
| 332 | 27x | state->elevation = solar_elevation; |
| 333 | ||
| 334 | 324x | for( unsigned int wl = 0; wl < 11; ++wl ) |
| 335 | { | |
| 336 | 297x | ArHosekSkyModel_CookConfiguration( |
| 337 | 297x | datasets[wl], |
| 338 | 297x | state->configs[wl], |
| 339 | atmospheric_turbidity, | |
| 340 | ground_albedo, | |
| 341 | solar_elevation | |
| 342 | ); | |
| 343 | ||
| 344 | 297x | state->radiances[wl] = |
| 345 | 594x | ArHosekSkyModel_CookRadianceConfiguration( |
| 346 | 297x | datasetsRad[wl], |
| 347 | atmospheric_turbidity, | |
| 348 | ground_albedo, | |
| 349 | solar_elevation | |
| 350 | ); | |
| 351 | ||
| 352 | 297x | state->emission_correction_factor_sun[wl] = 1.0; |
| 353 | 297x | state->emission_correction_factor_sky[wl] = 1.0; |
| 354 | } | |
| 355 | ||
| 356 | 27x | return state; |
| 357 | } | |
| 358 | ||
| 359 | // 'blackbody_scaling_factor' | |
| 360 | // | |
| 361 | // Fudge factor, computed in Mathematica, to scale the results of the | |
| 362 | // following function to match the solar radiance spectrum used in the | |
| 363 | // original simulation. The scaling is done so their integrals over the | |
| 364 | // range from 380.0 to 720.0 nanometers match for a blackbody temperature | |
| 365 | // of 5800 K. | |
| 366 | // Which leaves the original spectrum being less bright overall than the 5.8k | |
| 367 | // blackbody radiation curve if the ultra-violet part of the spectrum is | |
| 368 | // also considered. But the visible brightness should be very similar. | |
| 369 | ||
| 370 | const double blackbody_scaling_factor = 3.19992 * 10E-11; | |
| 371 | ||
| 372 | // 'art_blackbody_dd_value()' function | |
| 373 | // | |
| 374 | // Blackbody radiance, Planck's formula | |
| 375 | ||
| 376 | ! | double art_blackbody_dd_value( |
| 377 | const double temperature, | |
| 378 | const double lambda | |
| 379 | ) | |
| 380 | { | |
| 381 | ! | double c1 = 3.74177 * 10E-17; |
| 382 | ! | double c2 = 0.0143878; |
| 383 | double value; | |
| 384 | ||
| 385 | ! | value = ( c1 / ( pow( lambda, 5.0 ) ) ) |
| 386 | ! | * ( 1.0 / ( exp( c2 / ( lambda * temperature ) ) - 1.0 ) ); |
| 387 | ||
| 388 | ! | return value; |
| 389 | } | |
| 390 | ||
| 391 | // 'originalSolarRadianceTable[]' | |
| 392 | // | |
| 393 | // The solar spectrum incident at the top of the atmosphere, as it was used | |
| 394 | // in the brute force path tracer that generated the reference results the | |
| 395 | // model was fitted to. We need this as the yardstick to compare any altered | |
| 396 | // Blackbody emission spectra for alien world stars to. | |
| 397 | ||
| 398 | // This is just the data from the Preetham paper, extended into the UV range. | |
| 399 | ||
| 400 | const double originalSolarRadianceTable[] = | |
| 401 | { | |
| 402 | 7500.0, | |
| 403 | 12500.0, | |
| 404 | 21127.5, | |
| 405 | 26760.5, | |
| 406 | 30663.7, | |
| 407 | 27825.0, | |
| 408 | 25503.8, | |
| 409 | 25134.2, | |
| 410 | 23212.1, | |
| 411 | 21526.7, | |
| 412 | 19870.8 | |
| 413 | }; | |
| 414 | ||
| 415 | ! | ArHosekSkyModelState * arhosekskymodelstate_alienworld_alloc_init( |
| 416 | const double solar_elevation, | |
| 417 | const double solar_intensity, | |
| 418 | const double solar_surface_temperature_kelvin, | |
| 419 | const double atmospheric_turbidity, | |
| 420 | const double ground_albedo | |
| 421 | ) | |
| 422 | { | |
| 423 | ! | ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); |
| 424 | ||
| 425 | ! | state->turbidity = atmospheric_turbidity; |
| 426 | ! | state->albedo = ground_albedo; |
| 427 | ! | state->elevation = solar_elevation; |
| 428 | ||
| 429 | ! | for( unsigned int wl = 0; wl < 11; ++wl ) |
| 430 | { | |
| 431 | // Basic init as for the normal scenario | |
| 432 | ||
| 433 | ! | ArHosekSkyModel_CookConfiguration( |
| 434 | ! | datasets[wl], |
| 435 | ! | state->configs[wl], |
| 436 | atmospheric_turbidity, | |
| 437 | ground_albedo, | |
| 438 | solar_elevation | |
| 439 | ); | |
| 440 | ||
| 441 | ! | state->radiances[wl] = |
| 442 | ! | ArHosekSkyModel_CookRadianceConfiguration( |
| 443 | ! | datasetsRad[wl], |
| 444 | atmospheric_turbidity, | |
| 445 | ground_albedo, | |
| 446 | solar_elevation | |
| 447 | ); | |
| 448 | ||
| 449 | // The wavelength of this band in nanometers | |
| 450 | ||
| 451 | ! | double owl = ( 320.0 + 40.0 * wl ) * 10E-10; |
| 452 | ||
| 453 | // The original intensity we just computed | |
| 454 | ||
| 455 | ! | double osr = originalSolarRadianceTable[wl]; |
| 456 | ||
| 457 | // The intensity of a blackbody with the desired temperature | |
| 458 | // The fudge factor described above is used to make sure the BB | |
| 459 | // function matches the used radiance data reasonably well | |
| 460 | // in magnitude. | |
| 461 | ||
| 462 | double nsr = | |
| 463 | ! | art_blackbody_dd_value(solar_surface_temperature_kelvin, owl) |
| 464 | ! | * blackbody_scaling_factor; |
| 465 | ||
| 466 | // Correction factor for this waveband is simply the ratio of | |
| 467 | // the two. | |
| 468 | ||
| 469 | ! | state->emission_correction_factor_sun[wl] = nsr / osr; |
| 470 | } | |
| 471 | ||
| 472 | // We then compute the average correction factor of all wavebands. | |
| 473 | ||
| 474 | // Theoretically, some weighting to favour wavelengths human vision is | |
| 475 | // more sensitive to could be introduced here - think V(lambda). But | |
| 476 | // given that the whole effort is not *that* accurate to begin with (we | |
| 477 | // are talking about the appearance of alien worlds, after all), simple | |
| 478 | // averaging over the visible wavelenghts (! - this is why we start at | |
| 479 | // WL #2, and only use 2-11) seems like a sane first approximation. | |
| 480 | ||
| 481 | ! | double correctionFactor = 0.0; |
| 482 | ||
| 483 | ! | for ( unsigned int i = 2; i < 11; i++ ) |
| 484 | { | |
| 485 | ! | correctionFactor += |
| 486 | ! | state->emission_correction_factor_sun[i]; |
| 487 | } | |
| 488 | ||
| 489 | // This is the average ratio in emitted energy between our sun, and an | |
| 490 | // equally large sun with the blackbody spectrum we requested. | |
| 491 | ||
| 492 | // Division by 9 because we only used 9 of the 11 wavelengths for this | |
| 493 | // (see above). | |
| 494 | ||
| 495 | ! | double ratio = correctionFactor / 9.0; |
| 496 | ||
| 497 | // This ratio is then used to determine the radius of the alien sun | |
| 498 | // on the sky dome. The additional factor 'solar_intensity' can be used | |
| 499 | // to make the alien sun brighter or dimmer compared to our sun. | |
| 500 | ||
| 501 | ! | state->solar_radius = |
| 502 | ! | ( sqrt( solar_intensity ) * TERRESTRIAL_SOLAR_RADIUS ) |
| 503 | ! | / sqrt( ratio ); |
| 504 | ||
| 505 | // Finally, we have to reduce the scaling factor of the sky by the | |
| 506 | // ratio used to scale the solar disc size. The rationale behind this is | |
| 507 | // that the scaling factors apply to the new blackbody spectrum, which | |
| 508 | // can be more or less bright than the one our sun emits. However, we | |
| 509 | // just scaled the size of the alien solar disc so it is roughly as | |
| 510 | // bright (in terms of energy emitted) as the terrestrial sun. So the sky | |
| 511 | // dome has to be reduced in brightness appropriately - but not in an | |
| 512 | // uniform fashion across wavebands. If we did that, the sky colour would | |
| 513 | // be wrong. | |
| 514 | ||
| 515 | ! | for ( unsigned int i = 0; i < 11; i++ ) |
| 516 | { | |
| 517 | ! | state->emission_correction_factor_sky[i] = |
| 518 | solar_intensity | |
| 519 | ! | * state->emission_correction_factor_sun[i] / ratio; |
| 520 | } | |
| 521 | ||
| 522 | ! | return state; |
| 523 | } | |
| 524 | ||
| 525 | 27x | void arhosekskymodelstate_free( |
| 526 | ArHosekSkyModelState * state | |
| 527 | ) | |
| 528 | { | |
| 529 | 27x | free(state); |
| 530 | } | |
| 531 | ||
| 532 | 117655440x | double arhosekskymodel_radiance( |
| 533 | ArHosekSkyModelState * state, | |
| 534 | double theta, | |
| 535 | double gamma, | |
| 536 | double wavelength | |
| 537 | ) | |
| 538 | { | |
| 539 | 117655440x | int low_wl = (wavelength - 320.0 ) / 40.0; |
| 540 | ||
| 541 | 117655440x | if ( low_wl < 0 || low_wl >= 11 ) |
| 542 | ! | return 0.0f; |
| 543 | ||
| 544 | 117655440x | double interp = fmod((wavelength - 320.0 ) / 40.0, 1.0); |
| 545 | ||
| 546 | double val_low = | |
| 547 | 235310880x | ArHosekSkyModel_GetRadianceInternal( |
| 548 | 117655440x | state->configs[low_wl], |
| 549 | theta, | |
| 550 | gamma | |
| 551 | ) | |
| 552 | 117655440x | * state->radiances[low_wl] |
| 553 | 117655440x | * state->emission_correction_factor_sky[low_wl]; |
| 554 | ||
| 555 | 117655440x | if ( interp < 1e-6 ) |
| 556 | 117655440x | return val_low; |
| 557 | ||
| 558 | ! | double result = ( 1.0 - interp ) * val_low; |
| 559 | ||
| 560 | ! | if ( low_wl+1 < 11 ) |
| 561 | { | |
| 562 | ! | result += |
| 563 | interp | |
| 564 | ! | * ArHosekSkyModel_GetRadianceInternal( |
| 565 | ! | state->configs[low_wl+1], |
| 566 | theta, | |
| 567 | gamma | |
| 568 | ) | |
| 569 | ! | * state->radiances[low_wl+1] |
| 570 | ! | * state->emission_correction_factor_sky[low_wl+1]; |
| 571 | } | |
| 572 | ||
| 573 | ! | return result; |
| 574 | } | |
| 575 | ||
| 576 | ||
| 577 | // xyz and rgb versions | |
| 578 | ||
| 579 | ! | ArHosekSkyModelState * arhosek_xyz_skymodelstate_alloc_init( |
| 580 | const double turbidity, | |
| 581 | const double albedo, | |
| 582 | const double elevation | |
| 583 | ) | |
| 584 | { | |
| 585 | ! | ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); |
| 586 | ||
| 587 | ! | state->solar_radius = TERRESTRIAL_SOLAR_RADIUS; |
| 588 | ! | state->turbidity = turbidity; |
| 589 | ! | state->albedo = albedo; |
| 590 | ! | state->elevation = elevation; |
| 591 | ||
| 592 | ! | for( unsigned int channel = 0; channel < 3; ++channel ) |
| 593 | { | |
| 594 | ! | ArHosekSkyModel_CookConfiguration( |
| 595 | ! | datasetsXYZ[channel], |
| 596 | ! | state->configs[channel], |
| 597 | turbidity, | |
| 598 | albedo, | |
| 599 | elevation | |
| 600 | ); | |
| 601 | ||
| 602 | ! | state->radiances[channel] = |
| 603 | ! | ArHosekSkyModel_CookRadianceConfiguration( |
| 604 | ! | datasetsXYZRad[channel], |
| 605 | turbidity, | |
| 606 | albedo, | |
| 607 | elevation | |
| 608 | ); | |
| 609 | } | |
| 610 | ||
| 611 | ! | return state; |
| 612 | } | |
| 613 | ||
| 614 | ||
| 615 | ! | ArHosekSkyModelState * arhosek_rgb_skymodelstate_alloc_init( |
| 616 | const double turbidity, | |
| 617 | const double albedo, | |
| 618 | const double elevation | |
| 619 | ) | |
| 620 | { | |
| 621 | ! | ArHosekSkyModelState* state = ALLOC(ArHosekSkyModelState); |
| 622 | ||
| 623 | ! | state->solar_radius = TERRESTRIAL_SOLAR_RADIUS; |
| 624 | ! | state->turbidity = turbidity; |
| 625 | ! | state->albedo = albedo; |
| 626 | ! | state->elevation = elevation; |
| 627 | ||
| 628 | ! | for( unsigned int channel = 0; channel < 3; ++channel ) |
| 629 | { | |
| 630 | ! | ArHosekSkyModel_CookConfiguration( |
| 631 | ! | datasetsRGB[channel], |
| 632 | ! | state->configs[channel], |
| 633 | turbidity, | |
| 634 | albedo, | |
| 635 | elevation | |
| 636 | ); | |
| 637 | ||
| 638 | ! | state->radiances[channel] = |
| 639 | ! | ArHosekSkyModel_CookRadianceConfiguration( |
| 640 | ! | datasetsRGBRad[channel], |
| 641 | turbidity, | |
| 642 | albedo, | |
| 643 | elevation | |
| 644 | ); | |
| 645 | } | |
| 646 | ||
| 647 | ! | return state; |
| 648 | } | |
| 649 | ||
| 650 | ! | double arhosek_tristim_skymodel_radiance( |
| 651 | ArHosekSkyModelState * state, | |
| 652 | double theta, | |
| 653 | double gamma, | |
| 654 | int channel | |
| 655 | ) | |
| 656 | { | |
| 657 | return | |
| 658 | ! | ArHosekSkyModel_GetRadianceInternal( |
| 659 | ! | state->configs[channel], |
| 660 | theta, | |
| 661 | gamma | |
| 662 | ) | |
| 663 | ! | * state->radiances[channel]; |
| 664 | } | |
| 665 | ||
| 666 | const int pieces = 45; | |
| 667 | const int order = 4; | |
| 668 | ||
| 669 | 1197440x | double arhosekskymodel_sr_internal( |
| 670 | ArHosekSkyModelState * state, | |
| 671 | int turbidity, | |
| 672 | int wl, | |
| 673 | double elevation | |
| 674 | ) | |
| 675 | { | |
| 676 | int pos = | |
| 677 | 1197440x | (int) (pow(2.0*elevation / MATH_PI, 1.0/3.0) * pieces); // floor |
| 678 | ||
| 679 | 1197440x | if ( pos > 44 ) pos = 44; |
| 680 | ||
| 681 | const double break_x = | |
| 682 | 1197440x | pow(((double) pos / (double) pieces), 3.0) * (MATH_PI * 0.5); |
| 683 | ||
| 684 | 1197440x | const double * coefs = |
| 685 | 1197440x | solarDatasets[wl] + (order * pieces * turbidity + order * (pos+1) - 1); |
| 686 | ||
| 687 | 1197440x | double res = 0.0; |
| 688 | 1197440x | const double x = elevation - break_x; |
| 689 | 1197440x | double x_exp = 1.0; |
| 690 | ||
| 691 | 5987200x | for (int i = 0; i < order; ++i) |
| 692 | { | |
| 693 | 4789760x | res += x_exp * *coefs--; |
| 694 | 4789760x | x_exp *= x; |
| 695 | } | |
| 696 | ||
| 697 | 1197440x | return res * state->emission_correction_factor_sun[wl]; |
| 698 | } | |
| 699 | ||
| 700 | 58826440x | double arhosekskymodel_solar_radiance_internal2( |
| 701 | ArHosekSkyModelState * state, | |
| 702 | double wavelength, | |
| 703 | double elevation, | |
| 704 | double gamma | |
| 705 | ) | |
| 706 | { | |
| 707 | assert( | |
| 708 | wavelength >= 320.0 | |
| 709 | && wavelength <= 720.0 | |
| 710 | && state->turbidity >= 1.0 | |
| 711 | && state->turbidity <= 10.0 | |
| 712 | ); | |
| 713 | ||
| 714 | ||
| 715 | 58826440x | const double sol_rad_sin = sin(state->solar_radius); |
| 716 | 58826440x | const double ar2 = 1 / ( sol_rad_sin * sol_rad_sin ); |
| 717 | 58826440x | const double singamma = sin(gamma); |
| 718 | 58826440x | double sc2 = 1.0 - ar2 * singamma * singamma; |
| 719 | 58826440x | if (sc2 < 0.0 ) sc2 = 0.0; |
| 720 | 58826440x | double sampleCosine = sqrt (sc2); |
| 721 | 58826440x | if (sampleCosine == 0.) return 0.; |
| 722 | ||
| 723 | 299360x | int turb_low = (int) state->turbidity - 1; |
| 724 | 299360x | double turb_frac = state->turbidity - (double) (turb_low + 1); |
| 725 | ||
| 726 | 299360x | if ( turb_low == 9 ) |
| 727 | { | |
| 728 | ! | turb_low = 8; |
| 729 | ! | turb_frac = 1.0; |
| 730 | } | |
| 731 | ||
| 732 | 299360x | int wl_low = (int) ((wavelength - 320.0) / 40.0); |
| 733 | 299360x | double wl_frac = fmod(wavelength, 40.0) / 40.0; |
| 734 | ||
| 735 | 299360x | if ( wl_low == 10 ) |
| 736 | { | |
| 737 | 29936x | wl_low = 9; |
| 738 | 29936x | wl_frac = 1.0; |
| 739 | } | |
| 740 | ||
| 741 | double direct_radiance = | |
| 742 | 299360x | ( 1.0 - turb_frac ) |
| 743 | 598720x | * ( (1.0 - wl_frac) |
| 744 | 299360x | * arhosekskymodel_sr_internal( |
| 745 | state, | |
| 746 | turb_low, | |
| 747 | wl_low, | |
| 748 | elevation | |
| 749 | ) | |
| 750 | 299360x | + wl_frac |
| 751 | 299360x | * arhosekskymodel_sr_internal( |
| 752 | state, | |
| 753 | turb_low, | |
| 754 | wl_low+1, | |
| 755 | elevation | |
| 756 | ) | |
| 757 | ) | |
| 758 | + turb_frac | |
| 759 | 598720x | * ( ( 1.0 - wl_frac ) |
| 760 | 299360x | * arhosekskymodel_sr_internal( |
| 761 | state, | |
| 762 | turb_low+1, | |
| 763 | wl_low, | |
| 764 | elevation | |
| 765 | ) | |
| 766 | 299360x | + wl_frac |
| 767 | 299360x | * arhosekskymodel_sr_internal( |
| 768 | state, | |
| 769 | turb_low+1, | |
| 770 | wl_low+1, | |
| 771 | elevation | |
| 772 | ) | |
| 773 | ); | |
| 774 | ||
| 775 | double ldCoefficient[6]; | |
| 776 | ||
| 777 | 2095520x | for ( int i = 0; i < 6; i++ ) |
| 778 | 1796160x | ldCoefficient[i] = |
| 779 | 1796160x | (1.0 - wl_frac) * limbDarkeningDatasets[wl_low ][i] |
| 780 | 1796160x | + wl_frac * limbDarkeningDatasets[wl_low+1][i]; |
| 781 | ||
| 782 | // The following will be improved in future versions of the model: | |
| 783 | // here, we directly use fitted 5th order polynomials provided by the | |
| 784 | // astronomical community for the limb darkening effect. Astronomers need | |
| 785 | // such accurate fittings for their predictions. However, this sort of | |
| 786 | // accuracy is not really needed for CG purposes, so an approximated | |
| 787 | // dataset based on quadratic polynomials will be provided in a future | |
| 788 | // release. | |
| 789 | ||
| 790 | double darkeningFactor = | |
| 791 | 299360x | ldCoefficient[0] |
| 792 | 299360x | + ldCoefficient[1] * sampleCosine |
| 793 | 299360x | + ldCoefficient[2] * pow( sampleCosine, 2.0 ) |
| 794 | 299360x | + ldCoefficient[3] * pow( sampleCosine, 3.0 ) |
| 795 | 299360x | + ldCoefficient[4] * pow( sampleCosine, 4.0 ) |
| 796 | 299360x | + ldCoefficient[5] * pow( sampleCosine, 5.0 ); |
| 797 | ||
| 798 | 299360x | direct_radiance *= darkeningFactor; |
| 799 | ||
| 800 | 299360x | return direct_radiance; |
| 801 | } | |
| 802 | ||
| 803 | 58826440x | double arhosekskymodel_solar_radiance( |
| 804 | ArHosekSkyModelState * state, | |
| 805 | double theta, | |
| 806 | double gamma, | |
| 807 | double wavelength | |
| 808 | ) | |
| 809 | { | |
| 810 | double direct_radiance = | |
| 811 | 58826440x | arhosekskymodel_solar_radiance_internal2( |
| 812 | state, | |
| 813 | wavelength, | |
| 814 | ((MATH_PI/2.0)-theta), | |
| 815 | gamma | |
| 816 | ); | |
| 817 | ||
| 818 | double inscattered_radiance = | |
| 819 | 58826440x | arhosekskymodel_radiance( |
| 820 | state, | |
| 821 | theta, | |
| 822 | gamma, | |
| 823 | wavelength | |
| 824 | ); | |
| 825 | ||
| 826 | 58826440x | return direct_radiance + inscattered_radiance; |
| 827 | } | |
| 828 | ||
| 829 | #ifdef __cplusplus | |
| 830 | } | |
| 831 | #endif |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | Copyright (c) 2015 Eric Bruneton | |
| 9 | All rights reserved. | |
| 10 | ||
| 11 | Redistribution and use in source and binary forms, with or without | |
| 12 | modification, are permitted provided that the following conditions are met: | |
| 13 | ||
| 14 | 1. Redistributions of source code must retain the above copyright notice, this | |
| 15 | list of conditions and the following disclaimer. | |
| 16 | ||
| 17 | 2. Redistributions in binary form must reproduce the above copyright notice, | |
| 18 | this list of conditions and the following disclaimer in the documentation | |
| 19 | and/or other materials provided with the distribution. | |
| 20 | ||
| 21 | 3. Neither the name of the copyright holder nor the names of its contributors | |
| 22 | may be used to endorse or promote products derived from this software without | |
| 23 | specific prior written permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| 29 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 30 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| 31 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| 32 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| 33 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 34 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | #include "atmosphere.h" | |
| 37 | ||
| 38 | #include <vector> | |
| 39 | ||
| 40 | namespace { | |
| 41 | ||
| 42 | 3x | IrradianceSpectrum NewSolarSpectrum() { |
| 43 | // Values from "Reference Solar Spectral Irradiance: ASTM G-173", ETR column | |
| 44 | // (see http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/ASTMG173.html), | |
| 45 | // summed and averaged in each bin (e.g. the value for 360nm is the average of | |
| 46 | // the ASTM G-173 values for all wavelengths between 360 and 371.75nm). | |
| 47 | static const float kSpectralIrradiance[40] = { | |
| 48 | 1.13419, 1.09801, 1.03541, 1.45086, 1.72453, 1.654, 1.70536, 1.97393, | |
| 49 | 2.03543, 2.00643, 1.95531, 1.95426, 1.92438, 1.82092, 1.88517, 1.85545, | |
| 50 | 1.85083, 1.82758, 1.84475, 1.78771, 1.76683, 1.70858, 1.68278, 1.63849, | |
| 51 | 1.59608, 1.52211, 1.52468, 1.47836, 1.4485, 1.40522, 1.35526, 1.32788, | |
| 52 | 1.28834, 1.26938, 1.23241, 1.20345, 1.17087, 1.1344, 1.11012, 1.07147 | |
| 53 | }; | |
| 54 | 3x | IrradianceSpectrum result; |
| 55 | 123x | for (unsigned int i = 0; i < result.size(); ++i) { |
| 56 | 120x | result[i] = kSpectralIrradiance[i] * watt_per_square_meter_per_nm; |
| 57 | } | |
| 58 | 3x | return result; |
| 59 | } | |
| 60 | ||
| 61 | 3x | ScatteringSpectrum NewRayleighScattering() { |
| 62 | // Values from Table III in Penndorf 1957 "Tables of the Refractive Index for | |
| 63 | // Standard Air and the Rayleigh Scattering Coefficient for the Spectral | |
| 64 | // Region between 0.2 and 20.0 um and Their Application to Atmospheric Optics". | |
| 65 | static const float kPenndorf[48] = { | |
| 66 | 70.45E-6, 62.82E-6, 56.20E-6, 50.43E-6, 45.40E-6, 40.98E-6, 37.08E-6, | |
| 67 | 33.65E-6, 30.60E-6, 27.89E-6, 25.48E-6, 23.33E-6, 21.40E-6, 19.66E-6, | |
| 68 | 18.10E-6, 16.69E-6, 15.42E-6, 14.26E-6, 13.21E-6, 12.26E-6, 11.39E-6, | |
| 69 | 10.60E-6, 9.876E-6, 9.212E-6, 8.604E-6, 8.045E-6, 7.531E-6, 7.057E-6, | |
| 70 | 6.620E-6, 6.217E-6, 5.844E-6, 5.498E-6, 5.178E-6, 4.881E-6, 4.605E-6, | |
| 71 | 4.348E-6, 4.109E-6, 3.886E-6, 3.678E-6, 3.484E-6, 3.302E-6, 3.132E-6, | |
| 72 | 2.973E-6, 2.824E-6, 2.684E-6, 2.583E-6, 2.481E-6, 2.380E-6 | |
| 73 | }; | |
| 74 | 3x | std::vector<ScatteringCoefficient> penndorf_samples; |
| 75 | 147x | for (int i = 0; i < 48; ++i) { |
| 76 | // The above values are for T_0=0 deg C. For T=15 deg C, a correction factor | |
| 77 | // T_0 / T must be applied (Eq. (12) in Penndorf paper). | |
| 78 | 144x | constexpr double T_0 = 273.16; |
| 79 | 144x | constexpr double T = T_0 + 15.0; |
| 80 | 144x | penndorf_samples.push_back(kPenndorf[i] * (T_0 / T) / m); |
| 81 | } | |
| 82 | 6x | return ScatteringSpectrum(360.0 * nm, 830.0 * nm, penndorf_samples); |
| 83 | } | |
| 84 | ||
| 85 | 6x | ScatteringSpectrum NewMieExtinction(double angstrom_alpha, |
| 86 | double angstrom_beta) { | |
| 87 | 6x | ScatteringSpectrum mie; |
| 88 | 246x | for (unsigned int i = 0; i < mie.size(); ++i) { |
| 89 | 240x | double lambda = mie.GetSample(i).to(1000.0 * nm); |
| 90 | 240x | mie[i] = angstrom_beta * pow(lambda, -angstrom_alpha) / MieScaleHeight; |
| 91 | } | |
| 92 | 6x | return mie; |
| 93 | } | |
| 94 | ||
| 95 | 3x | ScatteringSpectrum NewMieScattering(double angstrom_alpha, |
| 96 | double angstrom_beta) { | |
| 97 | 3x | const double kSingleScatteringAlbedo = 0.8; |
| 98 | return | |
| 99 | 3x | NewMieExtinction(angstrom_alpha, angstrom_beta) * kSingleScatteringAlbedo; |
| 100 | } | |
| 101 | ||
| 102 | 3x | DimensionlessSpectrum NewGroundAlbedo() { |
| 103 | // Grass spectral albedo from Uwe Feister and Rolf Grewe, "Spectral albedo | |
| 104 | // measurements in the UV and visible region over different types of | |
| 105 | // surfaces", Photochemistry and Photobiology, 62, 736-744, 1995. | |
| 106 | static const float kGrassAlbedo[45] = { | |
| 107 | 0.018, 0.019, 0.019, 0.020, 0.022, 0.024, 0.027, 0.029, 0.030, 0.031, 0.032, | |
| 108 | 0.032, 0.032, 0.033, 0.035, 0.040, 0.055, 0.073, 0.084, 0.089, 0.089, 0.079, | |
| 109 | 0.069, 0.063, 0.061, 0.057, 0.052, 0.051, 0.048, 0.042, 0.039, 0.035, 0.035, | |
| 110 | 0.043, 0.087, 0.156, 0.234, 0.334, 0.437, 0.513, 0.553, 0.571, 0.579, 0.581, | |
| 111 | 0.587 | |
| 112 | }; | |
| 113 | 3x | std::vector<Number> grass_albedo_samples; |
| 114 | 138x | for (int i = 0; i < 45; ++i) { |
| 115 | 135x | grass_albedo_samples.push_back(kGrassAlbedo[i]); |
| 116 | } | |
| 117 | 6x | return DimensionlessSpectrum(360.0 * nm, 800.0 * nm, grass_albedo_samples); |
| 118 | } | |
| 119 | ||
| 120 | const IrradianceSpectrum solar_spectrum = NewSolarSpectrum(); | |
| 121 | const ScatteringSpectrum rayleigh_scattering = NewRayleighScattering(); | |
| 122 | const ScatteringSpectrum mie_extinction = | |
| 123 | NewMieExtinction(MieAngstromAlpha, MieAngstromBeta); | |
| 124 | const ScatteringSpectrum mie_scattering = | |
| 125 | NewMieScattering(MieAngstromAlpha, MieAngstromBeta); | |
| 126 | const DimensionlessSpectrum ground_albedo = NewGroundAlbedo(); | |
| 127 | ||
| 128 | } // anonymous namespace | |
| 129 | ||
| 130 | ! | const IrradianceSpectrum& SolarSpectrum() { return solar_spectrum; } |
| 131 | ! | const ScatteringSpectrum& RayleighScattering() { return rayleigh_scattering; } |
| 132 | ! | const ScatteringSpectrum& MieExtinction() { return mie_extinction; } |
| 133 | ! | const ScatteringSpectrum& MieScattering() { return mie_scattering; } |
| 134 | ||
| 135 | ! | ScatteringSpectrum MieExtinction(double angstrom_alpha, double angstrom_beta) { |
| 136 | ! | return NewMieExtinction(angstrom_alpha, angstrom_beta); |
| 137 | } | |
| 138 | ||
| 139 | ! | ScatteringSpectrum MieScattering(double angstrom_alpha, double angstrom_beta) { |
| 140 | ! | return NewMieScattering(angstrom_alpha, angstrom_beta); |
| 141 | } | |
| 142 | ||
| 143 | ! | InverseSolidAngle RayleighPhaseFunction(Angle scattering_angle) { |
| 144 | ! | return RayleighPhaseFunction(cos(scattering_angle)); |
| 145 | } | |
| 146 | ||
| 147 | ! | InverseSolidAngle RayleighPhaseFunction(Number scattering_angle_cosine) { |
| 148 | ! | constexpr InverseSolidAngle kRayleigh = |
| 149 | 3.0 / (16.0 * PI) * InverseSolidAngle::Unit(); | |
| 150 | ! | return kRayleigh * (1.0 + scattering_angle_cosine * scattering_angle_cosine); |
| 151 | } | |
| 152 | ||
| 153 | ! | InverseSolidAngle MiePhaseFunction(Angle scattering_angle) { |
| 154 | ! | return MiePhaseFunction(cos(scattering_angle)); |
| 155 | } | |
| 156 | ||
| 157 | ! | InverseSolidAngle MiePhaseFunction(Number scattering_angle_cosine) { |
| 158 | ! | constexpr double g = MiePhaseFunctionG; |
| 159 | ! | constexpr InverseSolidAngle kMie = 3.0 / (8.0 * PI) * |
| 160 | (1.0 - g * g) / (2.0 + g * g) * InverseSolidAngle::Unit(); | |
| 161 | ! | return kMie * (1.0 + scattering_angle_cosine * scattering_angle_cosine) / |
| 162 | ! | pow(1.0 + g * g - 2.0 * g * scattering_angle_cosine, 1.5); |
| 163 | } | |
| 164 | ||
| 165 | ! | InverseSolidAngle MiePhaseFunction(double g, Number scattering_angle_cosine) { |
| 166 | ! | const InverseSolidAngle kMie = 3.0 / (8.0 * PI) * |
| 167 | ! | (1.0 - g * g) / (2.0 + g * g) * InverseSolidAngle::Unit(); |
| 168 | ! | return kMie * (1.0 + scattering_angle_cosine * scattering_angle_cosine) / |
| 169 | ! | pow(1.0 + g * g - 2.0 * g * scattering_angle_cosine, 1.5); |
| 170 | } | |
| 171 | ||
| 172 | ! | const DimensionlessSpectrum& GroundAlbedo() { return ground_albedo; } |
| 173 | ||
| 174 | ! | int Atmosphere::GetOriginalNumberOfWavelengths() const { |
| 175 | ! | return DimensionlessSpectrum::SIZE; |
| 176 | } | |
| 177 | ||
| 178 | ! | IrradianceSpectrum Atmosphere::GetSkyIrradiance(Length altitude, |
| 179 | Angle sun_zenith) const { | |
| 180 | IrradianceSpectrum result = | |
| 181 | ! | IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm); |
| 182 | ! | const unsigned int N = 100; |
| 183 | ! | for (unsigned int i = 0; i < N / 2; ++i) { |
| 184 | ! | Angle view_zenith = (i + 0.5) * pi / N; |
| 185 | ! | Number cos_view_zenith = cos(view_zenith); |
| 186 | ! | Number sin_view_zenith = sin(view_zenith); |
| 187 | ! | for (unsigned int j = 0; j < 2 * N; ++j) { |
| 188 | ! | Angle view_azimuth = j * pi / N; |
| 189 | RadianceSpectrum incident_spectrum = | |
| 190 | ! | GetSkyRadiance(altitude, sun_zenith, view_zenith, view_azimuth); |
| 191 | ! | SolidAngle domega = sin_view_zenith * (PI / N) * (PI / N) * sr; |
| 192 | ! | result = result + incident_spectrum * cos_view_zenith * domega; |
| 193 | } | |
| 194 | } | |
| 195 | ! | return result; |
| 196 | } | |
| 197 | ||
| 198 | ! | RadianceSpectrum Atmosphere::GetSkyRadiance(Length altitude, Angle sun_zenith, |
| 199 | Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const { | |
| 200 | ! | return GetSkyRadiance( |
| 201 | ! | altitude, sun_zenith, view_zenith, view_azimuth - sun_azimuth); |
| 202 | } | |
| 203 | ||
| 204 | ! | Angle Atmosphere::GetViewSunAngle(Angle sun_zenith, Angle view_zenith, |
| 205 | Angle view_sun_azimuth) { | |
| 206 | ! | return acos(cos(view_sun_azimuth) * sin(view_zenith) * sin(sun_zenith) + |
| 207 | ! | cos(view_zenith) * cos(sun_zenith)); |
| 208 | } |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | * Copyright (c) 2016 Eric Bruneton | |
| 9 | * All rights reserved. | |
| 10 | * | |
| 11 | * Redistribution and use in source and binary forms, with or without | |
| 12 | * modification, are permitted provided that the following conditions | |
| 13 | * are met: | |
| 14 | * 1. Redistributions of source code must retain the above copyright | |
| 15 | * notice, this list of conditions and the following disclaimer. | |
| 16 | * 2. Redistributions in binary form must reproduce the above copyright | |
| 17 | * notice, this list of conditions and the following disclaimer in the | |
| 18 | * documentation and/or other materials provided with the distribution. | |
| 19 | * 3. Neither the name of the copyright holders nor the names of its | |
| 20 | * contributors may be used to endorse or promote products derived from | |
| 21 | * this software without specific prior written permission. | |
| 22 | * | |
| 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
| 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| 33 | * THE POSSIBILITY OF SUCH DAMAGE. | |
| 34 | */ | |
| 35 | ||
| 36 | #ifndef MATH_SCALAR_H_ | |
| 37 | #define MATH_SCALAR_H_ | |
| 38 | ||
| 39 | #include <algorithm> | |
| 40 | #include <cmath> | |
| 41 | ||
| 42 | namespace dimensional { | |
| 43 | ||
| 44 | // Internal class used to differentiate two Scalar constructors below. | |
| 45 | struct Double { | |
| 46 | const double value; | |
| 47 | 19698x | explicit inline constexpr Double(double value) : value(value) {} |
| 48 | }; | |
| 49 | ||
| 50 | // A scalar value with a dimension combining up to five base units (length, | |
| 51 | // mass, time, etc). The template parameters are the exponents of the base units | |
| 52 | // in the scalar value dimension. For instance, if U1 corresponds to length and | |
| 53 | // U3 to time, a speed is a Scalar<1, 0, -1, 0, 0> (length divided by time), an | |
| 54 | // area is a Scalar<2, 0, 0, 0, 0>, etc. The semantics of the base units is not | |
| 55 | // defined by this template so that it can be used with various unit systems. | |
| 56 | // NOTES: | |
| 57 | // - We intentionally do not provide a constructor from a literal value, except | |
| 58 | // for dimensionless scalars, in order to force the use of an explicit unit | |
| 59 | // (e.g. "Length l = 3.0 * m;"). | |
| 60 | // - Likewise, we intentionally do not provide a noarg accessor, except for | |
| 61 | // dimensionless scalars, in order to force the use of an explicit unit when | |
| 62 | // accessing a value (e.g. "double value = l.to(km);"). | |
| 63 | template<int U1, int U2, int U3, int U4, int U5> | |
| 64 | class Scalar { | |
| 65 | public: | |
| 66 | 1440x | Scalar() {} |
| 67 | 1440x | inline constexpr Scalar(double value) : value_(value) { |
| 68 | static_assert( | |
| 69 | U1 == 0 && U2 == 0 && U3 == 0 && U4 == 0 && U5 == 0, | |
| 70 | "This constructor is valid only for dimensionless values."); | |
| 71 | } | |
| 72 | 2400x | static constexpr Scalar Unit() { return Scalar(Double(1.0)); } |
| 73 | ||
| 74 | 1878x | inline constexpr double operator()() const { |
| 75 | static_assert( | |
| 76 | U1 == 0 && U2 == 0 && U3 == 0 && U4 == 0 && U5 == 0, | |
| 77 | "This operator is valid onlyfor dimensionless values."); | |
| 78 | 1878x | return value_; |
| 79 | } | |
| 80 | ||
| 81 | 240x | inline constexpr double to(const Scalar<U1, U2, U3, U4, U5> unit) const { |
| 82 | 240x | return value_ / unit.value_; |
| 83 | } | |
| 84 | ||
| 85 | 1440x | inline Scalar& operator=(const Scalar rhs) { |
| 86 | 1440x | value_ = rhs.value_; |
| 87 | 1440x | return *this; |
| 88 | } | |
| 89 | ||
| 90 | inline Scalar& operator+=(const Scalar rhs) { | |
| 91 | value_ += rhs.value_; | |
| 92 | return *this; | |
| 93 | } | |
| 94 | ||
| 95 | 3723x | inline constexpr Scalar operator+(const Scalar rhs) const { |
| 96 | 3723x | return Scalar(Double(value_ + rhs.value_)); |
| 97 | } | |
| 98 | ||
| 99 | inline constexpr Scalar operator-() const { | |
| 100 | return Scalar(Double(-value_)); | |
| 101 | } | |
| 102 | ||
| 103 | 1878x | inline constexpr Scalar operator-(const Scalar rhs) const { |
| 104 | 1878x | return Scalar(Double(value_ - rhs.value_)); |
| 105 | } | |
| 106 | ||
| 107 | 7566x | inline constexpr Scalar operator*(double rhs) const { |
| 108 | 7566x | return Scalar(Double(value_ * rhs)); |
| 109 | } | |
| 110 | ||
| 111 | template<int V1, int V2, int V3, int V4, int V5> | |
| 112 | inline constexpr | |
| 113 | ! | Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> operator*( |
| 114 | const Scalar<V1, V2, V3, V4, V5> rhs) const { | |
| 115 | ! | return Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>( |
| 116 | ! | Double(value_ * rhs.value_)); |
| 117 | } | |
| 118 | ||
| 119 | ! | inline constexpr Scalar operator/(double rhs) const { |
| 120 | ! | return Scalar(Double(value_ / rhs)); |
| 121 | } | |
| 122 | ||
| 123 | template<int V1, int V2, int V3, int V4, int V5> | |
| 124 | inline constexpr | |
| 125 | 939x | Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5> operator/( |
| 126 | const Scalar<V1, V2, V3, V4, V5> rhs) const { | |
| 127 | 939x | return Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>( |
| 128 | 1878x | Double(value_ / rhs.value_)); |
| 129 | } | |
| 130 | ||
| 131 | inline bool operator==(const Scalar<U1, U2, U3, U4, U5> rhs) const { | |
| 132 | return value_ == rhs.value_; | |
| 133 | } | |
| 134 | ||
| 135 | 5640x | inline bool operator<(const Scalar<U1, U2, U3, U4, U5> rhs) const { |
| 136 | 5640x | return value_ < rhs.value_; |
| 137 | } | |
| 138 | ||
| 139 | 960x | inline bool operator<=(const Scalar<U1, U2, U3, U4, U5> rhs) const { |
| 140 | 960x | return value_ <= rhs.value_; |
| 141 | } | |
| 142 | ||
| 143 | ! | inline bool operator>(const Scalar<U1, U2, U3, U4, U5> rhs) const { |
| 144 | ! | return value_ > rhs.value_; |
| 145 | } | |
| 146 | ||
| 147 | 945x | inline bool operator>=(const Scalar<U1, U2, U3, U4, U5> rhs) const { |
| 148 | 945x | return value_ >= rhs.value_; |
| 149 | } | |
| 150 | ||
| 151 | private: | |
| 152 | // Private constructor, which can construct a value of any dimension from | |
| 153 | // a double literal. In order to diffentiate this constructor from the | |
| 154 | // implicit constructor above, we use the auxilliary internal class "Double". | |
| 155 | 19698x | explicit inline constexpr Scalar(const Double value) : value_(value.value) {} |
| 156 | ||
| 157 | double value_; | |
| 158 | ||
| 159 | template<int V1, int V2, int V3, int V4, int V5> | |
| 160 | friend class Scalar; | |
| 161 | ||
| 162 | friend constexpr Scalar<0, 0, 0, 0, 0> operator+( | |
| 163 | double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 164 | ||
| 165 | friend constexpr Scalar<0, 0, 0, 0, 0> operator+( | |
| 166 | const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 167 | ||
| 168 | friend constexpr Scalar<0, 0, 0, 0, 0> operator-( | |
| 169 | double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 170 | ||
| 171 | friend constexpr Scalar<0, 0, 0, 0, 0> operator-( | |
| 172 | const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 173 | ||
| 174 | template<int V1, int V2, int V3, int V4, int V5> | |
| 175 | friend constexpr Scalar<V1, V2, V3, V4, V5> operator*( | |
| 176 | double lhs, const Scalar<V1, V2, V3, V4, V5> rhs); | |
| 177 | ||
| 178 | template<int V1, int V2, int V3, int V4, int V5> | |
| 179 | friend constexpr Scalar<-V1, -V2, -V3, -V4, -V5> operator/( | |
| 180 | double lhs, const Scalar<V1, V2, V3, V4, V5> rhs); | |
| 181 | ||
| 182 | friend bool operator<(const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 183 | friend bool operator<(double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 184 | friend bool operator<=(const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 185 | friend bool operator<=(double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 186 | friend bool operator>(const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 187 | friend bool operator>(double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 188 | friend bool operator>=(const Scalar<0, 0, 0, 0, 0> lhs, double rhs); | |
| 189 | friend bool operator>=(double lhs, const Scalar<0, 0, 0, 0, 0> rhs); | |
| 190 | ||
| 191 | friend constexpr Scalar<0, 0, 0, 0, 0> exp(const Scalar<0, 0, 0, 0, 0> x); | |
| 192 | friend Scalar<0, 0, 0, 0, 0> floor(const Scalar<0, 0, 0, 0, 0> x); | |
| 193 | friend constexpr Scalar<0, 0, 0, 0, 0> log(const Scalar<0, 0, 0, 0, 0> x); | |
| 194 | friend Scalar<0, 0, 0, 0, 0> max(const Scalar<0, 0, 0, 0, 0> x, double y); | |
| 195 | friend Scalar<0, 0, 0, 0, 0> max(double x, const Scalar<0, 0, 0, 0, 0> y); | |
| 196 | friend Scalar<0, 0, 0, 0, 0> min(const Scalar<0, 0, 0, 0, 0> x, double y); | |
| 197 | friend Scalar<0, 0, 0, 0, 0> min(double x, const Scalar<0, 0, 0, 0, 0> y); | |
| 198 | friend Scalar<0, 0, 0, 0, 0> pow(const Scalar<0, 0, 0, 0, 0> x, | |
| 199 | const Scalar<0, 0, 0, 0, 0> y); | |
| 200 | friend Scalar<0, 0, 0, 0, 0> pow(double x, const Scalar<0, 0, 0, 0, 0> y); | |
| 201 | friend Scalar<0, 0, 0, 0, 0> pow(const Scalar<0, 0, 0, 0, 0> x, double y); | |
| 202 | friend Scalar<0, 0, 0, 0, 0> sqrt(const Scalar<0, 0, 0, 0, 0> x); | |
| 203 | template<int V1, int V2, int V3, int V4, int V5> | |
| 204 | friend constexpr Scalar<V1 / 2, V2 / 2, V3 / 2, V4 / 2, V5 / 2> sqrt( | |
| 205 | const Scalar<V1, V2, V3, V4, V5> x); | |
| 206 | }; | |
| 207 | ||
| 208 | typedef Scalar<0, 0, 0, 0, 0> Dimensionless; | |
| 209 | typedef Scalar<0, 0, 0, 0, 0> Number; | |
| 210 | ||
| 211 | ! | inline constexpr Number operator+(double lhs, const Number rhs) { |
| 212 | ! | return lhs + rhs.value_; |
| 213 | } | |
| 214 | ||
| 215 | inline constexpr Number operator+(const Number lhs, double rhs) { | |
| 216 | return lhs.value_ + rhs; | |
| 217 | } | |
| 218 | ||
| 219 | ! | inline constexpr Number operator-(double lhs, const Number rhs) { |
| 220 | ! | return lhs - rhs.value_; |
| 221 | } | |
| 222 | ||
| 223 | inline constexpr Number operator-(const Number lhs, double rhs) { | |
| 224 | return lhs.value_ - rhs; | |
| 225 | } | |
| 226 | ||
| 227 | inline bool operator<(const Number lhs, double rhs) { | |
| 228 | return lhs.value_ < rhs; | |
| 229 | } | |
| 230 | ||
| 231 | inline bool operator<(double lhs, const Number rhs) { | |
| 232 | return lhs < rhs.value_; | |
| 233 | } | |
| 234 | ||
| 235 | inline bool operator<=(const Number lhs, double rhs) { | |
| 236 | return lhs.value_ <= rhs; | |
| 237 | } | |
| 238 | ||
| 239 | inline bool operator<=(double lhs, const Number rhs) { | |
| 240 | return lhs <= rhs.value_; | |
| 241 | } | |
| 242 | ||
| 243 | inline bool operator>(const Number lhs, double rhs) { | |
| 244 | return lhs.value_ > rhs; | |
| 245 | } | |
| 246 | ||
| 247 | inline bool operator>(double lhs, const Number rhs) { | |
| 248 | return lhs > rhs.value_; | |
| 249 | } | |
| 250 | ||
| 251 | inline bool operator>=(const Number lhs, double rhs) { | |
| 252 | return lhs.value_ >= rhs; | |
| 253 | } | |
| 254 | ||
| 255 | inline bool operator>=(double lhs, const Number rhs) { | |
| 256 | return lhs >= rhs.value_; | |
| 257 | } | |
| 258 | ||
| 259 | template<int U1, int U2, int U3, int U4, int U5> | |
| 260 | 2808x | inline constexpr Scalar<U1, U2, U3, U4, U5> operator*( |
| 261 | double lhs, const Scalar<U1, U2, U3, U4, U5> rhs) { | |
| 262 | 2808x | return Scalar<U1, U2, U3, U4, U5>(Double(lhs * rhs.value_)); |
| 263 | } | |
| 264 | ||
| 265 | template<int U1, int U2, int U3, int U4, int U5> | |
| 266 | 384x | inline constexpr Scalar<-U1, -U2, -U3, -U4, -U5> operator/( |
| 267 | double lhs, const Scalar<U1, U2, U3, U4, U5> rhs) { | |
| 268 | 384x | return Scalar<-U1, -U2, -U3, -U4, -U5>(Double(lhs / rhs.value_)); |
| 269 | } | |
| 270 | ||
| 271 | inline constexpr Number exp(const Number x) { return std::exp(x()); } | |
| 272 | inline Number floor(const Number x) { return std::floor(x()); } | |
| 273 | inline constexpr Number log(const Number x) { return std::log(x()); } | |
| 274 | inline Number max(const Number x, double y) { return std::max(x(), y); } | |
| 275 | inline Number max(double x, const Number y) { return std::max(x, y()); } | |
| 276 | inline Number min(const Number x, double y) { return std::min(x(), y); } | |
| 277 | inline Number min(double x, const Number y) { return std::min(x, y()); } | |
| 278 | inline Number pow(const Number x, const Number y) { return std::pow(x(), y()); } | |
| 279 | ! | inline Number pow(const Number x, double y) { return std::pow(x(), y); } |
| 280 | inline Number pow(double x, const Number y) { return std::pow(x, y()); } | |
| 281 | inline Number sqrt(const Number x) { return std::sqrt(x()); } | |
| 282 | ||
| 283 | template<int U1, int U2, int U3, int U4, int U5> | |
| 284 | constexpr Scalar<U1 / 2, U2 / 2, U3 / 2, U4 / 2, U5 / 2> sqrt( | |
| 285 | const Scalar<U1, U2, U3, U4, U5> x) { | |
| 286 | return Scalar<U1 / 2, U2 / 2, U3 / 2, U4 / 2, U5 / 2>( | |
| 287 | Double(std::sqrt(x.value_))); | |
| 288 | } | |
| 289 | ||
| 290 | template<typename T> | |
| 291 | T mod(T x, T y) { return x - y * floor(x / y); } | |
| 292 | inline double mod(double x, double y) { return x - y * std::floor(x / y); } | |
| 293 | inline Number mod(Number x, double y) { return x - y * floor(x / y); } | |
| 294 | inline Number mod(double x, Number y) { return x - y * floor(x / y); } | |
| 295 | ||
| 296 | template<typename T> | |
| 297 | 2784x | T lerp(T a, T b, double x) { return a * (1.0 - x) + b * x; } |
| 298 | ||
| 299 | template<typename T> | |
| 300 | T clamp(T x, T min, T max) { return std::max(min, std::min(max, x)); } | |
| 301 | ||
| 302 | template<typename T> | |
| 303 | T smoothstep(T edge0, T edge1, T x) { | |
| 304 | x = clamp((x - edge0) / (edge1 - edge0), T(0.0), T(1.0)); | |
| 305 | return x * x * (3.0 - 2.0 * x); | |
| 306 | } | |
| 307 | ||
| 308 | } // namespace dimensional | |
| 309 | ||
| 310 | #endif // MATH_SCALAR_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | * Copyright (c) 2016 Eric Bruneton | |
| 9 | * All rights reserved. | |
| 10 | * | |
| 11 | * Redistribution and use in source and binary forms, with or without | |
| 12 | * modification, are permitted provided that the following conditions | |
| 13 | * are met: | |
| 14 | * 1. Redistributions of source code must retain the above copyright | |
| 15 | * notice, this list of conditions and the following disclaimer. | |
| 16 | * 2. Redistributions in binary form must reproduce the above copyright | |
| 17 | * notice, this list of conditions and the following disclaimer in the | |
| 18 | * documentation and/or other materials provided with the distribution. | |
| 19 | * 3. Neither the name of the copyright holders nor the names of its | |
| 20 | * contributors may be used to endorse or promote products derived from | |
| 21 | * this software without specific prior written permission. | |
| 22 | * | |
| 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
| 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| 33 | * THE POSSIBILITY OF SUCH DAMAGE. | |
| 34 | */ | |
| 35 | ||
| 36 | #ifndef MATH_SCALAR_FUNCTION_H_ | |
| 37 | #define MATH_SCALAR_FUNCTION_H_ | |
| 38 | ||
| 39 | #include <algorithm> | |
| 40 | #include <cassert> | |
| 41 | #include <vector> | |
| 42 | ||
| 43 | #include "../math/scalar.h" | |
| 44 | ||
| 45 | namespace dimensional { | |
| 46 | ||
| 47 | // A function from scalars of type Scalar<U1, U2, U3, U4, U5> to scalars of type | |
| 48 | // Scalar<V1, V2, V3, V4, V5>, represented with N uniformly distributed samples | |
| 49 | // between MIN and MAX in the input domain, and linearly interpolated in | |
| 50 | // between. | |
| 51 | template< | |
| 52 | int U1, int U2, int U3, int U4, int U5, | |
| 53 | int V1, int V2, int V3, int V4, int V5, | |
| 54 | unsigned int N, int MIN, int MAX> | |
| 55 | class ScalarFunction { | |
| 56 | public: | |
| 57 | constexpr static unsigned int SIZE = N; | |
| 58 | typedef Scalar<U1, U2, U3, U4, U5> input_type; | |
| 59 | typedef Scalar<V1, V2, V3, V4, V5> output_type; | |
| 60 | ||
| 61 | 492x | ScalarFunction() {} |
| 62 | ||
| 63 | ! | explicit ScalarFunction(const output_type& constant_value) { |
| 64 | ! | for (unsigned int i = 0; i < N; ++i) { |
| 65 | ! | value_[i] = constant_value; |
| 66 | } | |
| 67 | } | |
| 68 | ||
| 69 | ScalarFunction(const std::vector<float>& sampled_values, output_type unit) { | |
| 70 | for (unsigned int i = 0; i < N; ++i) { | |
| 71 | value_[i] = (i < sampled_values.size() ? sampled_values[i] : 0.0) * unit; | |
| 72 | } | |
| 73 | } | |
| 74 | ||
| 75 | ScalarFunction(const ScalarFunction& rhs) { | |
| 76 | for (unsigned int i = 0; i < N; ++i) { | |
| 77 | value_[i] = rhs.value_[i]; | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | // Creates a new function from the given values, sampled at the given sampling | |
| 82 | // points. The given vectors must have the same size n and sampling_points | |
| 83 | // must be sorted in increasing order. The input function is supposed constant | |
| 84 | // outside the sampling interval (i.e. for x < sampling_points[0] and for | |
| 85 | // x > sampling_points[n - 1]) and is linearly interpolated between samples. | |
| 86 | ScalarFunction(const std::vector<input_type>& sampling_points, | |
| 87 | const std::vector<output_type>& sampled_values) { | |
| 88 | Init(sampling_points, sampled_values); | |
| 89 | } | |
| 90 | ||
| 91 | // Creates a new function from the given values, uniformly sampled from | |
| 92 | // 'min_input' and 'max_input' (inclusive). The input function is supposed | |
| 93 | // constant outside the sampling interval (i.e. for x < min_input and for | |
| 94 | // x > max_input) and is linearly interpolated between samples. | |
| 95 | 24x | ScalarFunction(input_type min_input, input_type max_input, |
| 96 | 984x | const std::vector<output_type> values) { |
| 97 | 24x | std::vector<input_type> sampling_points; |
| 98 | 1608x | for (unsigned int i = 0; i < values.size(); ++i) { |
| 99 | 1584x | sampling_points.push_back( |
| 100 | 3168x | lerp(min_input, max_input, i / (values.size() - 1.0))); |
| 101 | } | |
| 102 | 24x | Init(sampling_points, values); |
| 103 | } | |
| 104 | ||
| 105 | std::vector<double> to(output_type unit) { | |
| 106 | std::vector<double> result; | |
| 107 | for (unsigned int i = 0; i < N; ++i) { | |
| 108 | result.push_back(value_[i].to(unit)); | |
| 109 | } | |
| 110 | return result; | |
| 111 | } | |
| 112 | ||
| 113 | ! | ScalarFunction& operator=(const ScalarFunction& rhs) { |
| 114 | ! | for (unsigned int i = 0; i < N; ++i) { |
| 115 | ! | value_[i] = rhs.value_[i]; |
| 116 | } | |
| 117 | ! | return *this; |
| 118 | } | |
| 119 | ||
| 120 | ScalarFunction& operator+=(const ScalarFunction& rhs) { | |
| 121 | for (unsigned int i = 0; i < N; ++i) { | |
| 122 | value_[i] += rhs.value_[i]; | |
| 123 | } | |
| 124 | return *this; | |
| 125 | } | |
| 126 | ||
| 127 | ! | ScalarFunction operator+(const ScalarFunction& rhs) const { |
| 128 | ! | ScalarFunction result; |
| 129 | ! | for (unsigned int i = 0; i < N; ++i) { |
| 130 | ! | result.value_[i] = value_[i] + rhs.value_[i]; |
| 131 | } | |
| 132 | ! | return result; |
| 133 | } | |
| 134 | ||
| 135 | ScalarFunction operator-() const { | |
| 136 | ScalarFunction result; | |
| 137 | for (unsigned int i = 0; i < N; ++i) { | |
| 138 | result.value_[i] = -value_[i]; | |
| 139 | } | |
| 140 | return result; | |
| 141 | } | |
| 142 | ||
| 143 | ScalarFunction operator-(const ScalarFunction& rhs) const { | |
| 144 | ScalarFunction result; | |
| 145 | for (unsigned int i = 0; i < N; ++i) { | |
| 146 | result.value_[i] = value_[i] - rhs.value_[i]; | |
| 147 | } | |
| 148 | return result; | |
| 149 | } | |
| 150 | ||
| 151 | 3x | ScalarFunction operator*(double rhs) const { |
| 152 | 3x | ScalarFunction result; |
| 153 | 123x | for (unsigned int i = 0; i < N; ++i) { |
| 154 | 120x | result.value_[i] = value_[i] * rhs; |
| 155 | } | |
| 156 | 3x | return result; |
| 157 | } | |
| 158 | ||
| 159 | template<int W1, int W2, int W3, int W4, int W5> | |
| 160 | ScalarFunction< | |
| 161 | U1, U2, U3, U4, U5, | |
| 162 | V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5, | |
| 163 | N, MIN, MAX> | |
| 164 | ! | operator*(Scalar<W1, W2, W3, W4, W5> rhs) const { |
| 165 | ScalarFunction< | |
| 166 | U1, U2, U3, U4, U5, | |
| 167 | V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5, | |
| 168 | ! | N, MIN, MAX> result; |
| 169 | ! | for (unsigned int i = 0; i < N; ++i) { |
| 170 | ! | result[i] = value_[i] * rhs; |
| 171 | } | |
| 172 | ! | return result; |
| 173 | } | |
| 174 | ||
| 175 | template<int W1, int W2, int W3, int W4, int W5> | |
| 176 | ScalarFunction< | |
| 177 | U1, U2, U3, U4, U5, | |
| 178 | V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5, | |
| 179 | N, MIN, MAX> | |
| 180 | ! | operator*(const ScalarFunction< |
| 181 | U1, U2, U3, U4, U5, W1, W2, W3, W4, W5, N, MIN, MAX>& rhs) const { | |
| 182 | ScalarFunction< | |
| 183 | U1, U2, U3, U4, U5, | |
| 184 | V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5, | |
| 185 | ! | N, MIN, MAX> result; |
| 186 | ! | for (unsigned int i = 0; i < N; ++i) { |
| 187 | ! | result[i] = value_[i] * rhs[i]; |
| 188 | } | |
| 189 | ! | return result; |
| 190 | } | |
| 191 | ||
| 192 | template<int W1, int W2, int W3, int W4, int W5> | |
| 193 | ScalarFunction< | |
| 194 | U1, U2, U3, U4, U5, | |
| 195 | V1 - W1, V2 - W2, V3 - W3, V4 - W4, V5 - W5, | |
| 196 | N, MIN, MAX> | |
| 197 | operator/(const ScalarFunction< | |
| 198 | U1, U2, U3, U4, U5, W1, W2, W3, W4, W5, N, MIN, MAX>& rhs) const { | |
| 199 | ScalarFunction< | |
| 200 | U1, U2, U3, U4, U5, | |
| 201 | V1 - W1, V2 - W2, V3 - W3, V4 - W4, V5 - W5, | |
| 202 | N, MIN, MAX> result; | |
| 203 | for (unsigned int i = 0; i < N; ++i) { | |
| 204 | result[i] = value_[i] / rhs[i]; | |
| 205 | } | |
| 206 | return result; | |
| 207 | } | |
| 208 | ||
| 209 | 369x | inline unsigned int size() const { |
| 210 | 369x | return N; |
| 211 | } | |
| 212 | ||
| 213 | ! | inline const output_type operator[](int index) const { |
| 214 | ! | return value_[index]; |
| 215 | } | |
| 216 | ||
| 217 | 360x | inline output_type& operator[](int index) { |
| 218 | 360x | return value_[index]; |
| 219 | } | |
| 220 | ||
| 221 | 1200x | inline input_type GetSample(int sample_index) const { |
| 222 | 1200x | double u = static_cast<double>(sample_index) / N; |
| 223 | 1200x | return lerp(MIN * input_type::Unit(), MAX * input_type::Unit(), u); |
| 224 | } | |
| 225 | ||
| 226 | ! | const output_type operator()(input_type x) const { |
| 227 | ! | double u = (x.to(input_type::Unit()) - MIN) / (MAX - MIN) * N; |
| 228 | ! | int i = std::floor(u); |
| 229 | ! | u -= i; |
| 230 | ! | int i0 = std::max(0, std::min(static_cast<int>(N) - 1, i)); |
| 231 | ! | int i1 = std::max(0, std::min(static_cast<int>(N) - 1, i + 1)); |
| 232 | ! | return value_[i0] * (1.0 - u) + value_[i1] * u; |
| 233 | } | |
| 234 | ||
| 235 | private: | |
| 236 | 24x | void Init(const std::vector<input_type>& sampling_points, |
| 237 | const std::vector<output_type>& sampled_values) { | |
| 238 | assert(sampling_points.size() == sampled_values.size()); | |
| 239 | 984x | for (unsigned int i = 0; i < N; ++i) { |
| 240 | 960x | input_type x = GetSample(i); |
| 241 | // Find the two nearest sampling points around 'x' using binary search and | |
| 242 | // return the corresponding sampled values, linearly interpolated. | |
| 243 | 960x | int min_index = 0; |
| 244 | 960x | int max_index = sampling_points.size() - 1; |
| 245 | 960x | if (x <= sampling_points[min_index]) { |
| 246 | 15x | value_[i] = sampled_values[min_index]; |
| 247 | 21x | continue; |
| 248 | } | |
| 249 | 945x | if (x >= sampling_points[max_index]) { |
| 250 | 6x | value_[i] = sampled_values[max_index]; |
| 251 | 6x | continue; |
| 252 | } | |
| 253 | 6579x | while (max_index - min_index > 1) { |
| 254 | 5640x | int mid_index = (min_index + max_index) / 2; |
| 255 | 5640x | if (x < sampling_points[mid_index]) { |
| 256 | 2691x | max_index = mid_index; |
| 257 | } else { | |
| 258 | 2949x | min_index = mid_index; |
| 259 | } | |
| 260 | } | |
| 261 | 939x | Number u = (x - sampling_points[min_index]) / |
| 262 | 939x | (sampling_points[max_index] - sampling_points[min_index]); |
| 263 | 1878x | value_[i] = sampled_values[min_index] * (1.0 - u()) + |
| 264 | 939x | sampled_values[max_index] * u(); |
| 265 | } | |
| 266 | } | |
| 267 | ||
| 268 | output_type value_[N]; | |
| 269 | }; | |
| 270 | ||
| 271 | template< | |
| 272 | int U1, int U2, int U3, int U4, int U5, | |
| 273 | int V1, int V2, int V3, int V4, int V5, | |
| 274 | unsigned int N, int MIN, int MAX> | |
| 275 | ScalarFunction<U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX> | |
| 276 | min(const ScalarFunction< | |
| 277 | U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& a, | |
| 278 | const ScalarFunction< | |
| 279 | U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& b) { | |
| 280 | ScalarFunction<U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX> result; | |
| 281 | for (unsigned int i = 0; i < result.size(); ++i) { | |
| 282 | result[i] = a[i] < b[i] ? a[i] : b[i]; | |
| 283 | } | |
| 284 | return result; | |
| 285 | } | |
| 286 | ||
| 287 | template< | |
| 288 | int U1, int U2, int U3, int U4, int U5, | |
| 289 | unsigned int N, int MIN, int MAX> | |
| 290 | ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX> | |
| 291 | exp(const ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX>& f) { | |
| 292 | ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX> result; | |
| 293 | for (unsigned int i = 0; i < result.size(); ++i) { | |
| 294 | result[i] = exp(f[i]); | |
| 295 | } | |
| 296 | return result; | |
| 297 | } | |
| 298 | ||
| 299 | // Returns the integral of the given function over its range, | |
| 300 | // i.e. integral of function * dx from MIN to MAX. | |
| 301 | template< | |
| 302 | int U1, int U2, int U3, int U4, int U5, | |
| 303 | int V1, int V2, int V3, int V4, int V5, | |
| 304 | unsigned int N, int MIN, int MAX> | |
| 305 | Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> | |
| 306 | ! | Integral(const ScalarFunction< |
| 307 | U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f) { | |
| 308 | ! | Scalar<V1, V2, V3, V4, V5> sum = 0.0 * Scalar<V1, V2, V3, V4, V5>::Unit(); |
| 309 | ! | for (unsigned int i = 0; i < f.size(); ++i) { |
| 310 | ! | sum = sum + f[i]; |
| 311 | } | |
| 312 | ! | return sum * ((MAX - MIN) * Scalar<U1, U2, U3, U4, U5>::Unit() / N); |
| 313 | } | |
| 314 | ||
| 315 | // Returns the integral of the given function over a subset of its range, | |
| 316 | // i.e. integral of function * dx from min_value to max_value, using the | |
| 317 | // specified number of samples. | |
| 318 | template< | |
| 319 | int U1, int U2, int U3, int U4, int U5, | |
| 320 | int V1, int V2, int V3, int V4, int V5, | |
| 321 | unsigned int N, int MIN, int MAX> | |
| 322 | Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> | |
| 323 | ! | Integral(const ScalarFunction< |
| 324 | U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f, | |
| 325 | Scalar<U1, U2, U3, U4, U5> min_value, Scalar<U1, U2, U3, U4, U5> max_value, | |
| 326 | int number_of_samples) { | |
| 327 | const Scalar<U1, U2, U3, U4, U5> dx = | |
| 328 | ! | (max_value - min_value) / number_of_samples; |
| 329 | ! | Scalar<U1, U2, U3, U4, U5> x = min_value; |
| 330 | ! | Scalar<V1, V2, V3, V4, V5> sum = 0.0 * Scalar<V1, V2, V3, V4, V5>::Unit(); |
| 331 | ! | for (int i = 0; i < number_of_samples; ++i) { |
| 332 | ! | sum = sum + f(x); |
| 333 | ! | x = x + dx; |
| 334 | } | |
| 335 | ! | return sum * dx; |
| 336 | } | |
| 337 | ||
| 338 | // Returns the integral of the given function over a subset of its range, | |
| 339 | // i.e. integral of function * dx from min_value to max_value. | |
| 340 | template< | |
| 341 | int U1, int U2, int U3, int U4, int U5, | |
| 342 | int V1, int V2, int V3, int V4, int V5, | |
| 343 | unsigned int N, int MIN, int MAX> | |
| 344 | Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> | |
| 345 | Integral(const ScalarFunction< | |
| 346 | U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f, | |
| 347 | Scalar<U1, U2, U3, U4, U5> min_value, | |
| 348 | Scalar<U1, U2, U3, U4, U5> max_value) { | |
| 349 | constexpr auto kUnit = Scalar<U1, U2, U3, U4, U5>::Unit(); | |
| 350 | assert(min_value >= MIN * kUnit); | |
| 351 | assert(max_value <= MAX * kUnit); | |
| 352 | Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> sum = | |
| 353 | 0.0 * Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>::Unit(); | |
| 354 | for (unsigned int i = 0; i < f.size(); ++i) { | |
| 355 | Scalar<U1, U2, U3, U4, U5> dx = | |
| 356 | std::min(f.GetSample(i + 1), max_value) - | |
| 357 | std::max(f.GetSample(i), min_value); | |
| 358 | sum = sum + f[i] * std::max(dx, 0.0 * kUnit); | |
| 359 | } | |
| 360 | return sum; | |
| 361 | } | |
| 362 | ||
| 363 | } // namespace dimensional | |
| 364 | ||
| 365 | #endif // MATH_SCALAR_FUNCTION_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | * Copyright (c) 2016 Eric Bruneton | |
| 9 | * All rights reserved. | |
| 10 | * | |
| 11 | * Redistribution and use in source and binary forms, with or without | |
| 12 | * modification, are permitted provided that the following conditions | |
| 13 | * are met: | |
| 14 | * 1. Redistributions of source code must retain the above copyright | |
| 15 | * notice, this list of conditions and the following disclaimer. | |
| 16 | * 2. Redistributions in binary form must reproduce the above copyright | |
| 17 | * notice, this list of conditions and the following disclaimer in the | |
| 18 | * documentation and/or other materials provided with the distribution. | |
| 19 | * 3. Neither the name of the copyright holders nor the names of its | |
| 20 | * contributors may be used to endorse or promote products derived from | |
| 21 | * this software without specific prior written permission. | |
| 22 | * | |
| 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
| 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| 33 | * THE POSSIBILITY OF SUCH DAMAGE. | |
| 34 | */ | |
| 35 | ||
| 36 | #ifndef MATH_ANGLE_H_ | |
| 37 | #define MATH_ANGLE_H_ | |
| 38 | ||
| 39 | #include <cmath> | |
| 40 | ||
| 41 | #include "../math/scalar.h" | |
| 42 | ||
| 43 | namespace dimensional { | |
| 44 | ||
| 45 | // An angle, represented with its own class to make sure it is properly used | |
| 46 | // (e.g. that degrees are not used when radians are expected or vice versa). | |
| 47 | // NOTES: | |
| 48 | // - We intentionally do not provide a constructor from a literal value in order | |
| 49 | // to force the use of an explicit unit (e.g. "Angle a = 3.0 * deg;"). | |
| 50 | // - Likewise, we intentionally do not provide a noarg accessor, in order to | |
| 51 | // force the use of an explicit unit when accessing the angle value (e.g. | |
| 52 | // "double value = a.to(rad);"). | |
| 53 | class Angle { | |
| 54 | public: | |
| 55 | ! | Angle() {} |
| 56 | static constexpr Angle Unit() { return Angle(1.0); } | |
| 57 | ||
| 58 | ! | inline constexpr double to(const Angle unit) const { |
| 59 | ! | return value_ / unit.value_; |
| 60 | } | |
| 61 | ||
| 62 | ! | inline Angle& operator=(const Angle rhs) { |
| 63 | ! | value_ = rhs.value_; |
| 64 | ! | return *this; |
| 65 | } | |
| 66 | ||
| 67 | inline constexpr Angle operator+(const Angle rhs) const { | |
| 68 | return Angle(value_ + rhs.value_); | |
| 69 | } | |
| 70 | ||
| 71 | ! | inline constexpr Angle operator-(const Angle rhs) const { |
| 72 | ! | return Angle(value_ - rhs.value_); |
| 73 | } | |
| 74 | ||
| 75 | inline constexpr Angle operator-() const { | |
| 76 | return Angle(-value_); | |
| 77 | } | |
| 78 | ||
| 79 | inline constexpr Angle operator*(const Number rhs) const { | |
| 80 | return Angle(value_ * rhs()); | |
| 81 | } | |
| 82 | ||
| 83 | ! | inline constexpr Angle operator/(const Number rhs) const { |
| 84 | ! | return Angle(value_ / rhs()); |
| 85 | } | |
| 86 | ||
| 87 | inline constexpr Number operator/(const Angle rhs) const { | |
| 88 | return value_ / rhs.value_; | |
| 89 | } | |
| 90 | ||
| 91 | ! | inline bool operator==(const Angle rhs) const { |
| 92 | ! | return value_ == rhs.value_; |
| 93 | } | |
| 94 | ||
| 95 | inline constexpr bool operator<(const Angle rhs) const { | |
| 96 | return value_ < rhs.value_; | |
| 97 | } | |
| 98 | ||
| 99 | inline constexpr bool operator<=(const Angle rhs) const { | |
| 100 | return value_ <= rhs.value_; | |
| 101 | } | |
| 102 | ||
| 103 | inline constexpr bool operator>(const Angle rhs) const { | |
| 104 | return value_ > rhs.value_; | |
| 105 | } | |
| 106 | ||
| 107 | inline constexpr bool operator>=(const Angle rhs) const { | |
| 108 | return value_ >= rhs.value_; | |
| 109 | } | |
| 110 | ||
| 111 | private: | |
| 112 | ! | explicit constexpr Angle(double value) : value_(value) {} |
| 113 | ||
| 114 | double value_; | |
| 115 | ||
| 116 | friend constexpr Angle operator*(const Number lhs, const Angle rhs); | |
| 117 | friend Number cos(Angle); | |
| 118 | friend Number sin(Angle); | |
| 119 | friend Number tan(Angle); | |
| 120 | }; | |
| 121 | ||
| 122 | ! | inline constexpr Angle operator*(const Number lhs, const Angle rhs) { |
| 123 | ! | return Angle(lhs() * rhs.value_); |
| 124 | } | |
| 125 | ||
| 126 | constexpr double PI = 3.14159265358979323846; | |
| 127 | ||
| 128 | constexpr Angle rad = Angle::Unit(); | |
| 129 | constexpr Angle pi = PI * rad; | |
| 130 | constexpr Angle deg = pi / 180.0; | |
| 131 | ||
| 132 | ! | constexpr inline Angle acos(const Number cosine) { |
| 133 | ! | return std::acos(cosine()) * rad; |
| 134 | } | |
| 135 | constexpr inline Angle asin(const Number sine) { | |
| 136 | return std::asin(sine()) * rad; | |
| 137 | } | |
| 138 | inline Angle atan(const Number x) { return std::atan(x()) * rad; } | |
| 139 | inline Angle atan2(const Number y, const Number x) { | |
| 140 | return std::atan2(y(), x()) * rad; | |
| 141 | } | |
| 142 | ! | inline Number cos(const Angle angle) { return std::cos(angle.value_); } |
| 143 | ! | inline Number sin(const Angle angle) { return std::sin(angle.value_); } |
| 144 | inline Number tan(const Angle angle) { return std::tan(angle.value_); } | |
| 145 | ||
| 146 | } // namespace dimensional | |
| 147 | ||
| 148 | #endif // MATH_ANGLE_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | Copyright (c) 2015 Eric Bruneton | |
| 9 | All rights reserved. | |
| 10 | ||
| 11 | Redistribution and use in source and binary forms, with or without | |
| 12 | modification, are permitted provided that the following conditions are met: | |
| 13 | ||
| 14 | 1. Redistributions of source code must retain the above copyright notice, this | |
| 15 | list of conditions and the following disclaimer. | |
| 16 | ||
| 17 | 2. Redistributions in binary form must reproduce the above copyright notice, | |
| 18 | this list of conditions and the following disclaimer in the documentation | |
| 19 | and/or other materials provided with the distribution. | |
| 20 | ||
| 21 | 3. Neither the name of the copyright holder nor the names of its contributors | |
| 22 | may be used to endorse or promote products derived from this software without | |
| 23 | specific prior written permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| 29 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 30 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| 31 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| 32 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| 33 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 34 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | #include "cie.h" | |
| 37 | ||
| 38 | #include <algorithm> | |
| 39 | #include <vector> | |
| 40 | ||
| 41 | namespace { | |
| 42 | ||
| 43 | struct Tables { | |
| 44 | std::vector<Number> x_bar_samples; | |
| 45 | std::vector<Number> y_bar_samples; | |
| 46 | std::vector<Number> z_bar_samples; | |
| 47 | std::vector<Number> S0_samples; | |
| 48 | std::vector<Number> S1_samples; | |
| 49 | std::vector<Number> S2_samples; | |
| 50 | ||
| 51 | 3x | Tables() { |
| 52 | // Values from "CIE (1931) 2-deg color matching functions", see | |
| 53 | // "http://web.archive.org/web/20081228084047/ | |
| 54 | // http://www.cvrl.org/database/data/cmfs/ciexyz31.txt". | |
| 55 | 3x | Add(0.000000000000, 0.000000000000, 0.000000000000); |
| 56 | 3x | Add(0.000129900000, 0.000003917000, 0.000606100000); |
| 57 | 3x | Add(0.000232100000, 0.000006965000, 0.001086000000); |
| 58 | 3x | Add(0.000414900000, 0.000012390000, 0.001946000000); |
| 59 | 3x | Add(0.000741600000, 0.000022020000, 0.003486000000); |
| 60 | 3x | Add(0.001368000000, 0.000039000000, 0.006450001000); |
| 61 | 3x | Add(0.002236000000, 0.000064000000, 0.010549990000); |
| 62 | 3x | Add(0.004243000000, 0.000120000000, 0.020050010000); |
| 63 | 3x | Add(0.007650000000, 0.000217000000, 0.036210000000); |
| 64 | 3x | Add(0.014310000000, 0.000396000000, 0.067850010000); |
| 65 | 3x | Add(0.023190000000, 0.000640000000, 0.110200000000); |
| 66 | 3x | Add(0.043510000000, 0.001210000000, 0.207400000000); |
| 67 | 3x | Add(0.077630000000, 0.002180000000, 0.371300000000); |
| 68 | 3x | Add(0.134380000000, 0.004000000000, 0.645600000000); |
| 69 | 3x | Add(0.214770000000, 0.007300000000, 1.039050100000); |
| 70 | 3x | Add(0.283900000000, 0.011600000000, 1.385600000000); |
| 71 | 3x | Add(0.328500000000, 0.016840000000, 1.622960000000); |
| 72 | 3x | Add(0.348280000000, 0.023000000000, 1.747060000000); |
| 73 | 3x | Add(0.348060000000, 0.029800000000, 1.782600000000); |
| 74 | 3x | Add(0.336200000000, 0.038000000000, 1.772110000000); |
| 75 | 3x | Add(0.318700000000, 0.048000000000, 1.744100000000); |
| 76 | 3x | Add(0.290800000000, 0.060000000000, 1.669200000000); |
| 77 | 3x | Add(0.251100000000, 0.073900000000, 1.528100000000); |
| 78 | 3x | Add(0.195360000000, 0.090980000000, 1.287640000000); |
| 79 | 3x | Add(0.142100000000, 0.112600000000, 1.041900000000); |
| 80 | 3x | Add(0.095640000000, 0.139020000000, 0.812950100000); |
| 81 | 3x | Add(0.057950010000, 0.169300000000, 0.616200000000); |
| 82 | 3x | Add(0.032010000000, 0.208020000000, 0.465180000000); |
| 83 | 3x | Add(0.014700000000, 0.258600000000, 0.353300000000); |
| 84 | 3x | Add(0.004900000000, 0.323000000000, 0.272000000000); |
| 85 | 3x | Add(0.002400000000, 0.407300000000, 0.212300000000); |
| 86 | 3x | Add(0.009300000000, 0.503000000000, 0.158200000000); |
| 87 | 3x | Add(0.029100000000, 0.608200000000, 0.111700000000); |
| 88 | 3x | Add(0.063270000000, 0.710000000000, 0.078249990000); |
| 89 | 3x | Add(0.109600000000, 0.793200000000, 0.057250010000); |
| 90 | 3x | Add(0.165500000000, 0.862000000000, 0.042160000000); |
| 91 | 3x | Add(0.225749900000, 0.914850100000, 0.029840000000); |
| 92 | 3x | Add(0.290400000000, 0.954000000000, 0.020300000000); |
| 93 | 3x | Add(0.359700000000, 0.980300000000, 0.013400000000); |
| 94 | 3x | Add(0.433449900000, 0.994950100000, 0.008749999000); |
| 95 | 3x | Add(0.512050100000, 1.000000000000, 0.005749999000); |
| 96 | 3x | Add(0.594500000000, 0.995000000000, 0.003900000000); |
| 97 | 3x | Add(0.678400000000, 0.978600000000, 0.002749999000); |
| 98 | 3x | Add(0.762100000000, 0.952000000000, 0.002100000000); |
| 99 | 3x | Add(0.842500000000, 0.915400000000, 0.001800000000); |
| 100 | 3x | Add(0.916300000000, 0.870000000000, 0.001650001000); |
| 101 | 3x | Add(0.978600000000, 0.816300000000, 0.001400000000); |
| 102 | 3x | Add(1.026300000000, 0.757000000000, 0.001100000000); |
| 103 | 3x | Add(1.056700000000, 0.694900000000, 0.001000000000); |
| 104 | 3x | Add(1.062200000000, 0.631000000000, 0.000800000000); |
| 105 | 3x | Add(1.045600000000, 0.566800000000, 0.000600000000); |
| 106 | 3x | Add(1.002600000000, 0.503000000000, 0.000340000000); |
| 107 | 3x | Add(0.938400000000, 0.441200000000, 0.000240000000); |
| 108 | 3x | Add(0.854449900000, 0.381000000000, 0.000190000000); |
| 109 | 3x | Add(0.751400000000, 0.321000000000, 0.000100000000); |
| 110 | 3x | Add(0.642400000000, 0.265000000000, 0.000049999990); |
| 111 | 3x | Add(0.541900000000, 0.217000000000, 0.000030000000); |
| 112 | 3x | Add(0.447900000000, 0.175000000000, 0.000020000000); |
| 113 | 3x | Add(0.360800000000, 0.138200000000, 0.000010000000); |
| 114 | 3x | Add(0.283500000000, 0.107000000000, 0.000000000000); |
| 115 | 3x | Add(0.218700000000, 0.081600000000, 0.000000000000); |
| 116 | 3x | Add(0.164900000000, 0.061000000000, 0.000000000000); |
| 117 | 3x | Add(0.121200000000, 0.044580000000, 0.000000000000); |
| 118 | 3x | Add(0.087400000000, 0.032000000000, 0.000000000000); |
| 119 | 3x | Add(0.063600000000, 0.023200000000, 0.000000000000); |
| 120 | 3x | Add(0.046770000000, 0.017000000000, 0.000000000000); |
| 121 | 3x | Add(0.032900000000, 0.011920000000, 0.000000000000); |
| 122 | 3x | Add(0.022700000000, 0.008210000000, 0.000000000000); |
| 123 | 3x | Add(0.015840000000, 0.005723000000, 0.000000000000); |
| 124 | 3x | Add(0.011359160000, 0.004102000000, 0.000000000000); |
| 125 | 3x | Add(0.008110916000, 0.002929000000, 0.000000000000); |
| 126 | 3x | Add(0.005790346000, 0.002091000000, 0.000000000000); |
| 127 | 3x | Add(0.004109457000, 0.001484000000, 0.000000000000); |
| 128 | 3x | Add(0.002899327000, 0.001047000000, 0.000000000000); |
| 129 | 3x | Add(0.002049190000, 0.000740000000, 0.000000000000); |
| 130 | 3x | Add(0.001439971000, 0.000520000000, 0.000000000000); |
| 131 | 3x | Add(0.000999949300, 0.000361100000, 0.000000000000); |
| 132 | 3x | Add(0.000690078600, 0.000249200000, 0.000000000000); |
| 133 | 3x | Add(0.000476021300, 0.000171900000, 0.000000000000); |
| 134 | 3x | Add(0.000332301100, 0.000120000000, 0.000000000000); |
| 135 | 3x | Add(0.000234826100, 0.000084800000, 0.000000000000); |
| 136 | 3x | Add(0.000166150500, 0.000060000000, 0.000000000000); |
| 137 | 3x | Add(0.000117413000, 0.000042400000, 0.000000000000); |
| 138 | 3x | Add(0.000083075270, 0.000030000000, 0.000000000000); |
| 139 | 3x | Add(0.000058706520, 0.000021200000, 0.000000000000); |
| 140 | 3x | Add(0.000041509940, 0.000014990000, 0.000000000000); |
| 141 | 3x | Add(0.000029353260, 0.000010600000, 0.000000000000); |
| 142 | 3x | Add(0.000020673830, 0.000007465700, 0.000000000000); |
| 143 | 3x | Add(0.000014559770, 0.000005257800, 0.000000000000); |
| 144 | 3x | Add(0.000010253980, 0.000003702900, 0.000000000000); |
| 145 | 3x | Add(0.000007221456, 0.000002607800, 0.000000000000); |
| 146 | 3x | Add(0.000005085868, 0.000001836600, 0.000000000000); |
| 147 | 3x | Add(0.000003581652, 0.000001293400, 0.000000000000); |
| 148 | 3x | Add(0.000002522525, 0.000000910930, 0.000000000000); |
| 149 | 3x | Add(0.000001776509, 0.000000641530, 0.000000000000); |
| 150 | 3x | Add(0.000001251141, 0.000000451810, 0.000000000000); |
| 151 | 3x | Add(0.000000000000, 0.000000000000, 0.000000000000); |
| 152 | ||
| 153 | // Values from Table T.2 in CIE TR "Colorimetry" 15:2004 Third Edition | |
| 154 | // (ISBN 3 901 906 33 9). | |
| 155 | 3x | AddS(+61.5, 38.0, 5.3); |
| 156 | 3x | AddS(+68.8, 42.4, 6.1); |
| 157 | 3x | AddS(+63.4, 38.5, 3.0); |
| 158 | 3x | AddS(+65.8, 35.0, 1.2); |
| 159 | 3x | AddS(+94.8, 43.4, -1.1); |
| 160 | 3x | AddS(104.8, 46.3, -0.5); |
| 161 | 3x | AddS(105.9, 43.9, -0.7); |
| 162 | 3x | AddS(+96.8, 37.1, -1.2); |
| 163 | 3x | AddS(113.9, 36.7, -2.6); |
| 164 | 3x | AddS(125.6, 35.9, -2.9); |
| 165 | 3x | AddS(125.5, 32.6, -2.8); |
| 166 | 3x | AddS(121.3, 27.9, -2.6); |
| 167 | 3x | AddS(121.3, 24.3, -2.6); |
| 168 | 3x | AddS(113.5, 20.1, -1.8); |
| 169 | 3x | AddS(113.1, 16.2, -1.5); |
| 170 | 3x | AddS(110.8, 13.2, -1.3); |
| 171 | 3x | AddS(106.5, 8.6, -1.2); |
| 172 | 3x | AddS(108.8, 6.1, -1.0); |
| 173 | 3x | AddS(105.3, 4.2, -0.5); |
| 174 | 3x | AddS(104.4, 1.9, -0.3); |
| 175 | 3x | AddS(100.0, 0.0, 0.0); |
| 176 | 3x | AddS(+96.0, -1.6, 0.2); |
| 177 | 3x | AddS(+95.1, -3.5, 0.5); |
| 178 | 3x | AddS(+89.1, -3.5, 2.1); |
| 179 | 3x | AddS(+90.5, -5.8, 3.2); |
| 180 | 3x | AddS(+90.3, -7.2, 4.1); |
| 181 | 3x | AddS(+88.4, -8.6, 4.7); |
| 182 | 3x | AddS(+84.0, -9.5, 5.1); |
| 183 | 3x | AddS(+85.1, -10.9, 6.7); |
| 184 | 3x | AddS(+81.9, -10.7, 7.3); |
| 185 | 3x | AddS(+82.6, -12.0, 8.6); |
| 186 | 3x | AddS(+84.9, -14.0, 9.8); |
| 187 | 3x | AddS(+81.3, -13.6, 10.2); |
| 188 | 3x | AddS(+71.9, -12.0, 8.3); |
| 189 | 3x | AddS(+74.3, -13.3, 9.6); |
| 190 | 3x | AddS(+76.4, -12.9, 8.5); |
| 191 | 3x | AddS(+63.3, -10.6, 7.0); |
| 192 | 3x | AddS(+71.7, -11.6, 7.6); |
| 193 | 3x | AddS(+77.0, -12.2, 8.0); |
| 194 | 3x | AddS(+65.2, -10.2, 6.7); |
| 195 | 3x | AddS(+47.7, -7.8, 5.2); |
| 196 | 3x | AddS(+68.6, -11.2, 7.4); |
| 197 | 3x | AddS(+65.0, -10.4, 6.8); |
| 198 | 3x | AddS(+66.0, -10.6, 7.0); |
| 199 | 3x | AddS(+61.0, -9.7, 6.4); |
| 200 | 3x | AddS(+53.3, -8.3, 5.5); |
| 201 | 3x | AddS(+58.9, -9.3, 6.1); |
| 202 | 3x | AddS(+61.9, -9.8, 6.5); |
| 203 | } | |
| 204 | ||
| 205 | private: | |
| 206 | 291x | void Add(double x_bar_sample, double y_bar_sample, double z_bar_sample) { |
| 207 | 291x | x_bar_samples.push_back(x_bar_sample); |
| 208 | 291x | y_bar_samples.push_back(y_bar_sample); |
| 209 | 291x | z_bar_samples.push_back(z_bar_sample); |
| 210 | } | |
| 211 | ||
| 212 | 144x | void AddS(double s0_sample, double s1_sample, double s2_sample) { |
| 213 | 144x | S0_samples.push_back(s0_sample); |
| 214 | 144x | S1_samples.push_back(s1_sample); |
| 215 | 144x | S2_samples.push_back(s2_sample); |
| 216 | } | |
| 217 | }; | |
| 218 | ||
| 219 | const Tables tables = Tables(); | |
| 220 | const DimensionlessSpectrum x_bar(355.0 * nm, 835.0 * nm, tables.x_bar_samples); | |
| 221 | const DimensionlessSpectrum y_bar(355.0 * nm, 835.0 * nm, tables.y_bar_samples); | |
| 222 | const DimensionlessSpectrum z_bar(355.0 * nm, 835.0 * nm, tables.z_bar_samples); | |
| 223 | const DimensionlessSpectrum S0(360.0 * nm, 830.0 * nm, tables.S0_samples); | |
| 224 | const DimensionlessSpectrum S1(360.0 * nm, 830.0 * nm, tables.S1_samples); | |
| 225 | const DimensionlessSpectrum S2(360.0 * nm, 830.0 * nm, tables.S2_samples); | |
| 226 | ||
| 227 | } // anonymous namespace | |
| 228 | ||
| 229 | ! | const DimensionlessSpectrum& cie_x_bar_function() { return x_bar; } |
| 230 | ! | const DimensionlessSpectrum& cie_y_bar_function() { return y_bar; } |
| 231 | ! | const DimensionlessSpectrum& cie_z_bar_function() { return z_bar; } |
| 232 | ||
| 233 | ! | const DimensionlessSpectrum& S0_function() { return S0; } |
| 234 | ! | const DimensionlessSpectrum& S1_function() { return S1; } |
| 235 | ! | const DimensionlessSpectrum& S2_function() { return S2; } |
| 236 | ||
| 237 | ! | Luminance GetLuminance(const RadianceSpectrum& spectrum) { |
| 238 | ! | return MaxLuminousEfficacy * Integral(y_bar * spectrum); |
| 239 | } | |
| 240 | ||
| 241 | ! | Color GetSrgbColor(const RadianceSpectrum& spectrum) { |
| 242 | ! | Color RGB = XYZ_to_sRGB * Color( |
| 243 | ! | MaxLuminousEfficacy * Integral(cie_x_bar_function() * spectrum), |
| 244 | ! | MaxLuminousEfficacy * Integral(cie_y_bar_function() * spectrum), |
| 245 | ! | MaxLuminousEfficacy * Integral(cie_z_bar_function() * spectrum)); |
| 246 | return Color( | |
| 247 | ! | std::max(RGB.x, 0.0 * cd_per_square_meter), |
| 248 | ! | std::max(RGB.y, 0.0 * cd_per_square_meter), |
| 249 | ! | std::max(RGB.z, 0.0 * cd_per_square_meter)); |
| 250 | } | |
| 251 | ||
| 252 | ! | Color GetSrgbColor(const RadianceSpectrum& spectrum, Wavelength min_wavelength, |
| 253 | Wavelength max_wavelength, int number_of_wavelengths) { | |
| 254 | ! | Color RGB = XYZ_to_sRGB * Color( |
| 255 | ! | MaxLuminousEfficacy * Integral(cie_x_bar_function() * spectrum, |
| 256 | min_wavelength, max_wavelength, number_of_wavelengths), | |
| 257 | ! | MaxLuminousEfficacy * Integral(cie_y_bar_function() * spectrum, |
| 258 | min_wavelength, max_wavelength, number_of_wavelengths), | |
| 259 | ! | MaxLuminousEfficacy * Integral(cie_z_bar_function() * spectrum, |
| 260 | ! | min_wavelength, max_wavelength, number_of_wavelengths)); |
| 261 | return Color( | |
| 262 | ! | std::max(RGB.x, 0.0 * cd_per_square_meter), |
| 263 | ! | std::max(RGB.y, 0.0 * cd_per_square_meter), |
| 264 | ! | std::max(RGB.z, 0.0 * cd_per_square_meter)); |
| 265 | } |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | * Copyright (c) 2016 Eric Bruneton | |
| 9 | * All rights reserved. | |
| 10 | * | |
| 11 | * Redistribution and use in source and binary forms, with or without | |
| 12 | * modification, are permitted provided that the following conditions | |
| 13 | * are met: | |
| 14 | * 1. Redistributions of source code must retain the above copyright | |
| 15 | * notice, this list of conditions and the following disclaimer. | |
| 16 | * 2. Redistributions in binary form must reproduce the above copyright | |
| 17 | * notice, this list of conditions and the following disclaimer in the | |
| 18 | * documentation and/or other materials provided with the distribution. | |
| 19 | * 3. Neither the name of the copyright holders nor the names of its | |
| 20 | * contributors may be used to endorse or promote products derived from | |
| 21 | * this software without specific prior written permission. | |
| 22 | * | |
| 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
| 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| 33 | * THE POSSIBILITY OF SUCH DAMAGE. | |
| 34 | */ | |
| 35 | ||
| 36 | #ifndef MATH_MATRIX_H_ | |
| 37 | #define MATH_MATRIX_H_ | |
| 38 | ||
| 39 | #include "../math/scalar.h" | |
| 40 | #include "../math/vector.h" | |
| 41 | ||
| 42 | namespace dimensional { | |
| 43 | ||
| 44 | template<typename T> | |
| 45 | struct Matrix3 { | |
| 46 | T m00, m01, m02; | |
| 47 | T m10, m11, m12; | |
| 48 | T m20, m21, m22; | |
| 49 | inline Matrix3() {} | |
| 50 | constexpr inline Matrix3(T m00, T m01, T m02, | |
| 51 | T m10, T m11, T m12, | |
| 52 | T m20, T m21, T m22) | |
| 53 | : m00(m00), m01(m01), m02(m02), | |
| 54 | m10(m10), m11(m11), m12(m12), | |
| 55 | m20(m20), m21(m21), m22(m22) {} | |
| 56 | }; | |
| 57 | ||
| 58 | template<int U1, int U2, int U3, int U4, int U5, | |
| 59 | int V1, int V2, int V3, int V4, int V5> | |
| 60 | ! | Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*( |
| 61 | const Matrix3<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 62 | const Vector3<Scalar<V1, V2, V3, V4, V5>>& rhs) { | |
| 63 | return Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>( | |
| 64 | ! | lhs.m00 * rhs.x + lhs.m01 * rhs.y + lhs.m02 * rhs.z, |
| 65 | ! | lhs.m10 * rhs.x + lhs.m11 * rhs.y + lhs.m12 * rhs.z, |
| 66 | ! | lhs.m20 * rhs.x + lhs.m21 * rhs.y + lhs.m22 * rhs.z); |
| 67 | } | |
| 68 | ||
| 69 | template<int U1, int U2, int U3, int U4, int U5, | |
| 70 | int V1, int V2, int V3, int V4, int V5> | |
| 71 | Matrix3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*( | |
| 72 | const Matrix3<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 73 | const Matrix3<Scalar<V1, V2, V3, V4, V5>>& rhs) { | |
| 74 | return Matrix3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>( | |
| 75 | lhs.m00 * rhs.m00 + lhs.m01 * rhs.m10 + lhs.m02 * rhs.m20, | |
| 76 | lhs.m00 * rhs.m01 + lhs.m01 * rhs.m11 + lhs.m02 * rhs.m21, | |
| 77 | lhs.m00 * rhs.m02 + lhs.m01 * rhs.m12 + lhs.m02 * rhs.m22, | |
| 78 | lhs.m10 * rhs.m00 + lhs.m11 * rhs.m10 + lhs.m12 * rhs.m20, | |
| 79 | lhs.m10 * rhs.m01 + lhs.m11 * rhs.m11 + lhs.m12 * rhs.m21, | |
| 80 | lhs.m10 * rhs.m02 + lhs.m11 * rhs.m12 + lhs.m12 * rhs.m22, | |
| 81 | lhs.m20 * rhs.m00 + lhs.m21 * rhs.m10 + lhs.m22 * rhs.m20, | |
| 82 | lhs.m20 * rhs.m01 + lhs.m21 * rhs.m11 + lhs.m22 * rhs.m21, | |
| 83 | lhs.m20 * rhs.m02 + lhs.m21 * rhs.m12 + lhs.m22 * rhs.m22); | |
| 84 | } | |
| 85 | ||
| 86 | template<int U1, int U2, int U3, int U4, int U5> | |
| 87 | Matrix3<Scalar<-U1, -U2, -U3, -U4, -U5>> inverse( | |
| 88 | const Matrix3<Scalar<U1, U2, U3, U4, U5>>& mat) { | |
| 89 | auto c00 = mat.m11 * mat.m22 - mat.m12 * mat.m21; | |
| 90 | auto c01 = mat.m02 * mat.m21 - mat.m01 * mat.m22; | |
| 91 | auto c02 = mat.m01 * mat.m12 - mat.m02 * mat.m11; | |
| 92 | auto c10 = mat.m12 * mat.m20 - mat.m10 * mat.m22; | |
| 93 | auto c11 = mat.m00 * mat.m22 - mat.m02 * mat.m20; | |
| 94 | auto c12 = mat.m02 * mat.m10 - mat.m00 * mat.m12; | |
| 95 | auto c20 = mat.m10 * mat.m21 - mat.m11 * mat.m20; | |
| 96 | auto c21 = mat.m01 * mat.m20 - mat.m00 * mat.m21; | |
| 97 | auto c22 = mat.m00 * mat.m11 - mat.m01 * mat.m10; | |
| 98 | auto det = mat.m00 * c00 + mat.m01 * c10 + mat.m02 * c20; | |
| 99 | return Matrix3<Scalar<-U1, -U2, -U3, -U4, -U5>>( | |
| 100 | c00 / det, c01 / det, c02 / det, | |
| 101 | c10 / det, c11 / det, c12 / det, | |
| 102 | c20 / det, c21 / det, c22 / det); | |
| 103 | } | |
| 104 | ||
| 105 | } // namespace dimensional | |
| 106 | ||
| 107 | #endif // MATH_MATRIX_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | * Copyright (c) 2016 Eric Bruneton | |
| 9 | * All rights reserved. | |
| 10 | * | |
| 11 | * Redistribution and use in source and binary forms, with or without | |
| 12 | * modification, are permitted provided that the following conditions | |
| 13 | * are met: | |
| 14 | * 1. Redistributions of source code must retain the above copyright | |
| 15 | * notice, this list of conditions and the following disclaimer. | |
| 16 | * 2. Redistributions in binary form must reproduce the above copyright | |
| 17 | * notice, this list of conditions and the following disclaimer in the | |
| 18 | * documentation and/or other materials provided with the distribution. | |
| 19 | * 3. Neither the name of the copyright holders nor the names of its | |
| 20 | * contributors may be used to endorse or promote products derived from | |
| 21 | * this software without specific prior written permission. | |
| 22 | * | |
| 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
| 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| 33 | * THE POSSIBILITY OF SUCH DAMAGE. | |
| 34 | */ | |
| 35 | ||
| 36 | #ifndef MATH_VECTOR_H_ | |
| 37 | #define MATH_VECTOR_H_ | |
| 38 | ||
| 39 | #include "../math/scalar.h" | |
| 40 | ||
| 41 | namespace dimensional { | |
| 42 | ||
| 43 | template<typename T> | |
| 44 | struct Vector2 { | |
| 45 | T x, y; | |
| 46 | inline constexpr Vector2() {} | |
| 47 | inline constexpr Vector2(T x, T y) : x(x), y(y) {} | |
| 48 | }; | |
| 49 | ||
| 50 | template<int U1, int U2, int U3, int U4, int U5, | |
| 51 | int V1, int V2, int V3, int V4, int V5> | |
| 52 | inline Vector2<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/( | |
| 53 | const Vector2<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 54 | const Vector2<Scalar<V1, V2, V3, V4, V5>>& rhs) { | |
| 55 | return Vector2<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>( | |
| 56 | lhs.x / rhs.x, lhs.y / rhs.y); | |
| 57 | } | |
| 58 | ||
| 59 | template<typename T> | |
| 60 | struct Vector3 { | |
| 61 | T x, y, z; | |
| 62 | inline constexpr Vector3() {} | |
| 63 | ! | inline constexpr Vector3(T x, T y, T z) : x(x), y(y), z(z) {} |
| 64 | inline Vector3 operator+(const Vector3& rhs) const { | |
| 65 | return Vector3(x + rhs.x, y + rhs.y, z + rhs.z); | |
| 66 | } | |
| 67 | inline Vector3& operator+=(const Vector3& rhs) { | |
| 68 | x += rhs.x; | |
| 69 | y += rhs.y; | |
| 70 | z += rhs.z; | |
| 71 | return *this; | |
| 72 | } | |
| 73 | inline Vector3 operator-(const Vector3& rhs) const { | |
| 74 | return Vector3(x - rhs.x, y - rhs.y, z - rhs.z); | |
| 75 | } | |
| 76 | inline Vector3 operator-() const { | |
| 77 | return Vector3(-x, -y, -z); | |
| 78 | } | |
| 79 | inline Vector3 operator*(const double rhs) const { | |
| 80 | return Vector3(x * rhs, y * rhs, z * rhs); | |
| 81 | } | |
| 82 | }; | |
| 83 | ||
| 84 | template<int U1, int U2, int U3, int U4, int U5, | |
| 85 | int V1, int V2, int V3, int V4, int V5> | |
| 86 | inline Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*( | |
| 87 | const Vector3<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 88 | const Scalar<V1, V2, V3, V4, V5> rhs) { | |
| 89 | return Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>( | |
| 90 | lhs.x * rhs, lhs.y * rhs, lhs.z * rhs); | |
| 91 | } | |
| 92 | ||
| 93 | template<int U1, int U2, int U3, int U4, int U5, | |
| 94 | int V1, int V2, int V3, int V4, int V5> | |
| 95 | inline Vector3<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/( | |
| 96 | const Vector3<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 97 | const Scalar<V1, V2, V3, V4, V5>& rhs) { | |
| 98 | return Vector3<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>( | |
| 99 | lhs.x / rhs, lhs.y / rhs, lhs.z / rhs); | |
| 100 | } | |
| 101 | ||
| 102 | template<int U1, int U2, int U3, int U4, int U5, | |
| 103 | int V1, int V2, int V3, int V4, int V5> | |
| 104 | inline Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> dot( | |
| 105 | const Vector3<Scalar<U1, U2, U3, U4, U5>>& u, | |
| 106 | const Vector3<Scalar<V1, V2, V3, V4, V5>>& v) { | |
| 107 | return u.x * v.x + u.y * v.y + u.z * v.z; | |
| 108 | } | |
| 109 | ||
| 110 | template<typename T> | |
| 111 | T length(const Vector3<T>& v) { | |
| 112 | return sqrt(dot(v, v)); | |
| 113 | } | |
| 114 | ||
| 115 | template<typename T> | |
| 116 | Vector3<Number> normalize(const Vector3<T>& v) { | |
| 117 | T length = sqrt(dot(v, v)); | |
| 118 | return Vector3<Number>(v.x / length, v.y / length, v.z / length); | |
| 119 | } | |
| 120 | ||
| 121 | template<typename T> | |
| 122 | struct Vector4 { | |
| 123 | T x, y, z, w; | |
| 124 | inline constexpr Vector4() {} | |
| 125 | inline constexpr Vector4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {} | |
| 126 | }; | |
| 127 | ||
| 128 | template<int U1, int U2, int U3, int U4, int U5, | |
| 129 | int V1, int V2, int V3, int V4, int V5> | |
| 130 | inline Vector4<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/( | |
| 131 | const Vector4<Scalar<U1, U2, U3, U4, U5>>& lhs, | |
| 132 | const Vector4<Scalar<V1, V2, V3, V4, V5>>& rhs) { | |
| 133 | return Vector4<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>( | |
| 134 | lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); | |
| 135 | } | |
| 136 | ||
| 137 | typedef Vector2<Number> vec2; | |
| 138 | typedef Vector3<Number> vec3; | |
| 139 | typedef Vector4<Number> vec4; | |
| 140 | ||
| 141 | } // namespace dimensional | |
| 142 | ||
| 143 | #endif // MATH_VECTOR_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | Copyright (c) 2015 Eric Bruneton | |
| 9 | All rights reserved. | |
| 10 | ||
| 11 | Redistribution and use in source and binary forms, with or without | |
| 12 | modification, are permitted provided that the following conditions are met: | |
| 13 | ||
| 14 | 1. Redistributions of source code must retain the above copyright notice, this | |
| 15 | list of conditions and the following disclaimer. | |
| 16 | ||
| 17 | 2. Redistributions in binary form must reproduce the above copyright notice, | |
| 18 | this list of conditions and the following disclaimer in the documentation | |
| 19 | and/or other materials provided with the distribution. | |
| 20 | ||
| 21 | 3. Neither the name of the copyright holder nor the names of its contributors | |
| 22 | may be used to endorse or promote products derived from this software without | |
| 23 | specific prior written permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| 29 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 30 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| 31 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| 32 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| 33 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 34 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | #include "hosek.h" | |
| 37 | ||
| 38 | #include <algorithm> | |
| 39 | ||
| 40 | #include "ArHosekSkyModel.h" | |
| 41 | ||
| 42 | namespace { | |
| 43 | ||
| 44 | constexpr SolidAngle kSunSolidAngle = 6.87e-5 * sr; | |
| 45 | ||
| 46 | // Copied from ArHosekSkyModel.cc. | |
| 47 | const double originalSolarRadianceTable[] = { | |
| 48 | 7500.0, | |
| 49 | 12500.0, | |
| 50 | 21127.5, | |
| 51 | 26760.5, | |
| 52 | 30663.7, | |
| 53 | 27825.0, | |
| 54 | 25503.8, | |
| 55 | 25134.2, | |
| 56 | 23212.1, | |
| 57 | 21526.7, | |
| 58 | 19870.8 | |
| 59 | }; | |
| 60 | ||
| 61 | // The Hosek sky radiance was computed uding 'originalSolarRadianceTable' as | |
| 62 | // the solar radiance, but we want the result for SolarSpectrum(), used in all | |
| 63 | // other models. Thus we correct the result for each wavelength by the ratio | |
| 64 | // between the two spectra at this wavelength (including also the Sun solid | |
| 65 | // angle to convert radiance to irradiance values). | |
| 66 | ! | double SolarSpectrumCorrectionFactor(Wavelength lambda) { |
| 67 | ! | double x = (lambda.to(nm) - 320.0) / 40.0; |
| 68 | ! | if (x < 0.0 || x > 10.0) { |
| 69 | ! | return 1.0; |
| 70 | } | |
| 71 | ! | int i = floor(x); |
| 72 | ! | double u = x - i; |
| 73 | ! | SpectralIrradiance new_irradiance = SolarSpectrum()(lambda); |
| 74 | ! | SpectralRadiance old_radiance = (originalSolarRadianceTable[i] * (1.0 - u) + |
| 75 | ! | originalSolarRadianceTable[std::min(i + 1, 10)] * u) * |
| 76 | ! | watt_per_square_meter_per_sr_per_nm; |
| 77 | ! | return (new_irradiance / (old_radiance * kSunSolidAngle))(); |
| 78 | } | |
| 79 | ||
| 80 | } // anonymous namespace | |
| 81 | ||
| 82 | ! | Hosek::Hosek(double turbidity) : turbidity_(turbidity) { |
| 83 | ! | for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) { |
| 84 | ! | sky_model_state_[i] = NULL; |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | ! | Hosek::~Hosek() { |
| 89 | ! | for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) { |
| 90 | ! | if (sky_model_state_[i] != NULL) { |
| 91 | ! | arhosekskymodelstate_free(sky_model_state_[i]); |
| 92 | } | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | ! | IrradianceSpectrum Hosek::GetSunIrradiance(Length altitude, |
| 97 | Angle sun_zenith) const { | |
| 98 | ! | MaybeInitSkyModelState(sun_zenith); |
| 99 | ! | IrradianceSpectrum result; |
| 100 | ! | for (unsigned int i = 0; i < result.size(); ++i) { |
| 101 | ! | Wavelength lambda = result.GetSample(i); |
| 102 | ! | if (lambda < 320.0 * nm || lambda > 720.0 * nm) { |
| 103 | // arhosekskymodel_solar_radiance does not work for wavelengths outside | |
| 104 | // the 320-720nm range. | |
| 105 | ! | result[i] = 0.0 * watt_per_square_meter_per_nm; |
| 106 | ! | continue; |
| 107 | } | |
| 108 | ! | double sun_and_sky_radiance = arhosekskymodel_solar_radiance( |
| 109 | ! | sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm)); |
| 110 | ! | double sky_radiance = arhosekskymodel_radiance( |
| 111 | ! | sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm)); |
| 112 | ! | double sun_radiance = (sun_and_sky_radiance - sky_radiance) * |
| 113 | ! | SolarSpectrumCorrectionFactor(lambda); |
| 114 | ! | result[i] = |
| 115 | ! | sun_radiance * watt_per_square_meter_per_sr_per_nm * kSunSolidAngle; |
| 116 | } | |
| 117 | ! | return result; |
| 118 | } | |
| 119 | ||
| 120 | ! | RadianceSpectrum Hosek::GetSkyRadiance(Length altitude, Angle sun_zenith, |
| 121 | Angle view_zenith, Angle view_sun_azimuth) const { | |
| 122 | ! | MaybeInitSkyModelState(sun_zenith); |
| 123 | double gamma = | |
| 124 | ! | GetViewSunAngle(sun_zenith, view_zenith, view_sun_azimuth).to(rad); |
| 125 | ! | RadianceSpectrum result; |
| 126 | ! | for (unsigned int i = 0; i < result.size(); ++i) { |
| 127 | ! | Wavelength lambda = result.GetSample(i); |
| 128 | ! | result[i] = arhosekskymodel_radiance(sky_model_state_[i], |
| 129 | view_zenith.to(rad), gamma, lambda.to(nm)) * | |
| 130 | ! | SolarSpectrumCorrectionFactor(lambda) * |
| 131 | ! | watt_per_square_meter_per_sr_per_nm; |
| 132 | } | |
| 133 | ! | return result; |
| 134 | } | |
| 135 | ||
| 136 | ! | void Hosek::MaybeInitSkyModelState(Angle sun_zenith) const { |
| 137 | ! | if (sky_model_state_[0] != NULL && sun_zenith == current_sun_zenith_) { |
| 138 | ! | return; |
| 139 | } | |
| 140 | ! | if (sky_model_state_[0] != NULL) { |
| 141 | ! | for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) { |
| 142 | ! | arhosekskymodelstate_free(sky_model_state_[i]); |
| 143 | } | |
| 144 | } | |
| 145 | ! | for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) { |
| 146 | ! | sky_model_state_[i] = arhosekskymodelstate_alloc_init( |
| 147 | ! | (pi / 2.0 - sun_zenith).to(rad), turbidity_, GroundAlbedo()[i]()); |
| 148 | } | |
| 149 | ! | current_sun_zenith_ = sun_zenith; |
| 150 | } |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | Copyright (c) 2015 Eric Bruneton | |
| 9 | All rights reserved. | |
| 10 | ||
| 11 | Redistribution and use in source and binary forms, with or without | |
| 12 | modification, are permitted provided that the following conditions are met: | |
| 13 | ||
| 14 | 1. Redistributions of source code must retain the above copyright notice, this | |
| 15 | list of conditions and the following disclaimer. | |
| 16 | ||
| 17 | 2. Redistributions in binary form must reproduce the above copyright notice, | |
| 18 | this list of conditions and the following disclaimer in the documentation | |
| 19 | and/or other materials provided with the distribution. | |
| 20 | ||
| 21 | 3. Neither the name of the copyright holder nor the names of its contributors | |
| 22 | may be used to endorse or promote products derived from this software without | |
| 23 | specific prior written permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| 29 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 30 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| 31 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| 32 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| 33 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 34 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | #ifndef ATMOSPHERE_ATMOSPHERE_H_ | |
| 37 | #define ATMOSPHERE_ATMOSPHERE_H_ | |
| 38 | ||
| 39 | #include "math/angle.h" | |
| 40 | #include "units.h" | |
| 41 | ||
| 42 | constexpr Length EarthRadius = 6360.0 * km; | |
| 43 | constexpr Length AtmosphereRadius = 6420.0 * km; | |
| 44 | ||
| 45 | // The height of the atmosphere if its density was uniform. | |
| 46 | constexpr Length RayleighScaleHeight = 8000.0 * m; | |
| 47 | ||
| 48 | // The height of the Mie particle layer if its density was uniform. | |
| 49 | constexpr Length MieScaleHeight = 1200.0 * m; | |
| 50 | ||
| 51 | // The Angstrom alpha coefficient for the Mie optical depth. | |
| 52 | constexpr double MieAngstromAlpha = 0.8; | |
| 53 | ||
| 54 | // The Angstrom beta coefficient for the Mie optical depth. | |
| 55 | constexpr double MieAngstromBeta = 0.04; | |
| 56 | ||
| 57 | // The g parameter of the Cornette-Shanks phase function used for Mie particles. | |
| 58 | constexpr double MiePhaseFunctionG = 0.7; | |
| 59 | ||
| 60 | // The Linke turbidity value, for the Preetham and Hosek models. | |
| 61 | constexpr double Turbidity = 2.53; | |
| 62 | ||
| 63 | // Returns the spectral irradiance of the Sun at the top of the atmosphere. | |
| 64 | const IrradianceSpectrum& SolarSpectrum(); | |
| 65 | ||
| 66 | // Returns the Rayleigh scattering coefficient at sea level. | |
| 67 | const ScatteringSpectrum& RayleighScattering(); | |
| 68 | ||
| 69 | // Returns the Mie extinction coefficient at sea level. | |
| 70 | const ScatteringSpectrum& MieExtinction(); | |
| 71 | ||
| 72 | // Returns the Mie scattering coefficient at sea level. | |
| 73 | const ScatteringSpectrum& MieScattering(); | |
| 74 | ||
| 75 | // Returns the Mie extinction and scattering coefficients at sea level for | |
| 76 | // the given Angstrom parameters. | |
| 77 | ScatteringSpectrum MieExtinction(double angstrom_alpha, double angstrom_beta); | |
| 78 | ScatteringSpectrum MieScattering(double angstrom_alpha, double angstrom_beta); | |
| 79 | ||
| 80 | // Computes the Rayleigh phase function for the given scattering angle. | |
| 81 | // The integral of this function over all solid angles is 1. | |
| 82 | InverseSolidAngle RayleighPhaseFunction(Angle scattering_angle); | |
| 83 | InverseSolidAngle RayleighPhaseFunction(Number scattering_angle_cosine); | |
| 84 | ||
| 85 | // Computes the Mie phase function for the given scattering angle (using | |
| 86 | // the Cornette-Shanks approximation). | |
| 87 | // The integral of this function over all solid angles is 1. | |
| 88 | InverseSolidAngle MiePhaseFunction(Angle scattering_angle); | |
| 89 | InverseSolidAngle MiePhaseFunction(Number scattering_angle_cosine); | |
| 90 | InverseSolidAngle MiePhaseFunction(double g, Number scattering_angle_cosine); | |
| 91 | ||
| 92 | const DimensionlessSpectrum& GroundAlbedo(); | |
| 93 | ||
| 94 | // An abstract atmosphere model. | |
| 95 | class Atmosphere { | |
| 96 | public: | |
| 97 | ! | virtual ~Atmosphere() {} |
| 98 | ||
| 99 | // Returns the number of wavelengths originally used by this atmosphere model. | |
| 100 | // The default implementation returns spectrum::NUM_WAVELENGTH. | |
| 101 | virtual int GetOriginalNumberOfWavelengths() const; | |
| 102 | ||
| 103 | // Returns the irradiance on a plane perpendicular to the Sun direction. | |
| 104 | virtual IrradianceSpectrum GetSunIrradiance(Length altitude, | |
| 105 | Angle sun_zenith) const = 0; | |
| 106 | ||
| 107 | virtual RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith, | |
| 108 | Angle view_zenith, Angle view_sun_azimuth) const = 0; | |
| 109 | ||
| 110 | virtual RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith, | |
| 111 | Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const; | |
| 112 | ||
| 113 | // Returns the irradiance on a horizontal plane. | |
| 114 | virtual IrradianceSpectrum GetSkyIrradiance(Length altitude, | |
| 115 | Angle sun_zenith) const; | |
| 116 | ||
| 117 | protected: | |
| 118 | static Angle GetViewSunAngle(Angle sun_zenith, Angle view_zenith, | |
| 119 | Angle view_sun_azimuth); | |
| 120 | }; | |
| 121 | ||
| 122 | #endif // ATMOSPHERE_ATMOSPHERE_H_ |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | /** | |
| 8 | Copyright (c) 2015 Eric Bruneton | |
| 9 | All rights reserved. | |
| 10 | ||
| 11 | Redistribution and use in source and binary forms, with or without | |
| 12 | modification, are permitted provided that the following conditions are met: | |
| 13 | ||
| 14 | 1. Redistributions of source code must retain the above copyright notice, this | |
| 15 | list of conditions and the following disclaimer. | |
| 16 | ||
| 17 | 2. Redistributions in binary form must reproduce the above copyright notice, | |
| 18 | this list of conditions and the following disclaimer in the documentation | |
| 19 | and/or other materials provided with the distribution. | |
| 20 | ||
| 21 | 3. Neither the name of the copyright holder nor the names of its contributors | |
| 22 | may be used to endorse or promote products derived from this software without | |
| 23 | specific prior written permission. | |
| 24 | ||
| 25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| 26 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 27 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| 28 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| 29 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 30 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| 31 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| 32 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| 33 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| 34 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 35 | */ | |
| 36 | #ifndef ATMOSPHERE_MODEL_HOSEK_HOSEK_H_ | |
| 37 | #define ATMOSPHERE_MODEL_HOSEK_HOSEK_H_ | |
| 38 | ||
| 39 | #include "atmosphere.h" | |
| 40 | #include "math/angle.h" | |
| 41 | #include "units.h" | |
| 42 | ||
| 43 | struct ArHosekSkyModelState; | |
| 44 | ||
| 45 | class Hosek : public Atmosphere { | |
| 46 | public: | |
| 47 | explicit Hosek(double turbidity); | |
| 48 | virtual ~Hosek(); | |
| 49 | ||
| 50 | ! | int GetOriginalNumberOfWavelengths() const override { return 11; } |
| 51 | ||
| 52 | IrradianceSpectrum GetSunIrradiance(Length altitude, | |
| 53 | Angle sun_zenith) const override; | |
| 54 | ||
| 55 | RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith, | |
| 56 | Angle view_zenith, Angle view_sun_azimuth) const override; | |
| 57 | ||
| 58 | private: | |
| 59 | void MaybeInitSkyModelState(Angle sun_zenith) const; | |
| 60 | ||
| 61 | double turbidity_; | |
| 62 | mutable Angle current_sun_zenith_; | |
| 63 | mutable ArHosekSkyModelState* sky_model_state_[DimensionlessSpectrum::SIZE]; | |
| 64 | }; | |
| 65 | ||
| 66 | #endif // ATMOSPHERE_MODEL_HOSEK_HOSEK_H_ |
| 1 | #include <Rcpp.h> | |
| 2 | #include <RcppThread.h> | |
| 3 | ||
| 4 | extern "C" { | |
| 5 | #include "ArHosekSkyModel.h" | |
| 6 | } | |
| 7 | ||
| 8 | #include "PragueSkyModel.h" | |
| 9 | #include "prague_metal_backend.h" | |
| 10 | ||
| 11 | #include "CIE1931Data.h" | |
| 12 | #include <Imath/ImathBox.h> | |
| 13 | #include <Imath/ImathFun.h> | |
| 14 | #include <Imath/ImathVec.h> | |
| 15 | ||
| 16 | #include <algorithm> | |
| 17 | #include <cctype> | |
| 18 | #include <cmath> | |
| 19 | #include <iterator> | |
| 20 | #include <string> | |
| 21 | #include <vector> | |
| 22 | ||
| 23 | using namespace Imath; | |
| 24 | ||
| 25 | 11750948x | static inline double clamp_double(double x, double a, double b) { |
| 26 | 11750948x | return (x < a) ? a : (x > b) ? b : x; |
| 27 | } | |
| 28 | ||
| 29 | 27x | static inline double clamp_sun_elevation_deg(double elevation_deg, |
| 30 | double epsilon_deg = 1e-4) { | |
| 31 | // Avoid singularities at exactly 90 deg while preserving user-facing limits. | |
| 32 | 27x | const double kMaxSunElevationDeg = 90.0; |
| 33 | 27x | if (elevation_deg >= kMaxSunElevationDeg) { |
| 34 | 4x | return kMaxSunElevationDeg - epsilon_deg; |
| 35 | } | |
| 36 | 23x | return elevation_deg; |
| 37 | } | |
| 38 | ||
| 39 | 13x | static inline std::string normalize_render_mode(std::string mode) { |
| 40 | 13x | std::transform(mode.begin(), mode.end(), mode.begin(), [](unsigned char c) { |
| 41 | 53x | return static_cast<char>(std::tolower(c)); |
| 42 | }); | |
| 43 | 13x | if (mode == "true") { |
| 44 | ! | return "all"; |
| 45 | } | |
| 46 | 13x | if (mode == "false") { |
| 47 | ! | return "atmosphere"; |
| 48 | } | |
| 49 | 13x | return mode; |
| 50 | } | |
| 51 | ||
| 52 | 13x | static inline void resolve_render_mode(const std::string &render_mode, |
| 53 | bool &render_atmosphere, | |
| 54 | bool &render_sun) { | |
| 55 | 13x | const std::string mode = normalize_render_mode(render_mode); |
| 56 | 13x | if (mode == "all") { |
| 57 | 7x | render_atmosphere = true; |
| 58 | 7x | render_sun = true; |
| 59 | 7x | return; |
| 60 | } | |
| 61 | 6x | if (mode == "atmosphere") { |
| 62 | 2x | render_atmosphere = true; |
| 63 | 2x | render_sun = false; |
| 64 | 2x | return; |
| 65 | } | |
| 66 | 4x | if (mode == "sun") { |
| 67 | 4x | render_atmosphere = false; |
| 68 | 4x | render_sun = true; |
| 69 | 4x | return; |
| 70 | } | |
| 71 | ! | Rcpp::stop("render_mode must be one of \"all\", \"atmosphere\", or \"sun\""); |
| 72 | } | |
| 73 | ||
| 74 | // Forward conversion to Prague's tiny Vector3 wrapper | |
| 75 | ! | static inline PragueSkyModel::Vector3 toPrague(const Vec3<double> &v) { |
| 76 | ! | return {double(v.x), double(v.y), double(v.z)}; |
| 77 | } | |
| 78 | ||
| 79 | // Static instance so the .dat stays in RAM across calls | |
| 80 | static PragueSkyModel prague_model; | |
| 81 | static std::string prague_loaded_file; | |
| 82 | ||
| 83 | static PragueSkyModel::AvailableData | |
| 84 | ! | initialize_prague_model(const std::string &prg_dataset) { |
| 85 | ! | if (prg_dataset.empty()) { |
| 86 | ! | Rcpp::stop("prg_dataset must be supplied when model=\"prague\""); |
| 87 | } | |
| 88 | ||
| 89 | ! | if (prague_loaded_file != prg_dataset) { |
| 90 | ! | prague_model.initialize(prg_dataset); |
| 91 | ! | prague_loaded_file = prg_dataset; |
| 92 | } | |
| 93 | ||
| 94 | ! | return prague_model.getAvailableData(); |
| 95 | } | |
| 96 | ||
| 97 | static inline double | |
| 98 | ! | prague_lambda_upper_nm(const PragueSkyModel::AvailableData &avail) { |
| 99 | ! | return avail.channelStart + avail.channels * avail.channelWidth; |
| 100 | } | |
| 101 | ||
| 102 | ! | static void validate_prague_lambda_nm( |
| 103 | const Rcpp::NumericVector &lambda_nm, | |
| 104 | const PragueSkyModel::AvailableData &avail) { | |
| 105 | ! | const double lambda_upper = prague_lambda_upper_nm(avail); |
| 106 | ! | for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) { |
| 107 | ! | const double lam = lambda_nm[i]; |
| 108 | ! | if (!std::isfinite(lam) || lam < avail.channelStart || lam >= lambda_upper) { |
| 109 | ! | Rcpp::stop("lambda_nm entries must be within [%f, %f)", |
| 110 | ! | avail.channelStart, lambda_upper); |
| 111 | } | |
| 112 | } | |
| 113 | } | |
| 114 | ||
| 115 | 11750948x | static inline void xyz_to_srgb(double X, double Y, double Z, double &R, |
| 116 | double &G, double &B) { | |
| 117 | // IEC 61966-2-1 sRGB (D65), 1931 2 | |
| 118 | const double M[9] = {3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, | |
| 119 | 0.0415560, 0.0556434, -0.2040259, 1.0572252}; | |
| 120 | 11750948x | R = M[0] * X + M[1] * Y + M[2] * Z; |
| 121 | 11750948x | G = M[3] * X + M[4] * Y + M[5] * Z; |
| 122 | 11750948x | B = M[6] * X + M[7] * Y + M[8] * Z; |
| 123 | } | |
| 124 | ||
| 125 | struct CIETristimulus { | |
| 126 | double x; | |
| 127 | double y; | |
| 128 | double z; | |
| 129 | }; | |
| 130 | ||
| 131 | 12x | static const std::vector<double> &default_lambda_low() { |
| 132 | static const double lambda_low_arr[] = {360, 380, 400, 420, 440, 460, | |
| 133 | 480, 500, 520, 540, 560, 580, | |
| 134 | 600, 620, 640, 660, 680, 700}; | |
| 135 | static const std::vector<double> lambda_low(std::begin(lambda_low_arr), | |
| 136 | 15x | std::end(lambda_low_arr)); |
| 137 | 12x | return lambda_low; |
| 138 | } | |
| 139 | ||
| 140 | 270x | static CIETristimulus interpolate_cie_xyz(double lambda_nm_value) { |
| 141 | 270x | constexpr int n = CIE_N; |
| 142 | 270x | if (lambda_nm_value < cie_lambda_nm[0] || |
| 143 | 270x | lambda_nm_value > cie_lambda_nm[n - 1]) { |
| 144 | ! | Rcpp::stop("lambda_nm entries must be within [%f, %f]", cie_lambda_nm[0], |
| 145 | cie_lambda_nm[n - 1]); | |
| 146 | } | |
| 147 | 270x | const auto begin = std::begin(cie_lambda_nm); |
| 148 | 513x | const auto end = std::end(cie_lambda_nm); |
| 149 | ||
| 150 | 270x | auto upper = std::lower_bound(begin, end, lambda_nm_value); |
| 151 | ||
| 152 | 270x | if (upper == begin) { |
| 153 | 27x | return {cie_xbar[0], cie_ybar[0], cie_zbar[0]}; |
| 154 | } | |
| 155 | 243x | if (upper == end) { |
| 156 | ! | const int last = n - 1; |
| 157 | ! | return {cie_xbar[last], cie_ybar[last], cie_zbar[last]}; |
| 158 | } | |
| 159 | ||
| 160 | 243x | const int idx_hi = int(upper - begin); |
| 161 | 243x | const int idx_lo = idx_hi - 1; |
| 162 | ||
| 163 | 243x | if (*upper == lambda_nm_value) { |
| 164 | 243x | return {cie_xbar[idx_hi], cie_ybar[idx_hi], cie_zbar[idx_hi]}; |
| 165 | } | |
| 166 | ||
| 167 | ! | const double lam_lo = cie_lambda_nm[idx_lo]; |
| 168 | ! | const double lam_hi = cie_lambda_nm[idx_hi]; |
| 169 | ! | const double t = (lambda_nm_value - lam_lo) / (lam_hi - lam_lo); |
| 170 | ! | const double x = cie_xbar[idx_lo] + t * (cie_xbar[idx_hi] - cie_xbar[idx_lo]); |
| 171 | ! | const double y = cie_ybar[idx_lo] + t * (cie_ybar[idx_hi] - cie_ybar[idx_lo]); |
| 172 | ! | const double z = cie_zbar[idx_lo] + t * (cie_zbar[idx_hi] - cie_zbar[idx_lo]); |
| 173 | ! | return {x, y, z}; |
| 174 | } | |
| 175 | ||
| 176 | static std::vector<double> | |
| 177 | 27x | trapezoid_weights(const std::vector<double> &lambda_values) { |
| 178 | 27x | const size_t n = lambda_values.size(); |
| 179 | 27x | std::vector<double> weights(n, 0.0); |
| 180 | 27x | if (n == 0) |
| 181 | ! | return weights; |
| 182 | 27x | if (n == 1) { |
| 183 | ! | weights[0] = 1.0; |
| 184 | ! | return weights; |
| 185 | } | |
| 186 | 297x | for (size_t i = 0; i < n; ++i) { |
| 187 | 270x | if (i == 0) { |
| 188 | 27x | weights[i] = (lambda_values[1] - lambda_values[0]) / 2.0; |
| 189 | 243x | } else if (i == n - 1) { |
| 190 | 27x | weights[i] = (lambda_values[i] - lambda_values[i - 1]) / 2.0; |
| 191 | } else { | |
| 192 | 216x | weights[i] = (lambda_values[i + 1] - lambda_values[i - 1]) / 2.0; |
| 193 | } | |
| 194 | } | |
| 195 | 27x | return weights; |
| 196 | } | |
| 197 | ||
| 198 | // Evaluate a Hosek solar disk in its own tangent plane. Its resolution is | |
| 199 | // independent of the environment map, so preview quality cannot erase the Sun. | |
| 200 | // [[Rcpp::export]] | |
| 201 | 15x | Rcpp::NumericVector hosek_sun_disk_rcpp(double elevation, double azimuth, double albedo, |
| 202 | double turbidity, unsigned int resolution, | |
| 203 | unsigned int number_cores) { | |
| 204 | 30x | if (!std::isfinite(elevation) || elevation < -90 || elevation > 90 || |
| 205 | 15x | !std::isfinite(azimuth) || !std::isfinite(albedo) || albedo < 0 || albedo > 1 || |
| 206 | 15x | !std::isfinite(turbidity) || turbidity < 1.7 || turbidity > 10 || |
| 207 | 30x | resolution < 16 || number_cores < 1) { |
| 208 | ! | Rcpp::stop("Invalid Hosek solar disk inputs."); |
| 209 | } | |
| 210 | 15x | const size_t count = size_t(resolution) * resolution; |
| 211 | 15x | Rcpp::NumericVector image(count * 3); |
| 212 | 45x | image.attr("dim") = Rcpp::IntegerVector::create(resolution, resolution, 3); |
| 213 | // Below the model's daylight domain, retain the horizon profile until the | |
| 214 | // upper limb sets. The renderer clips each direction against the horizon. | |
| 215 | 15x | const double safe_elevation = clamp_sun_elevation_deg(std::max(0.0, elevation)); |
| 216 | ArHosekSkyModelState* state = | |
| 217 | 15x | arhosekskymodelstate_alloc_init(safe_elevation * M_PI / 180, turbidity, albedo); |
| 218 | 15x | if (!state) { |
| 219 | ! | Rcpp::stop("Hosek-Wilkie initialisation failed."); |
| 220 | } | |
| 221 | 15x | if (elevation < -state->solar_radius * 180 / M_PI) { |
| 222 | ! | arhosekskymodelstate_free(state); |
| 223 | ! | return image; |
| 224 | } | |
| 225 | 15x | const double elev = elevation * M_PI / 180; |
| 226 | 15x | const double az = azimuth * M_PI / 180; |
| 227 | Vec3<double> forward( | |
| 228 | 15x | -std::sin(az) * std::cos(elev), std::sin(elev), std::cos(az) * std::cos(elev)); |
| 229 | // Match the renderer's frame, including its alternate up axis at the pole. | |
| 230 | Vec3<double> vertical = | |
| 231 | 15x | std::abs(forward.y) < 0.999999 ? Vec3<double>(0, 1, 0) : Vec3<double>(0, 0, 1); |
| 232 | 15x | Vec3<double> right = forward.cross(vertical).normalized(); |
| 233 | 15x | Vec3<double> up = right.cross(forward); |
| 234 | 15x | const double radius = std::tan(state->solar_radius); |
| 235 | const std::vector<double> wavelengths = { | |
| 236 | 30x | 360, 400, 440, 480, 520, 560, 600, 640, 680, 720}; |
| 237 | 15x | const auto weights = trapezoid_weights(wavelengths); |
| 238 | 15x | std::vector<CIETristimulus> cie; |
| 239 | 180x | for (double wavelength : wavelengths) { |
| 240 | 150x | cie.push_back(interpolate_cie_xyz(wavelength)); |
| 241 | } | |
| 242 | 15x | RcppThread::parallelFor( |
| 243 | 0u, | |
| 244 | size_t(resolution), | |
| 245 | 512x | [&](size_t row) { |
| 246 | 512x | const double y = 1 - 2 * (row + 0.5) / resolution; |
| 247 | 18944x | for (size_t column = 0; column < resolution; ++column) { |
| 248 | 18432x | const double x = 2 * (column + 0.5) / resolution - 1; |
| 249 | 18432x | if (x * x + y * y > 1) { |
| 250 | 3836x | continue; |
| 251 | } | |
| 252 | const Vec3<double> direction = | |
| 253 | 14596x | (forward + radius * (x * right + y * up)).normalized(); |
| 254 | // Horizon samples use finite horizon radiance; visibility is not baked | |
| 255 | // into the texture. Clamp zenith numerically without shifting disk geometry. | |
| 256 | 14596x | const double theta = std::acos(clamp_double(direction.y, 0.0, 1.0 - 1e-12)); |
| 257 | 14596x | const double gamma = std::atan(radius * std::sqrt(x * x + y * y)); |
| 258 | 14596x | double X = 0, Y = 0, Z = 0; |
| 259 | 160556x | for (size_t c = 0; c < wavelengths.size(); ++c) { |
| 260 | const double total = | |
| 261 | 145960x | arhosekskymodel_solar_radiance(state, theta, gamma, wavelengths[c]); |
| 262 | const double sky = | |
| 263 | 145960x | arhosekskymodel_radiance(state, theta, gamma, wavelengths[c]); |
| 264 | 145960x | const double value = std::max(0.0, total - sky) * weights[c]; |
| 265 | 145960x | X += value * cie[c].x; |
| 266 | 145960x | Y += value * cie[c].y; |
| 267 | 145960x | Z += value * cie[c].z; |
| 268 | } | |
| 269 | double R, G, B; | |
| 270 | 14596x | xyz_to_srgb(X, Y, Z, R, G, B); |
| 271 | 14596x | const size_t pixel = row + resolution * column; |
| 272 | 14596x | image[pixel] = R; |
| 273 | 14596x | image[pixel + count] = G; |
| 274 | 14596x | image[pixel + 2 * count] = B; |
| 275 | } | |
| 276 | }, | |
| 277 | number_cores); | |
| 278 | 15x | arhosekskymodelstate_free(state); |
| 279 | 15x | return image; |
| 280 | } | |
| 281 | ||
| 282 | // [[Rcpp::export]] | |
| 283 | Rcpp::NumericVector | |
| 284 | 12x | makesky_rcpp(double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0, |
| 285 | double azimuth_deg = 90, unsigned int resolution = 2048, | |
| 286 | unsigned int number_cores = 1, | |
| 287 | std::string model = "hosek", // hosek | prague | |
| 288 | std::string prg_dataset = "", double altitude = 0.0, | |
| 289 | double visibility = 50.0, // Prague only (km) | |
| 290 | std::string render_mode = "all", | |
| 291 | Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue, | |
| 292 | bool below_horizon = true) { | |
| 293 | 12x | bool render_atmosphere = true; |
| 294 | 12x | bool render_sun = true; |
| 295 | 12x | resolve_render_mode(render_mode, render_atmosphere, render_sun); |
| 296 | ||
| 297 | 12x | if (albedo < 0.0 || albedo > 1.0) { |
| 298 | ! | Rcpp::stop("albedo must be in [0,1]"); |
| 299 | } | |
| 300 | 12x | if (resolution == 0) { |
| 301 | ! | Rcpp::stop("resolution must be >= 1"); |
| 302 | } | |
| 303 | ||
| 304 | // Nudge zenith by at least half a texel to keep the sun disk sampled at 90 | |
| 305 | // deg. | |
| 306 | const double elev_epsilon_deg = | |
| 307 | 12x | std::max(0.5 * 180.0 / static_cast<double>(resolution), 1e-4); |
| 308 | const double safe_elevation = | |
| 309 | 12x | clamp_sun_elevation_deg(elevation, elev_epsilon_deg); |
| 310 | 12x | double elev_rad = safe_elevation * M_PI / 180.0; |
| 311 | 12x | double az_rad = azimuth_deg * M_PI / 180.0; |
| 312 | ||
| 313 | // Prague model initialisation | |
| 314 | 12x | PragueSkyModel::AvailableData avail{}; |
| 315 | 12x | if (model == "prague") { |
| 316 | ! | if (prg_dataset.empty()) { |
| 317 | ! | Rcpp::stop("prg_dataset must be supplied when model=\"prague\""); |
| 318 | } | |
| 319 | ||
| 320 | ! | if (prague_loaded_file != prg_dataset) { |
| 321 | ! | prague_model.initialize(prg_dataset); |
| 322 | ! | prague_loaded_file = prg_dataset; |
| 323 | } | |
| 324 | ! | avail = prague_model.getAvailableData(); |
| 325 | ! | if (albedo < avail.albedoMin || albedo > avail.albedoMax || |
| 326 | ! | visibility < avail.visibilityMin || visibility > avail.visibilityMax) { |
| 327 | ! | Rcpp::stop("albedo or visibility outside dataset range"); |
| 328 | } | |
| 329 | 12x | } else if (model != "hosek") { |
| 330 | ! | Rcpp::stop("unknown model \"%s\"", model.c_str()); |
| 331 | } | |
| 332 | ||
| 333 | // Spectral sampling setup | |
| 334 | 12x | std::vector<double> lambda_values; |
| 335 | 12x | std::vector<double> lambda_weights; |
| 336 | 12x | std::vector<CIETristimulus> cie_samples; |
| 337 | ||
| 338 | 12x | if (model == "prague") { |
| 339 | // Prague sampling is locked to dataset channel centers within CIE bounds | |
| 340 | // (380-740 nm). | |
| 341 | ! | lambda_values.reserve(avail.channels); |
| 342 | ! | for (int i = 0; i < avail.channels; ++i) { |
| 343 | ! | const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth; |
| 344 | ! | if (lam >= 380.0 && lam <= 740.0) { |
| 345 | ! | lambda_values.push_back(lam); |
| 346 | } | |
| 347 | } | |
| 348 | ! | if (lambda_values.empty()) { |
| 349 | ! | Rcpp::stop("No Prague spectral channels fall within [380, 740] nm."); |
| 350 | } | |
| 351 | // Prague channels are evenly spaced bands. | |
| 352 | ! | lambda_weights.assign(lambda_values.size(), avail.channelWidth); |
| 353 | ! | cie_samples.reserve(lambda_values.size()); |
| 354 | ! | for (double lam : lambda_values) { |
| 355 | ! | cie_samples.push_back(interpolate_cie_xyz(lam)); |
| 356 | } | |
| 357 | ||
| 358 | } else { | |
| 359 | // Hosek path (unchanged behavior) | |
| 360 | 12x | const auto &default_values = default_lambda_low(); |
| 361 | ||
| 362 | 12x | if (lambda_nm.isNull()) { |
| 363 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 364 | } else { | |
| 365 | 12x | Rcpp::NumericVector lambda_vec(lambda_nm.get()); |
| 366 | 12x | if (lambda_vec.size() == 0) { |
| 367 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 368 | } else { | |
| 369 | 12x | lambda_values.assign(lambda_vec.begin(), lambda_vec.end()); |
| 370 | } | |
| 371 | } | |
| 372 | ||
| 373 | 12x | if (lambda_values.size() < 2) { |
| 374 | ! | Rcpp::stop("lambda_nm must contain at least two wavelengths"); |
| 375 | } | |
| 376 | 120x | for (size_t i = 1; i < lambda_values.size(); ++i) { |
| 377 | 108x | if (!(lambda_values[i] > lambda_values[i - 1])) { |
| 378 | ! | Rcpp::stop("lambda_nm must be strictly increasing"); |
| 379 | } | |
| 380 | } | |
| 381 | ||
| 382 | 12x | lambda_weights = trapezoid_weights(lambda_values); |
| 383 | ||
| 384 | 12x | cie_samples.reserve(lambda_values.size()); |
| 385 | 144x | for (double lam : lambda_values) { |
| 386 | 120x | cie_samples.push_back(interpolate_cie_xyz(lam)); |
| 387 | } | |
| 388 | } | |
| 389 | ||
| 390 | 12x | const size_t N_LAMBDA = lambda_values.size(); |
| 391 | ||
| 392 | 12x | ArHosekSkyModelState *hosek = nullptr; |
| 393 | 12x | if (model == "hosek") { |
| 394 | 12x | if (elevation < 0.0 || elevation > 90.0) { |
| 395 | ! | Rcpp::stop("elevation must be in [0,90]"); |
| 396 | } | |
| 397 | 12x | if (turbidity < 1.7 || turbidity > 10.0) { |
| 398 | ! | Rcpp::stop("turbidity must be in [1.7,10]"); |
| 399 | } | |
| 400 | 12x | hosek = arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo); |
| 401 | 12x | if (!hosek) |
| 402 | ! | Rcpp::stop("Hosek-Wilkie initialisation failed"); |
| 403 | ||
| 404 | } else { | |
| 405 | ! | if (elevation < -4.2 || elevation > 90.0) { |
| 406 | ! | Rcpp::stop("elevation must be in [-4.2, 90]"); |
| 407 | } | |
| 408 | } | |
| 409 | ||
| 410 | // Initialize image buffer | |
| 411 | 12x | const int nTheta = resolution; // rows (latitude) |
| 412 | 12x | const int nPhi = 2 * resolution; // cols (longitude) |
| 413 | 12x | std::vector<double> img(3 * nTheta * nPhi, 0.0); |
| 414 | 12x | std::vector<double> img_band(nTheta * nPhi, 0.0); |
| 415 | ||
| 416 | // Vec3<double> sun_dir(0.0, std::sin(elev_rad), std::cos(elev_rad)); | |
| 417 | 12x | Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad), // +X (South) |
| 418 | std::sin(elev_rad), // +Y (Up) | |
| 419 | 12x | std::sin(az_rad) * std::cos(elev_rad)); // +Z (West) |
| 420 | // Render loop (parallel over rows) | |
| 421 | 12x | RcppThread::parallelFor( |
| 422 | 0u, size_t(nTheta), | |
| 423 | 4804x | [&](size_t t) { |
| 424 | 4804x | double theta = |
| 425 | 4804x | (static_cast<double>(t) + 0.5) / static_cast<double>(nTheta) * M_PI; |
| 426 | ||
| 427 | 4804x | if (!below_horizon && theta > M_PI_2) { |
| 428 | ! | return; |
| 429 | } | |
| 430 | ||
| 431 | 11741156x | for (int p = 0; p < nPhi; ++p) { |
| 432 | 11736352x | double phi = (static_cast<double>(p) + 0.5) / nPhi * 2.0 * M_PI; |
| 433 | ||
| 434 | 11736352x | Vec3<double> v(std::cos(phi) * std::sin(theta), |
| 435 | std::cos(theta), | |
| 436 | 11736352x | std::sin(phi) * std::sin(theta)); |
| 437 | ||
| 438 | 11736352x | double X = 0.0, Y = 0.0, Z = 0.0; |
| 439 | 11736352x | double L_band = 0.0; |
| 440 | 11736352x | const bool view_above_horizon = theta <= M_PI_2; |
| 441 | ||
| 442 | 11736352x | if (model == "hosek") { |
| 443 | 11736352x | double gamma = std::acos(clamp_double(v.dot(sun_dir), -1.0, 1.0)); |
| 444 | 129099872x | for (size_t c = 0; c < N_LAMBDA; ++c) { |
| 445 | 117363520x | const double lam = lambda_values[c]; |
| 446 | 117363520x | double L = 0.0; |
| 447 | 117363520x | if (render_atmosphere) { |
| 448 | 85258240x | if (render_sun && view_above_horizon) { |
| 449 | 42627840x | L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam); |
| 450 | } else { | |
| 451 | 42630400x | L = arhosekskymodel_radiance(hosek, theta, gamma, lam); |
| 452 | } | |
| 453 | 32105280x | } else if (render_sun && view_above_horizon) { |
| 454 | const double L_total = | |
| 455 | 16052640x | arhosekskymodel_solar_radiance(hosek, theta, gamma, lam); |
| 456 | const double L_sky = | |
| 457 | 16052640x | arhosekskymodel_radiance(hosek, theta, gamma, lam); |
| 458 | 16052640x | L = L_total - L_sky; |
| 459 | 16052640x | if (L < 0.0) { |
| 460 | ! | L = 0.0; |
| 461 | } | |
| 462 | } | |
| 463 | // Accumulate XYZ | |
| 464 | 117363520x | double Li = static_cast<double>(L); |
| 465 | 117363520x | const double d_lambda = lambda_weights[c]; |
| 466 | 117363520x | X += Li * cie_samples[c].x * d_lambda; |
| 467 | 117363520x | Y += Li * cie_samples[c].y * d_lambda; |
| 468 | 117363520x | Z += Li * cie_samples[c].z * d_lambda; |
| 469 | 117363520x | L_band += Li * d_lambda; |
| 470 | } | |
| 471 | } else { | |
| 472 | // Prague uses Z-up vector | |
| 473 | ! | Vec3<double> v_zup(std::cos(phi) * std::sin(theta), |
| 474 | ! | std::sin(phi) * std::sin(theta), |
| 475 | ! | std::cos(theta)); |
| 476 | ! | auto P = prague_model.computeParameters({0.0, 0.0, altitude}, |
| 477 | ! | toPrague(v_zup), elev_rad, |
| 478 | az_rad, visibility, albedo); | |
| 479 | ||
| 480 | ! | for (size_t i = 0; i < N_LAMBDA; ++i) { |
| 481 | ! | double Li = 0.0; |
| 482 | ! | if (render_atmosphere) { |
| 483 | ! | Li = prague_model.skyRadiance(P, lambda_values[i]); |
| 484 | } | |
| 485 | ! | if (render_sun && view_above_horizon) { |
| 486 | const double sun = | |
| 487 | ! | prague_model.sunRadiance(P, lambda_values[i]); |
| 488 | ! | Li = render_atmosphere ? (Li + sun) : sun; |
| 489 | } | |
| 490 | ! | const double d_lambda = lambda_weights[i]; |
| 491 | ! | X += Li * cie_samples[i].x * d_lambda; |
| 492 | ! | Y += Li * cie_samples[i].y * d_lambda; |
| 493 | ! | Z += Li * cie_samples[i].z * d_lambda; |
| 494 | ! | L_band += Li * d_lambda; |
| 495 | } | |
| 496 | } | |
| 497 | 11736352x | if (!std::isfinite(X) || !std::isfinite(Y) || !std::isfinite(Z)) { |
| 498 | 4262912x | X = 0.0; |
| 499 | 4262912x | Y = 0.0; |
| 500 | 4262912x | Z = 0.0; |
| 501 | } | |
| 502 | double R, G, B; | |
| 503 | 11736352x | xyz_to_srgb(X, Y, Z, R, G, B); |
| 504 | ||
| 505 | 11736352x | if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) { |
| 506 | ! | R = 0.0; |
| 507 | ! | G = 0.0; |
| 508 | ! | B = 0.0; |
| 509 | } | |
| 510 | ||
| 511 | 11736352x | const int idx = 3 * (int(t) * nPhi + p); |
| 512 | 11736352x | img[idx + 0] = R; |
| 513 | 11736352x | img[idx + 1] = G; |
| 514 | 11736352x | img[idx + 2] = B; |
| 515 | 11736352x | img_band[int(t) * nPhi + p] = L_band; |
| 516 | } | |
| 517 | }, | |
| 518 | number_cores); | |
| 519 | ||
| 520 | 12x | const int width = nPhi; |
| 521 | 12x | const int height = nTheta; |
| 522 | 12x | const int nPix = width * height; |
| 523 | ||
| 524 | 12x | if (model == "hosek") { |
| 525 | 12x | arhosekskymodelstate_free(hosek); |
| 526 | } | |
| 527 | ||
| 528 | 12x | Rcpp::NumericVector result(nPix * 3); |
| 529 | 36x | result.attr("dim") = Rcpp::IntegerVector::create(height, width, 3); |
| 530 | ||
| 531 | 4816x | for (int t = 0; t < height; ++t) { |
| 532 | 11741156x | for (int p = 0; p < width; ++p) { |
| 533 | 11736352x | const int pix_index = t * width + p; |
| 534 | 46945408x | for (int c = 0; c < 3; ++c) { |
| 535 | 35209056x | const int arr_index = t + height * (p + width * c); |
| 536 | 35209056x | result[arr_index] = img[3 * pix_index + c]; |
| 537 | } | |
| 538 | } | |
| 539 | } | |
| 540 | ||
| 541 | 12x | Rcpp::NumericVector band(nPix); |
| 542 | 36x | band.attr("dim") = Rcpp::IntegerVector::create(height, width); |
| 543 | 4816x | for (int t = 0; t < height; ++t) { |
| 544 | 11741156x | for (int p = 0; p < width; ++p) { |
| 545 | 11736352x | const int pix_index = t * width + p; |
| 546 | 11736352x | band[pix_index] = img_band[pix_index]; |
| 547 | } | |
| 548 | } | |
| 549 | 12x | result.attr("L_band") = band; |
| 550 | ||
| 551 | 12x | return result; |
| 552 | } | |
| 553 | ||
| 554 | // [[Rcpp::export]] | |
| 555 | ! | double calculate_sun_brightness_rcpp( |
| 556 | double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0, | |
| 557 | double azimuth_deg = 90.0, std::string model = "hosek", | |
| 558 | std::string prg_dataset = "", double altitude = 0.0, | |
| 559 | double visibility = 50.0, | |
| 560 | Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue) { | |
| 561 | ! | if (albedo < 0.0 || albedo > 1.0) { |
| 562 | ! | Rcpp::stop("albedo must be in [0,1]"); |
| 563 | } | |
| 564 | ||
| 565 | ! | const double safe_elevation = clamp_sun_elevation_deg(elevation); |
| 566 | ! | const double elev_rad = safe_elevation * M_PI / 180.0; |
| 567 | ! | const double az_rad = azimuth_deg * M_PI / 180.0; |
| 568 | ||
| 569 | // Prague model initialisation | |
| 570 | ! | PragueSkyModel::AvailableData avail{}; |
| 571 | ! | if (model == "prague") { |
| 572 | ! | if (prg_dataset.empty()) { |
| 573 | ! | Rcpp::stop("prg_dataset must be supplied when model=\"prague\""); |
| 574 | } | |
| 575 | ||
| 576 | ! | if (prague_loaded_file != prg_dataset) { |
| 577 | ! | prague_model.initialize(prg_dataset); |
| 578 | ! | prague_loaded_file = prg_dataset; |
| 579 | } | |
| 580 | ! | avail = prague_model.getAvailableData(); |
| 581 | ! | if (albedo < avail.albedoMin || albedo > avail.albedoMax || |
| 582 | ! | visibility < avail.visibilityMin || visibility > avail.visibilityMax) { |
| 583 | ! | Rcpp::stop("albedo or visibility outside dataset range"); |
| 584 | } | |
| 585 | ! | } else if (model != "hosek") { |
| 586 | ! | Rcpp::stop("unknown model \"%s\"", model.c_str()); |
| 587 | } | |
| 588 | ||
| 589 | // Spectral sampling setup | |
| 590 | ! | std::vector<double> lambda_values; |
| 591 | ! | std::vector<double> lambda_weights; |
| 592 | ! | std::vector<double> cie_y_samples; |
| 593 | ||
| 594 | ! | if (model == "prague") { |
| 595 | // Prague sampling is locked to dataset channel centers within CIE bounds | |
| 596 | // (380-740 nm). | |
| 597 | ! | lambda_values.reserve(avail.channels); |
| 598 | ! | for (int i = 0; i < avail.channels; ++i) { |
| 599 | ! | const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth; |
| 600 | ! | if (lam >= 380.0 && lam <= 740.0) { |
| 601 | ! | lambda_values.push_back(lam); |
| 602 | } | |
| 603 | } | |
| 604 | ! | if (lambda_values.empty()) { |
| 605 | ! | Rcpp::stop("No Prague spectral channels fall within [380, 740] nm."); |
| 606 | } | |
| 607 | // Prague channels are evenly spaced bands. | |
| 608 | ! | lambda_weights.assign(lambda_values.size(), avail.channelWidth); |
| 609 | ! | cie_y_samples.reserve(lambda_values.size()); |
| 610 | ! | for (double lam : lambda_values) { |
| 611 | ! | cie_y_samples.push_back(interpolate_cie_xyz(lam).y); |
| 612 | } | |
| 613 | } else { | |
| 614 | // Hosek path (unchanged behavior) | |
| 615 | ! | const auto &default_values = default_lambda_low(); |
| 616 | ||
| 617 | ! | if (lambda_nm.isNull()) { |
| 618 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 619 | } else { | |
| 620 | ! | Rcpp::NumericVector lambda_vec(lambda_nm.get()); |
| 621 | ! | if (lambda_vec.size() == 0) { |
| 622 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 623 | } else { | |
| 624 | ! | lambda_values.assign(lambda_vec.begin(), lambda_vec.end()); |
| 625 | } | |
| 626 | } | |
| 627 | ||
| 628 | ! | if (lambda_values.size() < 2) { |
| 629 | ! | Rcpp::stop("lambda_nm must contain at least two wavelengths"); |
| 630 | } | |
| 631 | ! | for (size_t i = 1; i < lambda_values.size(); ++i) { |
| 632 | ! | if (!(lambda_values[i] > lambda_values[i - 1])) { |
| 633 | ! | Rcpp::stop("lambda_nm must be strictly increasing"); |
| 634 | } | |
| 635 | } | |
| 636 | ||
| 637 | ! | lambda_weights = trapezoid_weights(lambda_values); |
| 638 | ||
| 639 | ! | cie_y_samples.reserve(lambda_values.size()); |
| 640 | ! | for (double lam : lambda_values) { |
| 641 | ! | cie_y_samples.push_back(interpolate_cie_xyz(lam).y); |
| 642 | } | |
| 643 | } | |
| 644 | ||
| 645 | ! | const size_t N_LAMBDA = lambda_values.size(); |
| 646 | ! | double Y = 0.0; |
| 647 | ||
| 648 | ! | if (model == "hosek") { |
| 649 | ! | if (elevation < 0.0 || elevation > 90.0) { |
| 650 | ! | Rcpp::stop("elevation must be in [0,90]"); |
| 651 | } | |
| 652 | ! | if (turbidity < 1.7 || turbidity > 10.0) { |
| 653 | ! | Rcpp::stop("turbidity must be in [1.7,10]"); |
| 654 | } | |
| 655 | ||
| 656 | ArHosekSkyModelState *hosek = | |
| 657 | ! | arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo); |
| 658 | ! | if (!hosek) { |
| 659 | ! | Rcpp::stop("Hosek-Wilkie initialisation failed"); |
| 660 | } | |
| 661 | ||
| 662 | ! | const double theta = M_PI_2 - elev_rad; |
| 663 | ! | const double gamma = 0.0; |
| 664 | ! | for (size_t c = 0; c < N_LAMBDA; ++c) { |
| 665 | ! | const double lam = lambda_values[c]; |
| 666 | ! | const double L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam); |
| 667 | ! | const double d_lambda = lambda_weights[c]; |
| 668 | ! | Y += L * cie_y_samples[c] * d_lambda; |
| 669 | } | |
| 670 | ! | arhosekskymodelstate_free(hosek); |
| 671 | } else { | |
| 672 | ! | if (elevation < -4.2 || elevation > 90.0) { |
| 673 | ! | Rcpp::stop("elevation must be in [-4.2, 90]"); |
| 674 | } | |
| 675 | ||
| 676 | // Sample sun radiance along the sun direction. | |
| 677 | ! | Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad), |
| 678 | ! | std::sin(az_rad) * std::cos(elev_rad), |
| 679 | ! | std::sin(elev_rad)); |
| 680 | auto P = | |
| 681 | ! | prague_model.computeParameters({0.0, 0.0, altitude}, toPrague(sun_dir), |
| 682 | elev_rad, az_rad, visibility, albedo); | |
| 683 | ||
| 684 | ! | for (size_t i = 0; i < N_LAMBDA; ++i) { |
| 685 | ! | const double Li = prague_model.sunRadiance(P, lambda_values[i]); |
| 686 | ! | const double d_lambda = lambda_weights[i]; |
| 687 | ! | Y += Li * cie_y_samples[i] * d_lambda; |
| 688 | } | |
| 689 | } | |
| 690 | ||
| 691 | ! | if (!std::isfinite(Y)) { |
| 692 | ! | Y = 0.0; |
| 693 | } | |
| 694 | ||
| 695 | ! | return Y; |
| 696 | } | |
| 697 | ||
| 698 | // [[Rcpp::export]] | |
| 699 | ! | double calculate_sun_radiance_band_rcpp( |
| 700 | double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0, | |
| 701 | double azimuth_deg = 90.0, std::string model = "hosek", | |
| 702 | std::string prg_dataset = "", double altitude = 0.0, | |
| 703 | double visibility = 50.0, | |
| 704 | Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue) { | |
| 705 | ! | if (albedo < 0.0 || albedo > 1.0) { |
| 706 | ! | Rcpp::stop("albedo must be in [0,1]"); |
| 707 | } | |
| 708 | ||
| 709 | ! | const double safe_elevation = clamp_sun_elevation_deg(elevation); |
| 710 | ! | const double elev_rad = safe_elevation * M_PI / 180.0; |
| 711 | ! | const double az_rad = azimuth_deg * M_PI / 180.0; |
| 712 | ||
| 713 | // Prague model initialisation | |
| 714 | ! | PragueSkyModel::AvailableData avail{}; |
| 715 | ! | if (model == "prague") { |
| 716 | ! | if (prg_dataset.empty()) { |
| 717 | ! | Rcpp::stop("prg_dataset must be supplied when model=\"prague\""); |
| 718 | } | |
| 719 | ||
| 720 | ! | if (prague_loaded_file != prg_dataset) { |
| 721 | ! | prague_model.initialize(prg_dataset); |
| 722 | ! | prague_loaded_file = prg_dataset; |
| 723 | } | |
| 724 | ! | avail = prague_model.getAvailableData(); |
| 725 | ! | if (albedo < avail.albedoMin || albedo > avail.albedoMax || |
| 726 | ! | visibility < avail.visibilityMin || visibility > avail.visibilityMax) { |
| 727 | ! | Rcpp::stop("albedo or visibility outside dataset range"); |
| 728 | } | |
| 729 | ! | } else if (model != "hosek") { |
| 730 | ! | Rcpp::stop("unknown model \"%s\"", model.c_str()); |
| 731 | } | |
| 732 | ||
| 733 | // Spectral sampling setup | |
| 734 | ! | std::vector<double> lambda_values; |
| 735 | ! | std::vector<double> lambda_weights; |
| 736 | ||
| 737 | ! | if (model == "prague") { |
| 738 | ! | lambda_values.reserve(avail.channels); |
| 739 | ! | for (int i = 0; i < avail.channels; ++i) { |
| 740 | ! | const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth; |
| 741 | ! | if (lam >= 380.0 && lam <= 740.0) { |
| 742 | ! | lambda_values.push_back(lam); |
| 743 | } | |
| 744 | } | |
| 745 | ! | if (lambda_values.empty()) { |
| 746 | ! | Rcpp::stop("No Prague spectral channels fall within [380, 740] nm."); |
| 747 | } | |
| 748 | ! | lambda_weights.assign(lambda_values.size(), avail.channelWidth); |
| 749 | } else { | |
| 750 | ! | const auto &default_values = default_lambda_low(); |
| 751 | ||
| 752 | ! | if (lambda_nm.isNull()) { |
| 753 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 754 | } else { | |
| 755 | ! | Rcpp::NumericVector lambda_vec(lambda_nm.get()); |
| 756 | ! | if (lambda_vec.size() == 0) { |
| 757 | ! | lambda_values.assign(default_values.begin(), default_values.end()); |
| 758 | } else { | |
| 759 | ! | lambda_values.assign(lambda_vec.begin(), lambda_vec.end()); |
| 760 | } | |
| 761 | } | |
| 762 | ||
| 763 | ! | if (lambda_values.size() < 2) { |
| 764 | ! | Rcpp::stop("lambda_nm must contain at least two wavelengths"); |
| 765 | } | |
| 766 | ! | for (size_t i = 1; i < lambda_values.size(); ++i) { |
| 767 | ! | if (!(lambda_values[i] > lambda_values[i - 1])) { |
| 768 | ! | Rcpp::stop("lambda_nm must be strictly increasing"); |
| 769 | } | |
| 770 | } | |
| 771 | ||
| 772 | ! | lambda_weights = trapezoid_weights(lambda_values); |
| 773 | } | |
| 774 | ||
| 775 | ! | const size_t N_LAMBDA = lambda_values.size(); |
| 776 | ! | double L_band = 0.0; |
| 777 | ||
| 778 | ! | if (model == "hosek") { |
| 779 | ! | if (elevation < 0.0 || elevation > 90.0) { |
| 780 | ! | Rcpp::stop("elevation must be in [0,90]"); |
| 781 | } | |
| 782 | ! | if (turbidity < 1.7 || turbidity > 10.0) { |
| 783 | ! | Rcpp::stop("turbidity must be in [1.7,10]"); |
| 784 | } | |
| 785 | ||
| 786 | ArHosekSkyModelState *hosek = | |
| 787 | ! | arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo); |
| 788 | ! | if (!hosek) { |
| 789 | ! | Rcpp::stop("Hosek-Wilkie initialisation failed"); |
| 790 | } | |
| 791 | ||
| 792 | ! | const double theta = M_PI_2 - elev_rad; |
| 793 | ! | const double gamma = 0.0; |
| 794 | ! | for (size_t c = 0; c < N_LAMBDA; ++c) { |
| 795 | ! | const double lam = lambda_values[c]; |
| 796 | ! | const double L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam); |
| 797 | ! | const double d_lambda = lambda_weights[c]; |
| 798 | ! | L_band += L * d_lambda; |
| 799 | } | |
| 800 | ! | arhosekskymodelstate_free(hosek); |
| 801 | } else { | |
| 802 | ! | if (elevation < -4.2 || elevation > 90.0) { |
| 803 | ! | Rcpp::stop("elevation must be in [-4.2, 90]"); |
| 804 | } | |
| 805 | ||
| 806 | ! | Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad), |
| 807 | ! | std::sin(az_rad) * std::cos(elev_rad), |
| 808 | ! | std::sin(elev_rad)); |
| 809 | auto P = | |
| 810 | ! | prague_model.computeParameters({0.0, 0.0, altitude}, toPrague(sun_dir), |
| 811 | elev_rad, az_rad, visibility, albedo); | |
| 812 | ||
| 813 | ! | for (size_t i = 0; i < N_LAMBDA; ++i) { |
| 814 | ! | const double Li = prague_model.sunRadiance(P, lambda_values[i]); |
| 815 | ! | const double d_lambda = lambda_weights[i]; |
| 816 | ! | L_band += Li * d_lambda; |
| 817 | } | |
| 818 | } | |
| 819 | ||
| 820 | ! | if (!std::isfinite(L_band)) { |
| 821 | ! | L_band = 0.0; |
| 822 | } | |
| 823 | ||
| 824 | ! | return L_band; |
| 825 | } | |
| 826 | ||
| 827 | // [[Rcpp::export]] | |
| 828 | 5x | bool prague_gpu_available() { |
| 829 | 5x | return prague_metal_available(); |
| 830 | } | |
| 831 | ||
| 832 | // [[Rcpp::export]] | |
| 833 | 1x | Rcpp::NumericVector calculate_raw_prague_radiance( |
| 834 | Rcpp::NumericVector phi, Rcpp::NumericVector theta, | |
| 835 | Rcpp::NumericVector lambda_nm, Rcpp::NumericVector elevation, | |
| 836 | Rcpp::NumericVector albedo, Rcpp::NumericVector altitude, | |
| 837 | Rcpp::NumericVector visibility, Rcpp::NumericVector azimuth, | |
| 838 | unsigned int number_cores = 1, std::string prg_dataset = "", | |
| 839 | std::string render_mode = "all", std::string backend = "cpu") { | |
| 840 | 1x | bool render_atmosphere = true; |
| 841 | 1x | bool render_sun = true; |
| 842 | 1x | resolve_render_mode(render_mode, render_atmosphere, render_sun); |
| 843 | ||
| 844 | 1x | if (backend != "cpu" && backend != "gpu") { |
| 845 | ! | Rcpp::stop("backend must be one of \"cpu\" or \"gpu\""); |
| 846 | } | |
| 847 | 1x | if (backend == "gpu" && !prague_metal_available()) { |
| 848 | 1x | Rcpp::stop("backend = \"gpu\" requires macOS with an available Metal device. " |
| 849 | "Use backend = \"cpu\" on this system."); | |
| 850 | } | |
| 851 | // The native entry point also checks lengths before indexing borrowed columns. | |
| 852 | ! | for (const auto &column : {theta, lambda_nm, elevation, albedo, altitude, |
| 853 | ! | visibility, azimuth}) { |
| 854 | ! | if (column.size() != phi.size()) { |
| 855 | ! | Rcpp::stop("Radiance input columns must have equal lengths."); |
| 856 | } | |
| 857 | } | |
| 858 | ! | const auto avail = initialize_prague_model(prg_dataset); |
| 859 | ! | validate_prague_lambda_nm(lambda_nm, avail); |
| 860 | ||
| 861 | ! | if (backend == "gpu") { |
| 862 | ! | Rcpp::NumericVector radiance(phi.size()); |
| 863 | const PragueRadianceColumns columns = { | |
| 864 | ! | phi.begin(), theta.begin(), lambda_nm.begin(), elevation.begin(), |
| 865 | ! | albedo.begin(), altitude.begin(), visibility.begin(), azimuth.begin()}; |
| 866 | ! | prague_metal_radiance(prague_model, prg_dataset, columns, phi.size(), |
| 867 | render_atmosphere, render_sun, radiance.begin(), | |
| 868 | &Rcpp::checkUserInterrupt); | |
| 869 | ! | return radiance; |
| 870 | } | |
| 871 | ||
| 872 | ! | std::vector<double> radiance(phi.size(), 0.0); |
| 873 | ||
| 874 | ! | RcppThread::parallelFor( |
| 875 | ! | 0u, size_t(phi.size()), |
| 876 | ! | [&](size_t t) { |
| 877 | ! | const double theta_rad = theta[t] * M_PI / 180.0; |
| 878 | ! | const double phi_rad = phi[t] * M_PI / 180.0; |
| 879 | ! | const double lam = lambda_nm[t]; |
| 880 | ! | const double safe_elevation = clamp_sun_elevation_deg(elevation[t]); |
| 881 | ! | const double elev_rad = safe_elevation * M_PI / 180.0; |
| 882 | ! | const double az_rad = azimuth[t] * M_PI / 180.0; |
| 883 | ||
| 884 | ! | if (theta_rad > M_PI_2) { |
| 885 | ! | return; |
| 886 | } | |
| 887 | ||
| 888 | ! | Vec3<double> v_zup(std::cos(phi_rad) * std::cos(theta_rad), |
| 889 | ! | std::sin(phi_rad) * std::cos(theta_rad), |
| 890 | ! | std::sin(theta_rad)); |
| 891 | ! | auto P = prague_model.computeParameters( |
| 892 | ! | /*viewPoint*/ {0.0, 0.0, altitude[t]}, |
| 893 | ! | /*viewDir */ toPrague(v_zup), |
| 894 | /*sunElev */ elev_rad, | |
| 895 | /*sunAzim */ az_rad, | |
| 896 | ! | /*visibility*/ visibility[t], |
| 897 | ! | /*albedo */ albedo[t]); |
| 898 | ||
| 899 | ! | double Li = 0.0; |
| 900 | ! | if (render_atmosphere) { |
| 901 | ! | Li = prague_model.skyRadiance(P, lam); |
| 902 | } | |
| 903 | ! | if (render_sun) { |
| 904 | ! | const double sun = prague_model.sunRadiance(P, lam); |
| 905 | ! | Li = render_atmosphere ? (Li + sun) : sun; |
| 906 | } | |
| 907 | ! | if (!std::isfinite(Li)) { |
| 908 | ! | Li = 0.0; |
| 909 | } | |
| 910 | ! | radiance[t] = Li; |
| 911 | }, | |
| 912 | number_cores); | |
| 913 | ||
| 914 | ! | return Rcpp::NumericVector(radiance.begin(), radiance.end()); |
| 915 | } | |
| 916 | ||
| 917 | // [[Rcpp::export]] | |
| 918 | ! | Rcpp::NumericMatrix calculate_raw_prague( |
| 919 | Rcpp::NumericVector phi, Rcpp::NumericVector theta, | |
| 920 | Rcpp::NumericVector elevation, Rcpp::NumericVector albedo, | |
| 921 | Rcpp::NumericVector altitude, Rcpp::NumericVector visibility, | |
| 922 | Rcpp::NumericVector azimuth, unsigned int number_cores = 1, | |
| 923 | std::string prg_dataset = "", std::string render_mode = "all", | |
| 924 | bool atmospheric_attenuation = true) { | |
| 925 | ! | bool render_atmosphere = true; |
| 926 | ! | bool render_sun = true; |
| 927 | ! | resolve_render_mode(render_mode, render_atmosphere, render_sun); |
| 928 | ||
| 929 | ! | const auto avail = initialize_prague_model(prg_dataset); |
| 930 | ||
| 931 | // Spectral sampling: lock to Prague dataset channel centers within CIE range | |
| 932 | // (380-740 nm). | |
| 933 | ! | std::vector<double> lambda_values; |
| 934 | ! | lambda_values.reserve(avail.channels); |
| 935 | ! | for (int i = 0; i < avail.channels; ++i) { |
| 936 | ! | const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth; |
| 937 | ! | if (lam >= 380.0 && lam <= 740.0) { |
| 938 | ! | lambda_values.push_back(lam); |
| 939 | } | |
| 940 | } | |
| 941 | ! | if (lambda_values.empty()) { |
| 942 | ! | Rcpp::stop("No Prague spectral channels fall within [380, 740] nm."); |
| 943 | } | |
| 944 | ! | const size_t N_LAMBDA = lambda_values.size(); |
| 945 | // Constant band weights equal to channel width for rectangular integration. | |
| 946 | ! | std::vector<double> lambda_weights(N_LAMBDA, avail.channelWidth); |
| 947 | ! | std::vector<CIETristimulus> cie_samples; |
| 948 | ! | cie_samples.reserve(N_LAMBDA); |
| 949 | ! | for (double lam : lambda_values) { |
| 950 | ! | cie_samples.push_back(interpolate_cie_xyz(lam)); |
| 951 | } | |
| 952 | ||
| 953 | // Initialize image buffer | |
| 954 | ! | std::vector<double> img(3 * phi.size(), 0.0); |
| 955 | ! | std::vector<double> band(phi.size(), 0.0); |
| 956 | ||
| 957 | // Render loop (parallel over rows) | |
| 958 | ! | RcppThread::parallelFor( |
| 959 | ! | 0u, size_t(phi.size()), |
| 960 | ! | [&](size_t t) { |
| 961 | ! | double theta_rad = theta[t] * M_PI / 180; |
| 962 | ! | double phi_rad = phi[t] * M_PI / 180; |
| 963 | ! | const double safe_elevation = clamp_sun_elevation_deg(elevation[t]); |
| 964 | ! | double elev_rad = safe_elevation * M_PI / 180; |
| 965 | ! | double az_rad = azimuth[t] * M_PI / 180; |
| 966 | ||
| 967 | ! | if (theta_rad > M_PI_2) { |
| 968 | ! | return; |
| 969 | } | |
| 970 | ||
| 971 | ! | Vec3<double> v_zup(std::cos(phi_rad) * std::cos(theta_rad), |
| 972 | ! | std::sin(phi_rad) * std::cos(theta_rad), |
| 973 | ! | std::sin(theta_rad)); |
| 974 | ! | auto P = prague_model.computeParameters( |
| 975 | ! | /*viewPoint*/ {0.0, 0.0, altitude[t]}, |
| 976 | ! | /*viewDir */ toPrague(v_zup), |
| 977 | /*sunElev */ elev_rad, | |
| 978 | /*sunAzim */ az_rad, | |
| 979 | ! | /*visibility*/ visibility[t], |
| 980 | ! | /*albedo */ albedo[t]); |
| 981 | ! | double X = 0.0, Y = 0.0, Z = 0.0; |
| 982 | ! | double L_band = 0.0; |
| 983 | ! | const bool view_above_horizon = theta_rad <= M_PI_2; |
| 984 | ! | for (size_t c = 0; c < N_LAMBDA; ++c) { |
| 985 | ! | const double lam = lambda_values[c]; |
| 986 | ! | double Li = 0.0; |
| 987 | ! | if (render_atmosphere) { |
| 988 | ! | Li = prague_model.skyRadiance(P, lam); |
| 989 | } | |
| 990 | ! | if (render_sun && view_above_horizon) { |
| 991 | ! | const double sun = prague_model.sunRadiance(P, lam, atmospheric_attenuation); |
| 992 | ! | Li = render_atmosphere ? (Li + sun) : sun; |
| 993 | } | |
| 994 | ! | const double d_lambda = lambda_weights[c]; |
| 995 | ! | X += Li * cie_samples[c].x * d_lambda; |
| 996 | ! | Y += Li * cie_samples[c].y * d_lambda; |
| 997 | ! | Z += Li * cie_samples[c].z * d_lambda; |
| 998 | ! | L_band += Li * d_lambda; |
| 999 | } | |
| 1000 | ! | if (!std::isfinite(X) || !std::isfinite(Y) || !std::isfinite(Z)) { |
| 1001 | ! | X = 0.0; |
| 1002 | ! | Y = 0.0; |
| 1003 | ! | Z = 0.0; |
| 1004 | } | |
| 1005 | double R, G, B; | |
| 1006 | ! | xyz_to_srgb(X, Y, Z, R, G, B); |
| 1007 | ! | if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) { |
| 1008 | ! | R = 0.0; |
| 1009 | ! | G = 0.0; |
| 1010 | ! | B = 0.0; |
| 1011 | } | |
| 1012 | ! | img[3 * t + 0] = R; |
| 1013 | ! | img[3 * t + 1] = G; |
| 1014 | ! | img[3 * t + 2] = B; |
| 1015 | ! | band[t] = L_band; |
| 1016 | }, | |
| 1017 | number_cores); | |
| 1018 | ||
| 1019 | ! | Rcpp::NumericMatrix rgb(phi.size(), 3); |
| 1020 | ! | for (int p = 0; p < phi.size(); p++) { |
| 1021 | ! | rgb(p, 0) = img[3 * p]; |
| 1022 | ! | rgb(p, 1) = img[3 * p + 1]; |
| 1023 | ! | rgb(p, 2) = img[3 * p + 2]; |
| 1024 | } | |
| 1025 | ! | Rcpp::NumericVector band_vals(band.begin(), band.end()); |
| 1026 | ! | rgb.attr("L_band") = band_vals; |
| 1027 | ! | return (rgb); |
| 1028 | } |
| 1 | #ifndef SKYMODELR_PRAGUE_SKY_MODEL_H | |
| 2 | #define SKYMODELR_PRAGUE_SKY_MODEL_H | |
| 3 | /* | |
| 4 | This file is included in the skymodelr package, which is distributed as a | |
| 5 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 6 | preserved for attribution and compliance with upstream notice requirements. | |
| 7 | */ | |
| 8 | ||
| 9 | // Copyright 2022 Charles University | |
| 10 | // SPDX-License-Identifier: Apache-2.0 | |
| 11 | ||
| 12 | #include <array> | |
| 13 | #include <cmath> | |
| 14 | #include <cstdio> | |
| 15 | #include <exception> | |
| 16 | #include <string> | |
| 17 | #include <vector> | |
| 18 | #include "../../inst/include/skymodelr/prague_metal.h" | |
| 19 | ||
| 20 | ||
| 21 | ||
| 22 | namespace skymodelr_prague { | |
| 23 | ||
| 24 | double pragueLerp(const double from, const double to, const double factor); | |
| 25 | ||
| 26 | /// Implementation of the physically-based sky model presented by Wilkie et al. [2021] | |
| 27 | /// (https://cgg.mff.cuni.cz/publications/skymodel-2021/) and Vevoda et al. [2022]. Improves on previous work | |
| 28 | /// especially in accuracy of sunset scenarios. Based on reconstruction of radiance from a small dataset | |
| 29 | /// fitted to a large set of images obtained by brute force atmosphere simulation. | |
| 30 | /// | |
| 31 | /// Provides evaluation of spectral sky radiance, sun radiance, transmittance and polarisation for observer at | |
| 32 | /// a specific altitude above ground. The range of configurations depends on supplied dataset. The full | |
| 33 | /// version models atmosphere of visibility (meteorological range) from 20 km to 131.8 km for sun elevations | |
| 34 | /// from -4.2 degrees to 90 degrees, observer altitudes from 0 km to 15 km and ground albedo from 0 to 1, and | |
| 35 | /// provides results for wavelengths from 280 nm to 2480 nm. | |
| 36 | /// | |
| 37 | /// Usage: | |
| 38 | /// 1. Create PragueSkyModel object and call its initialize method with a path to the dataset file. | |
| 39 | /// 2. The model is parametrized by several values that are gathered in PragueSkyModel::Parameters structure. | |
| 40 | /// You can either fill this structure manually (in that case see its description) or just call | |
| 41 | /// computeParameters, which will compute it for you based on a few basic parameters. | |
| 42 | /// 3. Use the Parameters structure when calling skyRadiance, sunRadiance, transmittance, or polarisation | |
| 43 | /// methods to obtain the respective quantities. | |
| 44 | /// | |
| 45 | /// Throws: | |
| 46 | /// - DatasetNotFoundException: if the specified dataset file could not be found | |
| 47 | /// - DatasetReadException: if an error occurred while reading the dataset file | |
| 48 | /// - NoPolarisationException: if the polarisation method is called but the model does not contain | |
| 49 | /// polarisation data | |
| 50 | /// - NotInitializedException: if the model is used without calling the initialize method first | |
| 51 | /// | |
| 52 | /// Note: | |
| 53 | /// The entire model is written in a single class and does not depend on anything except of STL. It defines a | |
| 54 | /// simple Vector3 class to simplify working with points and directions and expects using this class when | |
| 55 | /// passing viewing point and direction to the computeParameters method. | |
| 56 | class PragueSkyModel { | |
| 57 | ||
| 58 | ||
| 59 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 60 | // Public types | |
| 61 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 62 | public: | |
| 63 | /// Exception thrown by the initialize method if the passed dataset file could not be found. | |
| 64 | class DatasetNotFoundException : public std::exception { | |
| 65 | private: | |
| 66 | const std::string message; | |
| 67 | ||
| 68 | public: | |
| 69 | 1x | DatasetNotFoundException(const std::string& filename) |
| 70 | 5x | : message(std::string("Dataset file ") + filename + std::string(" not found")) {} |
| 71 | ||
| 72 | 1x | virtual const char* what() const throw() { return message.c_str(); } |
| 73 | }; | |
| 74 | ||
| 75 | /// Exception thrown by the initialize method if an error occurred while reading the passed dataset file. | |
| 76 | class DatasetReadException : public std::exception { | |
| 77 | private: | |
| 78 | const std::string message; | |
| 79 | ||
| 80 | public: | |
| 81 | 1x | DatasetReadException(const std::string& parameterName) |
| 82 | 3x | : message(std::string("Dataset reading failed at ") + parameterName) {} |
| 83 | ||
| 84 | 1x | virtual const char* what() const throw() { return message.c_str(); } |
| 85 | }; | |
| 86 | ||
| 87 | /// Exception thrown by the polarisation method if the dataset passed to the initialize method does not | |
| 88 | /// contain polarisation data. | |
| 89 | class NoPolarisationException : public std::exception { | |
| 90 | private: | |
| 91 | const std::string message; | |
| 92 | ||
| 93 | public: | |
| 94 | ! | NoPolarisationException() |
| 95 | ! | : message(std::string("The supplied dataset does not contain polarisation data")) {} |
| 96 | ||
| 97 | ! | virtual const char* what() const throw() { return message.c_str(); } |
| 98 | }; | |
| 99 | ||
| 100 | /// Exception thrown when using the model without calling the initialize method first. | |
| 101 | class NotInitializedException : public std::exception { | |
| 102 | private: | |
| 103 | const std::string message; | |
| 104 | ||
| 105 | public: | |
| 106 | ! | NotInitializedException() |
| 107 | ! | : message(std::string("The model is not initialized")) {} |
| 108 | ||
| 109 | ! | virtual const char* what() const throw() { return message.c_str(); } |
| 110 | }; | |
| 111 | ||
| 112 | /// A simple 3D vector implementation. Provides some basic operations. | |
| 113 | class Vector3 { | |
| 114 | public: | |
| 115 | double x, y, z; | |
| 116 | ||
| 117 | ! | Vector3() { |
| 118 | ! | this->x = 0.0; |
| 119 | ! | this->y = 0.0; |
| 120 | ! | this->z = 0.0; |
| 121 | } | |
| 122 | ||
| 123 | ! | Vector3(double x, double y, double z) { |
| 124 | ! | this->x = x; |
| 125 | ! | this->y = y; |
| 126 | ! | this->z = z; |
| 127 | } | |
| 128 | ||
| 129 | ! | Vector3 operator+(const Vector3& other) const { |
| 130 | ! | return Vector3(x + other.x, y + other.y, z + other.z); |
| 131 | } | |
| 132 | ! | Vector3 operator-(const Vector3& other) const { |
| 133 | ! | return Vector3(x - other.x, y - other.y, z - other.z); |
| 134 | } | |
| 135 | ||
| 136 | ! | Vector3 operator*(const double factor) const { return Vector3(x * factor, y * factor, z * factor); } |
| 137 | ||
| 138 | ! | Vector3 operator/(const double factor) const { return Vector3(x / factor, y / factor, z / factor); } |
| 139 | ||
| 140 | bool isZero() const { return x == 0.0 && y == 0.0 && z == 0.0; } | |
| 141 | }; | |
| 142 | ||
| 143 | /// Structure holding all parameters necessary for querying the model. | |
| 144 | struct Parameters { | |
| 145 | /// Angle between view direction and direction to zenith in radians, supported values in range [0, | |
| 146 | /// PI]. | |
| 147 | double theta; | |
| 148 | ||
| 149 | /// Angle between view direction and direction to sun in radians, supported values in range [0, PI]. | |
| 150 | double gamma; | |
| 151 | ||
| 152 | /// Altitude-corrected angle between view direction and direction perpendicular to a shadow plane (= | |
| 153 | /// direction to sun rotated PI / 2 towards direction to zenith) in radians, used for negative solar | |
| 154 | /// elevations only, supported values in range [0, PI] | |
| 155 | double shadow; | |
| 156 | ||
| 157 | /// Altitude-corrected version of the theta angle in radians, supported values in range [0, PI]. | |
| 158 | double zero; | |
| 159 | ||
| 160 | /// Sun elevation at view point in radians, supported values in range [-0.073, PI/2] (for full | |
| 161 | /// dataset). For view points above ground differs from the ground level sun elevation expected by the | |
| 162 | /// computeParameters method. | |
| 163 | double elevation; | |
| 164 | ||
| 165 | /// Altitude of view point in meters, supported values in range [0, 15000] (for full dataset). | |
| 166 | double altitude; | |
| 167 | ||
| 168 | /// Horizontal visibility (meteorological range) at ground level in kilometers, supported values in | |
| 169 | /// range [20, 131.8] (for full dataset). | |
| 170 | double visibility; | |
| 171 | ||
| 172 | /// Ground albedo, supported values in range [0, 1] (for full dataset). | |
| 173 | double albedo; | |
| 174 | }; | |
| 175 | ||
| 176 | /// Structure with parameter ranges available in currently loaded dataset. | |
| 177 | struct AvailableData { | |
| 178 | double albedoMin; | |
| 179 | double albedoMax; | |
| 180 | double altitudeMin; | |
| 181 | double altitudeMax; | |
| 182 | double elevationMin; | |
| 183 | double elevationMax; | |
| 184 | double visibilityMin; | |
| 185 | double visibilityMax; | |
| 186 | bool polarisation; | |
| 187 | int channels; | |
| 188 | double channelStart; | |
| 189 | double channelWidth; | |
| 190 | }; | |
| 191 | ||
| 192 | ||
| 193 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 194 | // Private types | |
| 195 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 196 | private: | |
| 197 | /// Structure holding index and factor for interpolating with respect to two neighboring values of an | |
| 198 | /// array. | |
| 199 | struct InterpolationParameter { | |
| 200 | double factor; | |
| 201 | int index; | |
| 202 | }; | |
| 203 | ||
| 204 | /// Angles converted into interpolation parameters. | |
| 205 | struct AngleParameters { | |
| 206 | InterpolationParameter gamma, alpha, zero; | |
| 207 | }; | |
| 208 | ||
| 209 | /// Structure controlling interpolation with respect to visibility, albedo, altitude and elevation. | |
| 210 | struct ControlParameters { | |
| 211 | /// 16 sets of parameters that will be bi-linearly interpolated | |
| 212 | std::array<std::vector<float>::const_iterator, 16> coefficients; | |
| 213 | std::array<double, 4> interpolationFactor; | |
| 214 | }; | |
| 215 | ||
| 216 | /// Structure used for storing radiance and polarisation metadata. | |
| 217 | struct Metadata { | |
| 218 | int rank; | |
| 219 | ||
| 220 | int sunOffset; | |
| 221 | int sunStride; | |
| 222 | std::vector<double> sunBreaks; | |
| 223 | ||
| 224 | int zenithOffset; | |
| 225 | int zenithStride; | |
| 226 | std::vector<double> zenithBreaks; | |
| 227 | ||
| 228 | int emphOffset; // not used for polarisation | |
| 229 | std::vector<double> emphBreaks; // not used for polarisation | |
| 230 | ||
| 231 | int totalCoefsSingleConfig; | |
| 232 | int totalCoefsAllConfigs; | |
| 233 | }; | |
| 234 | ||
| 235 | /// Transmittance model internal parameters. | |
| 236 | struct TransmittanceParameters { | |
| 237 | InterpolationParameter altitude; | |
| 238 | InterpolationParameter distance; | |
| 239 | }; | |
| 240 | ||
| 241 | ||
| 242 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 243 | // Private data | |
| 244 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 245 | int channels; | |
| 246 | double channelStart; | |
| 247 | double channelWidth; | |
| 248 | ||
| 249 | bool initialized; | |
| 250 | ||
| 251 | // Exact reuse. A generation changes whenever coefficients load, | |
| 252 | // so thread-local caches cannot mistake a reused object address for old data. | |
| 253 | unsigned long long cacheGeneration = 0; | |
| 254 | bool cacheSky = false; | |
| 255 | std::vector<double> expandedTrans; | |
| 256 | int expandedVisibilityFirst = 0, expandedVisibilityCount = 0; | |
| 257 | void expandTransmission(double singleVisibility, double maxMiB); | |
| 258 | ||
| 259 | ||
| 260 | // Total number of configurations | |
| 261 | int totalConfigs; | |
| 262 | ||
| 263 | // Number of configurations skipped from the beginning of the radiance/polarisation coefficients part | |
| 264 | // of the dataset file (if loading of just one visibility was requested) | |
| 265 | int skippedConfigsBegin; | |
| 266 | ||
| 267 | // Number of configurations skipped till the end of the radiance/polarisation coefficients part | |
| 268 | // of the dataset file (if loading of just one visibility was requested) | |
| 269 | int skippedConfigsEnd; | |
| 270 | ||
| 271 | // Metadata common for radiance and polarisation | |
| 272 | ||
| 273 | std::vector<double> visibilitiesRad; | |
| 274 | std::vector<double> albedosRad; | |
| 275 | std::vector<double> altitudesRad; | |
| 276 | std::vector<double> elevationsRad; | |
| 277 | ||
| 278 | // Radiance metadata | |
| 279 | ||
| 280 | Metadata metadataRad; | |
| 281 | ||
| 282 | // Radiance data | |
| 283 | // | |
| 284 | // Structure: | |
| 285 | // [[[[[[ sunCoefsRad (sunBreaksCountRad * float), | |
| 286 | // zenithCoefsRad (zenithBreaksCountRad * float) ] * rankRad, | |
| 287 | // emphCoefsRad (emphBreaksCountRad * float) ] | |
| 288 | // * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount | |
| 289 | ||
| 290 | std::vector<float> dataRad; | |
| 291 | ||
| 292 | // Polarisation metadata | |
| 293 | ||
| 294 | Metadata metadataPol; | |
| 295 | ||
| 296 | // Polarisation data | |
| 297 | // | |
| 298 | // Struture: | |
| 299 | // [[[[[[ sunCoefsPol (sunBreaksCountPol * float), | |
| 300 | // zenithCoefsPol (zenithBreaksCountPol * float) ] * rankPol] | |
| 301 | // * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount | |
| 302 | ||
| 303 | std::vector<float> dataPol; | |
| 304 | ||
| 305 | // Transmittance metadata | |
| 306 | ||
| 307 | int aDim; | |
| 308 | int dDim; | |
| 309 | int rankTrans; | |
| 310 | std::vector<double> altitudesTrans; | |
| 311 | std::vector<double> visibilitiesTrans; | |
| 312 | ||
| 313 | // Transmittance data | |
| 314 | ||
| 315 | std::vector<float> dataTransU; | |
| 316 | std::vector<float> dataTransV; | |
| 317 | ||
| 318 | ||
| 319 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 320 | // Public methods | |
| 321 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 322 | public: | |
| 323 | 5x | PragueSkyModel() : initialized(false) {}; |
| 324 | void exportMetal(skymodelr_prague_gpu_layout &, std::vector<float> &) const; | |
| 325 | ||
| 326 | /// Prepares the model and loads the given dataset file into memory. | |
| 327 | /// | |
| 328 | /// If a positive visibility value is passed, only a portion of the dataset needed for evaluation of that | |
| 329 | /// particular visibility is loaded (two nearest visibilities are loaded if the value is included in the | |
| 330 | /// dataset or one nearest if not). Otherwise, the entire dataset is loaded. | |
| 331 | /// | |
| 332 | /// Throws: | |
| 333 | /// - DatasetNotFoundException: if the specified dataset file could not be found | |
| 334 | /// - DatasetReadException: if an error occurred while reading the dataset file | |
| 335 | // Native consumers can opt into exact reuse without changing the legacy | |
| 336 | // evaluator's loading policy. Neither option introduces a new model grid. | |
| 337 | void initialize(const std::string& filename, const double singleVisibility = 0.0, | |
| 338 | bool cacheSpectra = false, bool transmissionTable = false, | |
| 339 | double transmissionTableMaxMiB = 512); | |
| 340 | ||
| 341 | bool isInitialized() const { return initialized; } | |
| 342 | ||
| 343 | /// Gets parameter ranges available in currently loaded dataset. | |
| 344 | /// | |
| 345 | /// Throws NotInitializedException if called without initializing the model first. | |
| 346 | AvailableData getAvailableData() const; | |
| 347 | ||
| 348 | // skymodelr: report immutable coefficient storage for scene memory accounting. | |
| 349 | size_t memoryUsage() const; | |
| 350 | ||
| 351 | /// Computes all the parameters in the Parameters structure necessary for querying the model. | |
| 352 | /// | |
| 353 | /// Expects view point and direction, sun elevation and azimuth at origin, ground level visibility and | |
| 354 | /// ground albedo. Assumes origin at [0,0,0] with Z axis pointing up. Thus view point [0, 0, 100] defines | |
| 355 | /// observer altitude 100 m. Range of available values depends on the used dataset. The full version | |
| 356 | /// supports altitude from [0, 15000] m, elevation from [-0.073, PI/2] rad, azimuth from [0, PI] rad, visibility | |
| 357 | /// from [20, 131.8] km, and albedo from [0, 1]. Values outside range of the used dataset are clamped to the | |
| 358 | /// nearest supported value. | |
| 359 | Parameters computeParameters(const Vector3& viewPoint, | |
| 360 | const Vector3& viewDirection, | |
| 361 | const double groundLevelSolarElevationAtOrigin, | |
| 362 | const double groundLevelSolarAzimuthAtOrigin, | |
| 363 | const double visibility, | |
| 364 | const double albedo) const; | |
| 365 | ||
| 366 | /// Computes sky radiance only (without direct sun contribution) for given parameters and wavelength (full | |
| 367 | /// dataset supports wavelengths from 280 nm to 2480 nm). | |
| 368 | /// | |
| 369 | /// Throws NotInitializedException if called without initializing the model first. | |
| 370 | double skyRadiance(const Parameters& params, const double wavelength) const; | |
| 371 | // skymodelr: exact spectral batch; shares wavelength-independent lookups. | |
| 372 | void skyRadianceSpectrum(const Parameters& params, const double* wavelengths, | |
| 373 | size_t count, double* values) const; | |
| 374 | ||
| 375 | /// Computes sun radiance only (without radiance inscattered from the sky) for given parameters and | |
| 376 | /// wavelength (full dataset supports wavelengths from 280 nm to 2480 nm). | |
| 377 | /// | |
| 378 | /// Checks whether the parameters correspond to view direction hitting the sun and returns 0 if not. | |
| 379 | /// | |
| 380 | /// Throws NotInitializedException if called without initializing the model first. | |
| 381 | double sunRadiance(const Parameters& params, const double wavelength, | |
| 382 | const bool atmosphericAttenuation = true) const; | |
| 383 | ||
| 384 | /// Computes degree of polarisation for given parameters and wavelength (full | |
| 385 | /// dataset supports wavelengths from 280 nm to 2480 nm). Can be negative. | |
| 386 | /// | |
| 387 | /// Throws: | |
| 388 | /// - NoPolarisationException: if the polarisation method is called but the model does not contain | |
| 389 | /// polarisation data | |
| 390 | /// - NotInitializedException: if called without initializing the model first | |
| 391 | double polarisation(const Parameters& params, const double wavelength) const; | |
| 392 | ||
| 393 | /// Computes transmittance between view point and a point certain distance away from it along view | |
| 394 | /// direction. | |
| 395 | /// | |
| 396 | /// Expects the Parameters structure, wavelength (full dataset supports wavelengths from 280 nm | |
| 397 | /// to 2480 nm) and the distance (any positive number, use std::numeric_limits<double>::max() for | |
| 398 | /// infinity). | |
| 399 | /// | |
| 400 | /// Throws NotInitializedException if called without initializing the model first. | |
| 401 | double transmittance(const Parameters& params, const double wavelength, const double distance) const; | |
| 402 | void transmittanceSpectrum(const Parameters& params, const double* wavelengths, | |
| 403 | size_t count, double distance, double* values) const; | |
| 404 | ||
| 405 | ||
| 406 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 407 | // Private methods | |
| 408 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 409 | private: | |
| 410 | /// Reads radiance part of the dataset file into memory. | |
| 411 | /// | |
| 412 | /// If a positive visibility value is passed, only a portion of the dataset needed for evaluation of that | |
| 413 | /// particular visibility is loaded (two nearest visibilities are loaded if the value is included in the | |
| 414 | /// dataset or one nearest if not). Otherwise, the entire dataset is loaded. | |
| 415 | /// | |
| 416 | /// Throws DatasetReadException if an error occurred while reading the dataset file. | |
| 417 | void readRadiance(FILE* handle, const double singleVisibility); | |
| 418 | ||
| 419 | /// Reads transmittance part of the dataset file into memory. | |
| 420 | /// Throws DatasetReadException if an error occurred while reading the dataset file. | |
| 421 | void readTransmittance(FILE* handle); | |
| 422 | ||
| 423 | /// Reads polarisation part of the dataset file into memory. | |
| 424 | /// Throws DatasetReadException if an error occurred while reading the dataset file. | |
| 425 | void readPolarisation(FILE* handle); | |
| 426 | ||
| 427 | // Sky radiance and polarisation | |
| 428 | ||
| 429 | /// Gets iterator to coefficients in the dataset array corresponding to the given configuration. Used for | |
| 430 | /// sky radiance and polarisation. | |
| 431 | std::vector<float>::const_iterator getCoefficients(const std::vector<float>& dataset, | |
| 432 | const int totalCoefsSingleConfig, | |
| 433 | const int elevation, | |
| 434 | const int altitude, | |
| 435 | const int visibility, | |
| 436 | const int albedo, | |
| 437 | const int wavelength) const; | |
| 438 | ||
| 439 | /// Recursive function controlling interpolation of reconstructed radiance between two neighboring visibility, | |
| 440 | /// albedo, altitude and elevation values. | |
| 441 | template <int TOffset, int TLevel> | |
| 442 | ! | double interpolate(const AngleParameters& angleParameters, |
| 443 | const ControlParameters& controlParameters, | |
| 444 | const Metadata& metadata) const { | |
| 445 | /// Starts at level 0 and recursively goes down to level 4 while computing offset to the control | |
| 446 | /// parameters array. There it reconstructs radiance. When returning from recursion interpolates | |
| 447 | /// according to elevation, altitude, albedo and visibility at level 3, 2, 1 and 0, respectively. | |
| 448 | if constexpr (TLevel == 4) { | |
| 449 | ! | return reconstruct(angleParameters, controlParameters.coefficients[TOffset], metadata); |
| 450 | } else { | |
| 451 | // Compute the first value | |
| 452 | const double resultLow = | |
| 453 | ! | interpolate<TOffset, TLevel + 1>(angleParameters, controlParameters, metadata); |
| 454 | ||
| 455 | // Skip the second value if not useful or not available. | |
| 456 | ! | if (controlParameters.interpolationFactor[TLevel] < 1e-6) { |
| 457 | ! | return resultLow; |
| 458 | } | |
| 459 | ||
| 460 | // Compute the second value | |
| 461 | const double resultHigh = | |
| 462 | ! | interpolate<TOffset + (1 << (3 - TLevel)), TLevel + 1>(angleParameters, |
| 463 | controlParameters, | |
| 464 | metadata); | |
| 465 | ||
| 466 | /// Interpolate between the two | |
| 467 | ! | return pragueLerp(resultLow, resultHigh, controlParameters.interpolationFactor[TLevel]); |
| 468 | } | |
| 469 | } | |
| 470 | ||
| 471 | /// Reconstructs sky radiance or polarisation from the given control parameters by inverse tensor | |
| 472 | /// decomposition. | |
| 473 | double reconstruct(const AngleParameters& angleParameters, | |
| 474 | const std::vector<float>::const_iterator controlParameters, | |
| 475 | const Metadata& metadata) const; | |
| 476 | ||
| 477 | /// Get interpolation parameter for the given query value, i.e. finds position of the query value between | |
| 478 | /// a pair of break values. | |
| 479 | /// | |
| 480 | /// Used for albedo, elevation, altitude, visibility and angles (theta, alpha, or gamma). | |
| 481 | InterpolationParameter getInterpolationParameter(const double queryVal, | |
| 482 | const std::vector<double>& breaks) const; | |
| 483 | ||
| 484 | /// Evaluates the model. Used for computing sky radiance and polarisation. | |
| 485 | double evaluateModel(const Parameters& params, | |
| 486 | const double wavelength, | |
| 487 | const std::vector<float>& data, | |
| 488 | const Metadata& metadata) const; | |
| 489 | ||
| 490 | // Transmittance | |
| 491 | ||
| 492 | /// Gets iterator to base transmittance coefficients in the dataset array corresponding to the given | |
| 493 | /// configuration. | |
| 494 | std::vector<float>::const_iterator getCoefficientsTransBase(const int altitude, | |
| 495 | const int a, | |
| 496 | const int d) const; | |
| 497 | ||
| 498 | /// Gets iterator to transmittance coefficients in the dataset array corresponding to the given | |
| 499 | /// configuration. | |
| 500 | std::vector<float>::const_iterator getCoefficientsTrans(const int visibility, | |
| 501 | const int altitude, | |
| 502 | const int wavelength) const; | |
| 503 | ||
| 504 | /// Interpolates transmittances computed for two nearest altitudes. | |
| 505 | double interpolateTrans(const int visibilityIndex, | |
| 506 | const InterpolationParameter altitudeParam, | |
| 507 | const TransmittanceParameters transParams, | |
| 508 | const int channelIndex) const; | |
| 509 | ||
| 510 | /// For each channel reconstructs transmittances for the four nearest transmittance parameters and | |
| 511 | /// interpolates them. | |
| 512 | double reconstructTrans(const int visibilityIndex, | |
| 513 | const int altitudeIndex, | |
| 514 | const TransmittanceParameters transParams, | |
| 515 | const int channelIndex) const; | |
| 516 | ||
| 517 | /// Converts altitude or distance value used in the transmittance model into interpolation parameter. | |
| 518 | InterpolationParameter getInterpolationParameterTrans(const double value, | |
| 519 | const int paramCount, | |
| 520 | const int power) const; | |
| 521 | ||
| 522 | /// Transforms the given theta angle, observer altitude and distance along ray into transmittance model | |
| 523 | /// internal [altitude, distance] parametrization. | |
| 524 | TransmittanceParameters toTransmittanceParams(const double theta, | |
| 525 | const double distance, | |
| 526 | const double altitude) const; | |
| 527 | }; | |
| 528 | ||
| 529 | ||
| 530 | } // namespace skymodelr_prague | |
| 531 | ||
| 532 | // Internal source compatibility for skymodelr's existing R entry points. | |
| 533 | using PragueSkyModel = skymodelr_prague::PragueSkyModel; | |
| 534 | #endif |
| 1 | // Registered, versioned native interface. GPL-3. | |
| 2 | #include "../inst/include/skymodelr/prague_api.h" | |
| 3 | #include "PragueSkyModel/PragueSkyModel.h" | |
| 4 | #include <R_ext/Rdynload.h> | |
| 5 | #include <algorithm> | |
| 6 | #include <cmath> | |
| 7 | #include <cstring> | |
| 8 | #include <limits> | |
| 9 | #include <memory> | |
| 10 | #include <stdexcept> | |
| 11 | ||
| 12 | struct skymodelr_prague_handle { PragueSkyModel model; }; | |
| 13 | namespace { | |
| 14 | 3x | void error_message(char *output, size_t capacity, const char *message) noexcept { |
| 15 | 3x | if (!output || !capacity) return; |
| 16 | 3x | size_t n = std::min(capacity - 1, std::strlen(message)); |
| 17 | 3x | std::memcpy(output, message, n); output[n] = '\0'; |
| 18 | } | |
| 19 | 3x | template <typename F> int guarded(F fn, char *error, size_t capacity) noexcept { |
| 20 | 3x | try { fn(); return 1; } |
| 21 | 3x | catch (const std::exception &e) { error_message(error, capacity, e.what()); } |
| 22 | ! | catch (...) { error_message(error, capacity, "Unknown error in skymodelr Prague model."); } |
| 23 | 3x | return 0; |
| 24 | } | |
| 25 | 1x | const PragueSkyModel &model(const skymodelr_prague_handle *handle) { |
| 26 | 1x | if (!handle) throw std::invalid_argument("Prague model is not initialized."); |
| 27 | ! | return handle->model; |
| 28 | } | |
| 29 | 2x | void validate_finite(double value) { |
| 30 | 2x | if (!std::isfinite(value)) throw std::invalid_argument("Nonfinite Prague query parameter."); |
| 31 | } | |
| 32 | ! | void atmosphere(double visibility, double albedo) { |
| 33 | ! | validate_finite(visibility); validate_finite(albedo); |
| 34 | ! | if (visibility < 0 || albedo < 0 || albedo > 1) |
| 35 | ! | throw std::invalid_argument("Invalid Prague visibility or ground albedo."); |
| 36 | } | |
| 37 | ! | PragueSkyModel::Parameters parameters(const skymodelr_prague_parameters *p) { |
| 38 | ! | if (!p) throw std::invalid_argument("Missing Prague query parameters."); |
| 39 | ! | for (double angle : {p->theta, p->gamma, p->shadow, p->zero}) { |
| 40 | ! | validate_finite(angle); |
| 41 | ! | if (angle < 0 || angle > 3.14159265358979323846) |
| 42 | ! | throw std::invalid_argument("Prague direction angles must lie between zero and pi."); |
| 43 | } | |
| 44 | ! | validate_finite(p->elevation); validate_finite(p->altitude); atmosphere(p->visibility, p->albedo); |
| 45 | ! | if (p->altitude < 0) throw std::invalid_argument("Prague altitude must be nonnegative."); |
| 46 | ! | return {p->theta, p->gamma, p->shadow, p->zero, p->elevation, |
| 47 | ! | p->altitude, p->visibility, p->albedo}; |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | extern "C" { | |
| 52 | 2x | static skymodelr_prague_handle *create_model(const char *filename, double visibility, |
| 53 | int cache_spectra, int transmission_table, | |
| 54 | double max_mib, | |
| 55 | char *error, size_t capacity) noexcept { | |
| 56 | 2x | std::unique_ptr<skymodelr_prague_handle> result; |
| 57 | 2x | if (!guarded([&] { |
| 58 | 2x | if (!filename || !*filename) throw std::invalid_argument("Missing Prague coefficient filename."); |
| 59 | 2x | validate_finite(visibility); |
| 60 | 2x | if (visibility < 0) throw std::invalid_argument("Prague visibility must be nonnegative."); |
| 61 | 2x | if ((cache_spectra != 0 && cache_spectra != 1) || |
| 62 | 2x | (transmission_table != 0 && transmission_table != 1)) |
| 63 | ! | throw std::invalid_argument("Prague cache options must be zero or one."); |
| 64 | 2x | if (std::isnan(max_mib) || max_mib < 0) |
| 65 | ! | throw std::invalid_argument("Prague transmission table limit must be nonnegative MiB or infinity."); |
| 66 | 2x | result.reset(new skymodelr_prague_handle); |
| 67 | 6x | result->model.initialize(filename, visibility, cache_spectra != 0, transmission_table != 0, max_mib); |
| 68 | 2x | }, error, capacity)) return nullptr; |
| 69 | ! | return result.release(); |
| 70 | } | |
| 71 | ! | static void destroy_model(skymodelr_prague_handle *handle) noexcept { delete handle; } |
| 72 | ! | static size_t memory_usage(const skymodelr_prague_handle *handle) noexcept { |
| 73 | ! | return handle ? handle->model.memoryUsage() : 0; |
| 74 | } | |
| 75 | 1x | static int available(const skymodelr_prague_handle *handle, skymodelr_prague_available *out, |
| 76 | char *error, size_t capacity) noexcept { | |
| 77 | 1x | return guarded([&] { |
| 78 | 1x | if (!out) throw std::invalid_argument("Missing Prague metadata output."); |
| 79 | 1x | auto a = model(handle).getAvailableData(); |
| 80 | ! | *out = {a.albedoMin, a.albedoMax, a.altitudeMin, a.altitudeMax, |
| 81 | ! | a.elevationMin, a.elevationMax, a.visibilityMin, a.visibilityMax, |
| 82 | ! | a.polarisation ? 1 : 0, a.channels, a.channelStart, a.channelWidth}; |
| 83 | 1x | }, error, capacity); |
| 84 | } | |
| 85 | ! | static int compute_parameters(const skymodelr_prague_handle *handle, |
| 86 | const double *position, const double *direction, | |
| 87 | double elevation, double azimuth, double visibility, double albedo, | |
| 88 | skymodelr_prague_parameters *out, char *error, size_t capacity) noexcept { | |
| 89 | ! | return guarded([&] { |
| 90 | ! | if (!position || !direction || !out) throw std::invalid_argument("Missing Prague position, direction, or output."); |
| 91 | ! | validate_finite(elevation); validate_finite(azimuth); atmosphere(visibility, albedo); |
| 92 | ! | for (int i = 0; i < 3; ++i) { validate_finite(position[i]); validate_finite(direction[i]); } |
| 93 | ! | double magnitude = std::hypot(std::hypot(direction[0], direction[1]), direction[2]); |
| 94 | ! | if (!(magnitude > 0) || !std::isfinite(magnitude)) |
| 95 | ! | throw std::invalid_argument("Prague view direction must have finite nonzero length."); |
| 96 | ! | double radius = std::hypot(std::hypot(position[0], position[1]), position[2] + 6378000.0); |
| 97 | ! | if (!std::isfinite(radius) || radius < 6378000.0 - 1e-6) |
| 98 | ! | throw std::invalid_argument("Prague viewpoint lies inside the Earth."); |
| 99 | ! | auto p = model(handle).computeParameters({position[0], position[1], position[2]}, |
| 100 | ! | {direction[0], direction[1], direction[2]}, elevation, azimuth, visibility, albedo); |
| 101 | ! | *out = {p.theta, p.gamma, p.shadow, p.zero, p.elevation, p.altitude, p.visibility, p.albedo}; |
| 102 | ! | }, error, capacity); |
| 103 | } | |
| 104 | ! | static int spectrum(const skymodelr_prague_handle *handle, int quantity, |
| 105 | const skymodelr_prague_parameters *input, const double *wavelengths, | |
| 106 | size_t count, double distance, int attenuate_sun, double *out, | |
| 107 | char *error, size_t capacity) noexcept { | |
| 108 | ! | return guarded([&] { |
| 109 | ! | const auto &m = model(handle); |
| 110 | ! | auto p = parameters(input); |
| 111 | ! | if (count && (!wavelengths || !out)) throw std::invalid_argument("Missing Prague spectral input or output."); |
| 112 | ! | for (size_t i = 0; i < count; ++i) validate_finite(wavelengths[i]); |
| 113 | ! | switch (quantity) { |
| 114 | ! | case SKYMODELR_PRAGUE_SKY: m.skyRadianceSpectrum(p, wavelengths, count, out); break; |
| 115 | ! | case SKYMODELR_PRAGUE_TRANSMITTANCE: |
| 116 | ! | if (std::isnan(distance) || distance < 0) throw std::invalid_argument("Invalid Prague transmission distance."); |
| 117 | ! | m.transmittanceSpectrum(p, wavelengths, count, |
| 118 | ! | std::min(distance, std::numeric_limits<double>::max()), out); |
| 119 | ! | break; |
| 120 | ! | case SKYMODELR_PRAGUE_SUN: |
| 121 | ! | if (attenuate_sun != 0 && attenuate_sun != 1) throw std::invalid_argument("attenuate_sun must be zero or one."); |
| 122 | ! | for (size_t i = 0; i < count; ++i) out[i] = m.sunRadiance(p, wavelengths[i], attenuate_sun != 0); |
| 123 | ! | break; |
| 124 | ! | case SKYMODELR_PRAGUE_POLARISATION: |
| 125 | ! | for (size_t i = 0; i < count; ++i) out[i] = m.polarisation(p, wavelengths[i]); |
| 126 | ! | break; |
| 127 | ! | default: throw std::invalid_argument("Unknown Prague spectral quantity."); |
| 128 | } | |
| 129 | ! | }, error, capacity); |
| 130 | } | |
| 131 | 2x | static const skymodelr_prague_api *get_api() noexcept { |
| 132 | static const skymodelr_prague_api api = {SKYMODELR_PRAGUE_ABI_VERSION, sizeof(skymodelr_prague_api), | |
| 133 | create_model, destroy_model, available, memory_usage, compute_parameters, spectrum}; | |
| 134 | 2x | return &api; |
| 135 | } | |
| 136 | } | |
| 137 | ||
| 138 | // [[Rcpp::init]] | |
| 139 | 3x | void skymodelr_register_prague_api(DllInfo *dll) { |
| 140 | (void)dll; | |
| 141 | 3x | R_RegisterCCallable("skymodelr", "prague_get_api", reinterpret_cast<DL_FUNC>(&get_api)); |
| 142 | } | |
| 143 | ||
| 144 | struct skymodelr_prague_gpu_handle { | |
| 145 | skymodelr_prague_gpu_layout layout; | |
| 146 | std::vector<float> data; | |
| 147 | }; | |
| 148 | namespace { | |
| 149 | ! | skymodelr_prague_gpu_handle *gpu_create(const skymodelr_prague_handle *handle, |
| 150 | char *error, size_t capacity) noexcept { | |
| 151 | ! | std::unique_ptr<skymodelr_prague_gpu_handle> result; |
| 152 | ! | if (!guarded([&] { |
| 153 | ! | result.reset(new skymodelr_prague_gpu_handle); |
| 154 | ! | model(handle).exportMetal(result->layout,result->data); |
| 155 | ! | }, error, capacity)) return nullptr; |
| 156 | ! | return result.release(); |
| 157 | } | |
| 158 | ! | void gpu_destroy(skymodelr_prague_gpu_handle *handle) noexcept { delete handle; } |
| 159 | ! | const skymodelr_prague_gpu_layout *gpu_layout(const skymodelr_prague_gpu_handle *handle) noexcept { |
| 160 | ! | return handle ? &handle->layout : nullptr; |
| 161 | } | |
| 162 | ! | const float *gpu_data(const skymodelr_prague_gpu_handle *handle,size_t *count) noexcept { |
| 163 | ! | if(count) *count=handle ? handle->data.size() : 0; |
| 164 | ! | return handle ? handle->data.data() : nullptr; |
| 165 | } | |
| 166 | ! | const char *gpu_source() noexcept { |
| 167 | return | |
| 168 | #include "../inst/include/skymodelr/prague_metal.inc" | |
| 169 | ; | |
| 170 | } | |
| 171 | ! | const skymodelr_prague_gpu_api *gpu_get_api() noexcept { |
| 172 | static const skymodelr_prague_gpu_api api={SKYMODELR_PRAGUE_METAL_ABI_VERSION, | |
| 173 | sizeof(skymodelr_prague_gpu_api),gpu_create,gpu_destroy,gpu_layout,gpu_data,gpu_source}; | |
| 174 | ! | return &api; |
| 175 | } | |
| 176 | } | |
| 177 | // [[Rcpp::init]] | |
| 178 | 3x | void skymodelr_register_prague_gpu_api(DllInfo *dll) { |
| 179 | (void)dll; | |
| 180 | 3x | R_RegisterCCallable("skymodelr","prague_gpu_get_api",reinterpret_cast<DL_FUNC>(&gpu_get_api)); |
| 181 | } |
| 1 | ! | R"PRAGUE( |
| 2 | // Reconstruction derived from PragueSkyModel (Copyright 2022 Charles | |
| 3 | // University, Apache-2.0); distributed within the GPL-3 skymodelr package. | |
| 4 | // Same compressed spectral fit as the CPU evaluator. No RGB/angular LUT. | |
| 5 | namespace skymodelr_gpu { | |
| 6 | struct Axis { uint offset, count; }; | |
| 7 | struct Layout { | |
| 8 | Axis visibility, albedo, altitude, elevation, gamma, alpha, emphasis; | |
| 9 | Axis trans_altitude, trans_visibility, sun; | |
| 10 | uint radiance, trans_u, trans_v, rank, sun_offset, sun_stride; | |
| 11 | uint zenith_offset, zenith_stride, emphasis_offset, config_stride; | |
| 12 | uint trans_rank, a_dim, d_dim, channels; | |
| 13 | float channel_start, channel_width; | |
| 14 | }; | |
| 15 | struct Parameters { float theta, gamma, shadow, zero, elevation, altitude, visibility, albedo; }; | |
| 16 | struct Interpolation { uint index; float factor; }; | |
| 17 | constant float radius = 6378000.f; | |
| 18 | constant float pi = 3.14159265358979323846f; | |
| 19 | // Preserve metre/submetre heights: rationalize |p+(0,0,R)|-R instead of | |
| 20 | // subtracting two approximately 6,378,000 m floats. atan2 preserves small angles. | |
| 21 | float height(float3 p) { | |
| 22 | float n = dot(p,p) + 2*radius*p.z; | |
| 23 | return n / (length(p+float3(0,0,radius)) + radius); | |
| 24 | } | |
| 25 | float angle(float3 a, float3 b) { return atan2(length(cross(a,b)),dot(a,b)); } | |
| 26 | Parameters parameters(float3 p, float3 w, float elevation, float azimuth, float visibility, float albedo) { | |
| 27 | float3 up = normalize(p+float3(0,0,radius)); | |
| 28 | w = normalize(w); | |
| 29 | float h = max(0.f,height(p)+50.f); | |
| 30 | float correction = sqrt(h*(2*radius+h))/(radius+h); | |
| 31 | // Algebraic cancellation of the two shifted Earth-space points in the CPU | |
| 32 | // formula, before rounding, preserves the one-metre viewing direction. | |
| 33 | float3 corrected = normalize(w + up*correction); | |
| 34 | float3 sun(cos(azimuth)*cos(elevation),sin(azimuth)*cos(elevation),sin(elevation)); | |
| 35 | float3 shadow(-sin(elevation)*cos(azimuth),-sin(elevation)*sin(azimuth),cos(elevation)); | |
| 36 | return {angle(w,up), angle(w,sun), angle(corrected,shadow), angle(corrected,up), | |
| 37 | asin(clamp(dot(up,sun),-1.f,1.f)), h, visibility, albedo}; | |
| 38 | } | |
| 39 | Interpolation lookup(float value, Axis axis, device const float *data) { | |
| 40 | float v=clamp(value,data[axis.offset],data[axis.offset+axis.count-1]); | |
| 41 | uint lo=1,hi=axis.count; | |
| 42 | while(lo<hi) { uint mid=(lo+hi)/2; if(data[axis.offset+mid]<=v) lo=mid+1; else hi=mid; } | |
| 43 | uint i=lo-1; | |
| 44 | return {i,lo==axis.count ? 0.f : (v-data[axis.offset+i])/(data[axis.offset+lo]-data[axis.offset+i])}; | |
| 45 | } | |
| 46 | float linear(device const float *data,uint offset,float factor) { | |
| 47 | if(factor==0) return data[offset]; // Last knot need not have a successor. | |
| 48 | return (data[offset+1]-data[offset])*factor+data[offset]; | |
| 49 | } | |
| 50 | struct SkyQuery { Interpolation gamma, alpha, emphasis, config[4]; }; | |
| 51 | // Prepare wavelength-independent coordinates once for a spectral integration. | |
| 52 | SkyQuery prepare_sky(Parameters p,device const Layout &m,device const float *data) { | |
| 53 | return {lookup(p.gamma,m.gamma,data),lookup(p.elevation<0 ? p.shadow : p.zero,m.alpha,data), | |
| 54 | lookup(p.zero,m.emphasis,data),{lookup(p.visibility,m.visibility,data),lookup(p.albedo,m.albedo,data), | |
| 55 | lookup(p.altitude,m.altitude,data),lookup(p.elevation*180/pi,m.elevation,data)}}; | |
| 56 | } | |
| 57 | float sky_prepared(SkyQuery query,float wavelength,device const Layout &m,device const float *data) { | |
| 58 | if(wavelength<m.channel_start || wavelength>=m.channel_start+m.channels*m.channel_width) return 0; | |
| 59 | uint channel=uint((wavelength-m.channel_start)/m.channel_width); | |
| 60 | auto g=query.gamma,a=query.alpha,e=query.emphasis; | |
| 61 | auto config=query.config; | |
| 62 | uint counts[4]={m.visibility.count,m.albedo.count,m.altitude.count,m.elevation.count}; | |
| 63 | // Weighted corner accumulation avoids a dynamically indexed 16-value local | |
| 64 | // array. It retains the CPU's zero-weight threshold and per-corner clamping; | |
| 65 | // summation order differs, so numerical agreement is tolerance-based. | |
| 66 | float result=0; | |
| 67 | for(uint i=0;i<16;++i) { | |
| 68 | uint index=0; float weight=1; | |
| 69 | for(uint j=0;j<4;++j) { | |
| 70 | uint high=(i>>(3-j))&1; | |
| 71 | float f=config[j].factor<1e-6f ? 0.f : config[j].factor; | |
| 72 | weight*=high ? f : 1-f; | |
| 73 | index=index*counts[j]+min(config[j].index+high,counts[j]-1); | |
| 74 | } | |
| 75 | float value=0; | |
| 76 | if(weight>0) { | |
| 77 | uint base=m.radiance+(index*m.channels+channel)*m.config_stride; | |
| 78 | for(uint r=0;r<m.rank;++r) | |
| 79 | value+=linear(data,base+m.sun_offset+r*m.sun_stride+g.index,g.factor)* | |
| 80 | linear(data,base+m.zenith_offset+r*m.zenith_stride+a.index,a.factor); | |
| 81 | value=max(0.f,value*linear(data,base+m.emphasis_offset+e.index,e.factor)); | |
| 82 | } | |
| 83 | result+=weight*value; | |
| 84 | } | |
| 85 | return result; | |
| 86 | } | |
| 87 | float sky(Parameters p,float wavelength,device const Layout &m,device const float *data) { | |
| 88 | return sky_prepared(prepare_sky(p,m,data),wavelength,m,data); | |
| 89 | } | |
| 90 | // Nearest forward intersection. c is factored to preserve altitude close to | |
| 91 | // Earth; the near root uses c/(-b+sqrt(discriminant)) to avoid cancellation. | |
| 92 | float circle(float cosine,float altitude,float shell) { | |
| 93 | float r=radius+altitude, b=r*cosine; | |
| 94 | float c=(altitude-shell)*(2*radius+altitude+shell); | |
| 95 | float discriminant=b*b-c; | |
| 96 | if(discriminant<=0) return -1; | |
| 97 | float root=sqrt(discriminant), far=-b+root; | |
| 98 | float near=c/far; | |
| 99 | return near>0 && far>0 ? min(near,far) : max(near,far); | |
| 100 | } | |
| 101 | Interpolation trans_lookup(float value,uint n,uint power) { | |
| 102 | uint i=min(uint(value*n),n-1); float f=0; | |
| 103 | if(i<n-1) { | |
| 104 | float a=float(i)/n,b=float(i+1)/n; | |
| 105 | float va=pow(a,float(power)),vb=pow(b,float(power)); | |
| 106 | f=clamp((pow(value,float(power))-va)/(vb-va),0.f,1.f); | |
| 107 | } | |
| 108 | return {i,f}; | |
| 109 | } | |
| 110 | struct TransParameters { Interpolation altitude, distance; }; | |
| 111 | TransParameters trans_parameters(Parameters p,float distance,device const Layout &m) { | |
| 112 | float cosine=cos(p.theta),sine=sin(p.theta),t,shell=0; | |
| 113 | if(p.altitude<.3f) { | |
| 114 | if(p.theta<=pi/2) {shell=100000;t=circle(cosine,p.altitude,shell);} else t=0; | |
| 115 | } else { | |
| 116 | t=circle(cosine,p.altitude,0); | |
| 117 | if(t<0) {shell=100000;t=circle(cosine,p.altitude,shell);} | |
| 118 | } | |
| 119 | bool boundary=t<=distance; | |
| 120 | t=min(max(0.f,t),distance); | |
| 121 | float x=sine*t,z=p.altitude+cosine*t; | |
| 122 | float h=boundary ? shell : clamp(height(float3(x,0,z)),0.f,100000.f); | |
| 123 | float a=pow(h/100000.f,1.f/3.f); | |
| 124 | // acos(y/length) rounds to zero for short paths. atan2 is equivalent here. | |
| 125 | float d=min(1.f,sqrt(sqrt(atan2(abs(x),radius+z)*radius/1571524.413613f))); | |
| 126 | return {trans_lookup(a,m.a_dim,3),trans_lookup(d,m.d_dim,4)}; | |
| 127 | } | |
| 128 | float reconstruct_trans(uint visibility,uint altitude,uint channel,TransParameters p, | |
| 129 | device const Layout &m,device const float *data) { | |
| 130 | uint coefficients=m.trans_v+((visibility*m.trans_altitude.count+altitude)*m.channels+channel)*m.trans_rank; | |
| 131 | float values[4]={0,0,0,0}; uint index=0; | |
| 132 | for(uint a=p.altitude.index;a<=p.altitude.index+1;++a) if(a<m.a_dim) | |
| 133 | for(uint d=p.distance.index;d<=p.distance.index+1;++d) if(d<m.d_dim) { | |
| 134 | uint base=m.trans_u+((altitude*m.d_dim+d)*m.a_dim+a)*m.trans_rank; | |
| 135 | float value=0; | |
| 136 | for(uint r=0;r<m.trans_rank;++r) value+=data[base+r]*data[coefficients+r]; | |
| 137 | values[index++]=value; | |
| 138 | } | |
| 139 | if(p.distance.factor>0) { | |
| 140 | values[0]=mix(values[0],values[1],p.distance.factor); | |
| 141 | values[1]=mix(values[2],values[3],p.distance.factor); | |
| 142 | } | |
| 143 | return p.altitude.factor>0 ? mix(max(0.f,values[0]),max(0.f,values[1]),p.altitude.factor) : max(0.f,values[0]); | |
| 144 | } | |
| 145 | struct TransQuery { Interpolation visibility, altitude; TransParameters distance; }; | |
| 146 | TransQuery prepare_transmission(Parameters p,float distance,device const Layout &m,device const float *data) { | |
| 147 | return {lookup(p.visibility,m.trans_visibility,data),lookup(p.altitude,m.trans_altitude,data),trans_parameters(p,distance,m)}; | |
| 148 | } | |
| 149 | float transmission_prepared(TransQuery query,float wavelength,device const Layout &m,device const float *data) { | |
| 150 | if(wavelength<m.channel_start || wavelength>=m.channel_start+m.channels*m.channel_width) return 0; | |
| 151 | uint channel=uint((wavelength-m.channel_start)/m.channel_width); | |
| 152 | auto v=query.visibility,h=query.altitude;auto t=query.distance; | |
| 153 | float result[2]; | |
| 154 | for(uint j=0;j<2;++j) { | |
| 155 | uint vi=min(v.index+j,m.trans_visibility.count-1); | |
| 156 | float value=reconstruct_trans(vi,h.index,channel,t,m,data); | |
| 157 | if(h.factor>0) value=mix(value,reconstruct_trans(vi,h.index+1,channel,t,m,data),h.factor); | |
| 158 | result[j]=value; | |
| 159 | if(v.factor==0) break; | |
| 160 | } | |
| 161 | float value=v.factor>0 ? mix(result[0],result[1],v.factor) : result[0]; | |
| 162 | return value*value; | |
| 163 | } | |
| 164 | float transmission(Parameters p,float wavelength,float distance,device const Layout &m,device const float *data) { | |
| 165 | return transmission_prepared(prepare_transmission(p,distance,m,data),wavelength,m,data); | |
| 166 | } | |
| 167 | float sun(Parameters p,float wavelength,bool attenuate,device const Layout &m,device const float *data) { | |
| 168 | if(wavelength<280 || wavelength>=280+m.sun.count-1 || p.gamma>.004654793f) return 0; | |
| 169 | float index=wavelength-280; | |
| 170 | float value=linear(data,m.sun.offset+uint(index),fract(index)); | |
| 171 | return attenuate ? value*transmission(p,wavelength,INFINITY,m,data) : value; | |
| 172 | } | |
| 173 | // Batch input uses already computed parameters; consumers may also call | |
| 174 | // parameters() directly inside their own shaders. One thread per wavelength. | |
| 175 | struct Query { Parameters parameters; float wavelength, distance; uint quantity, attenuate_sun; }; | |
| 176 | struct Geometry { float4 position, direction, settings; }; | |
| 177 | } | |
| 178 | kernel void prague_parameters_batch(device const skymodelr_gpu::Geometry *input [[buffer(0)]], | |
| 179 | device skymodelr_gpu::Parameters *output [[buffer(1)]],constant uint &count [[buffer(2)]], | |
| 180 | uint i [[thread_position_in_grid]]) { | |
| 181 | if(i>=count) return; | |
| 182 | auto q=input[i]; | |
| 183 | output[i]=skymodelr_gpu::parameters(q.position.xyz,q.direction.xyz,q.settings.x,q.settings.y,q.settings.z,q.settings.w); | |
| 184 | } | |
| 185 | kernel void prague_spectrum_batch(device const skymodelr_gpu::Layout &model [[buffer(0)]], | |
| 186 | device const float *data [[buffer(1)]], device const skymodelr_gpu::Query *queries [[buffer(2)]], | |
| 187 | device float *output [[buffer(3)]],constant uint &count [[buffer(4)]],uint i [[thread_position_in_grid]]) { | |
| 188 | if(i>=count) return; | |
| 189 | auto q=queries[i]; | |
| 190 | output[i]=q.quantity==0 ? skymodelr_gpu::sky(q.parameters,q.wavelength,model,data) : | |
| 191 | (q.quantity==1 ? skymodelr_gpu::sun(q.parameters,q.wavelength,q.attenuate_sun,model,data) : | |
| 192 | skymodelr_gpu::transmission(q.parameters,q.wavelength,q.distance,model,data)); | |
| 193 | } | |
| 194 | )PRAGUE" |
| 1 | #include "prague_metal_backend.h" | |
| 2 | #include <stdexcept> | |
| 3 | ||
| 4 | 6x | bool prague_metal_available() { return false; } |
| 5 | ||
| 6 | ! | void prague_metal_radiance(const PragueSkyModel &, const std::string &, |
| 7 | const PragueRadianceColumns &, size_t, bool, bool, | |
| 8 | double *, void (*)()) { | |
| 9 | throw std::runtime_error( | |
| 10 | "backend = \"gpu\" requires macOS with an available Metal device. " | |
| 11 | ! | "Use backend = \"cpu\" on this system."); |
| 12 | } |
| 1 | /* | |
| 2 | This file is included in the skymodelr package, which is distributed as a | |
| 3 | whole under GPL-3. The following upstream copyright and provenance notice is | |
| 4 | preserved for attribution and compliance with upstream notice requirements. | |
| 5 | */ | |
| 6 | ||
| 7 | // Copyright 2022 Charles University | |
| 8 | // SPDX-License-Identifier: Apache-2.0 | |
| 9 | ||
| 10 | #include <algorithm> | |
| 11 | #include <array> | |
| 12 | #include <cassert> | |
| 13 | #include <limits> | |
| 14 | #include <cstring> | |
| 15 | #include <tuple> | |
| 16 | #include <memory> | |
| 17 | #include <stdexcept> | |
| 18 | #include <atomic> | |
| 19 | ||
| 20 | #include "PragueSkyModel.h" | |
| 21 | ||
| 22 | namespace skymodelr_prague { | |
| 23 | ||
| 24 | ||
| 25 | ||
| 26 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 27 | // Constants | |
| 28 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 29 | ||
| 30 | constexpr double PI = 3.141592653589793; | |
| 31 | constexpr double RAD_TO_DEG = 180.0 / PI; | |
| 32 | constexpr double PLANET_RADIUS = 6378000.0; | |
| 33 | constexpr double SAFETY_ALTITUDE = 50.0; | |
| 34 | constexpr double SUN_RADIUS = 0.004654793; // = 0.2667 degrees | |
| 35 | constexpr double DIST_TO_EDGE = 1571524.413613; // Maximum distance to the edge of the atmosphere in the transmittance model | |
| 36 | constexpr double ATMOSPHERE_WIDTH = 100000.0; | |
| 37 | constexpr double SUN_RAD_START = 280; | |
| 38 | constexpr double SUN_RAD_STEP = 1; | |
| 39 | constexpr double SUN_RAD_TABLE[] = { | |
| 40 | 4022.51, 4592.96, 5058.84, 5552.97, 6024.88, 6443.47, 6836.20, 7175.78, 7380.47, 7437.44, | |
| 41 | 7391.90, 7266.06, 7121.19, 7034.24, 7024.24, 7082.31, 7209.73, 7384.60, 7563.43, 7739.25, | |
| 42 | 7905.70, 8025.18, 8096.11, 8202.27, 8337.15, 8602.30, 8965.52, 9316.67, 9565.64, 9814.45, | |
| 43 | 9829.41, 10184., 10262.6, 10375.7, 10276., 10179.3, 10156.6, 10750.7, 11134., 11463.6, | |
| 44 | 11860.4, 12246.2, 12524.4, 12780., 13187.4, 13632.4, 13985.9, 13658.3, 13377.4, 13358.3, | |
| 45 | 13239., 13119.8, 13096.2, 13184., 13243.5, 13018.4, 12990.4, 13159.1, 13230.8, 13258.6, | |
| 46 | 13209.9, 13343.2, 13404.8, 13305.4, 13496.3, 13979.1, 14153.8, 14188.4, 14122.7, 13825.4, | |
| 47 | 14033.3, 13914.1, 13837.4, 14117.2, 13982.3, 13864.5, 14118.4, 14545.7, 15029.3, 15615.3, | |
| 48 | 15923.5, 16134.8, 16574.5, 16509., 16336.5, 16146.6, 15965.1, 15798.6, 15899.8, 16125.4, | |
| 49 | 15854.3, 15986.7, 15739.7, 15319.1, 15121.5, 15220.2, 15041.2, 14917.7, 14487.8, 14011., | |
| 50 | 14165.7, 14189.5, 14540.7, 14797.5, 14641.5, 14761.6, 15153.7, 14791.8, 14907.6, 15667.4, | |
| 51 | 16313.5, 16917., 17570.5, 18758.1, 20250.6, 21048.1, 21626.1, 22811.6, 23577.2, 23982.6, | |
| 52 | 24062.1, 23917.9, 23914.1, 23923.2, 24052.6, 24228.6, 24360.8, 24629.6, 24774.8, 24648.3, | |
| 53 | 24666.5, 24938.6, 24926.3, 24693.1, 24613.5, 24631.7, 24569.8, 24391.5, 24245.7, 24084.4, | |
| 54 | 23713.7, 22985.4, 22766.6, 22818.9, 22834.3, 22737.9, 22791.6, 23086.3, 23377.7, 23461., | |
| 55 | 23935.5, 24661.7, 25086.9, 25520.1, 25824.3, 26198., 26350.2, 26375.4, 26731.2, 27250.4, | |
| 56 | 27616., 28145.3, 28405.9, 28406.8, 28466.2, 28521.5, 28783.8, 29025.1, 29082.6, 29081.3, | |
| 57 | 29043.1, 28918.9, 28871.6, 29049., 29152.5, 29163.2, 29143.4, 28962.7, 28847.9, 28854., | |
| 58 | 28808.7, 28624.1, 28544.2, 28461.4, 28411.1, 28478., 28469.8, 28513.3, 28586.5, 28628.6, | |
| 59 | 28751.5, 28948.9, 29051., 29049.6, 29061.7, 28945.7, 28672.8, 28241.5, 27903.2, 27737., | |
| 60 | 27590.9, 27505.6, 27270.2, 27076.2, 26929.1, 27018.2, 27206.8, 27677.2, 27939.9, 27923.9, | |
| 61 | 27899.2, 27725.4, 27608.4, 27599.4, 27614.6, 27432.4, 27460.4, 27392.4, 27272., 27299.1, | |
| 62 | 27266.8, 27386.5, 27595.9, 27586.9, 27504.8, 27480.6, 27329.8, 26968.4, 26676.3, 26344.7, | |
| 63 | 26182.5, 26026.3, 25900.3, 25842.9, 25885.4, 25986.5, 26034.5, 26063.5, 26216.9, 26511.4, | |
| 64 | 26672.7, 26828.5, 26901.8, 26861.5, 26865.4, 26774.2, 26855.8, 27087.1, 27181.3, 27183.1, | |
| 65 | 27059.8, 26834.9, 26724.3, 26759.6, 26725.9, 26724.6, 26634.5, 26618.5, 26560.1, 26518.7, | |
| 66 | 26595.3, 26703.2, 26712.7, 26733.9, 26744.3, 26764.4, 26753.2, 26692.7, 26682.7, 26588.1, | |
| 67 | 26478., 26433.7, 26380.7, 26372.9, 26343.3, 26274.7, 26162.3, 26160.5, 26210., 26251.2, | |
| 68 | 26297.9, 26228.9, 26222.3, 26269.7, 26295.6, 26317.9, 26357.5, 26376.1, 26342.4, 26303.5, | |
| 69 | 26276.7, 26349.2, 26390., 26371.6, 26346.7, 26327.6, 26274.2, 26247.3, 26228.7, 26152.1, | |
| 70 | 25910.3, 25833.2, 25746.5, 25654.3, 25562., 25458.8, 25438., 25399.1, 25324.3, 25350., | |
| 71 | 25514., 25464.9, 25398.5, 25295.2, 25270.2, 25268.4, 25240.6, 25184.9, 25149.6, 25123.9, | |
| 72 | 25080.3, 25027.9, 25012.3, 24977.9, 24852.6, 24756.4, 24663.5, 24483.6, 24398.6, 24362.6, | |
| 73 | 24325.1, 24341.7, 24288.7, 24284.2, 24257.3, 24178.8, 24097.6, 24175.6, 24175.7, 24139.7, | |
| 74 | 24088.1, 23983.2, 23902.7, 23822.4, 23796.2, 23796.9, 23814.5, 23765.5, 23703., 23642., | |
| 75 | 23592.6, 23552., 23514.6, 23473.5, 23431., 23389.3, 23340., 23275.1, 23187.3, 23069.5, | |
| 76 | 22967., 22925.3, 22908.9, 22882.5, 22825., 22715.4, 22535.5, 22267.1, 22029.4, 21941.6, | |
| 77 | 21919.5, 21878.8, 21825.6, 21766., 21728.9, 21743.2, 21827.1, 21998.7, 22159.4, 22210., | |
| 78 | 22187.2, 22127.2, 22056.2, 22000.2, 21945.9, 21880.2, 21817.1, 21770.3, 21724.3, 21663.2, | |
| 79 | 21603.3, 21560.4, 21519.8, 21466.2, 21401.6, 21327.7, 21254.2, 21190.7, 21133.6, 21079.3, | |
| 80 | 21024., 20963.7, 20905.5, 20856.6, 20816.6, 20785.2, 20746.7, 20685.3, 20617.8, 20561.1, | |
| 81 | 20500.4, 20421.2, 20333.4, 20247., 20175.3, 20131.4, 20103.2, 20078.5, 20046.8, 19997.2, | |
| 82 | 19952.9, 19937.2, 19930.8, 19914.4, 19880.8, 19823., 19753.8, 19685.9, 19615.3, 19537.5, | |
| 83 | 19456.8, 19377.6, 19309.4, 19261.9, 19228., 19200.5, 19179.5, 19164.8, 19153.1, 19140.6, | |
| 84 | 19129.2, 19120.6, 19104.5, 19070.6, 19023.9, 18969.3, 18911.4, 18855., 18798.6, 18740.8, | |
| 85 | 18672.7, 18585.2, 18501., 18442.4, 18397.5, 18353.9, 18313.2, 18276.8, 18248.3, 18231.2, | |
| 86 | 18224., 18225.4, 18220.1, 18192.6, 18155.1, 18119.8, 18081.6, 18035.6, 17987.4, 17942.8, | |
| 87 | 17901.7, 17864.2, 17831.1, 17802.9, 17771.5, 17728.6, 17669.7, 17590.1, 17509.5, 17447.4, | |
| 88 | 17396., 17347.4, 17300.3, 17253.2, 17206.1, 17159., 17127.6, 17127.6, 17133.6, 17120.4, | |
| 89 | 17097.2, 17073.3, 17043.7, 17003.4, 16966.3, 16946.3, 16930.9, 16907.7, 16882.7, 16862., | |
| 90 | 16837.8, 16802.1, 16759.2, 16713.6, 16661.8, 16600.8, 16542.6, 16499.4, 16458.7, 16408., | |
| 91 | 16360.6, 16329.5, 16307.4, 16286.7, 16264.9, 16239.6, 16207.8, 16166.8, 16118.2, 16064., | |
| 92 | 16011.2, 15966.9, 15931.9, 15906.9, 15889.1, 15875.5, 15861.2, 15841.3, 15813.1, 15774.2, | |
| 93 | 15728.8, 15681.4, 15630., 15572.9, 15516.5, 15467.2, 15423., 15381.6, 15354.4, 15353., | |
| 94 | 15357.3, 15347.3, 15320.2, 15273.1, 15222., 15183.1, 15149.6, 15114.6, 15076.8, 15034.6, | |
| 95 | 14992.9, 14996.74, 14959.93, 14915.18, 14861.86, 14810.61, 14762.06, 14708.42, 14657.64, 14594.65, | |
| 96 | 14508.80, 14422.96, 14344.89, 14271.90, 14219.06, 14189.07, 14159.08, 14128.61, 14100.36, 14071.01, | |
| 97 | 14037.85, 13995.16, 13943.43, 13891.38, 13842.35, 13804.11, 13782.37, 13791.10, 13821.57, 13852.98, | |
| 98 | 13877.58, 13898.05, 13900.43, 13880.75, 13859.81, 13837.43, 13810.93, 13783.01, 13757.62, 13751.43, | |
| 99 | 13764.60, 13780.79, 13797.29, 13811.41, 13806.49, 13783.01, 13757.30, 13727.31, 13695.73, 13662.41, | |
| 100 | 13626.87, 13593.54, 13564.51, 13535.31, 13506.11, 13477.71, 13445.66, 13407.57, 13367.90, 13327.28, | |
| 101 | 13284.91, 13240.17, 13195.42, 13146.70, 13093.39, 13038.49, 12982.63, 12926.46, 12873.94, 12823.00, | |
| 102 | 12770.64, 12720.02, 12670.51, 12623.06, 12579.74, 12536.11, 12488.98, 12438.84, 12384.73, 12327.60, | |
| 103 | 12271.91, 12222.88, 12180.03, 12142.74, 12110.06, 12079.91, 12047.06, 12014.05, 11981.53, 11948.36, | |
| 104 | 11916.63, 11883.94, 11847.76, 11813.48, 11782.22, 11754.14, 11731.61, 11711.45, 11688.29, 11664.01, | |
| 105 | 11638.46, 11609.90, 11581.50, 11551.82, 11518.98, 11482.16, 11443.13, 11402.98, 11363.15, 11324.44, | |
| 106 | 11287.62, 11253.98, 11222.41, 11193.68, 11167.03, 11144.34, 11124.34, 11104.67, 11084.51, 11064.36, | |
| 107 | 11042.31, 11019.77, 10999.14, 10983.28, 10971.69, 10963.44, 10957.09, 10954.56, 10952.97, 10947.89, | |
| 108 | 10940.27, 10933.45, 10925.52, 10917.11, 10912.66, 10911.24, 10909.49, 10908.54, 10907.75, 10909.01, | |
| 109 | 10913.30, 10915.20, 10913.62, 10912.35, 10909.49, 10904.41, 10902.51, 10904.57, 10906.79, 10906.48, | |
| 110 | 10904.25, 10898.07, 10887.12, 10872.36, 10856.49, 10839.20, 10822.53, 10804.45, 10783.98, 10763.03, | |
| 111 | 10741.93, 10716.85, 10689.88, 10662.86, 10633.89, 10602.97, 10575.14, 10551.62, 10530.56, 10511.96, | |
| 112 | 10495.82, 10480.23, 10463.32, 10445.07, 10425.49, 10404.57, 10383.53, 10363.57, 10344.69, 10326.89, | |
| 113 | 10310.16, 10293.63, 10276.39, 10258.46, 10239.83, 10220.51, 10200.89, 10181.41, 10162.05, 10142.82, | |
| 114 | 10123.71, 10104.16, 10083.60, 10062.02, 10039.42, 10015.81, 9991.44, 9966.56, 9941.17, 9915.27, | |
| 115 | 9888.87, 9862.37, 9836.19, 9810.32, 9784.77, 9759.55, 9735.05, 9711.69, 9689.47, 9668.40, | |
| 116 | 9648.47, 9628.83, 9608.61, 9587.82, 9566.46, 9544.54, 9522.70, 9501.63, 9481.32, 9461.77, | |
| 117 | 9442.98, 9424.13, 9404.39, 9383.76, 9362.24, 9339.84, 9317.15, 9294.77, 9272.72, 9250.98, | |
| 118 | 9229.56, 9208.10, 9186.27, 9164.05, 9141.46, 9118.48, 9095.66, 9073.54, 9052.12, 9031.40, | |
| 119 | 9011.37, 8992.33, 8974.56, 8958.06, 8942.82, 8928.86, 8915.56, 8902.33, 8889.16, 8876.05, | |
| 120 | 8863.01, 8850.03, 8837.11, 8824.26, 8811.47, 8798.74, 8785.76, 8772.21, 8758.09, 8743.40, | |
| 121 | 8728.13, 8712.52, 8696.78, 8680.91, 8664.91, 8648.79, 8632.61, 8616.42, 8600.24, 8584.05, | |
| 122 | 8567.87, 8551.78, 8535.88, 8520.17, 8504.65, 8489.32, 8474.06, 8458.73, 8443.34, 8427.88, | |
| 123 | 8412.36, 8397.03, 8382.15, 8367.71, 8353.71, 8340.16, 8326.52, 8312.23, 8297.32, 8281.77, | |
| 124 | 8265.58, 8248.95, 8232.07, 8214.93, 8197.54, 8179.90, 8162.35, 8145.24, 8128.58, 8112.36, | |
| 125 | 8096.59, 8081.04, 8065.49, 8049.94, 8034.39, 8018.84, 8003.29, 7987.74, 7972.19, 7956.64, | |
| 126 | 7941.08, 7925.95, 7911.63, 7898.15, 7885.48, 7873.65, 7862.06, 7850.16, 7837.94, 7825.41, | |
| 127 | 7812.56, 7799.29, 7785.52, 7771.24, 7756.45, 7741.15, 7725.73, 7710.56, 7695.64, 7680.98, | |
| 128 | 7666.57, 7652.29, 7638.01, 7623.73, 7609.45, 7595.17, 7580.95, 7566.86, 7552.89, 7539.06, | |
| 129 | 7525.35, 7511.22, 7496.15, 7480.12, 7463.14, 7445.21, 7427.19, 7409.92, 7393.42, 7377.68, | |
| 130 | 7362.70, 7348.26, 7334.14, 7320.33, 7306.85, 7293.68, 7280.92, 7268.67, 7256.93, 7245.69, | |
| 131 | 7234.96, 7224.14, 7212.62, 7200.40, 7187.49, 7173.87, 7160.26, 7147.34, 7135.12, 7123.60, | |
| 132 | 7112.78, 7102.47, 7092.47, 7082.79, 7073.43, 7064.38, 7055.31, 7045.85, 7036.01, 7025.79, | |
| 133 | 7015.19, 7004.69, 6994.76, 6985.39, 6976.60, 6968.38, 6960.29, 6951.88, 6943.15, 6934.11, | |
| 134 | 6924.75, 6915.54, 6906.97, 6899.04, 6891.74, 6885.08, 6878.54, 6871.62, 6864.32, 6856.64, | |
| 135 | 6848.58, 6839.38, 6828.27, 6815.26, 6800.34, 6783.52, 6766.16, 6749.63, 6733.92, 6719.04, | |
| 136 | 6704.98, 6691.36, 6677.81, 6664.32, 6650.90, 6637.54, 6624.56, 6612.28, 6600.69, 6589.81, | |
| 137 | 6579.62, 6569.43, 6558.55, 6546.96, 6534.68, 6521.70, 6508.44, 6495.30, 6482.29, 6469.40, | |
| 138 | 6456.64, 6444.46, 6433.29, 6423.13, 6413.99, 6405.87, 6397.87, 6389.11, 6379.59, 6369.31, | |
| 139 | 6358.26, 6347.19, 6336.81, 6327.13, 6318.15, 6309.87, 6302.25, 6295.27, 6288.92, 6283.21, | |
| 140 | 6278.13, 6273.24, 6268.10, 6262.71, 6257.06, 6251.15, 6245.00, 6238.59, 6231.92, 6225.00, | |
| 141 | 6217.83, 6210.09, 6201.46, 6191.94, 6181.53, 6170.23, 6158.90, 6148.39, 6138.71, 6129.86, | |
| 142 | 6121.83, 6113.96, 6105.58, 6096.70, 6087.30, 6077.40, 6066.93, 6055.82, 6044.08, 6031.70, | |
| 143 | 6018.69, 6005.42, 5992.29, 5979.27, 5966.39, 5953.63, 5940.81, 5927.74, 5914.41, 5900.82, | |
| 144 | 5886.99, 5873.09, 5859.31, 5845.67, 5832.15, 5818.75, 5805.58, 5792.73, 5780.20, 5767.98, | |
| 145 | 5756.08, 5744.30, 5732.47, 5720.56, 5708.60, 5696.57, 5684.26, 5671.44, 5658.11, 5644.27, | |
| 146 | 5629.93, 5615.46, 5601.24, 5587.27, 5573.56, 5560.11, 5546.94, 5534.08, 5521.55, 5509.33, | |
| 147 | 5497.43, 5485.72, 5474.07, 5462.49, 5450.97, 5439.51, 5428.15, 5416.92, 5405.81, 5394.83, | |
| 148 | 5383.97, 5373.12, 5362.14, 5351.03, 5339.80, 5328.44, 5317.20, 5306.35, 5295.88, 5285.78, | |
| 149 | 5276.07, 5266.58, 5257.16, 5247.80, 5238.50, 5229.26, 5220.09, 5210.98, 5201.94, 5192.96, | |
| 150 | 5184.04, 5175.28, 5166.78, 5158.52, 5150.53, 5142.78, 5135.13, 5127.42, 5119.65, 5111.81, | |
| 151 | 5103.91, 5095.97, 5088.04, 5080.10, 5072.17, 5064.24, 5056.59, 5049.51, 5043.01, 5037.07, | |
| 152 | 5031.71, 5026.28, 5020.16, 5013.33, 5005.81, 4997.59, 4989.02, 4980.45, 4971.89, 4963.32, | |
| 153 | 4954.75, 4946.08, 4937.23, 4928.19, 4918.95, 4909.52, 4899.85, 4889.85, 4879.53, 4868.90, | |
| 154 | 4857.95, 4847.10, 4836.75, 4826.92, 4817.59, 4808.76, 4799.81, 4790.10, 4779.63, 4768.40, | |
| 155 | 4756.40, 4744.40, 4733.17, 4722.70, 4712.99, 4704.04, 4695.31, 4686.26, 4676.90, 4667.22, | |
| 156 | 4657.23, 4646.91, 4636.28, 4625.33, 4614.06, 4602.48, 4590.96, 4579.89, 4569.25, 4559.07, | |
| 157 | 4549.32, 4539.87, 4530.54, 4521.33, 4512.26, 4503.31, 4494.39, 4485.41, 4476.36, 4467.26, | |
| 158 | 4458.08, 4449.32, 4441.45, 4434.47, 4428.38, 4423.17, 4418.16, 4412.64, 4406.61, 4400.07, | |
| 159 | 4393.03, 4386.11, 4379.95, 4374.55, 4369.92, 4366.05, 4362.21, 4357.67, 4352.43, 4346.50, | |
| 160 | 4339.87, 4332.92, 4326.03, 4319.21, 4312.45, 4305.75, 4299.09, 4292.42, 4285.76, 4279.09, | |
| 161 | 4272.43, 4265.76, 4259.10, 4252.44, 4245.77, 4239.11, 4232.70, 4226.79, 4221.40, 4216.51, | |
| 162 | 4212.13, 4207.91, 4203.50, 4198.90, 4194.11, 4189.12, 4183.63, 4177.32, 4170.18, 4162.21, | |
| 163 | 4153.42, 4144.34, 4135.52, 4126.95, 4118.64, 4110.58, 4102.74, 4095.09, 4087.63, 4080.36, | |
| 164 | 4073.29, 4066.31, 4059.32, 4052.34, 4045.36, 4038.38, 4031.52, 4024.92, 4018.57, 4012.48, | |
| 165 | 4006.64, 4000.83, 3994.84, 3988.65, 3982.27, 3975.70, 3968.97, 3962.12, 3955.13, 3948.03, | |
| 166 | 3940.79, 3933.27, 3925.30, 3916.89, 3908.04, 3898.74, 3889.44, 3880.59, 3872.18, 3864.21, | |
| 167 | 3856.69, 3849.52, 3842.60, 3835.94, 3829.52, 3823.37, 3817.21, 3810.80, 3804.14, 3797.22, | |
| 168 | 3790.05, 3782.59, 3774.81, 3766.72, 3758.31, 3749.58, 3740.73, 3731.94, 3723.21, 3714.55, | |
| 169 | 3705.95, 3697.44, 3689.06, 3680.81, 3672.69, 3664.69, 3656.69, 3648.57, 3640.32, 3631.94, | |
| 170 | 3623.43, 3615.12, 3607.31, 3600.01, 3593.22, 3586.94, 3580.97, 3575.13, 3569.42, 3563.83, | |
| 171 | 3558.37, 3552.92, 3547.33, 3541.62, 3535.78, 3529.81, 3524.04, 3518.77, 3514.01, 3509.75, | |
| 172 | 3506.01, 3502.52, 3499.03, 3495.54, 3492.05, 3488.56, 3485.13, 3481.83, 3478.65, 3475.61, | |
| 173 | 3472.69, 3469.74, 3466.59, 3463.26, 3459.74, 3456.03, 3452.22, 3448.41, 3444.60, 3440.79, | |
| 174 | 3436.98, 3433.30, 3429.88, 3426.70, 3423.78, 3421.12, 3418.51, 3415.79, 3412.93, 3409.95, | |
| 175 | 3406.84, 3403.66, 3400.49, 3397.32, 3394.14, 3390.97, 3387.76, 3384.49, 3381.16, 3377.77, | |
| 176 | 3374.31, 3370.66, 3366.69, 3362.41, 3357.80, 3352.88, 3347.65, 3342.09, 3336.22, 3330.04, | |
| 177 | 3323.53, 3317.02, 3310.84, 3304.96, 3299.41, 3294.17, 3289.13, 3284.15, 3279.23, 3274.37, | |
| 178 | 3269.58, 3264.79, 3259.93, 3255.01, 3250.03, 3244.98, 3239.78, 3234.32, 3228.61, 3222.64, | |
| 179 | 3216.42, 3210.17, 3204.11, 3198.24, 3192.56, 3187.07, 3181.54, 3175.77, 3169.74, 3163.45, | |
| 180 | 3156.92, 3150.09, 3142.95, 3135.49, 3127.72, 3119.63, 3111.69, 3104.39, 3097.73, 3091.70, | |
| 181 | 3086.30, 3081.26, 3076.28, 3071.36, 3066.50, 3061.71, 3056.63, 3050.92, 3044.57, 3037.59, | |
| 182 | 3029.97, 3021.91, 3013.60, 3005.03, 2996.21, 2987.13, 2977.89, 2968.60, 2959.23, 2949.81, | |
| 183 | 2940.32, 2931.02, 2922.17, 2913.76, 2905.79, 2898.27, 2890.69, 2882.53, 2873.80, 2864.50, | |
| 184 | 2854.63, 2844.70, 2835.21, 2826.17, 2817.57, 2809.41, 2801.82, 2794.94, 2788.75, 2783.26, | |
| 185 | 2778.47, 2773.58, 2767.80, 2761.14, 2753.59, 2745.14, 2736.42, 2728.01, 2719.91, 2712.14, | |
| 186 | 2704.68, 2697.51, 2690.59, 2683.93, 2677.52, 2671.36, 2665.39, 2659.55, 2653.84, 2648.26, | |
| 187 | 2642.80, 2637.37, 2631.88, 2626.33, 2620.71, 2615.03, 2609.22, 2603.22, 2597.03, 2590.66, | |
| 188 | 2584.09, 2577.58, 2571.39, 2565.52, 2559.97, 2554.73, 2549.72, 2544.83, 2540.07, 2535.43, | |
| 189 | 2530.93, 2526.29, 2521.28, 2515.89, 2510.11, 2503.95, 2497.73, 2491.77, 2486.05, 2480.60, | |
| 190 | 2475.39, 2470.12, 2464.47, 2458.44, 2452.03, 2445.24, 2438.42, 2431.91, 2425.72, 2419.85, | |
| 191 | 2414.30, 2409.00, 2403.89, 2398.97, 2394.24, 2389.70, 2385.23, 2380.69, 2376.09, 2371.42, | |
| 192 | 2366.70, 2361.97, 2357.30, 2352.70, 2348.16, 2343.69, 2339.09, 2334.17, 2328.93, 2323.38, | |
| 193 | 2317.51, 2311.44, 2305.32, 2299.13, 2292.88, 2286.56, 2280.28, 2274.12, 2268.09, 2262.19, | |
| 194 | 2256.41, 2250.64, 2244.74, 2238.71, 2232.55, 2226.26, 2220.08, 2214.21, 2208.65, 2203.42, | |
| 195 | 2198.50, 2193.67, 2188.72, 2183.64, 2178.44, 2173.11, 2167.74, 2162.44, 2157.21, 2152.03, | |
| 196 | 2146.93, 2141.69, 2136.14, 2130.26, 2124.08, 2117.57, 2110.91, 2104.24, 2097.58, 2090.91, | |
| 197 | 2084.25, 2077.93, 2072.31, 2067.40, 2063.17, 2059.65, 2056.32, 2052.67, 2048.70, 2044.42, | |
| 198 | 2039.82, 2035.09, 2030.42, 2025.82, 2021.28, 2016.81, 2012.49, 2008.43, 2004.62, 2001.07, | |
| 199 | 1997.77, 1994.53, 1991.17, 1987.68, 1984.06, 1980.31, 1976.66, 1973.33, 1970.32, 1967.62, | |
| 200 | 1965.24, 1963.08, 1961.05, 1959.14, 1957.37, 1955.72, 1954.32, 1953.31, 1952.67, 1952.42, | |
| 201 | 1952.54, 1952.80, 1952.92, 1952.92, 1952.80, 1952.54, 1952.00, 1951.02, 1949.59, 1947.72, | |
| 202 | 1945.40, 1942.93, 1940.58, 1938.36, 1936.26, 1934.30, 1932.39, 1930.49, 1928.58, 1926.68, | |
| 203 | 1924.77, 1922.78, 1920.59, 1918.21, 1915.64, 1912.87, 1910.11, 1907.54, 1905.16, 1902.97, | |
| 204 | 1900.97, 1898.94, 1896.66, 1894.12, 1891.33, 1888.28, 1884.91, 1881.17, 1877.04, 1872.54, | |
| 205 | 1867.65, 1862.76, 1858.26, 1854.13, 1850.39, 1847.02, 1843.88, 1840.80, 1837.79, 1834.84, | |
| 206 | 1831.95, 1829.16, 1826.49, 1823.95, 1821.54, 1819.25, 1817.16, 1815.32, 1813.73, 1812.40, | |
| 207 | 1811.32, 1810.27, 1809.03, 1807.61, 1805.99, 1804.18, 1802.27, 1800.37, 1798.47, 1796.56, | |
| 208 | 1794.66, 1792.75, 1790.85, 1788.95, 1787.04, 1785.14, 1783.33, 1781.71, 1780.28, 1779.04, | |
| 209 | 1778.00, 1776.95, 1775.71, 1774.28, 1772.67, 1770.86, 1768.76, 1766.29, 1763.43, 1760.19, | |
| 210 | 1756.58, 1752.77, 1748.96, 1745.15, 1741.34, 1737.53, 1733.63, 1729.54, 1725.25, 1720.78, | |
| 211 | 1716.11, 1711.13, 1705.70, 1699.83, 1693.52, 1686.76, 1680.14, 1674.25, 1669.10, 1664.67, | |
| 212 | 1660.97, 1657.64, 1654.31, 1650.97, 1647.64, 1644.31, 1640.95, 1637.52, 1634.03, 1630.47, | |
| 213 | 1626.86, 1623.21, 1619.56, 1615.91, 1612.26, 1608.61, 1605.01, 1601.50, 1598.09, 1594.77, | |
| 214 | 1591.55, 1588.38, 1585.20, 1582.03, 1578.85, 1575.68, 1572.43, 1569.02, 1565.45, 1561.72, | |
| 215 | 1557.83, 1553.86, 1549.90, 1545.93, 1541.96, 1538.00, 1534.06, 1530.19, 1526.38, 1522.64, | |
| 216 | 1518.95, 1515.30, 1511.65, 1508.00, 1504.36, 1500.71, 1496.99, 1493.15, 1489.19, 1485.09, | |
| 217 | 1480.87, 1476.59, 1472.30, 1468.02, 1463.73, 1459.45, 1455.30, 1451.41, 1447.79, 1444.43, | |
| 218 | 1441.33, 1438.37, 1435.41, 1432.45, 1429.49, 1426.52, 1423.56, 1420.60, 1417.64, 1414.68, | |
| 219 | 1411.71, 1408.74, 1405.75, 1402.73, 1399.70, 1396.64, 1393.57, 1390.50, 1387.44, 1384.37, | |
| 220 | 1381.30, 1378.23, 1375.16, 1372.10, 1369.03, 1365.96, 1362.91, 1359.91, 1356.95, 1354.03, | |
| 221 | 1351.15, 1348.29, 1345.44, 1342.58, 1339.73, 1336.87, 1334.01, 1331.16, 1328.30, 1325.44, | |
| 222 | 1322.59, 1319.71, 1316.79, 1313.83, 1310.83, 1307.78, 1304.71, 1301.64, 1298.58, 1295.51, | |
| 223 | 1292.44, 1289.37, 1286.30, 1283.24, 1280.17, 1277.10, 1274.05, 1271.05, 1268.09, 1265.17, | |
| 224 | 1262.29, 1259.43, 1256.58, 1253.72, 1250.87, 1248.01, 1245.15, 1242.30, 1239.44, 1236.58, | |
| 225 | 1233.73, 1230.88, 1228.06, 1225.25, 1222.47, 1219.71, 1216.96, 1214.21, 1211.46, 1208.71, | |
| 226 | 1205.96, 1203.21, 1200.46, 1197.71, 1194.96, 1192.21, 1189.49, 1186.83, 1184.24, 1181.71, | |
| 227 | 1179.25, 1176.82, 1174.38, 1171.95, 1169.52, 1167.08, 1164.65, 1162.22, 1159.78, 1157.35, | |
| 228 | 1154.92, 1152.51, 1150.14, 1147.81, 1145.52, 1143.28, 1141.06, 1138.84, 1136.62, 1134.40, | |
| 229 | 1132.17, 1129.95, 1127.73, 1125.51, 1123.29, 1121.07, 1118.90, 1116.83, 1114.88, 1113.03, | |
| 230 | 1111.28, 1109.59, 1107.90, 1106.20, 1104.51, 1102.82, 1101.13, 1099.43, 1097.74, 1096.05, | |
| 231 | 1094.36, 1092.66, 1090.97, 1089.28, 1087.59, 1085.89, 1084.20, 1082.51, 1080.81, 1079.12, | |
| 232 | 1077.43, 1075.74, 1074.04, 1072.35, 1070.66, 1068.97, 1067.28, 1065.62, 1063.98, 1062.37, | |
| 233 | 1060.77, 1059.18, 1057.59, 1056.01, 1054.42, 1052.83, 1051.25, 1049.66, 1048.07, 1046.49, | |
| 234 | 1044.90, 1043.26, 1041.50, 1039.64, 1037.66, 1035.58, 1033.44, 1031.29, 1029.15, 1027.01, | |
| 235 | 1024.87, 1022.73, 1020.58, 1018.44, 1016.30, 1014.16, 1012.01, 1009.87, 1007.73, 1005.59, | |
| 236 | 1003.45, 1001.34, 999.30, 997.33, 995.43, 993.59, 991.80, 990.00, 988.20, 986.40, | |
| 237 | 984.60, 982.80, 981.01, 979.21, 977.41, 975.61, 973.93, 972.48, 971.26, 970.28, | |
| 238 | 969.53, 968.89, 968.26, 967.62, 966.99, 966.35, 965.72, 965.09, 964.45, 963.82, | |
| 239 | 963.18, 962.55, 961.91, 961.28, 960.64, 960.01, 959.28, 958.36, 957.25, 955.95, | |
| 240 | 954.45, 952.87, 951.28, 949.69, 948.11, 946.52, 944.93, 943.35, 941.76, 940.17, | |
| 241 | 938.59, 937.00, 935.41, 933.83, 932.24, 930.65, 929.06, 927.45, 925.82, 924.18, | |
| 242 | 922.52, 920.85, 919.19, 917.52, 915.85, 914.19, 912.52, 910.86, 909.19, 907.52, | |
| 243 | 905.86, 904.19, 902.53, 900.86, 899.19, 897.53, 895.91, 894.39, 892.96, 891.62, | |
| 244 | 890.39, 889.20, 888.01, 886.82, 885.63, 884.44, 883.25, 882.06, 880.87, 879.68, | |
| 245 | 878.49, 877.30, 876.11, 874.92, 873.73, 872.54, 871.31, 870.00, 868.61, 867.14, | |
| 246 | 865.59, 864.01, 862.42, 860.83, 859.25, 857.66, 856.07, 854.49, 852.90, 851.31, | |
| 247 | 849.73, 848.14, 846.55, 844.97, 843.38, 841.79, 840.24, 838.74, 837.32, 835.95, | |
| 248 | 834.65, 833.38, 832.11, 830.84, 829.57, 828.30, 827.03, 825.76, 824.50, 823.23, | |
| 249 | 821.96, 820.69, 819.42, 818.15, 816.88, 815.61, 814.37, 813.20, 812.09, 811.04, | |
| 250 | 810.06, 809.10, 808.15, 807.20, 806.25, 805.30, 804.34, 803.39, 802.44, 801.49, | |
| 251 | 800.53, 799.58, 798.63, 797.68, 796.73, 795.77, 794.87, 794.06, 793.35, 792.73, | |
| 252 | 792.20, 791.73, 791.25, 790.78, 790.30, 789.82, 789.35, 788.87, 788.40, 787.92, | |
| 253 | 787.44, 786.97, 786.49, 786.02, 785.54, 785.06, 784.61, 784.19, 783.81, 783.48, | |
| 254 | 783.18, 782.90, 782.62, 782.35, 782.07, 781.79, 781.51, 781.24, 780.96, 780.68, | |
| 255 | 780.40, 780.12, 779.85, 779.57, 779.29, 779.01, 778.68, 778.23, 777.66, 776.98, | |
| 256 | 776.18, 775.32, 774.46, 773.61, 772.75, 771.89, 771.04, 770.18, 769.32, 768.47, | |
| 257 | 767.61, 766.75, 765.90, 765.04, 764.18, 763.32, 762.47, 761.61, 760.75, 759.90, | |
| 258 | 759.04, 758.25, 757.59, 757.07, 756.68, 756.42, 756.23, 756.04, 755.85, 755.66, | |
| 259 | 755.47, 755.28, 755.09, 754.90, 754.71, 754.52, 754.33, 754.14, 753.95, 753.76, | |
| 260 | 753.57, 753.38, 753.19, 752.99, 752.80, 752.61, 752.43, 752.25, 752.08, 751.91, | |
| 261 | 751.76, 751.60, 751.45, 751.30, 751.15, 751.00, 750.84, 750.69, 750.54, 750.39, | |
| 262 | 750.2 | |
| 263 | }; | |
| 264 | constexpr double SUN_RAD_END = SUN_RAD_START + SUN_RAD_STEP * std::size(SUN_RAD_TABLE); | |
| 265 | ||
| 266 | ||
| 267 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 268 | // Conversion functions | |
| 269 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 270 | ||
| 271 | ! | double radiansToDegrees(const double radians) { |
| 272 | ! | return radians * RAD_TO_DEG; |
| 273 | } | |
| 274 | ||
| 275 | typedef unsigned short uint16; | |
| 276 | typedef unsigned int uint32; | |
| 277 | typedef unsigned long long uint64; | |
| 278 | ||
| 279 | ! | double doubleFromHalf(const uint16 half) { |
| 280 | ! | uint32 hi = uint32(half & 0x8000) << 16; |
| 281 | ! | uint16 abs = half & 0x7FFF; |
| 282 | ! | if (abs) { |
| 283 | ! | hi |= 0x3F000000 << uint16(abs >= 0x7C00); |
| 284 | ! | for (; abs < 0x400; abs <<= 1, hi -= 0x100000) |
| 285 | ; | |
| 286 | ! | hi += uint32(abs) << 10; |
| 287 | } | |
| 288 | ! | const uint64 dbits = uint64(hi) << 32; |
| 289 | double out; | |
| 290 | ! | std::memcpy(&out, &dbits, sizeof(double)); |
| 291 | ! | return out; |
| 292 | } | |
| 293 | ||
| 294 | ||
| 295 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 296 | // Vector3 operations | |
| 297 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 298 | ||
| 299 | ! | double dot(const PragueSkyModel::Vector3& v1, const PragueSkyModel::Vector3& v2) { |
| 300 | ! | return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; |
| 301 | } | |
| 302 | ||
| 303 | ! | double magnitude(const PragueSkyModel::Vector3& vector) { |
| 304 | ! | return std::sqrt(dot(vector, vector)); |
| 305 | } | |
| 306 | ||
| 307 | ! | PragueSkyModel::Vector3 normalize(const PragueSkyModel::Vector3& vector) { |
| 308 | ! | return vector / magnitude(vector); |
| 309 | } | |
| 310 | ||
| 311 | ||
| 312 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 313 | // Helper functions | |
| 314 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 315 | ||
| 316 | ! | double pragueLerp(const double from, const double to, const double factor) { |
| 317 | ! | return (1.0 - factor) * from + factor * to; |
| 318 | } | |
| 319 | ||
| 320 | ! | double nonlerp(const double a, const double b, const double w, const double p) { |
| 321 | ! | const double c1 = pow(a, p); |
| 322 | ! | const double c2 = pow(b, p); |
| 323 | ! | return ((pow(w, p) - c1) / (c2 - c1)); |
| 324 | } | |
| 325 | ||
| 326 | ||
| 327 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 328 | // Data reading | |
| 329 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 330 | ||
| 331 | // skymodelr: full-altitude datasets exceed 2 GB. Windows long/fseek offsets are | |
| 332 | // only 32 bits; use the platform's 64-bit seek and report a failed skip. | |
| 333 | ! | static void skipDatasetBytes(FILE* handle, size_t bytes) { |
| 334 | #ifdef _WIN32 | |
| 335 | int status = _fseeki64(handle, static_cast<__int64>(bytes), SEEK_CUR); | |
| 336 | #else | |
| 337 | ! | int status = fseeko(handle, static_cast<off_t>(bytes), SEEK_CUR); |
| 338 | #endif | |
| 339 | ! | if (status != 0) throw PragueSkyModel::DatasetReadException("coefficient offset"); |
| 340 | } | |
| 341 | ||
| 342 | 1x | void PragueSkyModel::readRadiance(FILE* handle, const double singleVisibility) { |
| 343 | // Read metadata. | |
| 344 | ||
| 345 | // Structure of the metadata part of the data file: | |
| 346 | // visibilityCount (1 * int), visibilities (visibilityCount * double), | |
| 347 | // albedoCount (1 * int), albedos (albedoCount * double), | |
| 348 | // altitudeCount (1 * int), altitudes (altitudeCount * double), | |
| 349 | // elevationCount (1 * int), elevations (elevationCount * double), | |
| 350 | // channels (1 * int), channelStart (1 * double), channelWidth (1 * double), | |
| 351 | // rankRad (1 * int), | |
| 352 | // sunBreaksCountRad (1 * int), sunBreaksRad (sunBreaksCountRad * double), | |
| 353 | // zenithBreaksCountRad (1 * int), zenithBreaksRad (zenithBreaksCountRad * double), | |
| 354 | // emphBreaksCountRad (1 * int), emphBreaksRad (emphBreaksCountRad * double) | |
| 355 | ||
| 356 | size_t valsRead; | |
| 357 | ||
| 358 | 1x | int visibilityCount = 0; |
| 359 | 1x | valsRead = fread(&visibilityCount, sizeof(int), 1, handle); |
| 360 | 1x | if (valsRead != 1 || visibilityCount < 1) |
| 361 | ! | throw DatasetReadException("visibilityCountRad"); |
| 362 | ||
| 363 | 1x | std::vector<double> visibilitiesRadInFile; |
| 364 | 1x | visibilitiesRadInFile.resize(visibilityCount); |
| 365 | 1x | valsRead = fread(visibilitiesRadInFile.data(), sizeof(double), visibilityCount, handle); |
| 366 | 1x | if (valsRead != visibilitiesRadInFile.size()) |
| 367 | 3x | throw DatasetReadException("visibilitesRad"); |
| 368 | ||
| 369 | ! | int skippedVisibilities = 0; |
| 370 | ! | if (singleVisibility <= 0.0 || visibilityCount <= 1) { |
| 371 | // If the given single visibility value is not valid or there is just one visibility present (so there | |
| 372 | // is nothing to save), all visibilities present are loaded. | |
| 373 | ! | visibilitiesRad.resize(visibilityCount); |
| 374 | ! | visibilitiesRad = visibilitiesRadInFile; |
| 375 | } else { | |
| 376 | // Otherwise, only the two visibilities closest to the single visibility value are loaded and the rest | |
| 377 | // is skipped. | |
| 378 | ! | if (singleVisibility <= visibilitiesRadInFile.front()) { |
| 379 | ! | visibilitiesRad.resize(1); |
| 380 | ! | visibilitiesRad[0] = visibilitiesRadInFile.front(); |
| 381 | ! | } else if (singleVisibility >= visibilitiesRadInFile.back()) { |
| 382 | ! | visibilitiesRad.resize(1); |
| 383 | ! | visibilitiesRad[0] = visibilitiesRadInFile.back(); |
| 384 | ! | skippedVisibilities = visibilitiesRadInFile.size() - 1; |
| 385 | } | |
| 386 | else { | |
| 387 | ! | int visIdx = 0; |
| 388 | ! | while (singleVisibility >= visibilitiesRadInFile[visIdx]) { |
| 389 | ! | ++visIdx; |
| 390 | } | |
| 391 | ! | visibilitiesRad.resize(2); |
| 392 | ! | visibilitiesRad[0] = visibilitiesRadInFile[visIdx - 1]; |
| 393 | ! | visibilitiesRad[1] = visibilitiesRadInFile[visIdx]; |
| 394 | ! | skippedVisibilities = visIdx - 1; |
| 395 | } | |
| 396 | } | |
| 397 | ||
| 398 | ! | int albedoCount = 0; |
| 399 | ! | valsRead = fread(&albedoCount, sizeof(int), 1, handle); |
| 400 | ! | if (valsRead != 1 || albedoCount < 1) |
| 401 | ! | throw DatasetReadException("albedoCountRad"); |
| 402 | ||
| 403 | ! | albedosRad.resize(albedoCount); |
| 404 | ! | valsRead = fread(albedosRad.data(), sizeof(double), albedoCount, handle); |
| 405 | ! | if (valsRead != albedosRad.size()) |
| 406 | ! | throw DatasetReadException("albedosRad"); |
| 407 | ||
| 408 | ! | int altitudeCount = 0; |
| 409 | ! | valsRead = fread(&altitudeCount, sizeof(int), 1, handle); |
| 410 | ! | if (valsRead != 1 || altitudeCount < 1) |
| 411 | ! | throw DatasetReadException("altitudeCountRad"); |
| 412 | ||
| 413 | ! | altitudesRad.resize(altitudeCount); |
| 414 | ! | valsRead = fread(altitudesRad.data(), sizeof(double), altitudeCount, handle); |
| 415 | ! | if (valsRead != altitudesRad.size()) |
| 416 | ! | throw DatasetReadException("altitudesRad"); |
| 417 | ||
| 418 | ! | int elevationCount = 0; |
| 419 | ! | valsRead = fread(&elevationCount, sizeof(int), 1, handle); |
| 420 | ! | if (valsRead != 1 || elevationCount < 1) |
| 421 | ! | throw DatasetReadException(" elevationCountRad"); |
| 422 | ||
| 423 | ! | elevationsRad.resize(elevationCount); |
| 424 | ! | valsRead = fread(elevationsRad.data(), sizeof(double), elevationCount, handle); |
| 425 | ! | if (valsRead != elevationsRad.size()) |
| 426 | ! | throw DatasetReadException("elevationsRad"); |
| 427 | ||
| 428 | ! | valsRead = fread(&channels, sizeof(int), 1, handle); |
| 429 | ! | if (valsRead != 1 || channels < 1) |
| 430 | ! | throw DatasetReadException("channels"); |
| 431 | ||
| 432 | ! | valsRead = fread(&channelStart, sizeof(double), 1, handle); |
| 433 | ! | if (valsRead != 1 || channelStart < 0) |
| 434 | ! | throw DatasetReadException("channelStart"); |
| 435 | ||
| 436 | ! | valsRead = fread(&channelWidth, sizeof(double), 1, handle); |
| 437 | ! | if (valsRead != 1 || channelWidth <= 0) |
| 438 | ! | throw DatasetReadException("channelWidth"); |
| 439 | ||
| 440 | ! | totalConfigs = |
| 441 | ! | channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * visibilitiesRad.size(); |
| 442 | ||
| 443 | ! | skippedConfigsBegin = |
| 444 | ! | channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * skippedVisibilities; |
| 445 | ||
| 446 | ! | skippedConfigsEnd = channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * |
| 447 | ! | (visibilitiesRadInFile.size() - skippedVisibilities - visibilitiesRad.size()); |
| 448 | ||
| 449 | ! | valsRead = fread(&metadataRad.rank, sizeof(int), 1, handle); |
| 450 | ! | if (valsRead != 1 || metadataRad.rank < 1) |
| 451 | ! | throw DatasetReadException("rankRad"); |
| 452 | ||
| 453 | ! | int sunBreaksCount = 0; |
| 454 | ! | valsRead = fread(&sunBreaksCount, sizeof(int), 1, handle); |
| 455 | ! | if (valsRead != 1 || sunBreaksCount < 2) |
| 456 | ! | throw DatasetReadException("sunBreaksCountRad"); |
| 457 | ||
| 458 | ! | metadataRad.sunBreaks.resize(sunBreaksCount); |
| 459 | ! | valsRead = fread(metadataRad.sunBreaks.data(), sizeof(double), sunBreaksCount, handle); |
| 460 | ! | if (valsRead != metadataRad.sunBreaks.size()) |
| 461 | ! | throw DatasetReadException("sunBreaksRad"); |
| 462 | ||
| 463 | ! | int zenitBreaksCount = 0; |
| 464 | ! | valsRead = fread(&zenitBreaksCount, sizeof(int), 1, handle); |
| 465 | ! | if (valsRead != 1 || zenitBreaksCount < 2) |
| 466 | ! | throw DatasetReadException("zenitBreaksCountRad"); |
| 467 | ||
| 468 | ! | metadataRad.zenithBreaks.resize(zenitBreaksCount); |
| 469 | ! | valsRead = fread(metadataRad.zenithBreaks.data(), sizeof(double), zenitBreaksCount, handle); |
| 470 | ! | if (valsRead != metadataRad.zenithBreaks.size()) |
| 471 | ! | throw DatasetReadException("zenithBreaksRad"); |
| 472 | ||
| 473 | ! | int emphBreaksCount = 0; |
| 474 | ! | valsRead = fread(&emphBreaksCount, sizeof(int), 1, handle); |
| 475 | ! | if (valsRead != 1 || emphBreaksCount < 2) |
| 476 | ! | throw DatasetReadException("emphBreaksCountRad"); |
| 477 | ||
| 478 | ! | metadataRad.emphBreaks.resize(emphBreaksCount); |
| 479 | ! | valsRead = fread(metadataRad.emphBreaks.data(), sizeof(double), emphBreaksCount, handle); |
| 480 | ! | if (valsRead != metadataRad.emphBreaks.size()) |
| 481 | ! | throw DatasetReadException("emphBreaksRad"); |
| 482 | ||
| 483 | // Calculate offsets and strides. | |
| 484 | ||
| 485 | ! | metadataRad.sunOffset = 0; |
| 486 | ! | metadataRad.sunStride = metadataRad.sunBreaks.size() + metadataRad.zenithBreaks.size(); |
| 487 | ||
| 488 | ! | metadataRad.zenithOffset = metadataRad.sunOffset + metadataRad.sunBreaks.size(); |
| 489 | ! | metadataRad.zenithStride = metadataRad.sunStride; |
| 490 | ||
| 491 | ! | metadataRad.emphOffset = metadataRad.sunOffset + metadataRad.rank * metadataRad.sunStride; |
| 492 | ||
| 493 | ! | metadataRad.totalCoefsSingleConfig = |
| 494 | ! | metadataRad.emphOffset + metadataRad.emphBreaks.size(); // this is for one specific configuration |
| 495 | ! | metadataRad.totalCoefsAllConfigs = metadataRad.totalCoefsSingleConfig * totalConfigs; |
| 496 | ||
| 497 | // Read data. | |
| 498 | ||
| 499 | // Structure of the data part of the data file: | |
| 500 | // [[[[[[ sunCoefsRad (sunBreaksCountRad * half), zenithScale (1 * double), | |
| 501 | // zenithCoefsRad (zenithBreaksCountRad * half) ] * rankRad, | |
| 502 | // emphCoefsRad (emphBreaksCountRad * half) ] | |
| 503 | // * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount | |
| 504 | ||
| 505 | ! | int offset = 0; |
| 506 | ! | dataRad.resize(metadataRad.totalCoefsAllConfigs); |
| 507 | ||
| 508 | ! | std::vector<uint16> radianceTemp; |
| 509 | ! | radianceTemp.resize(std::max(metadataRad.sunBreaks.size(), |
| 510 | ! | std::max(metadataRad.zenithBreaks.size(), metadataRad.emphBreaks.size()))); |
| 511 | ||
| 512 | size_t oneConfigByteCount = | |
| 513 | ! | ((metadataRad.sunBreaks.size() + metadataRad.zenithBreaks.size()) * sizeof(uint16) + sizeof(double)) * |
| 514 | ! | metadataRad.rank + |
| 515 | ! | metadataRad.emphBreaks.size() * sizeof(uint16); |
| 516 | ||
| 517 | // If a single visibility was requested, skip all configurations from the beginning till those needed for | |
| 518 | // the requested visibility. | |
| 519 | ! | skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsBegin); |
| 520 | ||
| 521 | // Read configurations needed for the requested visibility (or all if none requested). | |
| 522 | ! | for (int con = 0; con < totalConfigs; ++con) { |
| 523 | ! | for (int r = 0; r < metadataRad.rank; ++r) { |
| 524 | // Read sun params. | |
| 525 | ! | valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.sunBreaks.size(), handle); |
| 526 | ! | if (valsRead != metadataRad.sunBreaks.size()) |
| 527 | ! | throw DatasetReadException("sunCoefsRad"); |
| 528 | ||
| 529 | // Unpack sun params from half. | |
| 530 | ! | for (size_t i = 0; i < metadataRad.sunBreaks.size(); ++i) { |
| 531 | ! | dataRad[offset++] = float(doubleFromHalf(radianceTemp[i])); |
| 532 | } | |
| 533 | ||
| 534 | // Read scaling factor for zenith params. | |
| 535 | double zenithScale; | |
| 536 | ! | valsRead = fread(&zenithScale, sizeof(double), 1, handle); |
| 537 | ! | if (valsRead != 1) |
| 538 | ! | throw DatasetReadException("zenithScaleRad"); |
| 539 | ||
| 540 | // Read zenith params. | |
| 541 | ! | valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.zenithBreaks.size(), handle); |
| 542 | ! | if (valsRead != metadataRad.zenithBreaks.size()) |
| 543 | ! | throw DatasetReadException("zenithCoefsRad"); |
| 544 | ||
| 545 | // Unpack zenith params from half (these need additional rescaling). | |
| 546 | ! | for (size_t i = 0; i < metadataRad.zenithBreaks.size(); ++i) { |
| 547 | ! | dataRad[offset++] = float(doubleFromHalf(radianceTemp[i]) / zenithScale); |
| 548 | } | |
| 549 | } | |
| 550 | ||
| 551 | // Read emphasize params. | |
| 552 | ! | valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.emphBreaks.size(), handle); |
| 553 | ! | if (valsRead != metadataRad.emphBreaks.size()) |
| 554 | ! | throw DatasetReadException("emphCoefsRad"); |
| 555 | ||
| 556 | // Unpack emphasize params from half. | |
| 557 | ! | for (size_t i = 0; i < metadataRad.emphBreaks.size(); ++i) { |
| 558 | ! | dataRad[offset++] = float(doubleFromHalf(radianceTemp[i])); |
| 559 | } | |
| 560 | } | |
| 561 | ||
| 562 | // Skip remaining configurations till the end. | |
| 563 | ! | skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsEnd); |
| 564 | } | |
| 565 | ||
| 566 | ! | void PragueSkyModel::readTransmittance(FILE* handle) { |
| 567 | // Read metadata | |
| 568 | ||
| 569 | size_t valsRead; | |
| 570 | ||
| 571 | ! | valsRead = fread(&dDim, sizeof(int), 1, handle); |
| 572 | ! | if (valsRead != 1 || dDim < 1) |
| 573 | ! | throw DatasetReadException("dDim"); |
| 574 | ||
| 575 | ! | valsRead = fread(&aDim, sizeof(int), 1, handle); |
| 576 | ! | if (valsRead != 1 || aDim < 1) |
| 577 | ! | throw DatasetReadException("aDim"); |
| 578 | ||
| 579 | ! | int visibilitiesCount = 0; |
| 580 | ! | valsRead = fread(&visibilitiesCount, sizeof(int), 1, handle); |
| 581 | ! | if (valsRead != 1 || visibilitiesCount < 1) |
| 582 | ! | throw DatasetReadException("visibilitiesCountTrans"); |
| 583 | ||
| 584 | ! | int altitudesCount = 0; |
| 585 | ! | valsRead = fread(&altitudesCount, sizeof(int), 1, handle); |
| 586 | ! | if (valsRead != 1 || altitudesCount < 1) |
| 587 | ! | throw DatasetReadException("altitudesCountTrans"); |
| 588 | ||
| 589 | ! | valsRead = fread(&rankTrans, sizeof(int), 1, handle); |
| 590 | ! | if (valsRead != 1 || rankTrans < 1) |
| 591 | ! | throw DatasetReadException("rankTrans"); |
| 592 | ||
| 593 | ! | std::vector<float> temp; |
| 594 | ! | temp.resize(std::max(altitudesCount, visibilitiesCount)); |
| 595 | ||
| 596 | ! | altitudesTrans.resize(altitudesCount); |
| 597 | ! | valsRead = fread(temp.data(), sizeof(float), altitudesCount, handle); |
| 598 | ! | if (valsRead != altitudesTrans.size()) |
| 599 | ! | throw DatasetReadException("altitudesTrans"); |
| 600 | ! | for (int i = 0; i < altitudesCount; i++) { |
| 601 | ! | altitudesTrans[i] = double(temp[i]); |
| 602 | } | |
| 603 | ||
| 604 | ! | visibilitiesTrans.resize(visibilitiesCount); |
| 605 | ! | valsRead = fread(temp.data(), sizeof(float), visibilitiesCount, handle); |
| 606 | ! | if (valsRead != visibilitiesTrans.size()) |
| 607 | ! | throw DatasetReadException("visibilitiesTrans"); |
| 608 | ! | for (int i = 0; i < visibilitiesCount; i++) { |
| 609 | ! | visibilitiesTrans[i] = double(temp[i]); |
| 610 | } | |
| 611 | ||
| 612 | ! | const size_t totalCoefsU = dDim * aDim * rankTrans * altitudesTrans.size(); |
| 613 | ! | const size_t totalCoefsV = visibilitiesTrans.size() * rankTrans * channels * altitudesTrans.size(); |
| 614 | ||
| 615 | // Read data | |
| 616 | ||
| 617 | ! | dataTransU.resize(totalCoefsU); |
| 618 | ! | valsRead = fread(dataTransU.data(), sizeof(float), totalCoefsU, handle); |
| 619 | ! | if (valsRead != totalCoefsU) |
| 620 | ! | throw DatasetReadException("datasetTransU"); |
| 621 | ||
| 622 | ! | dataTransV.resize(totalCoefsV); |
| 623 | ! | valsRead = fread(dataTransV.data(), sizeof(float), totalCoefsV, handle); |
| 624 | ! | if (valsRead != totalCoefsV) |
| 625 | ! | throw DatasetReadException("datasetTransV"); |
| 626 | } | |
| 627 | ||
| 628 | ! | void PragueSkyModel::readPolarisation(FILE* handle) { |
| 629 | // Read metadata. | |
| 630 | ||
| 631 | // Structure of the metadata part of the data file: | |
| 632 | // rankPol (1 * int), | |
| 633 | // sunBreaksCountPol (1 * int), sunBreaksPol (sunBreaksCountPol * double), | |
| 634 | // zenithBreaksCountPol (1 * int), zenithBreaksPol (zenithBreaksCountPol * double), | |
| 635 | ||
| 636 | size_t valsRead; | |
| 637 | ||
| 638 | ! | valsRead = fread(&metadataPol.rank, sizeof(int), 1, handle); |
| 639 | ! | if (valsRead != 1) { |
| 640 | // Polarisation dataset not present | |
| 641 | ! | metadataPol.rank = 0; |
| 642 | ! | return; |
| 643 | } | |
| 644 | ||
| 645 | ! | int sunBreaksCount = 0; |
| 646 | ! | valsRead = fread(&sunBreaksCount, sizeof(int), 1, handle); |
| 647 | ! | if (valsRead != 1 || sunBreaksCount < 1) |
| 648 | ! | throw DatasetReadException("sunBreaksCountPol"); |
| 649 | ||
| 650 | ! | metadataPol.sunBreaks.resize(sunBreaksCount); |
| 651 | ! | valsRead = fread(metadataPol.sunBreaks.data(), sizeof(double), sunBreaksCount, handle); |
| 652 | ! | if (valsRead != metadataPol.sunBreaks.size()) |
| 653 | ! | throw DatasetReadException("sunBreaksPol"); |
| 654 | ||
| 655 | ! | int zenithBreaksCount = 0; |
| 656 | ! | valsRead = fread(&zenithBreaksCount, sizeof(int), 1, handle); |
| 657 | ! | if (valsRead != 1 || zenithBreaksCount < 1) |
| 658 | ! | throw DatasetReadException("zenithBreaksCountPol"); |
| 659 | ||
| 660 | ! | metadataPol.zenithBreaks.resize(zenithBreaksCount); |
| 661 | ! | valsRead = fread(metadataPol.zenithBreaks.data(), sizeof(double), zenithBreaksCount, handle); |
| 662 | ! | if (valsRead != metadataPol.zenithBreaks.size()) |
| 663 | ! | throw DatasetReadException("zenithBreaksPol"); |
| 664 | ||
| 665 | ! | metadataPol.emphBreaks.clear(); |
| 666 | ||
| 667 | // Calculate offsets and strides. | |
| 668 | ||
| 669 | ! | metadataPol.sunOffset = 0; |
| 670 | ! | metadataPol.sunStride = metadataPol.sunBreaks.size() + metadataPol.zenithBreaks.size(); |
| 671 | ||
| 672 | ! | metadataPol.zenithOffset = metadataPol.sunOffset + metadataPol.sunBreaks.size(); |
| 673 | ! | metadataPol.zenithStride = metadataPol.sunStride; |
| 674 | ||
| 675 | ! | metadataPol.emphOffset = 0; |
| 676 | ||
| 677 | ! | metadataPol.totalCoefsSingleConfig = |
| 678 | ! | metadataPol.sunOffset + |
| 679 | ! | metadataPol.rank * metadataPol.sunStride; // this is for one specific configuration |
| 680 | ! | metadataPol.totalCoefsAllConfigs = metadataPol.totalCoefsSingleConfig * totalConfigs; |
| 681 | ||
| 682 | // Read data. | |
| 683 | ||
| 684 | // Structure of the data part of the data file: | |
| 685 | // [[[[[[ sunCoefsPol (sunBreaksCountPol * float), | |
| 686 | // zenithCoefsPol (zenithBreaksCountPol * float) ] * rankPol] | |
| 687 | // * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount | |
| 688 | ||
| 689 | ! | size_t offset = 0; |
| 690 | ! | dataPol.resize(metadataPol.totalCoefsAllConfigs); |
| 691 | ||
| 692 | size_t oneConfigByteCount = | |
| 693 | ! | (metadataPol.sunBreaks.size() + metadataPol.zenithBreaks.size()) * sizeof(float) * metadataPol.rank; |
| 694 | ||
| 695 | // If a single visibility was requested, skip all configurations from the beginning till those needed for | |
| 696 | // the requested visibility. | |
| 697 | ! | skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsBegin); |
| 698 | ||
| 699 | ! | for (int con = 0; con < totalConfigs; ++con) { |
| 700 | ! | for (int r = 0; r < metadataPol.rank; ++r) { |
| 701 | // Read sun params. | |
| 702 | ! | valsRead = fread(dataPol.data() + offset, sizeof(float), metadataPol.sunBreaks.size(), handle); |
| 703 | ! | if (valsRead != metadataPol.sunBreaks.size()) |
| 704 | ! | throw DatasetReadException("sunCoefsPol"); |
| 705 | ! | offset += metadataPol.sunBreaks.size(); |
| 706 | ||
| 707 | // Read zenith params. | |
| 708 | ! | valsRead = fread(dataPol.data() + offset, sizeof(float), metadataPol.zenithBreaks.size(), handle); |
| 709 | ! | if (valsRead != metadataPol.zenithBreaks.size()) |
| 710 | ! | throw DatasetReadException("zenithCoefsPol"); |
| 711 | ! | offset += metadataPol.zenithBreaks.size(); |
| 712 | } | |
| 713 | } | |
| 714 | } | |
| 715 | ||
| 716 | ||
| 717 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 718 | // Initialization | |
| 719 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 720 | ||
| 721 | 2x | void PragueSkyModel::initialize(const std::string& filename, const double singleVisibility, |
| 722 | bool cacheSpectra, bool transmissionTable, double transmissionTableMaxMiB) { | |
| 723 | 2x | if (std::isnan(transmissionTableMaxMiB) || transmissionTableMaxMiB < 0) |
| 724 | ! | throw std::invalid_argument("Prague transmission table limit must be nonnegative MiB or infinity."); |
| 725 | 2x | if (FILE* handle = fopen(filename.c_str(), "rb")) { |
| 726 | // skymodelr: close the file if a truncated dataset throws while loading. | |
| 727 | 1x | auto closeFile = [](FILE* stream) noexcept { fclose(stream); }; |
| 728 | 1x | std::unique_ptr<FILE, decltype(closeFile)> file(handle, closeFile); |
| 729 | 1x | initialized = false; |
| 730 | static std::atomic<unsigned long long> nextGeneration{1}; | |
| 731 | 1x | cacheGeneration = nextGeneration.fetch_add(1, std::memory_order_relaxed); |
| 732 | 1x | cacheSky = cacheSpectra; |
| 733 | 1x | std::vector<double>().swap(expandedTrans); |
| 734 | 1x | expandedVisibilityCount = 0; |
| 735 | // Read data | |
| 736 | 1x | readRadiance(handle, singleVisibility); |
| 737 | ! | readTransmittance(handle); |
| 738 | ! | readPolarisation(handle); |
| 739 | ! | if (transmissionTable) expandTransmission(singleVisibility, transmissionTableMaxMiB); |
| 740 | ! | initialized = true; |
| 741 | } else { | |
| 742 | 1x | throw DatasetNotFoundException(filename); |
| 743 | } | |
| 744 | } | |
| 745 | ||
| 746 | ! | size_t PragueSkyModel::memoryUsage() const { |
| 747 | ! | size_t bytes = sizeof(*this) + expandedTrans.capacity() * sizeof(double); |
| 748 | ! | for (const auto* values : {&dataRad, &dataPol, &dataTransU, &dataTransV}) |
| 749 | ! | bytes += values->capacity() * sizeof(float); |
| 750 | ! | for (const auto* values : {&visibilitiesRad, &albedosRad, &altitudesRad, &elevationsRad, |
| 751 | ! | &altitudesTrans, &visibilitiesTrans, &metadataRad.sunBreaks, |
| 752 | ! | &metadataRad.zenithBreaks, &metadataRad.emphBreaks, |
| 753 | ! | &metadataPol.sunBreaks, &metadataPol.zenithBreaks, &metadataPol.emphBreaks}) |
| 754 | ! | bytes += values->capacity() * sizeof(double); |
| 755 | ! | return bytes; |
| 756 | } | |
| 757 | ||
| 758 | ! | PragueSkyModel::AvailableData PragueSkyModel::getAvailableData() const { |
| 759 | ! | if (!initialized) { |
| 760 | ! | throw NotInitializedException(); |
| 761 | } | |
| 762 | ||
| 763 | AvailableData available; | |
| 764 | ! | available.albedoMin = albedosRad.front(); |
| 765 | ! | available.albedoMax = albedosRad.back(); |
| 766 | ! | available.altitudeMin = altitudesRad.front(); |
| 767 | ! | available.altitudeMax = altitudesRad.back(); |
| 768 | ! | available.elevationMin = elevationsRad.front(); |
| 769 | ! | available.elevationMax = elevationsRad.back(); |
| 770 | ! | available.visibilityMin = visibilitiesRad.front(); |
| 771 | ! | available.visibilityMax = visibilitiesRad.back(); |
| 772 | ! | available.polarisation = (metadataPol.rank != 0); |
| 773 | ! | available.channels = channels; |
| 774 | ! | available.channelStart = channelStart; |
| 775 | ! | available.channelWidth = channelWidth; |
| 776 | ||
| 777 | ! | return available; |
| 778 | } | |
| 779 | ||
| 780 | ||
| 781 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 782 | // Filling the Parameters structure | |
| 783 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 784 | ||
| 785 | ! | PragueSkyModel::Parameters PragueSkyModel::computeParameters(const Vector3& viewpoint, |
| 786 | const Vector3& viewDirection, | |
| 787 | const double groundLevelSolarElevationAtOrigin, | |
| 788 | const double groundLevelSolarAzimuthAtOrigin, | |
| 789 | const double visibility, | |
| 790 | const double albedo) const { | |
| 791 | // The caller validates radial altitude in the planet-centered frame. | |
| 792 | assert(magnitude(viewDirection) > 0.0); | |
| 793 | assert(visibility >= 0.0); | |
| 794 | assert(albedo >= 0.0 && albedo <= 1.0); | |
| 795 | ||
| 796 | Parameters params; | |
| 797 | ! | params.visibility = visibility; |
| 798 | ! | params.albedo = albedo; |
| 799 | ||
| 800 | // Shift viewpoint about safety altitude up | |
| 801 | ||
| 802 | ! | const Vector3 centerOfTheEarth = Vector3(0.0, 0.0, -PLANET_RADIUS); |
| 803 | ! | Vector3 toViewpoint = viewpoint - centerOfTheEarth; |
| 804 | ! | Vector3 toViewpointN = normalize(toViewpoint); |
| 805 | ! | const double distanceToView = magnitude(toViewpoint) + SAFETY_ALTITUDE; |
| 806 | ! | Vector3 toShiftedViewpoint = toViewpointN * distanceToView; |
| 807 | ! | Vector3 shiftedViewpoint = centerOfTheEarth + toShiftedViewpoint; |
| 808 | ||
| 809 | ! | Vector3 viewDirectionN = normalize(viewDirection); |
| 810 | ||
| 811 | // Compute altitude of viewpoint | |
| 812 | ||
| 813 | ! | params.altitude = distanceToView - PLANET_RADIUS; |
| 814 | ! | params.altitude = std::max(params.altitude, 0.0); |
| 815 | ||
| 816 | // Direction to sun | |
| 817 | ||
| 818 | ! | Vector3 directionToSunN; |
| 819 | ! | directionToSunN.x = cos(groundLevelSolarAzimuthAtOrigin) * cos(groundLevelSolarElevationAtOrigin); |
| 820 | ! | directionToSunN.y = sin(groundLevelSolarAzimuthAtOrigin) * cos(groundLevelSolarElevationAtOrigin); |
| 821 | ! | directionToSunN.z = sin(groundLevelSolarElevationAtOrigin); |
| 822 | ||
| 823 | // Solar elevation at viewpoint (more precisely, solar elevation at the point | |
| 824 | // on the ground directly below viewpoint) | |
| 825 | ||
| 826 | ! | const double dotZenithSun = dot(toViewpointN, directionToSunN); |
| 827 | ! | params.elevation = 0.5 * PI - acos(std::clamp(dotZenithSun, -1.0, 1.0)); |
| 828 | ||
| 829 | // Altitude-corrected view direction | |
| 830 | ||
| 831 | ! | Vector3 correctViewN; |
| 832 | ! | if (distanceToView > PLANET_RADIUS) { |
| 833 | ! | Vector3 lookAt = shiftedViewpoint + viewDirectionN; |
| 834 | ||
| 835 | const double correction = | |
| 836 | ! | sqrt(distanceToView * distanceToView - PLANET_RADIUS * PLANET_RADIUS) / distanceToView; |
| 837 | ||
| 838 | ! | Vector3 toNewOrigin = toViewpointN * (distanceToView - correction); |
| 839 | ! | Vector3 newOrigin = centerOfTheEarth + toNewOrigin; |
| 840 | ! | Vector3 correctView = lookAt - newOrigin; |
| 841 | ||
| 842 | ! | correctViewN = normalize(correctView); |
| 843 | } else { | |
| 844 | ! | correctViewN = viewDirectionN; |
| 845 | } | |
| 846 | ||
| 847 | // Sun angle (gamma) - no correction | |
| 848 | ||
| 849 | ! | double dotProductSun = dot(viewDirectionN, directionToSunN); |
| 850 | ! | params.gamma = acos(std::clamp(dotProductSun, -1.0, 1.0)); |
| 851 | ||
| 852 | // Shadow angle - requires correction | |
| 853 | ||
| 854 | ! | const double effectiveElevation = groundLevelSolarElevationAtOrigin; |
| 855 | ! | const double effectiveAzimuth = groundLevelSolarAzimuthAtOrigin; |
| 856 | ! | const double shadowAngle = effectiveElevation + PI * 0.5; |
| 857 | ||
| 858 | ! | Vector3 shadowDirectionN = Vector3(cos(shadowAngle) * cos(effectiveAzimuth), |
| 859 | ! | cos(shadowAngle) * sin(effectiveAzimuth), |
| 860 | ! | sin(shadowAngle)); |
| 861 | ||
| 862 | ! | const double dotProductShadow = dot(correctViewN, shadowDirectionN); |
| 863 | ! | params.shadow = acos(std::clamp(dotProductShadow, -1.0, 1.0)); |
| 864 | ||
| 865 | // Zenith angle (theta) - corrected version stored in otherwise unused zero | |
| 866 | // angle | |
| 867 | ||
| 868 | ! | double cosThetaCor = dot(correctViewN, toViewpointN); |
| 869 | ! | params.zero = acos(std::clamp(cosThetaCor, -1.0, 1.0)); |
| 870 | ||
| 871 | // Zenith angle (theta) - uncorrected version goes outside | |
| 872 | ||
| 873 | ! | double cosTheta = dot(viewDirectionN, toViewpointN); |
| 874 | ! | params.theta = acos(std::clamp(cosTheta, -1.0, 1.0)); |
| 875 | ||
| 876 | ! | return params; |
| 877 | } | |
| 878 | ||
| 879 | ||
| 880 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 881 | // Model evaluation for sky radiance and polarisation | |
| 882 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 883 | ||
| 884 | /// Evaluates piecewise linear approximation | |
| 885 | ! | double evalPL(const std::vector<float>::const_iterator coefs, const double factor) { |
| 886 | ! | if (factor == 0) return double(coefs[0]); // No successor at the final knot. |
| 887 | ! | return (double(coefs[1]) - double(coefs[0])) * factor + double(coefs[0]); |
| 888 | } | |
| 889 | ||
| 890 | ! | std::vector<float>::const_iterator PragueSkyModel::getCoefficients(const std::vector<float>& dataset, |
| 891 | const int totalCoefsSingleConfig, | |
| 892 | const int elevation, | |
| 893 | const int altitude, | |
| 894 | const int visibility, | |
| 895 | const int albedo, | |
| 896 | const int wavelength) const { | |
| 897 | ! | return dataset.cbegin() + |
| 898 | ! | (totalCoefsSingleConfig * |
| 899 | ! | (wavelength + size_t(channels) * elevation + channels * elevationsRad.size() * altitude + |
| 900 | ! | channels * elevationsRad.size() * altitudesRad.size() * albedo + |
| 901 | ! | channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * visibility)); |
| 902 | } | |
| 903 | ||
| 904 | ! | PragueSkyModel::InterpolationParameter PragueSkyModel::getInterpolationParameter( |
| 905 | const double queryVal, | |
| 906 | const std::vector<double>& breaks) const { | |
| 907 | // Clamp the value to the valid range. | |
| 908 | ! | const double clamped = std::clamp(queryVal, breaks.front(), breaks.back()); |
| 909 | ||
| 910 | // Get the nearest greater parameter value. | |
| 911 | ! | const auto next = std::upper_bound(breaks.cbegin() + 1, breaks.cend(), clamped); |
| 912 | ||
| 913 | // Compute the index and float factor. | |
| 914 | InterpolationParameter parameter; | |
| 915 | ! | parameter.index = int(next - breaks.cbegin()) - 1; |
| 916 | ! | if (next == breaks.cend()) { |
| 917 | ! | parameter.factor = 0.0; |
| 918 | } else { | |
| 919 | ! | parameter.factor = (clamped - *(next - 1)) / (*next - *(next - 1)); |
| 920 | } | |
| 921 | ||
| 922 | assert(0 <= parameter.index && parameter.index < breaks.size() && | |
| 923 | (parameter.index < breaks.size() - 1 || parameter.factor == 0.f)); | |
| 924 | assert(0 <= parameter.factor && parameter.factor <= 1); | |
| 925 | ! | return parameter; |
| 926 | } | |
| 927 | ||
| 928 | ! | double PragueSkyModel::reconstruct(const AngleParameters& radianceParameters, |
| 929 | const std::vector<float>::const_iterator channelParameters, | |
| 930 | const Metadata& metadata) const { | |
| 931 | // The original image was emphasized (for radiance only), re-parametrized into gamma-alpha space, | |
| 932 | // decomposed into sum of rankRad outer products of 'sun' and 'zenith' vectors and these vectors were | |
| 933 | // stored as piece-wise polynomial approximation. Here the process is reversed (for one point). | |
| 934 | ||
| 935 | ! | double result = 0.0; |
| 936 | ! | for (int r = 0; r < metadata.rank; ++r) { |
| 937 | // Restore the right value in the 'sun' vector | |
| 938 | ! | const double sunParam = evalPL(channelParameters + metadata.sunOffset + r * metadata.sunStride + |
| 939 | ! | radianceParameters.gamma.index, |
| 940 | ! | radianceParameters.gamma.factor); |
| 941 | ||
| 942 | // Restore the right value in the 'zenith' vector | |
| 943 | ! | const double zenithParam = evalPL(channelParameters + metadata.zenithOffset + |
| 944 | ! | r * metadata.zenithStride + radianceParameters.alpha.index, |
| 945 | ! | radianceParameters.alpha.factor); |
| 946 | ||
| 947 | // Accumulate their "outer" product | |
| 948 | ! | result += sunParam * zenithParam; |
| 949 | } | |
| 950 | ||
| 951 | // De-emphasize (for radiance only) | |
| 952 | ! | if (!metadata.emphBreaks.empty()) { |
| 953 | const double emphParam = | |
| 954 | ! | evalPL(channelParameters + metadata.emphOffset + radianceParameters.zero.index, |
| 955 | ! | radianceParameters.zero.factor); |
| 956 | ! | result *= emphParam; |
| 957 | ! | result = std::max(result, 0.0); |
| 958 | } | |
| 959 | ||
| 960 | ! | return result; |
| 961 | } | |
| 962 | ||
| 963 | ! | double PragueSkyModel::evaluateModel(const Parameters& params, |
| 964 | const double wavelength, | |
| 965 | const std::vector<float>& data, | |
| 966 | const Metadata& metadata) const { | |
| 967 | // Ignore wavelengths outside the dataset range. | |
| 968 | ! | if (wavelength < channelStart || wavelength >= (channelStart + channels * channelWidth)) { |
| 969 | ! | return 0.0; |
| 970 | } | |
| 971 | // Don't interpolate wavelengths inside the dataset range. | |
| 972 | ! | const int channelIndex = int(floor((wavelength - channelStart) / channelWidth)); |
| 973 | ||
| 974 | // Translate angle values to indices and interpolation factors. | |
| 975 | AngleParameters angleParameters; | |
| 976 | ! | angleParameters.gamma = getInterpolationParameter(params.gamma, metadata.sunBreaks); |
| 977 | ! | if (!metadata.emphBreaks.empty()) { // for radiance |
| 978 | angleParameters.alpha = | |
| 979 | ! | getInterpolationParameter(params.elevation < 0.0 ? params.shadow : params.zero, |
| 980 | ! | metadata.zenithBreaks); |
| 981 | ! | angleParameters.zero = getInterpolationParameter(params.zero, metadata.emphBreaks); |
| 982 | } else { // for polarisation | |
| 983 | ! | angleParameters.alpha = getInterpolationParameter(params.zero, metadata.zenithBreaks); |
| 984 | } | |
| 985 | ||
| 986 | // Translate configuration values to indices and interpolation factors. | |
| 987 | const InterpolationParameter visibilityParam = | |
| 988 | ! | getInterpolationParameter(params.visibility, visibilitiesRad); |
| 989 | ! | const InterpolationParameter albedoParam = getInterpolationParameter(params.albedo, albedosRad); |
| 990 | ! | const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesRad); |
| 991 | const InterpolationParameter elevationParam = | |
| 992 | ! | getInterpolationParameter(radiansToDegrees(params.elevation), elevationsRad); |
| 993 | ||
| 994 | // Prepare parameters controlling the interpolation. | |
| 995 | ! | ControlParameters controlParameters; |
| 996 | ! | for (int i = 0; i < 16; ++i) { |
| 997 | ! | const int visibilityIndex = std::min(visibilityParam.index + i / 8, int(visibilitiesRad.size() - 1)); |
| 998 | ! | const int albedoIndex = std::min(albedoParam.index + (i % 8) / 4, int(albedosRad.size() - 1)); |
| 999 | ! | const int altitudeIndex = std::min(altitudeParam.index + (i % 4) / 2, int(altitudesRad.size() - 1)); |
| 1000 | ! | const int elevationIndex = std::min(elevationParam.index + i % 2, int(elevationsRad.size() - 1)); |
| 1001 | ||
| 1002 | ! | controlParameters.coefficients[i] = getCoefficients(data, |
| 1003 | ! | metadata.totalCoefsSingleConfig, |
| 1004 | elevationIndex, | |
| 1005 | altitudeIndex, | |
| 1006 | visibilityIndex, | |
| 1007 | albedoIndex, | |
| 1008 | channelIndex); | |
| 1009 | } | |
| 1010 | ! | controlParameters.interpolationFactor[0] = visibilityParam.factor; |
| 1011 | ! | controlParameters.interpolationFactor[1] = albedoParam.factor; |
| 1012 | ! | controlParameters.interpolationFactor[2] = altitudeParam.factor; |
| 1013 | ! | controlParameters.interpolationFactor[3] = elevationParam.factor; |
| 1014 | ||
| 1015 | // Interpolate. | |
| 1016 | ! | const double result = interpolate<0, 0>(angleParameters, controlParameters, metadata); |
| 1017 | assert(metadata.emphBreaks.empty() || result >= 0.0); // polarisation can be negative | |
| 1018 | ||
| 1019 | ! | return result; |
| 1020 | } | |
| 1021 | ||
| 1022 | ||
| 1023 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1024 | // Sky radiance | |
| 1025 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1026 | ||
| 1027 | // skymodelr: reuse wavelength-independent lookup work for a whole spectrum. | |
| 1028 | ! | void PragueSkyModel::skyRadianceSpectrum(const Parameters& params, const double* wavelengths, |
| 1029 | size_t count, double* values) const { | |
| 1030 | ! | if (!initialized) throw NotInitializedException(); |
| 1031 | struct SkyEntry { | |
| 1032 | unsigned long long generation = 0; | |
| 1033 | Parameters parameters{}; | |
| 1034 | size_t count = 0; | |
| 1035 | std::array<double, 16> wavelengths{}, values{}; | |
| 1036 | }; | |
| 1037 | struct SkyCache { std::array<SkyEntry, 16> entries{}; size_t next = 0; }; | |
| 1038 | static thread_local SkyCache cache; | |
| 1039 | ! | const bool eligible = cacheSky && count > 0 && count <= 16; |
| 1040 | ! | if (eligible) { |
| 1041 | ! | for (size_t offset = 0; offset < cache.entries.size(); ++offset) { |
| 1042 | ! | const auto &entry = cache.entries[(cache.next + 15 - offset) % 16]; |
| 1043 | ! | if (entry.generation == cacheGeneration && entry.count == count && |
| 1044 | ! | std::memcmp(&entry.parameters, ¶ms, sizeof(Parameters)) == 0 && |
| 1045 | ! | std::equal(wavelengths, wavelengths + count, entry.wavelengths.begin())) { |
| 1046 | ! | std::copy_n(entry.values.begin(), count, values); |
| 1047 | ! | return; |
| 1048 | } | |
| 1049 | } | |
| 1050 | } | |
| 1051 | ! | const auto& metadata = metadataRad; |
| 1052 | ! | const auto& data = dataRad; |
| 1053 | // Translate angle values to indices and interpolation factors. | |
| 1054 | AngleParameters angleParameters; | |
| 1055 | ! | angleParameters.gamma = getInterpolationParameter(params.gamma, metadata.sunBreaks); |
| 1056 | ! | if (!metadata.emphBreaks.empty()) { // for radiance |
| 1057 | angleParameters.alpha = | |
| 1058 | ! | getInterpolationParameter(params.elevation < 0.0 ? params.shadow : params.zero, |
| 1059 | ! | metadata.zenithBreaks); |
| 1060 | ! | angleParameters.zero = getInterpolationParameter(params.zero, metadata.emphBreaks); |
| 1061 | } else { // for polarisation | |
| 1062 | ! | angleParameters.alpha = getInterpolationParameter(params.zero, metadata.zenithBreaks); |
| 1063 | } | |
| 1064 | ||
| 1065 | // Translate configuration values to indices and interpolation factors. | |
| 1066 | const InterpolationParameter visibilityParam = | |
| 1067 | ! | getInterpolationParameter(params.visibility, visibilitiesRad); |
| 1068 | ! | const InterpolationParameter albedoParam = getInterpolationParameter(params.albedo, albedosRad); |
| 1069 | ! | const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesRad); |
| 1070 | const InterpolationParameter elevationParam = | |
| 1071 | ! | getInterpolationParameter(radiansToDegrees(params.elevation), elevationsRad); |
| 1072 | ||
| 1073 | // Prepare parameters controlling the interpolation. | |
| 1074 | ! | ControlParameters controlParameters; |
| 1075 | ! | for (int i = 0; i < 16; ++i) { |
| 1076 | ! | const int visibilityIndex = std::min(visibilityParam.index + i / 8, int(visibilitiesRad.size() - 1)); |
| 1077 | ! | const int albedoIndex = std::min(albedoParam.index + (i % 8) / 4, int(albedosRad.size() - 1)); |
| 1078 | ! | const int altitudeIndex = std::min(altitudeParam.index + (i % 4) / 2, int(altitudesRad.size() - 1)); |
| 1079 | ! | const int elevationIndex = std::min(elevationParam.index + i % 2, int(elevationsRad.size() - 1)); |
| 1080 | ||
| 1081 | ! | controlParameters.coefficients[i] = getCoefficients(data, |
| 1082 | ! | metadata.totalCoefsSingleConfig, |
| 1083 | elevationIndex, | |
| 1084 | altitudeIndex, | |
| 1085 | visibilityIndex, | |
| 1086 | albedoIndex, | |
| 1087 | 0); | |
| 1088 | } | |
| 1089 | ! | controlParameters.interpolationFactor[0] = visibilityParam.factor; |
| 1090 | ! | controlParameters.interpolationFactor[1] = albedoParam.factor; |
| 1091 | ! | controlParameters.interpolationFactor[2] = altitudeParam.factor; |
| 1092 | ! | controlParameters.interpolationFactor[3] = elevationParam.factor; |
| 1093 | ||
| 1094 | ||
| 1095 | ! | const ControlParameters base = controlParameters; |
| 1096 | ! | for (size_t channel = 0; channel < count; ++channel) { |
| 1097 | ! | const double wavelength = wavelengths[channel]; |
| 1098 | ! | if (wavelength < channelStart || wavelength >= channelStart + channels * channelWidth) { |
| 1099 | ! | values[channel] = 0; |
| 1100 | ! | continue; |
| 1101 | } | |
| 1102 | ! | const int index = int(floor((wavelength - channelStart) / channelWidth)); |
| 1103 | ! | for (int i = 0; i < 16; ++i) |
| 1104 | ! | controlParameters.coefficients[i] = base.coefficients[i] + index * metadata.totalCoefsSingleConfig; |
| 1105 | ! | values[channel] = interpolate<0, 0>(angleParameters, controlParameters, metadata); |
| 1106 | } | |
| 1107 | ! | if (eligible) { |
| 1108 | ! | auto &entry = cache.entries[cache.next]; |
| 1109 | ! | entry.generation = cacheGeneration; |
| 1110 | ! | entry.parameters = params; |
| 1111 | ! | entry.count = count; |
| 1112 | ! | std::copy_n(wavelengths, count, entry.wavelengths.begin()); |
| 1113 | ! | std::copy_n(values, count, entry.values.begin()); |
| 1114 | ! | cache.next = (cache.next + 1) % cache.entries.size(); |
| 1115 | } | |
| 1116 | } | |
| 1117 | ||
| 1118 | ! | double PragueSkyModel::skyRadiance(const Parameters& params, const double wavelength) const { |
| 1119 | ! | if (!initialized) { |
| 1120 | ! | throw NotInitializedException(); |
| 1121 | } | |
| 1122 | ||
| 1123 | ! | return evaluateModel(params, wavelength, dataRad, metadataRad); |
| 1124 | } | |
| 1125 | ||
| 1126 | ||
| 1127 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1128 | // Sun radiance | |
| 1129 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1130 | ||
| 1131 | ! | double PragueSkyModel::sunRadiance(const Parameters& params, const double wavelength, |
| 1132 | const bool atmosphericAttenuation) const { | |
| 1133 | ! | if (!initialized) { |
| 1134 | ! | throw NotInitializedException(); |
| 1135 | } | |
| 1136 | ||
| 1137 | // Ignore wavelengths outside the dataset range. | |
| 1138 | ! | if (wavelength < SUN_RAD_START || wavelength >= SUN_RAD_END) { |
| 1139 | ! | return 0.0; |
| 1140 | } | |
| 1141 | ||
| 1142 | // Return zero for rays not hitting the sun. | |
| 1143 | ! | if (params.gamma > SUN_RADIUS) { |
| 1144 | ! | return 0.0; |
| 1145 | } | |
| 1146 | ||
| 1147 | // Compute index into the sun radiance table. | |
| 1148 | ! | const double idx = (wavelength - SUN_RAD_START) / SUN_RAD_STEP; |
| 1149 | assert(idx >= 0 && idx < std::size(SUN_RAD_TABLE) - 1); | |
| 1150 | ! | const int idxInt = int(floor(idx)); |
| 1151 | ! | const double idxFloat = idx - floor(idx); |
| 1152 | ||
| 1153 | // Interpolate between the two closest values in the sun radiance table. | |
| 1154 | ! | const double sunRadiance = |
| 1155 | ! | SUN_RAD_TABLE[idxInt] * (1.0 - idxFloat) + SUN_RAD_TABLE[idxInt + 1] * idxFloat; |
| 1156 | assert(sunRadiance > 0.0); | |
| 1157 | ||
| 1158 | // skymodelr: retain the intrinsic spectrum for unattenuated textured disks. | |
| 1159 | ! | if (!atmosphericAttenuation) return sunRadiance; |
| 1160 | ||
| 1161 | // Compute transmittance towards the sun. | |
| 1162 | ! | const double tau = PragueSkyModel::transmittance(params, wavelength, std::numeric_limits<double>::max()); |
| 1163 | assert(tau >= 0.0 && tau <= 1.0); | |
| 1164 | ||
| 1165 | // Combine. | |
| 1166 | ! | return sunRadiance * tau; |
| 1167 | } | |
| 1168 | ||
| 1169 | ||
| 1170 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1171 | // Polarisation | |
| 1172 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1173 | ||
| 1174 | ! | double PragueSkyModel::polarisation(const Parameters& params, const double wavelength) const { |
| 1175 | ! | if (!initialized) { |
| 1176 | ! | throw NotInitializedException(); |
| 1177 | } | |
| 1178 | ||
| 1179 | // If no polarisation data available | |
| 1180 | ! | if (metadataPol.rank == 0) { |
| 1181 | ! | throw NoPolarisationException(); |
| 1182 | } | |
| 1183 | ||
| 1184 | ! | return -evaluateModel(params, wavelength, dataPol, metadataPol); |
| 1185 | } | |
| 1186 | ||
| 1187 | ||
| 1188 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1189 | // Transmittance | |
| 1190 | ///////////////////////////////////////////////////////////////////////////////////// | |
| 1191 | ||
| 1192 | ! | std::vector<float>::const_iterator PragueSkyModel::getCoefficientsTrans(const int visibility, |
| 1193 | const int altitude, | |
| 1194 | const int wavelength) const { | |
| 1195 | ! | return dataTransV.cbegin() + |
| 1196 | ! | ((visibility * altitudesTrans.size() + altitude) * channels + wavelength) * rankTrans; |
| 1197 | } | |
| 1198 | ||
| 1199 | ! | std::vector<float>::const_iterator PragueSkyModel::getCoefficientsTransBase(const int altitude, |
| 1200 | const int a, | |
| 1201 | const int d) const { | |
| 1202 | ! | return dataTransU.cbegin() + size_t(altitude) * aDim * dDim * rankTrans + |
| 1203 | ! | (size_t(d) * aDim + a) * rankTrans; |
| 1204 | } | |
| 1205 | ||
| 1206 | /// Intersects the given ray (assuming rayPosX == 0) with a circle at origin with the given radius. | |
| 1207 | /// \return In the case the ray intersects the circle, distance to the circle is returned, otherwise the | |
| 1208 | /// function returns negative number. | |
| 1209 | ! | double intersectRayWithCircle2D(const double rayDirX, |
| 1210 | const double rayDirY, | |
| 1211 | const double rayPosY, | |
| 1212 | const double circleRadius) { | |
| 1213 | assert(rayPosY > 0.0); | |
| 1214 | assert(circleRadius > 0.0); | |
| 1215 | ||
| 1216 | // Compute discriminant | |
| 1217 | ! | const double qA = rayDirX * rayDirX + rayDirY * rayDirY; |
| 1218 | ! | const double qB = 2.0 * rayPosY * rayDirY; |
| 1219 | ! | const double qC = rayPosY * rayPosY - circleRadius * circleRadius; |
| 1220 | ! | double discrim = qB * qB - 4.0 * qA * qC; |
| 1221 | ||
| 1222 | // No intersection or touch only | |
| 1223 | ! | if (discrim <= 0.0) { |
| 1224 | ! | return -1.0; |
| 1225 | } | |
| 1226 | ||
| 1227 | ! | discrim = std::sqrt(discrim); |
| 1228 | ||
| 1229 | // Compute distances to both intersections | |
| 1230 | ! | const double d1 = (-qB + discrim) / (2.0 * qA); |
| 1231 | ! | const double d2 = (-qB - discrim) / (2.0 * qA); |
| 1232 | ||
| 1233 | // Try to take the nearest positive one | |
| 1234 | ! | const double distToIsect = (d1 > 0.0 && d2 > 0.0) ? std::min(d1, d2) : std::max(d1, d2); |
| 1235 | ! | return distToIsect; |
| 1236 | } | |
| 1237 | ||
| 1238 | /// Auxiliary function for \ref toTransmittanceParams. Computes [altitude, distance] parameters from | |
| 1239 | /// coordinates of intersection of view ray and ground or atmosphere edge. Note: using floats here instead of | |
| 1240 | /// doubles will cause banding artifacts. | |
| 1241 | ! | std::tuple<double, double> isectToAltitudeDistance(const double isectX, const double isectY) { |
| 1242 | // Distance to the intersection from world origin (not along ray as distToIsect in the calling method). | |
| 1243 | ! | const double isectDist = std::sqrt(isectX * isectX + isectY * isectY); |
| 1244 | assert(isectDist > 0.0); | |
| 1245 | ||
| 1246 | // Compute normalized and non-linearly scaled position in the atmosphere | |
| 1247 | ! | double altitude = std::clamp(isectDist - PLANET_RADIUS, 0.0, ATMOSPHERE_WIDTH); |
| 1248 | ! | altitude = std::pow(altitude / ATMOSPHERE_WIDTH, 1.0 / 3.0); |
| 1249 | // atan2 preserves sub-metre angular distances. acos(y / length) loses | |
| 1250 | // them to rounding (and can jump between zero and a ~0.1 m distance). | |
| 1251 | ! | double distance = std::atan2(std::abs(isectX), isectY) * PLANET_RADIUS; |
| 1252 | ! | distance = std::sqrt(distance / DIST_TO_EDGE); |
| 1253 | ! | distance = std::sqrt(distance); // Calling twice sqrt, since it is faster than pow(...,0.25) |
| 1254 | ! | distance = std::min(1.0, distance); |
| 1255 | assert(0.0 <= altitude && altitude <= 1.0); | |
| 1256 | assert(0.0 <= distance && distance <= 1.0); | |
| 1257 | ||
| 1258 | ! | return std::make_tuple(altitude, distance); |
| 1259 | } | |
| 1260 | ||
| 1261 | ! | PragueSkyModel::InterpolationParameter PragueSkyModel::getInterpolationParameterTrans(const double value, |
| 1262 | const int paramCount, | |
| 1263 | const int power) const { | |
| 1264 | InterpolationParameter param; | |
| 1265 | ! | param.index = std::min(int(value * paramCount), paramCount - 1); |
| 1266 | ! | param.factor = 0.0; |
| 1267 | ! | if (param.index < paramCount - 1) { |
| 1268 | ! | param.factor = |
| 1269 | ! | nonlerp(double(param.index) / paramCount, double(param.index + 1) / paramCount, value, power); |
| 1270 | ! | param.factor = std::clamp(param.factor, 0.0, 1.0); |
| 1271 | } | |
| 1272 | ! | return param; |
| 1273 | } | |
| 1274 | ||
| 1275 | ! | PragueSkyModel::TransmittanceParameters PragueSkyModel::toTransmittanceParams(const double theta, |
| 1276 | const double distance, | |
| 1277 | const double altitude) const { | |
| 1278 | assert(theta >= 0.0 && theta <= PI); | |
| 1279 | assert(distance >= 0.0); | |
| 1280 | assert(altitude >= 0.0); | |
| 1281 | ||
| 1282 | ! | const double rayDirX = sin(theta); |
| 1283 | ! | const double rayDirY = cos(theta); |
| 1284 | ! | const double rayPosY = PLANET_RADIUS + altitude; // rayPosX == 0 |
| 1285 | ||
| 1286 | ! | constexpr double ATMOSPHERE_EDGE = PLANET_RADIUS + ATMOSPHERE_WIDTH; |
| 1287 | ||
| 1288 | // Find intersection of the ground-to-sun ray with edge of the atmosphere (in 2D) | |
| 1289 | ! | double distToIsect = -1.0; |
| 1290 | ! | constexpr double LOW_ALTITUDE = 0.3; |
| 1291 | ! | if (altitude < LOW_ALTITUDE) { |
| 1292 | // Special handling of almost zero altitude case to avoid numerical issues. | |
| 1293 | ! | if (theta <= 0.5 * PI) { |
| 1294 | ! | distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, ATMOSPHERE_EDGE); |
| 1295 | } else { | |
| 1296 | ! | distToIsect = 0.0; |
| 1297 | } | |
| 1298 | } else { | |
| 1299 | ! | distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, PLANET_RADIUS); |
| 1300 | ! | if (distToIsect < 0.0) { |
| 1301 | ! | distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, ATMOSPHERE_EDGE); |
| 1302 | } | |
| 1303 | } | |
| 1304 | // The ray should always hit either the edge of the atmosphere or the planet (we are starting inside the | |
| 1305 | // atmosphere). | |
| 1306 | assert(distToIsect >= 0.0); | |
| 1307 | ||
| 1308 | ! | distToIsect = std::min(distToIsect, distance); |
| 1309 | ||
| 1310 | // Compute intersection coordinates | |
| 1311 | ! | const double isectX = rayDirX * distToIsect; |
| 1312 | ! | const double isectY = rayDirY * distToIsect + rayPosY; |
| 1313 | ||
| 1314 | // Get the internal [altitude, distance] parameters | |
| 1315 | ! | const auto [altitudeParam, distanceParam] = isectToAltitudeDistance(isectX, isectY); |
| 1316 | ||
| 1317 | // Convert to interpolation parameters | |
| 1318 | TransmittanceParameters params; | |
| 1319 | ! | params.altitude = getInterpolationParameterTrans(altitudeParam, aDim, 3); |
| 1320 | ! | params.distance = getInterpolationParameterTrans(distanceParam, dDim, 4); |
| 1321 | ||
| 1322 | ! | return params; |
| 1323 | } | |
| 1324 | ||
| 1325 | // Spend memory at initialization to remove repeated rank reconstruction. | |
| 1326 | // A single-visibility model still accepts transmission queries at other | |
| 1327 | // visibilities: those retain the original compressed evaluator as a fallback. | |
| 1328 | ! | void PragueSkyModel::expandTransmission(double singleVisibility, double maxMiB) { |
| 1329 | ! | expandedVisibilityFirst = 0; |
| 1330 | ! | expandedVisibilityCount = int(visibilitiesTrans.size()); |
| 1331 | ! | if (singleVisibility > 0) { |
| 1332 | ! | auto parameter = getInterpolationParameter(singleVisibility, visibilitiesTrans); |
| 1333 | ! | expandedVisibilityFirst = parameter.index; |
| 1334 | ! | expandedVisibilityCount = parameter.factor > 0 ? 2 : 1; |
| 1335 | } | |
| 1336 | // Check before multiplying, including when the caller requests no cap. | |
| 1337 | // Saturate at the addressable vector size before converting to size_t; | |
| 1338 | // fractional budgets round down, and zero disables expansion. | |
| 1339 | ! | size_t limit = std::min(expandedTrans.max_size(), |
| 1340 | ! | std::numeric_limits<size_t>::max() / sizeof(double)); |
| 1341 | ! | long double requested = static_cast<long double>(maxMiB) * (1024 * 1024 / sizeof(double)); |
| 1342 | ! | if (requested < static_cast<long double>(limit)) limit = static_cast<size_t>(requested); |
| 1343 | ! | size_t count = 1; |
| 1344 | ! | for (size_t dimension : {size_t(expandedVisibilityCount), altitudesTrans.size(), |
| 1345 | ! | size_t(channels), size_t(aDim), size_t(dDim)}) { |
| 1346 | ! | if (!dimension || dimension > limit / count) { |
| 1347 | ! | expandedVisibilityCount = 0; |
| 1348 | ! | return; |
| 1349 | } | |
| 1350 | ! | count *= dimension; |
| 1351 | } | |
| 1352 | try { | |
| 1353 | ! | expandedTrans.resize(count); |
| 1354 | ! | } catch (const std::bad_alloc &) { |
| 1355 | ! | expandedVisibilityCount = 0; |
| 1356 | ! | return; |
| 1357 | } | |
| 1358 | ! | for (int v = 0; v < expandedVisibilityCount; ++v) |
| 1359 | ! | for (int h = 0; h < int(altitudesTrans.size()); ++h) |
| 1360 | ! | for (int c = 0; c < channels; ++c) { |
| 1361 | ! | auto coefficients = getCoefficientsTrans(v + expandedVisibilityFirst, h, c); |
| 1362 | ! | for (int d = 0; d < dDim; ++d) |
| 1363 | ! | for (int a = 0; a < aDim; ++a) { |
| 1364 | ! | auto base = getCoefficientsTransBase(h, a, d); |
| 1365 | ! | double value = 0; |
| 1366 | ! | for (int r = 0; r < rankTrans; ++r) |
| 1367 | ! | value += double(base[r]) * double(coefficients[r]); |
| 1368 | ! | size_t offset = (((size_t(v) * altitudesTrans.size() + h) * channels + c) * |
| 1369 | ! | dDim + d) * aDim + a; |
| 1370 | ! | expandedTrans[offset] = value; |
| 1371 | } | |
| 1372 | } | |
| 1373 | } | |
| 1374 | ||
| 1375 | ! | double PragueSkyModel::reconstructTrans(const int visibilityIndex, |
| 1376 | const int altitudeIndex, | |
| 1377 | const TransmittanceParameters transParams, | |
| 1378 | const int channelIndex) const { | |
| 1379 | const std::vector<float>::const_iterator coefs = | |
| 1380 | ! | getCoefficientsTrans(visibilityIndex, altitudeIndex, channelIndex); |
| 1381 | ||
| 1382 | // Load transmittance values for bi-linear interpolation | |
| 1383 | ! | std::array<double, 4> transmittance = { 0.0, 0.0, 0.0, 0.0 }; |
| 1384 | ! | int index = 0; |
| 1385 | ! | for (int a = transParams.altitude.index; a <= transParams.altitude.index + 1; ++a) { |
| 1386 | ! | if (a < aDim) { |
| 1387 | ! | for (int d = transParams.distance.index; d <= transParams.distance.index + 1; ++d) { |
| 1388 | ! | if (d < dDim) { |
| 1389 | const std::vector<float>::const_iterator baseCoefs = | |
| 1390 | ! | getCoefficientsTransBase(altitudeIndex, a, d); |
| 1391 | ! | if (visibilityIndex >= expandedVisibilityFirst && |
| 1392 | ! | visibilityIndex < expandedVisibilityFirst + expandedVisibilityCount) { |
| 1393 | ! | size_t offset = (((size_t(visibilityIndex - expandedVisibilityFirst) * |
| 1394 | ! | altitudesTrans.size() + altitudeIndex) * channels + channelIndex) * |
| 1395 | ! | dDim + d) * aDim + a; |
| 1396 | ! | transmittance[index] = expandedTrans[offset]; |
| 1397 | } else { | |
| 1398 | ! | for (int i = 0; i < rankTrans; ++i) { |
| 1399 | // Same accumulation order as the pre-expanded knots. | |
| 1400 | ! | transmittance[index] += double(baseCoefs[i]) * double(coefs[i]); |
| 1401 | } | |
| 1402 | } | |
| 1403 | ! | index++; |
| 1404 | } | |
| 1405 | } | |
| 1406 | } | |
| 1407 | } | |
| 1408 | ||
| 1409 | // Perform bi-linear interpolation | |
| 1410 | ! | if (transParams.distance.factor > 0.f) { |
| 1411 | ! | transmittance[0] = pragueLerp(transmittance[0], transmittance[1], transParams.distance.factor); |
| 1412 | ! | transmittance[1] = pragueLerp(transmittance[2], transmittance[3], transParams.distance.factor); |
| 1413 | } | |
| 1414 | ! | transmittance[0] = std::max(transmittance[0], 0.0); |
| 1415 | ||
| 1416 | ! | if (transParams.altitude.factor > 0.f) { |
| 1417 | ! | transmittance[1] = std::max(transmittance[1], 0.0); |
| 1418 | ! | transmittance[0] = pragueLerp(transmittance[0], transmittance[1], transParams.altitude.factor); |
| 1419 | } | |
| 1420 | ||
| 1421 | assert(transmittance[0] >= 0.0); | |
| 1422 | ! | return transmittance[0]; |
| 1423 | } | |
| 1424 | ||
| 1425 | ! | double PragueSkyModel::interpolateTrans(const int visibilityIndex, |
| 1426 | const InterpolationParameter altitudeParam, | |
| 1427 | const TransmittanceParameters transParams, | |
| 1428 | const int channelIndex) const { | |
| 1429 | // Get transmittance for the nearest lower altitude. | |
| 1430 | ! | double trans = reconstructTrans(visibilityIndex, altitudeParam.index, transParams, channelIndex); |
| 1431 | ||
| 1432 | // Interpolate with transmittance for the nearest higher altitude if needed. | |
| 1433 | ! | if (altitudeParam.factor > 0.0) { |
| 1434 | const double transHigh = | |
| 1435 | ! | reconstructTrans(visibilityIndex, altitudeParam.index + 1, transParams, channelIndex); |
| 1436 | ! | trans = pragueLerp(trans, transHigh, altitudeParam.factor); |
| 1437 | } | |
| 1438 | ||
| 1439 | ! | return trans; |
| 1440 | } | |
| 1441 | ||
| 1442 | ! | double PragueSkyModel::transmittance(const Parameters& params, |
| 1443 | const double wavelength, | |
| 1444 | const double distance) const { | |
| 1445 | assert(distance > 0.0); | |
| 1446 | ||
| 1447 | ! | if (!initialized) { |
| 1448 | ! | throw NotInitializedException(); |
| 1449 | } | |
| 1450 | ||
| 1451 | // Ignore wavelengths outside the dataset range. | |
| 1452 | ! | if (wavelength < channelStart || wavelength >= (channelStart + channels * channelWidth)) { |
| 1453 | ! | return 0.0; |
| 1454 | } | |
| 1455 | // Don't interpolate wavelengths inside the dataset range. | |
| 1456 | ! | const int channelIndex = int(floor((wavelength - channelStart) / channelWidth)); |
| 1457 | ||
| 1458 | // Translate configuration values to indices and interpolation factors. | |
| 1459 | const InterpolationParameter visibilityParam = | |
| 1460 | ! | getInterpolationParameter(params.visibility, visibilitiesTrans); |
| 1461 | ! | const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesTrans); |
| 1462 | ||
| 1463 | // Calculate position in the atmosphere. | |
| 1464 | ! | const TransmittanceParameters transParams = toTransmittanceParams(params.theta, distance, params.altitude); |
| 1465 | ||
| 1466 | // Get transmittance for the nearest lower visibility. | |
| 1467 | ! | double trans = interpolateTrans(visibilityParam.index, altitudeParam, transParams, channelIndex); |
| 1468 | ||
| 1469 | // Interpolate with transmittance for the nearest higher visibility if needed. | |
| 1470 | ! | if (visibilityParam.factor > 0.0) { |
| 1471 | const double transHigh = | |
| 1472 | ! | interpolateTrans(visibilityParam.index + 1, altitudeParam, transParams, channelIndex); |
| 1473 | ||
| 1474 | ! | trans = pragueLerp(trans, transHigh, visibilityParam.factor); |
| 1475 | } | |
| 1476 | ||
| 1477 | // Transmittance is stored as a square root. Needs to be restored here. | |
| 1478 | ! | trans = trans * trans; |
| 1479 | assert(trans >= 0.0 && trans <= 1.0); | |
| 1480 | ||
| 1481 | ! | return trans; |
| 1482 | } | |
| 1483 | ||
| 1484 | // skymodelr: the geometry and interpolation coordinates do not depend on wavelength. | |
| 1485 | ! | void PragueSkyModel::transmittanceSpectrum(const Parameters& params, const double* wavelengths, |
| 1486 | size_t count, double distance, double* values) const { | |
| 1487 | assert(distance > 0.0); | |
| 1488 | ! | if (!initialized) throw NotInitializedException(); |
| 1489 | ! | const auto visibilityParam = getInterpolationParameter(params.visibility, visibilitiesTrans); |
| 1490 | ! | const auto altitudeParam = getInterpolationParameter(params.altitude, altitudesTrans); |
| 1491 | ! | const auto transParams = toTransmittanceParams(params.theta, distance, params.altitude); |
| 1492 | ! | for (size_t channel = 0; channel < count; ++channel) { |
| 1493 | ! | const double wavelength = wavelengths[channel]; |
| 1494 | ! | if (wavelength < channelStart || wavelength >= channelStart + channels * channelWidth) { |
| 1495 | ! | values[channel] = 0; |
| 1496 | ! | continue; |
| 1497 | } | |
| 1498 | ! | const int index = int(floor((wavelength - channelStart) / channelWidth)); |
| 1499 | ! | double trans = interpolateTrans(visibilityParam.index, altitudeParam, transParams, index); |
| 1500 | ! | if (visibilityParam.factor > 0.0) { |
| 1501 | ! | const double high = interpolateTrans(visibilityParam.index + 1, altitudeParam, transParams, index); |
| 1502 | ! | trans = pragueLerp(trans, high, visibilityParam.factor); |
| 1503 | } | |
| 1504 | ! | values[channel] = trans * trans; |
| 1505 | } | |
| 1506 | } | |
| 1507 | ||
| 1508 | ||
| 1509 | ||
| 1510 | } // namespace skymodelr_prague | |
| 1511 | ||
| 1512 | // Export the loaded visibility slice, not a second full dataset. Geometry and | |
| 1513 | // spectral reconstruction remain independent of renderer-specific RGB weights. | |
| 1514 | ! | void skymodelr_prague::PragueSkyModel::exportMetal(skymodelr_prague_gpu_layout &out, |
| 1515 | std::vector<float> &packed) const { | |
| 1516 | ! | if (!initialized) throw NotInitializedException(); |
| 1517 | ! | out = {}; |
| 1518 | // The radiance slice can exceed a gigabyte. Reserve its exact packed size | |
| 1519 | // once rather than briefly holding two copies during vector growth. | |
| 1520 | ! | size_t count = 0; |
| 1521 | ! | for (size_t size : {visibilitiesRad.size(), albedosRad.size(), altitudesRad.size(), |
| 1522 | ! | elevationsRad.size(), metadataRad.sunBreaks.size(), metadataRad.zenithBreaks.size(), |
| 1523 | ! | metadataRad.emphBreaks.size(), altitudesTrans.size(), visibilitiesTrans.size(), |
| 1524 | ! | std::size(SUN_RAD_TABLE), dataRad.size(), dataTransU.size(), dataTransV.size()}) { |
| 1525 | ! | if (size > UINT32_MAX - count) |
| 1526 | ! | throw std::runtime_error("Prague Metal coefficient buffer exceeds 32-bit addressing."); |
| 1527 | ! | count += size; |
| 1528 | } | |
| 1529 | ! | packed.reserve(count); |
| 1530 | ! | auto append = [&](const auto &values) { |
| 1531 | ! | if (values.size() > UINT32_MAX - packed.size()) |
| 1532 | ! | throw std::runtime_error("Prague Metal coefficient buffer exceeds 32-bit addressing."); |
| 1533 | ! | skymodelr_prague_gpu_axis axis{uint32_t(packed.size()), uint32_t(values.size())}; |
| 1534 | ! | packed.insert(packed.end(), values.begin(), values.end()); |
| 1535 | ! | return axis; |
| 1536 | }; | |
| 1537 | ! | out.visibility=append(visibilitiesRad); out.albedo=append(albedosRad); |
| 1538 | ! | out.altitude=append(altitudesRad); out.elevation=append(elevationsRad); |
| 1539 | ! | out.gamma=append(metadataRad.sunBreaks); out.alpha=append(metadataRad.zenithBreaks); |
| 1540 | ! | out.emphasis=append(metadataRad.emphBreaks); |
| 1541 | ! | out.trans_altitude=append(altitudesTrans); out.trans_visibility=append(visibilitiesTrans); |
| 1542 | ! | out.sun=append(std::vector<double>(std::begin(SUN_RAD_TABLE),std::end(SUN_RAD_TABLE))); |
| 1543 | ! | out.radiance=append(dataRad).offset; out.trans_u=append(dataTransU).offset; |
| 1544 | ! | out.trans_v=append(dataTransV).offset; |
| 1545 | ! | out.rank=metadataRad.rank; out.sun_offset=metadataRad.sunOffset; out.sun_stride=metadataRad.sunStride; |
| 1546 | ! | out.zenith_offset=metadataRad.zenithOffset; out.zenith_stride=metadataRad.zenithStride; |
| 1547 | ! | out.emphasis_offset=metadataRad.emphOffset; out.config_stride=metadataRad.totalCoefsSingleConfig; |
| 1548 | ! | out.trans_rank=rankTrans; out.a_dim=aDim; out.d_dim=dDim; out.channels=channels; |
| 1549 | ! | out.channel_start=channelStart; out.channel_width=channelWidth; |
| 1550 | } |
| 1 | #include <Rcpp.h> | |
| 2 | ||
| 3 | #include "CIE1931Data.h" | |
| 4 | #include "hosek/cie.h" | |
| 5 | #include "math/units.h" | |
| 6 | ||
| 7 | #include <algorithm> | |
| 8 | #include <cctype> | |
| 9 | #include <cmath> | |
| 10 | #include <string> | |
| 11 | ||
| 12 | 44x | static inline std::string to_lower(std::string value) { |
| 13 | 44x | std::transform(value.begin(), value.end(), value.begin(), |
| 14 | 264x | [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); |
| 15 | 44x | return value; |
| 16 | } | |
| 17 | ||
| 18 | 20724x | static inline double spd_blackbody(double lambda_nm, double temperature_k) { |
| 19 | 20724x | const double lambda_m = lambda_nm * 1e-9; |
| 20 | 20724x | const double c2 = 1.4387769e-2; // hc/k |
| 21 | 20724x | const double expo = c2 / (lambda_m * temperature_k); |
| 22 | 20724x | const double denom = std::exp(expo) - 1.0; |
| 23 | 20724x | if (!std::isfinite(denom) || denom <= 0.0) { |
| 24 | ! | return 0.0; |
| 25 | } | |
| 26 | 20724x | return 1.0 / (std::pow(lambda_m, 5.0) * denom); |
| 27 | } | |
| 28 | ||
| 29 | ! | static inline double spd_d65(double lambda_nm) { |
| 30 | ! | constexpr double x_d = 0.31271; |
| 31 | ! | constexpr double y_d = 0.32902; |
| 32 | ! | const double denom = 0.0241 + 0.2562 * x_d - 0.7341 * y_d; |
| 33 | ! | const double m1 = (-1.3515 - 1.7703 * x_d + 5.9114 * y_d) / denom; |
| 34 | ! | const double m2 = (0.03 - 31.4424 * x_d + 30.0717 * y_d) / denom; |
| 35 | ! | const auto &s0 = S0_function(); |
| 36 | ! | const auto &s1 = S1_function(); |
| 37 | ! | const auto &s2 = S2_function(); |
| 38 | ! | const auto wl = lambda_nm * nm; |
| 39 | ! | const double s0_val = s0(wl)(); |
| 40 | ! | const double s1_val = s1(wl)(); |
| 41 | ! | const double s2_val = s2(wl)(); |
| 42 | ! | return s0_val + m1 * s1_val + m2 * s2_val; |
| 43 | } | |
| 44 | ||
| 45 | // [[Rcpp::export]] | |
| 46 | 46x | Rcpp::List cie_1931_2deg_rcpp() { |
| 47 | 46x | Rcpp::NumericVector lambda_nm(CIE_N); |
| 48 | 46x | Rcpp::NumericVector x_bar(CIE_N); |
| 49 | 46x | Rcpp::NumericVector y_bar(CIE_N); |
| 50 | 46x | Rcpp::NumericVector z_bar(CIE_N); |
| 51 | 21712x | for (int i = 0; i < CIE_N; ++i) { |
| 52 | 21666x | lambda_nm[i] = cie_lambda_nm[i]; |
| 53 | 21666x | x_bar[i] = cie_xbar[i]; |
| 54 | 21666x | y_bar[i] = cie_ybar[i]; |
| 55 | 21666x | z_bar[i] = cie_zbar[i]; |
| 56 | } | |
| 57 | return Rcpp::List::create( | |
| 58 | 92x | Rcpp::Named("lambda_nm") = lambda_nm, |
| 59 | 92x | Rcpp::Named("x_bar") = x_bar, |
| 60 | 92x | Rcpp::Named("y_bar") = y_bar, |
| 61 | 92x | Rcpp::Named("z_bar") = z_bar |
| 62 | ); | |
| 63 | } | |
| 64 | ||
| 65 | // [[Rcpp::export]] | |
| 66 | 44x | Rcpp::NumericVector spd_values_rcpp(Rcpp::NumericVector lambda_nm, |
| 67 | std::string spd_type = "D65") { | |
| 68 | 44x | const std::string key = to_lower(spd_type); |
| 69 | 44x | Rcpp::NumericVector spd(lambda_nm.size()); |
| 70 | 44x | if (key == "d65") { |
| 71 | ! | for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) { |
| 72 | ! | spd[i] = spd_d65(lambda_nm[i]); |
| 73 | } | |
| 74 | 44x | } else if (key == "bb5778") { |
| 75 | 20768x | for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) { |
| 76 | 20724x | spd[i] = spd_blackbody(lambda_nm[i], 5778.0); |
| 77 | } | |
| 78 | } else { | |
| 79 | ! | Rcpp::stop("Unknown spd_type \"%s\"", spd_type.c_str()); |
| 80 | } | |
| 81 | 44x | return spd; |
| 82 | } |
| 1 | // [[Rcpp::plugins(cpp17)]] | |
| 2 | #include <Rcpp.h> | |
| 3 | #include <RcppThread.h> | |
| 4 | #include <algorithm> | |
| 5 | #include <mutex> | |
| 6 | #include <cmath> | |
| 7 | #include <vector> | |
| 8 | ||
| 9 | #include "CIE1931Data.h" | |
| 10 | ||
| 11 | // Photometric illuminance (lux) from V-band magnitude. | |
| 12 | 4573x | inline double mag_to_illuminance_lux(double Vmagnitude, |
| 13 | double zeroPoint = 1.0) { | |
| 14 | 4573x | return zeroPoint * std::pow(10.0, (-14.18 - Vmagnitude)/2.5); |
| 15 | } | |
| 16 | ||
| 17 | 4557x | static inline double bv_to_temperature_K(double bv) { |
| 18 | 4557x | if (!std::isfinite(bv)) return 5778.0; |
| 19 | 4557x | const double bv_clamped = std::clamp(bv, -0.4, 2.0); |
| 20 | 4557x | const double t = 4600.0 * (1.0 / (0.92 * bv_clamped + 1.7) + |
| 21 | 4557x | 1.0 / (0.92 * bv_clamped + 0.62)); |
| 22 | 4557x | return std::clamp(t, 1000.0, 40000.0); |
| 23 | } | |
| 24 | ||
| 25 | 2153883x | static inline double blackbody_spd(double lambda_nm, double temperature_k) { |
| 26 | 2153883x | const double lambda_m = lambda_nm * 1e-9; |
| 27 | 2153883x | const double c2 = 1.4387769e-2; // hc/k |
| 28 | 2153883x | const double expo = c2 / (lambda_m * temperature_k); |
| 29 | 2153883x | const double denom = std::exp(expo) - 1.0; |
| 30 | 2153883x | if (!std::isfinite(denom) || denom <= 0.0) return 0.0; |
| 31 | 2153883x | return 1.0 / (std::pow(lambda_m, 5.0) * denom); |
| 32 | } | |
| 33 | ||
| 34 | 4573x | static inline const std::vector<double>& cie_weights() { |
| 35 | 4573x | static std::vector<double> weights; |
| 36 | 4573x | if (!weights.empty()) return weights; |
| 37 | 1x | weights.resize(CIE_N, 0.0); |
| 38 | 472x | for (int i = 0; i < CIE_N; ++i) { |
| 39 | 471x | if (i == 0) { |
| 40 | 1x | weights[i] = (cie_lambda_nm[i + 1] - cie_lambda_nm[i]) / 2.0; |
| 41 | 470x | } else if (i == CIE_N - 1) { |
| 42 | 1x | weights[i] = (cie_lambda_nm[i] - cie_lambda_nm[i - 1]) / 2.0; |
| 43 | } else { | |
| 44 | 469x | weights[i] = (cie_lambda_nm[i + 1] - cie_lambda_nm[i - 1]) / 2.0; |
| 45 | } | |
| 46 | } | |
| 47 | 1x | return weights; |
| 48 | } | |
| 49 | ||
| 50 | 4573x | static inline void xyz_to_srgb(double X, double Y, double Z, |
| 51 | double& R, double& G, double& B) { | |
| 52 | const double M[9] = { | |
| 53 | 3.2404542, -1.5371385, -0.4985314, | |
| 54 | -0.9692660, 1.8760108, 0.0415560, | |
| 55 | 0.0556434, -0.2040259, 1.0572252 | |
| 56 | }; | |
| 57 | 4573x | R = M[0]*X + M[1]*Y + M[2]*Z; |
| 58 | 4573x | G = M[3]*X + M[4]*Y + M[5]*Z; |
| 59 | 4573x | B = M[6]*X + M[7]*Y + M[8]*Z; |
| 60 | } | |
| 61 | ||
| 62 | 4573x | static inline void blackbody_rgb_unit(double temperature_k, |
| 63 | double& K_eff, | |
| 64 | double& R, double& G, double& B) { | |
| 65 | 4573x | const auto& w = cie_weights(); |
| 66 | 4573x | double sum_spd = 0.0; |
| 67 | 4573x | double sum_v = 0.0; |
| 68 | 4573x | double X = 0.0; |
| 69 | 4573x | double Y = 0.0; |
| 70 | 4573x | double Z = 0.0; |
| 71 | 2158456x | for (int i = 0; i < CIE_N; ++i) { |
| 72 | 2153883x | const double spd = blackbody_spd(cie_lambda_nm[i], temperature_k); |
| 73 | 2153883x | const double wi = w[i]; |
| 74 | 2153883x | sum_spd += spd * wi; |
| 75 | 2153883x | sum_v += spd * cie_ybar[i] * wi; |
| 76 | 2153883x | X += spd * cie_xbar[i] * wi; |
| 77 | 2153883x | Y += spd * cie_ybar[i] * wi; |
| 78 | 2153883x | Z += spd * cie_zbar[i] * wi; |
| 79 | } | |
| 80 | 4573x | if (sum_spd > 0.0 && std::isfinite(sum_spd)) { |
| 81 | 4573x | K_eff = 683.0 * sum_v / sum_spd; |
| 82 | } else { | |
| 83 | ! | K_eff = 0.0; |
| 84 | } | |
| 85 | 4573x | xyz_to_srgb(X, Y, Z, R, G, B); |
| 86 | 4573x | if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) { |
| 87 | ! | R = 0.0; |
| 88 | ! | G = 0.0; |
| 89 | ! | B = 0.0; |
| 90 | } | |
| 91 | 4573x | R = std::max(R, 0.0); |
| 92 | 4573x | G = std::max(G, 0.0); |
| 93 | 4573x | B = std::max(B, 0.0); |
| 94 | 4573x | const double sum_rgb = R + G + B; |
| 95 | 4573x | if (sum_rgb > 0.0 && std::isfinite(sum_rgb)) { |
| 96 | 4573x | R /= sum_rgb; |
| 97 | 4573x | G /= sum_rgb; |
| 98 | 4573x | B /= sum_rgb; |
| 99 | } else { | |
| 100 | ! | R = G = B = 1.0 / 3.0; |
| 101 | } | |
| 102 | } | |
| 103 | ||
| 104 | ||
| 105 | 114325x | static inline int wrap_col(int x, int W) { |
| 106 | 114325x | int r = x % W; return r < 0 ? r + W : r; |
| 107 | } | |
| 108 | ||
| 109 | 3x | static inline double jd_to_gmst(double jd) |
| 110 | { | |
| 111 | 3x | double d = jd - 2451545.0; // days since J2000 |
| 112 | 3x | double t = d / 36525.0; // Julian centuries |
| 113 | 3x | double gmst = |
| 114 | 3x | 280.46061837 + 360.98564736629 * d + |
| 115 | 3x | 0.000387933 * t * t - t * t * t / 38710000.0; // IAU 2006 |
| 116 | 3x | gmst = fmod(gmst, 360.0); |
| 117 | 3x | if (gmst < 0) gmst += 360.0; |
| 118 | 3x | return gmst * M_PI / 180.0; // rad |
| 119 | } | |
| 120 | ||
| 121 | // [[Rcpp::export]] | |
| 122 | 3x | Rcpp::NumericVector make_starfield_rcpp(Rcpp::DataFrame stars, |
| 123 | unsigned int resolution = 2048, | |
| 124 | double zero_point = 1.0, | |
| 125 | double lon_deg = 0.0, | |
| 126 | double lat_deg = 0.0, | |
| 127 | double jd = 2451545.0, // Julian Date of the frame (UTC noon 1 Jan 2000 = 2451545.0) | |
| 128 | double turbidity = 3.0, | |
| 129 | double ozone_du = 300.0, | |
| 130 | double altitude = 0.0, | |
| 131 | double star_width = 1.0, | |
| 132 | bool use_rgb = true, | |
| 133 | bool atmosphere_effects = true, | |
| 134 | bool upper_hemisphere_only = true, | |
| 135 | unsigned int number_cores = 1) | |
| 136 | { | |
| 137 | 3x | if (resolution == 0) Rcpp::stop("resolution must be greater than or equal to 1"); |
| 138 | 3x | if(!upper_hemisphere_only & atmosphere_effects) { |
| 139 | ! | atmosphere_effects = false; |
| 140 | ! | Rcpp::message(Rcpp::CharacterVector("When rendering full sphere (`upper_hemisphere_only = false`), atmosphere effects are not rendered (setting `atmosphere_effects = false`)")); |
| 141 | } | |
| 142 | 3x | const int nTheta = resolution; // rows (latitude) |
| 143 | 3x | const int nPhi = 2 * resolution; // cols (longitude) |
| 144 | 3x | const int nPix = nTheta * nPhi; |
| 145 | 3x | const double dtheta = M_PI / double(nTheta); |
| 146 | 3x | const double dphi = 2.0 * M_PI / double(nPhi); |
| 147 | ||
| 148 | 22865x | auto omega_row = [&](int t) { |
| 149 | 22865x | double theta_c = (double(t) + 0.5) * dtheta; |
| 150 | 22865x | double s = std::sin(theta_c); |
| 151 | 22865x | if (s < 1e-8) s = 1e-8; |
| 152 | 22865x | return dtheta * dphi * s; |
| 153 | }; | |
| 154 | ||
| 155 | 3x | std::vector<double> img(3 * nPix, 0.0); |
| 156 | ||
| 157 | // pull columns out of the data frame | |
| 158 | 6x | Rcpp::NumericVector ra = stars["ra_rad"]; |
| 159 | 6x | Rcpp::NumericVector dec = stars["dec_rad"]; |
| 160 | 6x | Rcpp::NumericVector mag = stars["v_mag"]; |
| 161 | 6x | Rcpp::NumericVector r_vec = stars["r"]; |
| 162 | 6x | Rcpp::NumericVector g_vec = stars["g"]; |
| 163 | 6x | Rcpp::NumericVector b_vec = stars["b"]; |
| 164 | 3x | const bool has_bv = stars.containsElementNamed("b_v"); |
| 165 | 3x | Rcpp::NumericVector bv_vec; |
| 166 | 3x | if (has_bv) { |
| 167 | 9x | bv_vec = stars["b_v"]; |
| 168 | } | |
| 169 | ||
| 170 | 3x | const std::size_t N = ra.size(); |
| 171 | ||
| 172 | 3x | double psf_fwhm_pix = star_width; |
| 173 | 3x | double psf_trunc_sigma = 3.0; // truncate at 3 sigma |
| 174 | ||
| 175 | 3x | double gmst_rad = jd_to_gmst(jd); |
| 176 | 3x | double lst_rad = gmst_rad + lon_deg * M_PI / 180.0; |
| 177 | 3x | double sin_lat = std::sin(lat_deg * M_PI / 180.0); |
| 178 | 3x | double cos_lat = std::cos(lat_deg * M_PI / 180.0); |
| 179 | 3x | std::vector<std::mutex> row_locks(nTheta); |
| 180 | ||
| 181 | // parallelise over stars | |
| 182 | 3x | RcppThread::parallelFor(0u, (unsigned)N, [&](unsigned i) |
| 183 | { | |
| 184 | 9112x | double ha = lst_rad - ra[i]; |
| 185 | ||
| 186 | 9112x | double sin_alt = std::sin(dec[i]) * sin_lat + |
| 187 | 9112x | std::cos(dec[i]) * cos_lat * std::cos(ha); |
| 188 | 9112x | double alt_rad = std::asin( std::clamp(sin_alt, -1.0, 1.0) ); |
| 189 | 9112x | double cos_alt = std::cos(alt_rad); |
| 190 | ||
| 191 | 9112x | if(cos_alt < 1e-6) cos_alt = 1e-6; |
| 192 | ||
| 193 | 9112x | double sin_az = std::cos(dec[i]) * std::sin(ha) / cos_alt; |
| 194 | 9112x | double cos_az = (std::sin(dec[i]) * cos_lat - |
| 195 | 9112x | std::cos(dec[i]) * std::cos(ha) * sin_lat) / cos_alt; |
| 196 | ||
| 197 | 9112x | double x_h = -cos_alt * cos_az; |
| 198 | 9112x | double y_h = sin_alt; |
| 199 | 9112x | double z_h = -cos_alt * sin_az; |
| 200 | ||
| 201 | //map to lat/long image | |
| 202 | 9112x | double theta = std::acos(std::clamp(y_h, -1.0, 1.0)); |
| 203 | 9112x | double phi = std::atan2(-z_h, x_h); |
| 204 | 9112x | if (phi < 0.0) phi += 2.0 * M_PI; |
| 205 | ||
| 206 | 9112x | double phi_img = phi + M_PI; |
| 207 | 9112x | if (phi_img >= 2.0 * M_PI) phi_img -= 2.0 * M_PI; |
| 208 | ||
| 209 | 9112x | double r = 1.0, g = 1.0, b = 1.0; |
| 210 | 9112x | if(use_rgb) { |
| 211 | 9112x | r = r_vec[i]; |
| 212 | 9112x | g = g_vec[i]; |
| 213 | 9112x | b = b_vec[i]; |
| 214 | } | |
| 215 | ||
| 216 | 9112x | double T_r = 1.0, T_g = 1.0, T_b = 1.0; |
| 217 | 9112x | constexpr double tauR[9] = {0.00835,0.00673,0.00595,0.01750,0.01350, |
| 218 | 0.01100,0.02690,0.02050,0.01880}; | |
| 219 | 9112x | constexpr double tauM0[9]= {0.00220,0.00190,0.00175,0.00300,0.00265, |
| 220 | 0.00245,0.00360,0.00320,0.00310}; | |
| 221 | 9112x | constexpr double tauO[9] = {0.0030,0.0048,0.0060,0.0014,0.0010, |
| 222 | 0.0009,0.0006,0.0007,0.0008}; | |
| 223 | 9112x | if (theta < M_PI_2) { // above horizon only |
| 224 | // ---------- airmass m(theta) ----------------------------------------- | |
| 225 | 4573x | double secz = 1.0 / std::max(1e-6, std::cos(theta)); |
| 226 | double m = secz < 12.0 | |
| 227 | 4573x | ? secz - 0.001816*pow(secz-1,1) |
| 228 | 4181x | - 0.002875*pow(secz-1,2) |
| 229 | 4181x | - 0.000808*pow(secz-1,3) |
| 230 | 4573x | : secz; |
| 231 | ||
| 232 | // density scale with observer altitude | |
| 233 | 4573x | double rho = std::exp(-altitude / 8000.0); // rho/rho0 (simple barometric) |
| 234 | ||
| 235 | // coefficient scalers | |
| 236 | 4573x | double kR = rho; // Rayleigh air density |
| 237 | 4573x | double kM = rho * (turbidity - 1.0); // Mie 0 at T=1 |
| 238 | 4573x | double kO = ozone_du / 300.0; // 1.0 at 300 DU |
| 239 | ||
| 240 | double T_band[9]; | |
| 241 | 45730x | for (int c=0; c<9; ++c) { |
| 242 | 41157x | T_band[c] = std::exp( -(kR*tauR[c] + kM*tauM0[c] + kO*tauO[c]) * m ); |
| 243 | } | |
| 244 | 4573x | T_r = (T_band[0] + T_band[1] + T_band[2]) / 3.0; |
| 245 | 4573x | T_g = (T_band[3] + T_band[4] + T_band[5]) / 3.0; |
| 246 | 4573x | T_b = (T_band[6] + T_band[7] + T_band[8]) / 3.0; |
| 247 | } else { | |
| 248 | 4539x | T_r = T_g = T_b = 0.0; // star is below horizon |
| 249 | } | |
| 250 | ||
| 251 | 9112x | if(!upper_hemisphere_only) { |
| 252 | 2x | T_r = T_g = T_b = 1.0; |
| 253 | } | |
| 254 | ||
| 255 | 9112x | if (T_r==0.0 && T_g==0.0 && T_b==0.0) return; |
| 256 | ||
| 257 | // ----- continuous image coords ----- | |
| 258 | 4573x | double u = (phi_img / (2.0 * M_PI)) * nPhi; // column in [0, nPhi) |
| 259 | 4573x | double v = (theta / M_PI) * nTheta; // row in [0, nTheta) |
| 260 | ||
| 261 | // avoid rare u == nPhi or v == nTheta due to floating point | |
| 262 | 4573x | if (u >= nPhi) u = std::nextafter((double)nPhi, 0.0); |
| 263 | 4573x | if (v >= nTheta) v = std::nextafter((double)nTheta, 0.0); |
| 264 | ||
| 265 | // subpixel center and integer anchors | |
| 266 | 4573x | int p0 = (int)std::floor(u); |
| 267 | 4573x | int t0 = (int)std::floor(v); |
| 268 | ||
| 269 | // PSF parameters | |
| 270 | 4573x | double sigma = psf_fwhm_pix / 2.355; // FWHM -> sigma |
| 271 | 4573x | int rad = (int)std::ceil(psf_trunc_sigma * sigma); |
| 272 | 4573x | double inv_2s2 = 1.0 / (2.0 * sigma * sigma); |
| 273 | ||
| 274 | // Pre-compute 1D weights using distance from the pixel center (p + 0.5, t + 0.5) | |
| 275 | 13719x | std::vector<double> wx(2*rad + 1), wy(2*rad + 1); |
| 276 | ||
| 277 | 27438x | for (int dx = -rad; dx <= rad; ++dx) { |
| 278 | 22865x | double px_center = (p0 + dx) + 0.5; |
| 279 | 22865x | double ddx = px_center - u; // subpixel offset in x |
| 280 | 22865x | double w = std::exp(-ddx*ddx * inv_2s2); |
| 281 | 22865x | wx[dx + rad] = w; |
| 282 | } | |
| 283 | 27438x | for (int dy = -rad; dy <= rad; ++dy) { |
| 284 | 22865x | int ty = std::clamp(t0 + dy, 0, nTheta - 1); |
| 285 | 22865x | double py_center = ty + 0.5; |
| 286 | 22865x | double ddy = py_center - v; // subpixel offset in y |
| 287 | 22865x | double w = std::exp(-ddy*ddy * inv_2s2); |
| 288 | 22865x | wy[dy + rad] = w; |
| 289 | } | |
| 290 | ||
| 291 | // Previous norm was image-space only; now include solid angle for env-map consistency | |
| 292 | 4573x | double norm = 0.0; |
| 293 | 27438x | for (int dy = -rad; dy <= rad; ++dy) { |
| 294 | 22865x | int t = std::clamp(t0 + dy, 0, nTheta - 1); |
| 295 | 22865x | double wyj = wy[dy + rad]; |
| 296 | 22865x | double omega = omega_row(t); |
| 297 | 137190x | for (int dx = -rad; dx <= rad; ++dx) { |
| 298 | 114325x | double w = wyj * wx[dx + rad]; |
| 299 | 114325x | norm += w * omega; |
| 300 | } | |
| 301 | } | |
| 302 | 4573x | if (norm <= 0.0) return; |
| 303 | ||
| 304 | // Star radiance in channels (radiometric; RGB unit sums to 1) | |
| 305 | 4573x | double temperature_k = 5778.0; |
| 306 | 4573x | if (has_bv && std::isfinite(bv_vec[i])) { |
| 307 | 4557x | temperature_k = bv_to_temperature_K(bv_vec[i]); |
| 308 | } | |
| 309 | 4573x | double K_eff = 0.0; |
| 310 | 4573x | double r_unit = 0.0, g_unit = 0.0, b_unit = 0.0; |
| 311 | 4573x | blackbody_rgb_unit(temperature_k, K_eff, r_unit, g_unit, b_unit); |
| 312 | 4573x | if (use_rgb && (!has_bv || !std::isfinite(bv_vec[i]))) { |
| 313 | 16x | const double sum_rgb = r + g + b; |
| 314 | 16x | if (sum_rgb > 0.0 && std::isfinite(sum_rgb)) { |
| 315 | 16x | r_unit = r / sum_rgb; |
| 316 | 16x | g_unit = g / sum_rgb; |
| 317 | 16x | b_unit = b / sum_rgb; |
| 318 | } | |
| 319 | } | |
| 320 | 4573x | if (!use_rgb) { |
| 321 | ! | r_unit = g_unit = b_unit = 1.0 / 3.0; |
| 322 | } | |
| 323 | 4573x | if (K_eff <= 0.0 || !std::isfinite(K_eff)) return; |
| 324 | 4573x | double E_v = mag_to_illuminance_lux(mag[i], double(zero_point)); |
| 325 | 4573x | double E_e = E_v / K_eff; |
| 326 | 4573x | if (E_e <= 0.0 || !std::isfinite(E_e)) return; |
| 327 | 4573x | double R0 = E_e * r_unit * T_r / norm; |
| 328 | 4573x | double G0 = E_e * g_unit * T_g / norm; |
| 329 | 4573x | double B0 = E_e * b_unit * T_b / norm; |
| 330 | ||
| 331 | // ----- accumulate with row locks (one lock per affected row) ----- | |
| 332 | 27438x | for (int dy = -rad; dy <= rad; ++dy) { |
| 333 | 22865x | int t = std::clamp(t0 + dy, 0, nTheta - 1); |
| 334 | 22865x | double wyj = wy[dy + rad]; |
| 335 | ||
| 336 | // lock the row once; update all columns for this row | |
| 337 | { | |
| 338 | 22865x | std::scoped_lock lock(row_locks[t]); |
| 339 | 22865x | std::size_t base = 3ULL * ( (std::size_t)t * (std::size_t)nPhi ); |
| 340 | ||
| 341 | 137190x | for (int dx = -rad; dx <= rad; ++dx) { |
| 342 | 114325x | int p = wrap_col(p0 + dx, nPhi); |
| 343 | 114325x | double w = wyj * wx[dx + rad]; // separable Gaussian |
| 344 | ||
| 345 | 114325x | std::size_t idx = base + 3ULL * (std::size_t)p; |
| 346 | 114325x | img[idx ] += double(w * R0); |
| 347 | 114325x | img[idx + 1] += double(w * G0); |
| 348 | 114325x | img[idx + 2] += double(w * B0); |
| 349 | } | |
| 350 | } | |
| 351 | } | |
| 352 | 4573x | }, number_cores); |
| 353 | ||
| 354 | 3x | Rcpp::NumericVector result(nPix * 3); |
| 355 | 9x | result.attr("dim") = Rcpp::IntegerVector::create(nTheta, nPhi, 3); |
| 356 | ||
| 357 | 203x | for (int t = 0; t < nTheta; ++t) { |
| 358 | 41288x | for (int p = 0; p < nPhi; ++p) { |
| 359 | 41088x | const int pix_index = t * nPhi + p; |
| 360 | 164352x | for (int c = 0; c < 3; ++c) { |
| 361 | 123264x | const int arr_index = t + nTheta * (p + nPhi * c); |
| 362 | 123264x | result[arr_index] = img[3 * pix_index + c]; |
| 363 | } | |
| 364 | } | |
| 365 | } | |
| 366 | ||
| 367 | 3x | return result; |
| 368 | } |