Instrument Neutral Distributed Interface INDI 2.2.5
sky_renderer.cpp
Go to the documentation of this file.
1#include "sky_renderer.h"
2#include "indicom.h"
3#include "locale_compat.h"
4
5#include <algorithm>
6#include <cmath>
7#include <cstdio>
8#include <cstring>
9#include <random>
10#include <unordered_set>
11
12double SkyRenderer::flux(double mag) const
13{
14 if (m_Cfg.limitingMag == m_Cfg.saturationMag)
15 return 1.0;
16 double const z = m_Cfg.limitingMag;
17 double const k = 2.5 * log10(m_Cfg.maxVal) / (m_Cfg.limitingMag - m_Cfg.saturationMag);
18 return pow(10.0, (z - mag) * k / 2.5);
19}
20
21int SkyRenderer::addToPixel(INDI::CCDChip *chip, int x, int y, int val)
22{
23 int const nwidth = chip->getSubW();
24 int const nheight = chip->getSubH();
25
26 x -= chip->getSubX();
27 y -= chip->getSubY();
28
29 if (x < 0 || x >= nwidth || y < 0 || y >= nheight)
30 return 0;
31
32 auto *pt = reinterpret_cast<uint16_t *>(chip->getFrameBuffer());
33 pt += y * nwidth + x;
34
35 int newval = static_cast<int>(pt[0]) + val;
36 if (newval > m_Cfg.maxVal)
37 newval = m_Cfg.maxVal;
38 if (newval > m_MaxPix)
39 m_MaxPix = newval;
40 if (newval < m_MinPix)
41 m_MinPix = newval;
42 pt[0] = static_cast<uint16_t>(newval);
43
44 return 1;
45}
46
47int SkyRenderer::drawImageStar(INDI::CCDChip *chip, float mag, float x, float y, float exp_s)
48{
49 int drew = 0;
50
51 int const subX = chip->getSubX();
52 int const subY = chip->getSubY();
53 int const subW = chip->getSubW() + subX;
54 int const subH = chip->getSubH() + subY;
55
56 if (x < subX || x > subW || y < subY || y > subH)
57 return 0;
58
59 float const totalFlux = static_cast<float>(flux(mag) * exp_s);
60
61 // Compute position-dependent seeing to simulate sensor tilt.
62 // Instead of a global seeing, compute per-star seeing by shifting the
63 // effective focus position based on star location on the sensor.
64 // This causes each tile's V-curve minimum to land at a different focuser
65 // position — which is exactly what the Aberration Inspector detects as tilt.
66 float effectiveSeeing = m_Cfg.seeing;
67 if (m_Cfg.tiltLR != 0.0f || m_Cfg.tiltTB != 0.0f)
68 {
69 float const cx = chip->getXRes() / 2.0f;
70 float const cy = chip->getYRes() / 2.0f;
71 float const dx = (x - cx) / cx; // normalized [-1, +1]
72 float const dy = (y - cy) / cy;
73 // tiltLR/tiltTB in arcsec: directly added to seeing at that position.
74 // This shifts where the V-curve minimum occurs for edge tiles vs center.
75 float const tiltOffset = m_Cfg.tiltLR * dx + m_Cfg.tiltTB * dy;
76 effectiveSeeing += tiltOffset;
77 if (effectiveSeeing < 0.5f)
78 effectiveSeeing = 0.5f; // Floor to prevent degenerate PSF
79 }
80
81 int const boxsizey = static_cast<int>(3.0f * effectiveSeeing / m_ImageScaleY) + 1;
82
83 float const sigma = effectiveSeeing / (2.0f * std::sqrt(2.0f * std::log(2.0f)));
84 float const norm = 1.0f / (sigma * std::sqrt(2.0f * float(M_PI)));
85 float const inv2sig2 = 1.0f / (2.0f * sigma * sigma);
86
87 // Sub-pixel centering: keep the fractional part of the star position so the
88 // PSF is centred on the true (floating-point) location rather than snapped to
89 // the truncated integer pixel. Without this, sub-pixel drift is discarded and
90 // the measured centroid quantises to a lattice (see indilib/indi#2465).
91 float const fracX = x - static_cast<int>(x);
92 float const fracY = y - static_cast<int>(y);
93
94 for (int sy = -boxsizey; sy <= boxsizey; sy++)
95 {
96 for (int sx = -boxsizey; sx <= boxsizey; sx++)
97 {
98 float const ddx = m_ImageScaleX * (sx - fracX);
99 float const ddy = m_ImageScaleY * (sy - fracY);
100 float const dc2 = ddx * ddx + ddy * ddy;
101 float const fa = norm * std::exp(-dc2 * inv2sig2);
102 int const fp = static_cast<int>(fa * totalFlux);
103 if (fp > 0)
104 {
105 if (addToPixel(chip,
106 static_cast<int>(x) + sx,
107 static_cast<int>(y) + sy, fp) != 0)
108 drew = 1;
109 }
110 }
111 }
112 return drew;
113}
114
115void SkyRenderer::applyReadoutNoise(INDI::CCDChip *chip, int bias, int maxNoise)
116{
117 if (maxNoise <= 0)
118 return;
119
120 int const nx = chip->getSubW();
121 int const ny = chip->getSubH();
122 auto *buf = reinterpret_cast<uint16_t *>(chip->getFrameBuffer());
123
124 for (int y = 0; y < ny; y++)
125 for (int x = 0; x < nx; x++)
126 {
127 int newval = static_cast<int>(buf[y * nx + x]) + bias + (random() % maxNoise);
128 if (newval > m_Cfg.maxVal)
129 newval = m_Cfg.maxVal;
130 buf[y * nx + x] = static_cast<uint16_t>(newval);
131 }
132}
133
134std::vector<SensorDefect> SkyRenderer::generateDefects(int xres, int yres, int hotCount, int coldCount,
135 float hotRate, uint32_t seed)
136{
137 std::vector<SensorDefect> defects;
138 if (xres <= 0 || yres <= 0)
139 return defects;
140
141 uint64_t const total = static_cast<uint64_t>(xres) * yres;
142 hotCount = std::max(0, hotCount);
143 coldCount = std::max(0, coldCount);
144 if (static_cast<uint64_t>(hotCount) + coldCount > total)
145 {
146 hotCount = static_cast<int>(std::min<uint64_t>(hotCount, total));
147 coldCount = static_cast<int>(total - hotCount);
148 }
149
150 // std::mt19937 output is fully specified by the standard, unlike the std:: distributions, so the
151 // layout is the same with every standard library.
152 std::mt19937 rng(seed);
153 std::unordered_set<uint64_t> used;
154 defects.reserve(hotCount + coldCount);
155
156 auto const pickFree = [&]()
157 {
158 uint64_t index;
159 do
160 {
161 // Two statements: the evaluation order of operands within one expression is unspecified.
162 uint64_t const high = rng();
163 uint64_t const low = rng();
164 index = ((high << 32) | low) % total;
165 }
166 while (!used.insert(index).second);
167 return index;
168 };
169
170 for (int i = 0; i < hotCount + coldCount; i++)
171 {
172 uint64_t const index = pickFree();
173 SensorDefect defect;
174 defect.x = static_cast<int>(index % xres);
175 defect.y = static_cast<int>(index / xres);
176 defect.cold = (i >= hotCount);
177 if (!defect.cold)
178 defect.rate = hotRate * (0.5f + static_cast<float>(rng()) / 4294967296.0f);
179 defects.push_back(defect);
180 }
181
182 return defects;
183}
184
185void SkyRenderer::applyDefects(INDI::CCDChip *chip, const std::vector<SensorDefect> &defects, float exposure_s,
186 int bias) const
187{
188 int const subX = chip->getSubX();
189 int const subY = chip->getSubY();
190 int const nx = chip->getSubW();
191 int const ny = chip->getSubH();
192 auto *buf = reinterpret_cast<uint16_t *>(chip->getFrameBuffer());
193
194 for (const auto &defect : defects)
195 {
196 int const x = defect.x - subX;
197 int const y = defect.y - subY;
198 if (x < 0 || x >= nx || y < 0 || y >= ny)
199 continue;
200
201 uint16_t &pixel = buf[y * nx + x];
202 if (defect.cold)
203 {
204 pixel = static_cast<uint16_t>(std::max(0, bias / 2));
205 continue;
206 }
207
208 double const value = static_cast<double>(pixel) + static_cast<double>(defect.rate) * exposure_s;
209 pixel = static_cast<uint16_t>(std::min(value, static_cast<double>(m_Cfg.maxVal)));
210 }
211}
212
213void SkyRenderer::drawSkyGlow(INDI::CCDChip *chip, float exp_s)
214{
215 float const skyflux = static_cast<float>(flux(m_Cfg.skyGlow)) * exp_s;
216
217 int const nwidth = chip->getSubW();
218 int const nheight = chip->getSubH();
219
220 auto *pt = reinterpret_cast<uint16_t *>(chip->getFrameBuffer());
221
222 float const vig = std::min(nwidth, nheight) * m_ImageScaleX;
223 float const invVig2 = 1.0f / (vig * vig);
224
225 for (int y = 0; y < nheight; y++)
226 {
227 float const sy = nheight / 2.0f - y;
228
229 for (int x = 0; x < nwidth; x++)
230 {
231 float const sx = nwidth / 2.0f - x;
232
233 float const dc2 = sx * sx * m_ImageScaleX * m_ImageScaleX
234 + sy * sy * m_ImageScaleY * m_ImageScaleY;
235
236 float const fa = std::exp(-2.0f * 0.7f * dc2 * invVig2);
237
238 float fp = (pt[0] + skyflux) * fa;
239
240 if (fp > m_Cfg.maxVal) fp = static_cast<float>(m_Cfg.maxVal);
241 if (fp < pt[0]) fp = pt[0]; // never darken an already-bright pixel
242 if (fp > m_MaxPix) m_MaxPix = static_cast<int>(fp);
243 if (fp < m_MinPix) m_MinPix = static_cast<int>(fp);
244
245 pt[0] = static_cast<uint16_t>(fp);
246 pt++;
247 }
248 }
249}
250
252 INDI::CCDChip *chip,
253 double ra_j2000_deg,
254 double dec_j2000_deg,
255 double focal_length_mm,
256 double rotation_deg,
257 float exposure_s,
258 bool renderStars,
259 double minSearchRadiusArcmin)
260{
261 m_MaxPix = 0;
262 m_MinPix = 65000;
263
264 // Image scale (arcsec/pixel) from focal length and pixel size
265 m_ImageScaleX = static_cast<float>((chip->getPixelSizeX() / focal_length_mm) * 206.3);
266 m_ImageScaleY = static_cast<float>((chip->getPixelSizeY() / focal_length_mm) * 206.3);
267
268 // Plate matrix: maps standard coords to pixel coords, with camera rotation applied
269 double const theta = rotation_deg * (M_PI / 180.0);
270 double const pprx = focal_length_mm / chip->getPixelSizeX() * 1000.0; // pixels per radian, X
271 double const ppry = focal_length_mm / chip->getPixelSizeY() * 1000.0; // pixels per radian, Y
272
273 double const pa = pprx * std::cos(theta);
274 double const pb = ppry * std::sin(theta);
275 double const pd = -pprx * std::sin(theta);
276 double const pe = ppry * std::cos(theta);
277 double const pc = chip->getXRes() / 2.0; // X center pixel
278 double const pf = chip->getYRes() / 2.0; // Y center pixel
279 double const ccdW = chip->getXRes();
280
281 // Field center in radians
282 double const rar = ra_j2000_deg * (M_PI / 180.0);
283 double const decr = dec_j2000_deg * (M_PI / 180.0);
284
285 // GSC search radius (arcmin): half-diagonal of the chip in arcsec, converted to arcmin
286 double radius = std::sqrt(
287 m_ImageScaleX * m_ImageScaleX * chip->getXRes() / 2.0 * chip->getXRes() / 2.0 +
288 m_ImageScaleY * m_ImageScaleY * chip->getYRes() / 2.0 * chip->getYRes() / 2.0) / 60.0;
289 if (minSearchRadiusArcmin > 0 && radius < minSearchRadiusArcmin)
290 radius = minSearchRadiusArcmin;
291
292 // Cap lookup magnitude for very wide fields to limit GSC processing time
293 double lookuplimit = m_Cfg.limitingMag;
294 if (radius > 60)
295 lookuplimit = 11;
296
297 // Clear the frame buffer
298 memset(chip->getFrameBuffer(), 0, chip->getFrameBufferSize());
299
300 int drawn = 0;
301
302 if (renderStars)
303 {
304 AutoCNumeric locale;
305 char gsccmd[250];
306
307 // Handbook of astronomical image processing, eqs. 9.1/9.2 (gnomonic projection)
308 snprintf(gsccmd, sizeof(gsccmd),
309 "gsc -c %8.6f %+8.6f -r %4.1f -m 0 %4.2f -n 3000",
310 range360(ra_j2000_deg),
311 rangeDec(dec_j2000_deg),
312 radius,
313 lookuplimit);
314
315 FILE *pp = popen(gsccmd, "r");
316 if (pp != nullptr)
317 {
318 char line[256];
319
320 while (fgets(line, sizeof(line), pp) != nullptr)
321 {
322 char id[20], plate[6], ob[6];
323 float ra, dec, pose, mag, mage, dist;
324 int band, c, dir;
325
326 int rc = sscanf(line, "%10s %f %f %f %f %f %d %d %4s %2s %f %d",
327 id, &ra, &dec, &pose, &mag, &mage,
328 &band, &c, plate, ob, &dist, &dir);
329 if (rc != 12)
330 continue;
331
332 double const srar = ra * (M_PI / 180.0);
333 double const sdecr = dec * (M_PI / 180.0);
334
335 double const denom = cos(decr) * cos(sdecr) * cos(srar - rar)
336 + sin(decr) * sin(sdecr);
337 if (denom <= 0)
338 continue;
339
340 double const sx = cos(sdecr) * sin(srar - rar) / denom;
341 double const sy = (sin(decr) * cos(sdecr) * cos(srar - rar)
342 - cos(decr) * sin(sdecr)) / denom;
343
344 // Invert horizontally (CW->CCW, origin North)
345 double const ccdx = ccdW - (pa * sx + pb * sy + pc);
346 double const ccdy = pd * sx + pe * sy + pf;
347
348 drawn += drawImageStar(chip, mag,
349 static_cast<float>(ccdx),
350 static_cast<float>(ccdy),
351 exposure_s);
352 }
353 pclose(pp);
354 }
355 else
356 {
357 drawn = -1;
358 }
359 }
360
361 drawSkyGlow(chip, exposure_s);
362
363 return drawn;
364}
The CCDChip class provides functionality of a CCD Chip within a CCD.
Definition indiccdchip.h:39
int getSubX() const
getSubX Get the starting left coordinates (X) of the frame.
Definition indiccdchip.h:99
int getSubY() const
getSubY Get the starting top coordinates (Y) of the frame.
float getPixelSizeY() const
getPixelSizeY Get vertical pixel size in microns.
int getSubH() const
getSubH Get the height of the frame
float getPixelSizeX() const
getPixelSizeX Get horizontal pixel size in microns.
int getXRes() const
getXRes Get the horizontal resolution in pixels of the CCD Chip.
Definition indiccdchip.h:81
uint8_t * getFrameBuffer()
getFrameBuffer Get raw frame buffer of the CCD chip.
int getSubW() const
getSubW Get the width of the frame
int getFrameBufferSize() const
getFrameBufferSize Get allocated frame buffer size to hold the CCD image frame.
int getYRes() const
Get the vertical resolution in pixels of the CCD Chip.
Definition indiccdchip.h:90
void applyDefects(INDI::CCDChip *chip, const std::vector< SensorDefect > &defects, float exposure_s, int bias) const
int renderFrame(INDI::CCDChip *chip, double ra_j2000_deg, double dec_j2000_deg, double focal_length_mm, double rotation_deg, float exposure_s, bool renderStars=true, double minSearchRadiusArcmin=0)
void applyReadoutNoise(INDI::CCDChip *chip, int bias, int maxNoise)
int drawImageStar(INDI::CCDChip *, float mag, float x, float y, float exp_s)
static std::vector< SensorDefect > generateDefects(int xres, int yres, int hotCount, int coldCount, float hotRate, uint32_t seed=1)
#define M_PI
Definition dsp.h:52
double ra
double dec
double range360(double r)
range360 Limits an angle to be between 0-360 degrees.
Definition indicom.c:1321
double rangeDec(double decdegrees)
rangeDec Limits declination value to be in -90 to 90 range.
Definition indicom.c:1341
Implementations for common driver routines.