Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
ear_heatmap_overlay.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#define _POSIX_C_SOURCE 200809L
19
20/**
21 * @file ear_heatmap_overlay.c
22 * @brief Render EARcam acoustic fields over cached or downloaded map tiles.
23 * @details Host-side review utility. It does not run in the MORA service or
24 * change acoustic samples, source estimates or flight-control decisions.
25 */
26#include "version.h"
28
29#include <ctype.h>
30#include <errno.h>
31#include <math.h>
32#include <setjmp.h>
33#include <stdbool.h>
34#include <stdint.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <jpeglib.h>
39#include <sys/stat.h>
40#include <sys/wait.h>
41#include <unistd.h>
42
43/** Web Mercator XYZ tile geometry and local projection constants. */
44#define TILE_SIZE 256U
45#define PI 3.14159265358979323846
46#define EARTH_RADIUS_M 6378137.0
47#define DEG_TO_RAD 0.017453292519943295
48/** Explicit I/O/image/CSV ceilings keep malformed inputs from growing memory unboundedly. */
49#define MAX_PATH_LENGTH 4096U
50#define MAX_TILE_COUNT 4096U
51#define MAX_OUTPUT_PIXELS 16000000U
52#define MAX_INPUT_PIXELS 1048576U
53#define MAX_CSV_POINTS 200000U
54#define MAX_CSV_LINE 8192U
55/** Review defaults: visual framing only; none of these imply spatial accuracy. */
56#define DEFAULT_MAX_ZOOM 20U
57#define DEFAULT_MARGIN_M 15.0
58#define DEFAULT_ALPHA 0.55
59#define DEFAULT_TRACK_GAP_S 1.5
60#define JPEG_QUALITY 92
61
62/**
63 * @struct rgb_image
64 * @brief Non-owning view of a bounded interleaved RGB workspace.
65 * @details Caller-provided capacity is checked before libjpeg writes scanlines;
66 * keeping ownership outside this view makes scratch-buffer reuse explicit.
67 */
68struct rgb_image {
69 unsigned int width; /**< Decoded or composed width in pixels. */
70 unsigned int height; /**< Decoded or composed height in pixels. */
71 uint8_t *pixels; /**< Borrowed storage; this descriptor never frees it. */
72 size_t capacity_bytes; /**< Maximum writable size of @c pixels. */
73};
74
75/**
76 * @struct point
77 * @brief One timestamped geographic position for a replay annotation.
78 */
79struct point {
80 double time_s; /**< Timestamp normalized to seconds for gap handling. */
81 double lat; /**< Latitude in degrees. */
82 double lon; /**< Longitude in degrees. */
83};
84
85/**
86 * @struct point_list
87 * @brief Fixed-capacity, non-owning view over parsed session/track points.
88 */
89struct point_list {
90 struct point *items; /**< Caller-owned record array. */
91 size_t count; /**< Number of initialized points. */
92 size_t capacity; /**< Hard record limit; excess valid rows fail the read. */
93};
94
95/**
96 * @struct obstacle
97 * @brief One optional terrain-height cell supplied for visual context.
98 */
99struct obstacle {
100 double east_m; /**< Projected east coordinate used to infer grid pitch. */
101 double lat; /**< Cell-center latitude in degrees. */
102 double lon; /**< Cell-center longitude in degrees. */
103 double height_m; /**< Height above terrain in metres. */
104};
105
106/**
107 * @struct obstacle_list
108 * @brief Bounded view over LiDAR cells and their inferred regular spacing.
109 */
111 struct obstacle *items; /**< Caller-owned fixed cell array. */
112 size_t count; /**< Initialized cells. */
113 size_t capacity; /**< Maximum accepted grid cells. */
114};
115
116/** @brief Reused input, tile and final RGB workspaces; avoid per-image allocator churn. */
117static uint8_t input_pixels[(size_t)MAX_INPUT_PIXELS * 3U];
118static uint8_t tile_pixels[(size_t)TILE_SIZE * TILE_SIZE * 3U];
119static uint8_t output_pixels[(size_t)MAX_OUTPUT_PIXELS * 3U];
124
125/**
126 * @struct options
127 * @brief Parsed overlay policy; all strings are borrowed from the process argument vector.
128 */
129struct options {
130 const char *input; /**< Replay JPEG used to locate matching field and geometry files. */
131 const char *geo_path; /**< Explicit geometry sidecar, or NULL for stem-derived naming. */
132 const char *log_path; /**< Optional EAR session log for observation dots. */
133 const char *track_path; /**< Optional timestamped aircraft track. */
134 const char *truth_text; /**< Optional known simulation position. */
135 const char *search_text; /**< Optional search center and radius. */
136 const char *obstacles_path; /**< Optional LiDAR grid with heights above terrain. */
137 const char *output_path; /**< Output override, or NULL for the @c _sat.jpg default. */
138 const char *source; /**< Selected satellite source and cache namespace. */
139 const char *cache_path; /**< Paparazzi map-cache root. */
140 unsigned int zoom; /**< Explicit XYZ zoom; zero requests automatic selection. */
141 unsigned int max_zoom; /**< Upper bound for automatic zoom selection. */
142 double alpha; /**< Opacity for valid heat-field pixels. */
143 double margin_m; /**< Ground extent around the heatmap. */
144 double track_gap_s; /**< Largest timestamp gap connected by a track segment. */
145 bool quiet; /**< Suppress progress messages. */
146 bool offline; /**< Forbid downloads when a cache tile is missing. */
147};
148
150 struct jpeg_error_mgr manager;
151 jmp_buf recovery;
152};
153
154/**
155 * @brief Convert libjpeg's fatal callback into a jump to the active operation.
156 * @param info Codec state carrying the recovery record in its error manager.
157 * @details Default libjpeg behavior exits the process; keeping recovery local lets
158 * corrupt cached tiles fail this overlay without terminating other host tools.
159 */
160static void jpeg_error_exit(j_common_ptr info)
161{
162 struct jpeg_failure *failure = (struct jpeg_failure *)info->err;
163 longjmp(failure->recovery, 1);
164}
165
166/**
167 * @brief Invalidate an RGB view before its shared workspace is reused.
168 * @param image Descriptor to clear; its backing pixels are caller-owned static storage.
169 */
170static void image_free(struct rgb_image *image)
171{
172 image->pixels = NULL;
173 image->width = 0;
174 image->height = 0;
175 image->capacity_bytes = 0;
176}
177
178/**
179 * @brief Decode one JPEG into the caller's bounded RGB workspace.
180 * @param path JPEG file path.
181 * @param image Supplies pixel pointer/capacity and receives decoded dimensions.
182 * @return 0 after complete decode, or -1 for I/O, codec, size or capacity failure.
183 * @details The pixel cap is checked before scanlines are decoded; image dimensions
184 * from a file header never trigger allocation or out-of-bounds writes.
185 */
186static int image_read_jpeg(const char *path, struct rgb_image *image)
187{
188 FILE *input = fopen(path, "rb");
189 if (input == NULL) { return -1; }
190 struct jpeg_decompress_struct decoder;
191 struct jpeg_failure failure;
192 decoder.err = jpeg_std_error(&failure.manager);
193 failure.manager.error_exit = jpeg_error_exit;
194 if (setjmp(failure.recovery) != 0) {
195 jpeg_destroy_decompress(&decoder);
196 fclose(input);
198 return -1;
199 }
200 jpeg_create_decompress(&decoder);
201 jpeg_stdio_src(&decoder, input);
202 jpeg_read_header(&decoder, TRUE);
203 decoder.out_color_space = JCS_RGB;
204 jpeg_start_decompress(&decoder);
205 if (decoder.output_components != 3 || decoder.output_width == 0 || decoder.output_height == 0
206 || (uint64_t)decoder.output_width * decoder.output_height > MAX_INPUT_PIXELS) {
207 jpeg_destroy_decompress(&decoder);
208 fclose(input);
209 return -1;
210 }
211 unsigned int width = decoder.output_width;
212 unsigned int height = decoder.output_height;
213 size_t bytes = (size_t)width * height * 3U;
214 if (image->pixels == NULL || image->capacity_bytes < bytes) {
215 jpeg_destroy_decompress(&decoder);
216 fclose(input);
217 return -1;
218 }
219 image->width = width;
220 image->height = height;
221 while (decoder.output_scanline < decoder.output_height) {
222 JSAMPROW row = &image->pixels[(size_t)decoder.output_scanline * image->width * 3U];
223 jpeg_read_scanlines(&decoder, &row, 1);
224 }
225 jpeg_finish_decompress(&decoder);
226 jpeg_destroy_decompress(&decoder);
227 return fclose(input) == 0 ? 0 : -1;
228}
229
230/**
231 * @brief Encode a bounded RGB view to a JPEG file.
232 * @param path Output JPEG path.
233 * @param image Image dimensions and borrowed RGB pixels.
234 * @return 0 on successful encode/close, or -1 on open, codec or close failure.
235 * @details Scanlines are passed directly from the single output workspace so no
236 * image-sized staging copy is required.
237 */
238static int image_write_jpeg(const char *path, const struct rgb_image *image)
239{
240 FILE *output = fopen(path, "wb");
241 if (output == NULL) { return -1; }
242 struct jpeg_compress_struct encoder;
243 struct jpeg_failure failure;
244 encoder.err = jpeg_std_error(&failure.manager);
245 failure.manager.error_exit = jpeg_error_exit;
246 if (setjmp(failure.recovery) != 0) {
247 jpeg_destroy_compress(&encoder);
248 fclose(output);
249 return -1;
250 }
251 jpeg_create_compress(&encoder);
252 jpeg_stdio_dest(&encoder, output);
253 encoder.image_width = image->width;
254 encoder.image_height = image->height;
255 encoder.input_components = 3;
256 encoder.in_color_space = JCS_RGB;
257 jpeg_set_defaults(&encoder);
258 jpeg_set_quality(&encoder, JPEG_QUALITY, TRUE);
259 jpeg_start_compress(&encoder, TRUE);
260 while (encoder.next_scanline < encoder.image_height) {
261 JSAMPROW row = (JSAMPROW)&image->pixels[(size_t)encoder.next_scanline * image->width * 3U];
262 jpeg_write_scanlines(&encoder, &row, 1);
263 }
264 jpeg_finish_compress(&encoder);
265 jpeg_destroy_compress(&encoder);
266 return fclose(output) == 0 ? 0 : -1;
267}
268
269/**
270 * @brief Parse a finite floating-point token in full.
271 * @param text NUL-terminated command-line value.
272 * @param value Receives the result only on success.
273 * @return false for empty, non-finite, out-of-range or partially numeric strings.
274 * @details Rejecting trailing characters prevents a typo like `0.5junk` from
275 * silently changing image opacity or another numeric option.
276 */
277static bool parse_double(const char *text, double *value)
278{
279 errno = 0;
280 char *end = NULL;
281 double parsed = strtod(text, &end);
282 if (end == text || errno == ERANGE || !isfinite(parsed) || *end != '\0') { return false; }
283 *value = parsed;
284 return true;
285}
286
287/**
288 * @brief Parse an unsigned integer option without accepting suffix characters.
289 * @param text NUL-terminated decimal token.
290 * @param value Receives the value only when it fits `unsigned int`.
291 * @return true for a complete conversion within the destination range.
292 */
293static bool parse_unsigned(const char *text, unsigned int *value)
294{
295 errno = 0;
296 char *end = NULL;
297 unsigned long parsed = strtoul(text, &end, 10);
298 if (end == text || errno == ERANGE || *end != '\0' || parsed > UINT32_MAX) { return false; }
299 *value = (unsigned int)parsed;
300 return true;
301}
302
303/**
304 * @brief Print command synopsis and defaults from the same option vocabulary parsed below.
305 * @param program Invocation name displayed to the user.
306 */
307static void print_help(const char *program)
308{
309 printf("%s\nUsage: %s HEATMAP.jpg [options]\n"
310 "Overlay a USHER EARcam heatmap on cached/downloaded satellite tiles.\n\n"
311 " --geo FILE Sidecar path (default: HEATMAP.geo)\n"
312 " -o, --output FILE Output JPEG (default: HEATMAP_sat.jpg)\n"
313 " --source google|esri Tile source (default: google)\n"
314 " --cache DIR Shared tile cache (default: XDG_DATA_HOME/paparazzi/pprzgcs/map)\n"
315 " --zoom N Tile zoom (otherwise choose from heatmap resolution)\n"
316 " --max-zoom N Maximum automatic zoom (default: 20)\n"
317 " --alpha N Heatmap opacity from 0 to 1 (default: 0.55)\n"
318 " --margin-m N Imagery margin (default: 15)\n"
319 " --log FILE Session CSV; redraw sample positions\n"
320 " --track FILE Track CSV: t_s,lat_deg,lon_deg,...\n"
321 " --track-gap-s N Break track after this gap (default: 1.5)\n"
322 " --search LAT,LON[,M] Search point and radius (default radius: 25 m)\n"
323 " --truth LAT,LON Known source position for simulation comparison\n"
324 " --obstacles FILE LiDAR CSV with x_east_m,lat,lon,mnh_m columns\n"
325 " --offline Use cached tiles only; fail if any tile is missing\n"
326 " --quiet Suppress tile progress messages\n"
327 " -h, --help Show this help\n"
328 " -V, --version Show build version\n", EAR_HEATMAP_OVERLAY_BUILD_VERSION, program);
329}
330
331/**
332 * @brief Parse one positional heatmap and the supported optional controls.
333 * @param argc Argument count.
334 * @param argv Process argument vector.
335 * @param options Receives validated values; strings borrow `argv` storage.
336 * @return true when exactly one positional input and all recognized values are present.
337 * @details Options are accepted before or after the image to avoid shell-order
338 * surprises; unknown switches and duplicate positional images are rejected.
339 */
340static bool parse_options(int argc, char **argv, struct options *options)
341{
342 memset(options, 0, sizeof(*options));
343 options->source = "google";
348 for (int index = 1; index < argc; index++) {
349 const char *arg = argv[index];
350 if (arg[0] != '-') {
351 if (options->input != NULL) { return false; }
352 options->input = arg;
353 continue;
354 }
355 if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
356 print_help(argv[0]);
357 exit(0);
358 }
359 if (strcmp(arg, "--version") == 0 || strcmp(arg, "-V") == 0) {
361 exit(0);
362 }
363 if (strcmp(arg, "--quiet") == 0) { options->quiet = true; continue; }
364 if (strcmp(arg, "--offline") == 0) { options->offline = true; continue; }
365 if (index + 1 >= argc) { return false; }
366 const char *value = argv[++index];
367 if (strcmp(arg, "--geo") == 0) { options->geo_path = value; }
368 else if (strcmp(arg, "--log") == 0) { options->log_path = value; }
369 else if (strcmp(arg, "--track") == 0) { options->track_path = value; }
370 else if (strcmp(arg, "--truth") == 0) { options->truth_text = value; }
371 else if (strcmp(arg, "--search") == 0) { options->search_text = value; }
372 else if (strcmp(arg, "--obstacles") == 0) { options->obstacles_path = value; }
373 else if (strcmp(arg, "--output") == 0 || strcmp(arg, "-o") == 0) { options->output_path = value; }
374 else if (strcmp(arg, "--source") == 0) { options->source = value; }
375 else if (strcmp(arg, "--cache") == 0) { options->cache_path = value; }
376 else if (strcmp(arg, "--zoom") == 0) {
377 if (!parse_unsigned(value, &options->zoom)) { return false; }
378 } else if (strcmp(arg, "--max-zoom") == 0) {
379 if (!parse_unsigned(value, &options->max_zoom)) { return false; }
380 } else if (strcmp(arg, "--alpha") == 0) {
381 if (!parse_double(value, &options->alpha)) { return false; }
382 } else if (strcmp(arg, "--margin-m") == 0) {
383 if (!parse_double(value, &options->margin_m)) { return false; }
384 } else if (strcmp(arg, "--track-gap-s") == 0) {
385 if (!parse_double(value, &options->track_gap_s)) { return false; }
386 } else { return false; }
387 }
388 return options->input != NULL;
389}
390
391/**
392 * @brief Project latitude/longitude into fractional Web Mercator tile coordinates.
393 * @param lat Latitude in degrees.
394 * @param lon Longitude in degrees.
395 * @param zoom XYZ zoom level.
396 * @param x Receives fractional tile X, increasing eastward.
397 * @param y Receives fractional tile Y, increasing southward.
398 * @details Clamp to the finite square-tile Mercator latitude limit; callers separately
399 * reject overlays whose geographic bounds are not supported by this projection.
400 */
401static void mercator_xy(double lat, double lon, unsigned int zoom, double *x, double *y)
402{
403 const double n = ldexp(1.0, (int)zoom);
404 double bounded_lat = fmax(-85.05112878, fmin(85.05112878, lat));
405 double lat_rad = bounded_lat * DEG_TO_RAD;
406 *x = (lon + 180.0) / 360.0 * n;
407 *y = (1.0 - asinh(tan(lat_rad)) / PI) * 0.5 * n;
408}
409
410/**
411 * @brief Estimate ground metres per tile pixel at a latitude.
412 * @param lat Latitude in degrees.
413 * @param zoom XYZ zoom level.
414 * @return Local ground resolution in metres per 256-pixel tile pixel.
415 * @details Mercator scale varies by latitude, so zoom selection and the scale
416 * annotation consistently use the heatmap's center latitude.
417 */
418static double mercator_m_per_pixel(double lat, unsigned int zoom)
419{
420 return 2.0 * PI * EARTH_RADIUS_M * cos(lat * DEG_TO_RAD) / (TILE_SIZE * ldexp(1.0, (int)zoom));
421}
422
423/**
424 * @brief Select the first basemap zoom at least as detailed as the heatmap.
425 * @param geo Heatmap pixel scale and center latitude.
426 * @param max_zoom Highest permitted map zoom.
427 * @return Selected zoom, capped at `max_zoom` when the map remains coarser.
428 * @details More detailed imagery cannot increase acoustic measurement resolution;
429 * this default avoids needless tile downloads at higher-than-useful zoom.
430 */
431static unsigned int choose_zoom(const struct ear_heatmap_georef *geo, unsigned int max_zoom)
432{
433 for (unsigned int zoom = 12; zoom <= max_zoom; zoom++) {
434 if (mercator_m_per_pixel(geo->lat_center, zoom) <= geo->m_per_px) { return zoom; }
435 }
436 return max_zoom;
437}
438
439/**
440 * @brief Parse `LAT,LON` or `LAT,LON,RADIUS_M` into bounded geographic values.
441 * @param text Comma-separated command-line token.
442 * @param with_radius Allow/require interpretation of a third optional field.
443 * @param lat Receives latitude in degrees.
444 * @param lon Receives longitude in degrees.
445 * @param radius Receives the parsed radius or the 25 m default when enabled.
446 * @return true only when every field is consumed and within its geographic/radius range.
447 */
448static bool parse_location(const char *text, bool with_radius, double *lat, double *lon, double *radius)
449{
450 if (text == NULL) { return false; }
451 char buffer[128];
452 size_t length = strlen(text);
453 if (length == 0 || length >= sizeof(buffer)) { return false; }
454 for (size_t index = 0; index <= length; index++) { buffer[index] = text[index]; }
455 char *first = strchr(buffer, ',');
456 if (first == NULL) { return false; }
457 *first++ = '\0';
458 char *second = strchr(first, ',');
459 if (second != NULL) { *second++ = '\0'; }
460 if (!parse_double(buffer, lat) || !parse_double(first, lon)) { return false; }
461 if (*lat < -90.0 || *lat > 90.0 || *lon < -180.0 || *lon > 180.0) { return false; }
462 if (with_radius) {
463 *radius = 25.0;
464 if (second != NULL && (!parse_double(second, radius) || *radius <= 0.0 || *radius > 100000.0)) { return false; }
465 return second == NULL || strchr(second, ',') == NULL;
466 }
467 return second == NULL;
468}
469
470/**
471 * @brief Derive a sibling `.geo`, `_field.jpg` or `_sat.jpg` path from an image.
472 * @param path Input JPEG path.
473 * @param suffix Replacement suffix.
474 * @param output Destination path buffer.
475 * @param capacity Capacity in bytes.
476 * @return 0 when the path fits, -1 rather than returning a truncated filename.
477 * @details Stem-derived names keep replay artifacts paired without asking users
478 * to type a second path that can silently refer to another session.
479 */
480static int make_stem_path(const char *path, const char *suffix, char *output, size_t capacity)
481{
482 size_t length = strlen(path);
483 size_t stem = length;
484 if (length >= 4 && (strcmp(path + length - 4, ".jpg") == 0 || strcmp(path + length - 4, ".JPG") == 0)) {
485 stem = length - 4;
486 } else if (length >= 5 && (strcmp(path + length - 5, ".jpeg") == 0 || strcmp(path + length - 5, ".JPEG") == 0)) {
487 stem = length - 5;
488 }
489 if (stem + strlen(suffix) + 1 > capacity) { return -1; }
490 for (size_t index = 0; index < stem; index++) { output[index] = path[index]; }
491 output[stem] = '\0';
492 return snprintf(output + stem, capacity - stem, "%s", suffix) < 0 ? -1 : 0;
493}
494
495/**
496 * @brief Resolve the Paparazzi GCS map-cache root from XDG environment settings.
497 * @param path Receives `$XDG_DATA_HOME/paparazzi/pprzgcs/map` or the HOME fallback.
498 * @param capacity Destination capacity in bytes.
499 * @return 0 for a usable environment/path, -1 if HOME is absent or the result cannot fit.
500 * @details GCS imagery belongs to its user-data cache, not the source checkout;
501 * using this shared location is what makes local tiles the fast/default path.
502 */
503static int default_cache_path(char *path, size_t capacity)
504{
505 const char *xdg_data_home = getenv("XDG_DATA_HOME");
506 const char *home = getenv("HOME");
507 if (xdg_data_home != NULL && *xdg_data_home != '\0') {
508 if (snprintf(path, capacity, "%s/paparazzi/pprzgcs/map", xdg_data_home) >= (int)capacity) { return -1; }
509 } else {
510 if (home == NULL || *home == '\0') { return -1; }
511 if (snprintf(path, capacity, "%s/.local/share/paparazzi/pprzgcs/map", home) >= (int)capacity) { return -1; }
512 }
513 return 0;
514}
515
516/**
517 * @brief Create parent directories for a tile file without treating the file as a directory.
518 * @param path Full destination filename.
519 * @return 0 if all parents exist or are created, otherwise -1.
520 * @details Downloads go to a sibling temporary path and are renamed on success;
521 * partial transfers therefore cannot masquerade as cache hits.
522 */
523static int make_directories(const char *path)
524{
525 char buffer[MAX_PATH_LENGTH] = {0};
526 if (!path) { return -1; }
527 size_t length = strnlen(path, sizeof(buffer));
528 if (length == 0 || length >= sizeof(buffer)) { return -1; }
529 for (size_t index = 0; index <= length; index++) { buffer[index] = path[index]; }
530 char *last_separator = strrchr(buffer, '/');
531 if (last_separator == NULL) { return 0; }
532 *last_separator = '\0';
533 length = strlen(buffer);
534 for (size_t index = 1; index < length; index++) {
535 if (buffer[index] != '/') { continue; }
536 buffer[index] = '\0';
537 if (mkdir(buffer, 0775) != 0 && errno != EEXIST) { return -1; }
538 buffer[index] = '/';
539 }
540 if (mkdir(buffer, 0775) != 0 && errno != EEXIST) { return -1; }
541 return 0;
542}
543
544/**
545 * @brief Encode an XYZ address using Paparazzi's legacy Google quadkey alphabet.
546 * @param x Tile column.
547 * @param y Tile row, increasing southward.
548 * @param zoom Number of quadkey digits.
549 * @param key Caller-owned string buffer.
550 * @param capacity Buffer capacity including the terminator.
551 * @details This is a compatibility fallback; current Paparazzi cache entries
552 * are searched in the uppercase XYZ layout first.
553 */
554static void gcs_key(unsigned int x, unsigned int y, unsigned int zoom, char *key, size_t capacity)
555{
556 static const char quadrants[2][2] = {{'q', 't'}, {'r', 's'}};
557 size_t position = 0;
558 key[position++] = 't';
559 for (int bit = (int)zoom - 1; bit >= 0 && position + 1 < capacity; bit--) {
560 key[position++] = quadrants[(x >> bit) & 1U][(y >> bit) & 1U];
561 }
562 key[position] = '\0';
563}
564
565/**
566 * @brief Select the first known local filename for an XYZ source tile.
567 * @param options Source namespace and cache root.
568 * @param x Tile column.
569 * @param y Tile row.
570 * @param zoom Tile zoom.
571 * @param path Receives an existing tile path when found, otherwise preferred download path.
572 * @param capacity Destination buffer size.
573 * @return 0 when a candidate fits the buffer; -1 if path formatting would truncate.
574 * @details Current `GOOGLE/{z}/{x}/{y}.jpeg` and Esri layouts are checked before
575 * historical spellings so existing locally cached imagery is reused without network.
576 */
577static int tile_path(const struct options *options, unsigned int x, unsigned int y,
578 unsigned int zoom, char *path, size_t capacity)
579{
580 if (strcmp(options->source, "google") == 0) {
581 if (snprintf(path, capacity, "%s/GOOGLE/%u/%u/%u.jpeg", options->cache_path, zoom, x, y) >= (int)capacity) { return -1; }
582 if (access(path, R_OK) == 0) { return 0; }
583 if (snprintf(path, capacity, "%s/GOOGLE/%u/%u/%u.jpg", options->cache_path, zoom, x, y) >= (int)capacity) { return -1; }
584 if (access(path, R_OK) == 0) { return 0; }
585 char key[32];
586 gcs_key(x, y, zoom, key, sizeof(key));
587 if (snprintf(path, capacity, "%s/Google/%s.jpg", options->cache_path, key) >= (int)capacity) { return -1; }
588 if (access(path, R_OK) == 0) { return 0; }
589 return snprintf(path, capacity, "%s/Google/%s.jpeg", options->cache_path, key) >= (int)capacity ? -1 : 0;
590 }
591 if (snprintf(path, capacity, "%s/ESRI/%u/%u/%u.jpeg", options->cache_path, zoom, x, y) >= (int)capacity) { return -1; }
592 if (access(path, R_OK) == 0) { return 0; }
593 if (snprintf(path, capacity, "%s/esri/%u/%u_%u.jpg", options->cache_path, zoom, x, y) >= (int)capacity) { return -1; }
594 if (access(path, R_OK) == 0) { return 0; }
595 return snprintf(path, capacity, "%s/esri/%u/%u_%u.jpeg", options->cache_path, zoom, x, y) >= (int)capacity ? -1 : 0;
596}
597
598/**
599 * @brief Download one cache miss with the existing curl executable.
600 * @param options Source/cache policy.
601 * @param x Tile column.
602 * @param y Tile row.
603 * @param zoom Tile zoom level.
604 * @param path Final cache filename.
605 * @return 0 after an atomic install, otherwise -1 on process, network or file failure.
606 * @details Called only after every local cache spelling misses. `execvp` avoids
607 * shell interpretation; the temporary file is renamed only after curl exits cleanly.
608 */
609static int download_tile(const struct options *options, unsigned int x, unsigned int y,
610 unsigned int zoom, const char *path)
611{
612 if (make_directories(path) != 0) { return -1; }
613 char temporary[MAX_PATH_LENGTH];
614 if (snprintf(temporary, sizeof(temporary), "%s.part.%ld", path, (long)getpid()) >= (int)sizeof(temporary)) { return -1; }
615 char url[512];
616 if (strcmp(options->source, "google") == 0) {
617 snprintf(url, sizeof(url), "https://mt1.google.com/vt/lyrs=s&x=%u&y=%u&z=%u", x, y, zoom);
618 } else {
619 snprintf(url, sizeof(url), "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/%u/%u/%u",
620 zoom, y, x);
621 }
622 char *const arguments[] = {"curl", "--fail", "--location", "--silent", "--show-error",
623 "--connect-timeout", "15", "--max-time", "30", "--retry", "2",
624 "--retry-delay", "1", "--user-agent", "sensoraia-ear-heatmap-overlay/1",
625 "--output", temporary, url, NULL};
626 pid_t child = fork();
627 if (child < 0) { return -1; }
628 if (child == 0) {
629 execvp(arguments[0], arguments);
630 _exit(127);
631 }
632 int child_status = 0;
633 while (waitpid(child, &child_status, 0) < 0) {
634 if (errno != EINTR) { unlink(temporary); return -1; }
635 }
636 if (!WIFEXITED(child_status) || WEXITSTATUS(child_status) != 0
637 || rename(temporary, path) != 0) {
638 unlink(temporary);
639 return -1;
640 }
641 return 0;
642}
643
644/**
645 * @brief Read a local hit, fetch a miss if permitted, and decode one 256x256 tile.
646 * @param options Source/cache/offline policy.
647 * @param x Tile column.
648 * @param y Tile row.
649 * @param zoom Tile zoom level.
650 * @param tile Receives RGB pixels in the fixed tile workspace.
651 * @return 0 for a readable tile/placeholder; -1 for offline misses or invalid cached JPEGs.
652 * @details Offline mode is deliberately strict: replacing missing terrain with blank
653 * pixels would make incomplete geographic context look like a successful map review.
654 */
655static int fetch_tile(const struct options *options, unsigned int x, unsigned int y,
656 unsigned int zoom, struct rgb_image *tile)
657{
658 char path[MAX_PATH_LENGTH];
659 if (tile_path(options, x, y, zoom, path, sizeof(path)) != 0) { return -1; }
660 if (access(path, R_OK) != 0 && options->offline) {
661 fprintf(stderr, "offline mode: cached tile is missing: %s\n", path);
662 return -1;
663 }
664 if (access(path, R_OK) != 0 && download_tile(options, x, y, zoom, path) != 0) {
665 if (!options->quiet) { fprintf(stderr, "warning: tile z%u %u/%u unavailable; using dark placeholder\n", zoom, x, y); }
666 tile->width = TILE_SIZE;
667 tile->height = TILE_SIZE;
668 tile->pixels = tile_pixels;
669 tile->capacity_bytes = sizeof(tile_pixels);
670 for (size_t index = 0; index < (size_t)TILE_SIZE * TILE_SIZE; index++) {
671 tile->pixels[index * 3] = 40;
672 tile->pixels[index * 3 + 1] = 40;
673 tile->pixels[index * 3 + 2] = 40;
674 }
675 return 0;
676 }
677 if (image_read_jpeg(path, tile) != 0 || tile->width != TILE_SIZE || tile->height != TILE_SIZE) {
678 image_free(tile);
679 return -1;
680 }
681 return 0;
682}
683
684/**
685 * @brief Copy only the part of a source tile intersecting the cropped output.
686 * @param tile Decoded fixed-size map tile.
687 * @param output Bounded destination mosaic.
688 * @param tile_x Absolute XYZ column.
689 * @param tile_y Absolute XYZ row.
690 * @param crop_x Crop origin in the assembled tile-grid pixels.
691 * @param crop_y Crop origin in the assembled tile-grid pixels.
692 * @return 0 after a clipped copy; nonintersecting edges need no work.
693 * @details Direct clipped copies avoid constructing a larger full-tile mosaic
694 * that would immediately be cropped and discarded.
695 */
696static int copy_tile_to_output(const struct rgb_image *tile, struct rgb_image *output,
697 int tile_x, int tile_y, int crop_x, int crop_y)
698{
699 int left = tile_x * (int)TILE_SIZE - crop_x;
700 int top = tile_y * (int)TILE_SIZE - crop_y;
701 int x0 = left < 0 ? 0 : left;
702 int y0 = top < 0 ? 0 : top;
703 int x1 = left + (int)TILE_SIZE > (int)output->width ? (int)output->width : left + (int)TILE_SIZE;
704 int y1 = top + (int)TILE_SIZE > (int)output->height ? (int)output->height : top + (int)TILE_SIZE;
705 if (x0 >= x1 || y0 >= y1) { return 0; }
706 for (int y = y0; y < y1; y++) {
707 size_t source_offset = ((size_t)(y - top) * TILE_SIZE + (unsigned int)(x0 - left)) * 3U;
708 size_t target_offset = ((size_t)y * output->width + (unsigned int)x0) * 3U;
709 size_t bytes = (size_t)(x1 - x0) * 3U;
710 for (size_t index = 0; index < bytes; index++) { output->pixels[target_offset + index] = tile->pixels[source_offset + index]; }
711 }
712 return 0;
713}
714
715/**
716 * @brief Invert fractional Web Mercator tile Y into a geographic latitude.
717 * @param tile_y Fractional tile row, increasing southward.
718 * @param zoom XYZ zoom level.
719 * @return Latitude in degrees.
720 */
721static double mercator_latitude(double tile_y, unsigned int zoom)
722{
723 double n = ldexp(1.0, (int)zoom);
724 return atan(sinh(PI * (1.0 - 2.0 * tile_y / n))) / DEG_TO_RAD;
725}
726
727/**
728 * @brief Resample the local equirectangular heat field onto the Mercator tile mosaic.
729 * @param base In/out satellite RGB image.
730 * @param field Undecorated EAR heatmap raster.
731 * @param geo Validated sidecar footprint and scale.
732 * @param zoom Basemap XYZ zoom shared by tile placement and output projection.
733 * @param crop_x Cropped image origin within the tile grid, pixels.
734 * @param crop_y Cropped image origin within the tile grid, pixels.
735 * @param alpha Opacity for covered heatmap pixels.
736 * @details Every basemap pixel is transformed back into the heatmap's local frame.
737 * This avoids stretching the field to fit a differently projected map and preserves
738 * the renderer's no-data color as transparent coverage rather than false evidence.
739 */
740static void composite_heatmap(struct rgb_image *base, const struct rgb_image *field,
741 const struct ear_heatmap_georef *geo, unsigned int zoom,
742 int crop_x, int crop_y, double alpha)
743{
744 double m_per_deg_lat = DEG_TO_RAD * EARTH_RADIUS_M;
745 double cos_lat = cos(geo->lat_center * DEG_TO_RAD);
746 double m_per_deg_lon = m_per_deg_lat * cos_lat;
747 double east0 = (geo->lon_west - geo->lon_center) * m_per_deg_lon;
748 double north0 = (geo->lat_north - geo->lat_center) * m_per_deg_lat;
749 double tile_count = ldexp(1.0, (int)zoom);
750 for (unsigned int y = 0; y < base->height; y++) {
751 double tile_y = ((double)(crop_y + (int)y) + 0.5) / TILE_SIZE;
752 double lat = mercator_latitude(tile_y, zoom);
753 double hy = (north0 - (lat - geo->lat_center) * m_per_deg_lat) / geo->m_per_px;
754 if (hy < 0.0 || hy >= field->height) { continue; }
755 unsigned int fy = (unsigned int)hy;
756 for (unsigned int x = 0; x < base->width; x++) {
757 double tile_x = ((double)(crop_x + (int)x) + 0.5) / TILE_SIZE;
758 double lon = tile_x / tile_count * 360.0 - 180.0;
759 double hx = ((lon - geo->lon_center) * m_per_deg_lon - east0) / geo->m_per_px;
760 if (hx < 0.0 || hx >= field->width) { continue; }
761 unsigned int fx = (unsigned int)hx;
762 size_t source = ((size_t)fy * field->width + fx) * 3U;
763 int dr = (int)field->pixels[source] - (int)EAR_HEATMAP_NO_DATA_RED;
764 int dg = (int)field->pixels[source + 1] - (int)EAR_HEATMAP_NO_DATA_GREEN;
765 int db = (int)field->pixels[source + 2] - (int)EAR_HEATMAP_NO_DATA_BLUE;
766 if (dr * dr + dg * dg + db * db < 24 * 24) { continue; }
767 size_t target = ((size_t)y * base->width + x) * 3U;
768 for (unsigned int channel = 0; channel < 3U; channel++) {
769 double value = base->pixels[target + channel] * (1.0 - alpha) + field->pixels[source + channel] * alpha;
770 base->pixels[target + channel] = (uint8_t)(value + 0.5);
771 }
772 }
773 }
774}
775
776/**
777 * @brief Blend one annotation pixel while clipping out-of-image coordinates.
778 * @param image Destination RGB image.
779 * @param x Image-space X.
780 * @param y Image-space Y.
781 * @param red Annotation red channel.
782 * @param green Annotation green channel.
783 * @param blue Annotation blue channel.
784 * @param alpha Blend amount from transparent to opaque.
785 * @details Central clipping lets each simple raster primitive draw across map
786 * boundaries without a separate bounds check for every caller.
787 */
788static void put_blended_pixel(struct rgb_image *image, int x, int y,
789 uint8_t red, uint8_t green, uint8_t blue, double alpha)
790{
791 if (x < 0 || y < 0 || (unsigned int)x >= image->width || (unsigned int)y >= image->height) { return; }
792 size_t offset = ((size_t)y * image->width + (unsigned int)x) * 3U;
793 const uint8_t color[3] = {red, green, blue};
794 for (unsigned int channel = 0; channel < 3U; channel++) {
795 double value = image->pixels[offset + channel] * (1.0 - alpha) + color[channel] * alpha;
796 image->pixels[offset + channel] = (uint8_t)(value + 0.5);
797 }
798}
799
800/**
801 * @brief Stamp a square brush centered at an integer pixel.
802 * @param image Destination RGB image.
803 * @param x Center X.
804 * @param y Center Y.
805 * @param width Nominal stroke width.
806 * @param red Stroke red channel.
807 * @param green Stroke green channel.
808 * @param blue Stroke blue channel.
809 * @param alpha Stroke opacity.
810 */
811static void draw_brush(struct rgb_image *image, int x, int y, int width,
812 uint8_t red, uint8_t green, uint8_t blue, double alpha)
813{
814 int radius = width / 2;
815 for (int dy = -radius; dy <= radius; dy++) {
816 for (int dx = -radius; dx <= radius; dx++) {
817 put_blended_pixel(image, x + dx, y + dy, red, green, blue, alpha);
818 }
819 }
820}
821
822/**
823 * @brief Draw a raster line with an integer Bresenham walk.
824 * @param image Destination RGB image.
825 * @param x0 Start X.
826 * @param y0 Start Y.
827 * @param x1 End X.
828 * @param y1 End Y.
829 * @param width Brush width.
830 * @param red Stroke red channel.
831 * @param green Stroke green channel.
832 * @param blue Stroke blue channel.
833 * @param alpha Stroke opacity.
834 * @details A compact local rasterizer avoids a drawing library for a few crisp
835 * lines; per-pixel clipping remains centralized in `put_blended_pixel`.
836 */
837static void draw_line(struct rgb_image *image, int x0, int y0, int x1, int y1,
838 int width, uint8_t red, uint8_t green, uint8_t blue, double alpha)
839{
840 int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
841 int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
842 int error = dx + dy;
843 for (;;) {
844 draw_brush(image, x0, y0, width, red, green, blue, alpha);
845 if (x0 == x1 && y0 == y1) { break; }
846 int twice = 2 * error;
847 if (twice >= dy) { error += dy; x0 += sx; }
848 if (twice <= dx) { error += dx; y0 += sy; }
849 }
850}
851
852/**
853 * @brief Draw a filled disc or clipped ring with a fixed-width stroke.
854 * @param image Destination RGB image.
855 * @param cx Center X in output pixels.
856 * @param cy Center Y in output pixels.
857 * @param radius Outer radius in pixels.
858 * @param width Ring thickness, ignored for a filled disc.
859 * @param red Annotation red channel.
860 * @param green Annotation green channel.
861 * @param blue Annotation blue channel.
862 * @param alpha Annotation opacity.
863 * @details Reject circles vastly larger than the image before squaring radii;
864 * clipping the remaining scan bounds avoids visiting pixels outside the output.
865 */
866static void draw_circle(struct rgb_image *image, int cx, int cy, int radius,
867 int width, uint8_t red, uint8_t green, uint8_t blue, double alpha)
868{
869 if (radius <= 0 || radius > (int)(image->width + image->height)) { return; }
870 int inner = radius - width;
871 int x0 = cx - radius - 1, x1 = cx + radius + 1;
872 int y0 = cy - radius - 1, y1 = cy + radius + 1;
873 if (x0 < 0) { x0 = 0; }
874 if (y0 < 0) { y0 = 0; }
875 if (x1 >= (int)image->width) { x1 = (int)image->width - 1; }
876 if (y1 >= (int)image->height) { y1 = (int)image->height - 1; }
877 for (int y = y0; y <= y1; y++) {
878 for (int x = x0; x <= x1; x++) {
879 int dx = x - cx, dy = y - cy;
880 int distance2 = dx * dx + dy * dy;
881 if (distance2 <= radius * radius && (inner <= 0 || distance2 >= inner * inner)) {
882 put_blended_pixel(image, x, y, red, green, blue, alpha);
883 }
884 }
885 }
886}
887
888/**
889 * @brief Draw a distinct, high-contrast marker for the estimated loudest spot.
890 * @param image Destination image.
891 * @param x Marker center X.
892 * @param y Marker center Y.
893 * @param red Foreground red channel.
894 * @param green Foreground green channel.
895 * @param blue Foreground blue channel.
896 * @details A dark casing pass precedes the colored stroke so the estimate remains
897 * visible over both bright and dark map/heat pixels.
898 */
899static void draw_crosshair(struct rgb_image *image, int x, int y,
900 uint8_t red, uint8_t green, uint8_t blue)
901{
902 const int radius = 9, arm = 24, gap = 4;
903 for (int pass = 0; pass < 2; pass++) {
904 int width = pass == 0 ? 5 : 2;
905 uint8_t r = pass == 0 ? 0 : red;
906 uint8_t g = pass == 0 ? 0 : green;
907 uint8_t b = pass == 0 ? 0 : blue;
908 for (int axis = 0; axis < 2; axis++) {
909 int dx = axis == 0 ? 1 : 0;
910 int dy = axis == 0 ? 0 : 1;
911 draw_line(image, x + dx * gap, y + dy * gap, x + dx * arm, y + dy * arm, width, r, g, b, 1.0);
912 draw_line(image, x - dx * gap, y - dy * gap, x - dx * arm, y - dy * arm, width, r, g, b, 1.0);
913 draw_circle(image, x, y, radius, width, r, g, b, 1.0);
914 }
915 }
916}
917
918/**
919 * @brief Draw the known simulation source as a shape distinct from the estimate.
920 * @param image Destination image.
921 * @param x Diamond center X.
922 * @param y Diamond center Y.
923 * @param radius Diamond half-width and half-height.
924 * @param red Foreground red channel.
925 * @param green Foreground green channel.
926 * @param blue Foreground blue channel.
927 * @details Truth is a separate simulation reference, not another sensor reading;
928 * the black outline keeps that distinction visible on any background.
929 */
930static void draw_diamond(struct rgb_image *image, int x, int y, int radius,
931 uint8_t red, uint8_t green, uint8_t blue)
932{
933 const int offsets[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
934 for (int pass = 0; pass < 2; pass++) {
935 int width = pass == 0 ? 5 : 2;
936 uint8_t r = pass == 0 ? 0 : red;
937 uint8_t g = pass == 0 ? 0 : green;
938 uint8_t b = pass == 0 ? 0 : blue;
939 for (int side = 0; side < 4; side++) {
940 int next = (side + 1) % 4;
941 draw_line(image, x + offsets[side][0] * radius, y + offsets[side][1] * radius,
942 x + offsets[next][0] * radius, y + offsets[next][1] * radius,
943 width, r, g, b, 1.0);
944 }
945 }
946}
947
948/**
949 * @brief Return one embedded 5x7 uppercase bitmap glyph.
950 * @param character ASCII label character; unsupported characters become blank.
951 * @return Seven row bitmasks with five meaningful bits each.
952 * @details This tiny font keeps annotation text independent of system font files
953 * and avoids adding a font-rendering library to the host utility.
954 */
955static const uint8_t *glyph_rows(char character)
956{
957 static const uint8_t font[59][7] = {
958 ['(' - 32] = {2, 4, 8, 8, 8, 4, 2}, [')' - 32] = {8, 4, 2, 2, 2, 4, 8},
959 [',' - 32] = {0, 0, 0, 0, 0, 4, 8}, ['-' - 32] = {0, 0, 0, 31, 0, 0, 0},
960 ['.' - 32] = {0, 0, 0, 0, 0, 12, 12}, ['0' - 32] = {14, 17, 19, 21, 25, 17, 14},
961 ['1' - 32] = {4, 12, 4, 4, 4, 4, 14}, ['2' - 32] = {14, 17, 1, 2, 4, 8, 31},
962 ['3' - 32] = {30, 1, 1, 14, 1, 1, 30}, ['4' - 32] = {2, 6, 10, 18, 31, 2, 2},
963 ['5' - 32] = {31, 16, 16, 30, 1, 1, 30}, ['6' - 32] = {14, 16, 16, 30, 17, 17, 14},
964 ['7' - 32] = {31, 1, 2, 4, 8, 8, 8}, ['8' - 32] = {14, 17, 17, 14, 17, 17, 14},
965 ['9' - 32] = {14, 17, 17, 15, 1, 1, 14}, [':' - 32] = {0, 12, 12, 0, 12, 12, 0},
966 ['=' - 32] = {0, 31, 0, 31, 0, 0, 0}, ['>' - 32] = {16, 8, 4, 2, 4, 8, 16},
967 ['A' - 32] = {14, 17, 17, 31, 17, 17, 17}, ['B' - 32] = {30, 17, 17, 30, 17, 17, 30},
968 ['C' - 32] = {14, 17, 16, 16, 16, 17, 14}, ['D' - 32] = {30, 17, 17, 17, 17, 17, 30},
969 ['E' - 32] = {31, 16, 16, 30, 16, 16, 31}, ['F' - 32] = {31, 16, 16, 30, 16, 16, 16},
970 ['G' - 32] = {14, 17, 16, 23, 17, 17, 15}, ['H' - 32] = {17, 17, 17, 31, 17, 17, 17},
971 ['I' - 32] = {14, 4, 4, 4, 4, 4, 14}, ['J' - 32] = {7, 2, 2, 2, 18, 18, 12},
972 ['K' - 32] = {17, 18, 20, 24, 20, 18, 17}, ['L' - 32] = {16, 16, 16, 16, 16, 16, 31},
973 ['M' - 32] = {17, 27, 21, 21, 17, 17, 17}, ['N' - 32] = {17, 25, 21, 19, 17, 17, 17},
974 ['O' - 32] = {14, 17, 17, 17, 17, 17, 14}, ['P' - 32] = {30, 17, 17, 30, 16, 16, 16},
975 ['Q' - 32] = {14, 17, 17, 17, 21, 18, 13}, ['R' - 32] = {30, 17, 17, 30, 20, 18, 17},
976 ['S' - 32] = {15, 16, 16, 14, 1, 1, 30}, ['T' - 32] = {31, 4, 4, 4, 4, 4, 4},
977 ['U' - 32] = {17, 17, 17, 17, 17, 17, 14}, ['V' - 32] = {17, 17, 17, 17, 17, 10, 4},
978 ['W' - 32] = {17, 17, 17, 21, 21, 21, 10}, ['X' - 32] = {17, 17, 10, 4, 10, 17, 17},
979 ['Y' - 32] = {17, 17, 10, 4, 4, 4, 4}, ['Z' - 32] = {31, 1, 2, 4, 8, 16, 31}
980 };
981 unsigned char upper = (unsigned char)toupper((unsigned char)character);
982 return upper >= 32U && upper <= 90U ? font[upper - 32U] : font[' ' - 32];
983}
984
985/**
986 * @brief Paint one foreground or outline pass of bitmap text.
987 * @param image Destination image.
988 * @param x Left coordinate.
989 * @param y Top coordinate.
990 * @param text NUL-terminated label.
991 * @param scale Integer expansion per glyph pixel.
992 * @param red Text red channel.
993 * @param green Text green channel.
994 * @param blue Text blue channel.
995 */
996static void draw_text_pass(struct rgb_image *image, int x, int y, const char *text,
997 unsigned int scale, uint8_t red, uint8_t green, uint8_t blue)
998{
999 for (const unsigned char *cursor = (const unsigned char *)text; *cursor != '\0'; cursor++) {
1000 const uint8_t *glyph = glyph_rows((char)*cursor);
1001 for (unsigned int row = 0; row < 7U; row++) {
1002 for (unsigned int column = 0; column < 5U; column++) {
1003 if ((glyph[row] & (1U << (4U - column))) == 0) { continue; }
1004 for (unsigned int dy = 0; dy < scale; dy++) {
1005 for (unsigned int dx = 0; dx < scale; dx++) {
1006 put_blended_pixel(image, x + (int)(column * scale + dx), y + (int)(row * scale + dy),
1007 red, green, blue, 1.0);
1008 }
1009 }
1010 }
1011 }
1012 x += (int)(6U * scale);
1013 }
1014}
1015
1016/**
1017 * @brief Draw a small outlined label over arbitrary imagery.
1018 * @param image Destination image.
1019 * @param x Left coordinate.
1020 * @param y Top coordinate.
1021 * @param text NUL-terminated label.
1022 * @param red Foreground red channel.
1023 * @param green Foreground green channel.
1024 * @param blue Foreground blue channel.
1025 * @details The eight-neighbor dark casing is a lightweight contrast aid; no
1026 * external font or graphics library is needed for these short map labels.
1027 */
1028static void draw_text(struct rgb_image *image, int x, int y, const char *text,
1029 uint8_t red, uint8_t green, uint8_t blue)
1030{
1031 const unsigned int scale = 2U;
1032 for (int dy = -1; dy <= 1; dy++) {
1033 for (int dx = -1; dx <= 1; dx++) {
1034 if (dx != 0 || dy != 0) { draw_text_pass(image, x + dx, y + dy, text, scale, 0, 0, 0); }
1035 }
1036 }
1037 draw_text_pass(image, x, y, text, scale, red, green, blue);
1038}
1039
1040/**
1041 * @brief Convert a geographic annotation to pixels in the cropped tile mosaic.
1042 * @param lat Latitude in degrees.
1043 * @param lon Longitude in degrees.
1044 * @param origin_x Fractional XYZ X coordinate of output origin.
1045 * @param origin_y Fractional XYZ Y coordinate of output origin.
1046 * @param zoom Shared Web Mercator zoom.
1047 * @param x Receives image-space X.
1048 * @param y Receives image-space Y.
1049 */
1050static void pixel_location(double lat, double lon, double origin_x, double origin_y,
1051 unsigned int zoom, int *x, int *y)
1052{
1053 double tile_x, tile_y;
1054 mercator_xy(lat, lon, zoom, &tile_x, &tile_y);
1055 *x = (int)floor((tile_x - origin_x) * TILE_SIZE);
1056 *y = (int)floor((tile_y - origin_y) * TILE_SIZE);
1057}
1058
1059/**
1060 * @brief Append a point into caller-owned bounded storage.
1061 * @param list Point list view.
1062 * @param point Validated point to copy.
1063 * @return 0 on append, -1 when its fixed capacity is exhausted.
1064 */
1065static int append_point(struct point_list *list, const struct point *point)
1066{
1067 if (list->count >= list->capacity) { return -1; }
1068 list->items[list->count++] = *point;
1069 return 0;
1070}
1071
1072/**
1073 * @brief Parse one complete numeric field from a bounded CSV row.
1074 * @param line CSV record buffer.
1075 * @param column Zero-based field index.
1076 * @param value Receives the finite number on success.
1077 * @return true only when the selected field exists and contains a complete number.
1078 * @details A short stack token buffer rejects overlong cells rather than sizing
1079 * memory from untrusted file contents.
1080 */
1081static bool csv_number(const char *line, unsigned int column, double *value)
1082{
1083 const char *field = line;
1084 for (unsigned int index = 0; index < column; index++) {
1085 field = strchr(field, ',');
1086 if (field == NULL) { return false; }
1087 field++;
1088 }
1089 char buffer[128];
1090 size_t length = strcspn(field, ",\r\n");
1091 if (length == 0 || length >= sizeof(buffer)) { return false; }
1092 for (size_t index = 0; index < length; index++) { buffer[index] = field[index]; }
1093 buffer[length] = '\0';
1094 return parse_double(buffer, value);
1095}
1096
1097/**
1098 * @brief Read geographic points from an EAR session or aircraft-track CSV.
1099 * @param path CSV path.
1100 * @param session_log Select session columns/timestamps instead of track schema.
1101 * @param points Bounded destination list view.
1102 * @return 0 after a complete read, -1 for I/O errors or record-cap overflow.
1103 * @details Session time is milliseconds and positions are columns 2/3; track time
1104 * is seconds and positions are columns 1/2. Invalid poses are skipped, not plotted.
1105 */
1106static int read_points(const char *path, bool session_log, struct point_list *points)
1107{
1108 FILE *input = fopen(path, "r");
1109 if (input == NULL) { perror(path); return -1; }
1110 char line[MAX_CSV_LINE];
1111 int status = 0;
1112 while (fgets(line, sizeof(line), input) != NULL) {
1113 if (line[0] == '\0' || line[0] == '#' || line[0] == 't') { continue; }
1114 struct point point = {0};
1115 double stamp = 0.0;
1116 bool valid = csv_number(line, 0, &stamp)
1117 && csv_number(line, session_log ? 2U : 1U, &point.lat)
1118 && csv_number(line, session_log ? 3U : 2U, &point.lon);
1119 if (!valid || !isfinite(point.lat) || !isfinite(point.lon) || fabs(point.lat) <= 1e-6
1120 || fabs(point.lat) > 90.0 || fabs(point.lon) > 180.0) { continue; }
1121 point.time_s = session_log ? stamp / 1000.0 : stamp;
1122 if (append_point(points, &point) != 0) { status = -1; break; }
1123 }
1124 if (ferror(input) != 0) { status = -1; }
1125 if (fclose(input) != 0) { status = -1; }
1126 if (status != 0) { fprintf(stderr, "%s: invalid or excessive CSV input\n", path); }
1127 return status;
1128}
1129
1130/**
1131 * @brief Locate an exact field name in a CSV header without mutating the source.
1132 * @param header Bounded header row.
1133 * @param name Required column name.
1134 * @return Zero-based field index, or -1 when absent or overlong.
1135 * @details Each lookup tokenizes a stack copy so querying several required fields
1136 * does not consume or corrupt the shared header.
1137 */
1138static int header_column(const char *header, const char *name)
1139{
1140 char copy[MAX_CSV_LINE];
1141 size_t length = strnlen(header, sizeof(copy));
1142 if (length >= sizeof(copy)) { return -1; }
1143 for (size_t index = 0; index <= length; index++) { copy[index] = header[index]; }
1144 int column = 0;
1145 char *save = NULL;
1146 for (char *field = strtok_r(copy, ",\r\n", &save); field != NULL; field = strtok_r(NULL, ",\r\n", &save), column++) {
1147 if (strcmp(field, name) == 0) { return column; }
1148 }
1149 return -1;
1150}
1151
1152/** @brief Read one required numeric column from a LiDAR CSV row. */
1153static bool csv_column(const char *line, unsigned int column, double *value)
1154{
1155 return csv_number(line, column, value);
1156}
1157
1158/**
1159 * @brief Append one obstacle cell when fixed storage has room.
1160 * @param list Bounded obstacle list view.
1161 * @param obstacle Validated cell to copy.
1162 * @return 0 on append, -1 when the configured cell cap is reached.
1163 */
1164static int append_obstacle(struct obstacle_list *list, const struct obstacle *obstacle)
1165{
1166 if (list->count >= list->capacity) { return -1; }
1167 list->items[list->count++] = *obstacle;
1168 return 0;
1169}
1170
1171/** @brief Order projected eastings so adjacent positive deltas reveal cell pitch. */
1172static int compare_double(const void *left, const void *right)
1173{
1174 double a = *(const double *)left;
1175 double b = *(const double *)right;
1176 return (a > b) - (a < b);
1177}
1178
1179/**
1180 * @brief Read the optional regular LiDAR height grid and infer its cell width.
1181 * @param path CSV with `x_east_m`, `lat`, `lon`, and `mnh_m` header columns.
1182 * @param obstacles Receives validated cells in fixed-capacity storage.
1183 * @param cell_size Receives the smallest positive spacing between eastings.
1184 * @return 0 for a usable grid, -1 for I/O, schema, capacity or spacing failures.
1185 * @details Sorting the projected eastings distinguishes grid pitch from geographic
1186 * map scale; height colors remain visual context, not a clearance/navigation result.
1187 */
1188static int read_obstacles(const char *path, struct obstacle_list *obstacles, double *cell_size)
1189{
1190 FILE *input = fopen(path, "r");
1191 if (input == NULL) { perror(path); return -1; }
1192 char line[MAX_CSV_LINE];
1193 int east_column = -1, lat_column = -1, lon_column = -1, height_column = -1;
1194 if (fgets(line, sizeof(line), input) != NULL) {
1195 east_column = header_column(line, "x_east_m");
1196 lat_column = header_column(line, "lat");
1197 lon_column = header_column(line, "lon");
1198 height_column = header_column(line, "mnh_m");
1199 }
1200 if (east_column < 0 || lat_column < 0 || lon_column < 0 || height_column < 0) {
1201 fclose(input);
1202 fprintf(stderr, "%s: expected x_east_m,lat,lon,mnh_m columns\n", path);
1203 return -1;
1204 }
1205 double *eastings = obstacle_eastings;
1206 size_t easting_count = 0;
1207 int status = 0;
1208 while (fgets(line, sizeof(line), input) != NULL) {
1209 double values[4];
1210 int columns[4] = {east_column, lat_column, lon_column, height_column};
1211 bool valid = true;
1212 for (int index = 0; index < 4; index++) {
1213 if (!csv_column(line, (unsigned int)columns[index], &values[index])) { valid = false; break; }
1214 }
1215 if (!valid || fabs(values[1]) > 90.0 || fabs(values[2]) > 180.0) { continue; }
1216 struct obstacle obstacle = {values[0], values[1], values[2], values[3]};
1217 if (append_obstacle(obstacles, &obstacle) != 0) { status = -1; break; }
1218 if (easting_count >= MAX_CSV_POINTS) { status = -1; break; }
1219 eastings[easting_count++] = values[0];
1220 }
1221 if (ferror(input) != 0) { status = -1; }
1222 fclose(input);
1223 if (status == 0 && easting_count > 1) {
1224 qsort(eastings, easting_count, sizeof(*eastings), compare_double);
1225 *cell_size = INFINITY;
1226 for (size_t index = 1; index < easting_count; index++) {
1227 double difference = eastings[index] - eastings[index - 1];
1228 if (difference > 0.0 && difference < *cell_size) { *cell_size = difference; }
1229 }
1230 if (!isfinite(*cell_size)) { status = -1; }
1231 } else { status = -1; }
1232 if (status != 0) { fprintf(stderr, "%s: no usable obstacle-grid spacing\n", path); }
1233 return status;
1234}
1235
1236/**
1237 * @brief Compute great-circle distance between two latitude/longitude points.
1238 * @param lat_a First latitude in degrees.
1239 * @param lon_a First longitude in degrees.
1240 * @param lat_b Second latitude in degrees.
1241 * @param lon_b Second longitude in degrees.
1242 * @return Spherical-Earth separation in metres.
1243 * @details Used to annotate known simulation truth versus the estimate; it does
1244 * not correct the estimate or certify field accuracy.
1245 */
1246static double haversine_m(double lat_a, double lon_a, double lat_b, double lon_b)
1247{
1248 double d_lat = (lat_b - lat_a) * DEG_TO_RAD;
1249 double d_lon = (lon_b - lon_a) * DEG_TO_RAD;
1250 double a = sin(d_lat / 2.0) * sin(d_lat / 2.0)
1251 + cos(lat_a * DEG_TO_RAD) * cos(lat_b * DEG_TO_RAD)
1252 * sin(d_lon / 2.0) * sin(d_lon / 2.0);
1253 return 2.0 * EARTH_RADIUS_M * asin(sqrt(fmax(0.0, fmin(1.0, a))));
1254}
1255
1256/**
1257 * @brief Redraw sample locations as crisp dots over the blended sound field.
1258 * @param image Output map.
1259 * @param points Parsed EAR session observations.
1260 * @param origin_x Fractional XYZ X coordinate of output origin.
1261 * @param origin_y Fractional XYZ Y coordinate of output origin.
1262 * @param zoom Map tile zoom.
1263 * @details A black edge and white core keep individual observations visible on
1264 * both satellite imagery and the heat palette.
1265 */
1266static void draw_log_points(struct rgb_image *image, const struct point_list *points,
1267 double origin_x, double origin_y, unsigned int zoom)
1268{
1269 for (size_t index = 0; index < points->count; index++) {
1270 int x, y;
1271 pixel_location(points->items[index].lat, points->items[index].lon, origin_x, origin_y, zoom, &x, &y);
1272 draw_circle(image, x, y, 2, 2, 0, 0, 0, 1.0);
1273 draw_circle(image, x, y, 1, 1, 255, 255, 255, 1.0);
1274 }
1275}
1276
1277/**
1278 * @brief Draw aircraft-track segments, breaking where fixes are too far apart.
1279 * @param image Output map.
1280 * @param points Ordered fixes with normalized second timestamps.
1281 * @param origin_x Fractional XYZ X coordinate of output origin.
1282 * @param origin_y Fractional XYZ Y coordinate of output origin.
1283 * @param zoom Map tile zoom.
1284 * @param gap_s Largest allowed timestamp gap within a connected segment.
1285 * @details Breaking stale intervals avoids drawing a fabricated straight path
1286 * through periods where no aircraft positions were recorded.
1287 */
1288static void draw_track(struct rgb_image *image, const struct point_list *points,
1289 double origin_x, double origin_y, unsigned int zoom, double gap_s)
1290{
1291 for (size_t index = 1; index < points->count; index++) {
1292 if (points->items[index].time_s - points->items[index - 1].time_s > gap_s) { continue; }
1293 int x0, y0, x1, y1;
1294 pixel_location(points->items[index - 1].lat, points->items[index - 1].lon, origin_x, origin_y, zoom, &x0, &y0);
1295 pixel_location(points->items[index].lat, points->items[index].lon, origin_x, origin_y, zoom, &x1, &y1);
1296 draw_line(image, x0, y0, x1, y1, 3, 0, 0, 0, 0.9);
1297 draw_line(image, x0, y0, x1, y1, 1, 255, 235, 120, 1.0);
1298 }
1299}
1300
1301/**
1302 * @brief Paint optional height-above-terrain cells over the output map.
1303 * @param image Output map.
1304 * @param obstacles Parsed regular LiDAR cells.
1305 * @param cell_size Projected cell pitch in metres.
1306 * @param m_per_deg_lat Local metres per latitude degree.
1307 * @param m_per_deg_lon Local metres per longitude degree.
1308 * @param origin_x Fractional XYZ X coordinate of output origin.
1309 * @param origin_y Fractional XYZ Y coordinate of output origin.
1310 * @param zoom Map tile zoom.
1311 * @details Cell bounds are clipped before painting, and color bands are only
1312 * qualitative review aids; no collision or flight-control logic consumes them.
1313 */
1314static void draw_obstacles(struct rgb_image *image, const struct obstacle_list *obstacles,
1315 double cell_size, double m_per_deg_lat, double m_per_deg_lon,
1316 double origin_x, double origin_y, unsigned int zoom)
1317{
1318 for (size_t index = 0; index < obstacles->count; index++) {
1319 const struct obstacle *cell = &obstacles->items[index];
1320 if (cell->height_m < 3.0) { continue; }
1321 int x0, y0, x1, y1;
1322 pixel_location(cell->lat + cell_size / (2.0 * m_per_deg_lat),
1323 cell->lon - cell_size / (2.0 * m_per_deg_lon), origin_x, origin_y, zoom, &x0, &y0);
1324 pixel_location(cell->lat - cell_size / (2.0 * m_per_deg_lat),
1325 cell->lon + cell_size / (2.0 * m_per_deg_lon), origin_x, origin_y, zoom, &x1, &y1);
1326 if (x0 > x1) { int swap = x0; x0 = x1; x1 = swap; }
1327 if (y0 > y1) { int swap = y0; y0 = y1; y1 = swap; }
1328 if (x1 < 0 || y1 < 0 || x0 >= (int)image->width || y0 >= (int)image->height) { continue; }
1329 if (x0 < 0) { x0 = 0; }
1330 if (y0 < 0) { y0 = 0; }
1331 if (x1 >= (int)image->width) { x1 = (int)image->width - 1; }
1332 if (y1 >= (int)image->height) { y1 = (int)image->height - 1; }
1333 double alpha = cell->height_m > 6.0 ? 0.48 : 0.35;
1334 for (int y = y0; y <= y1; y++) {
1335 for (int x = x0; x <= x1; x++) { put_blended_pixel(image, x, y, 255, cell->height_m > 6.0 ? 40 : 150, 40, alpha); }
1336 }
1337 }
1338}
1339
1340/**
1341 * @brief Assemble basemap tiles, heatfield and optional annotations into one output raster.
1342 * @param options Parsed cache, projection and annotation policy.
1343 * @param geo Validated local-projection footprint from the `.geo` sidecar.
1344 * @param heat Undecorated `_field.jpg` when present, otherwise the input JPEG.
1345 * @param output Receives the final cropped raster in fixed output storage.
1346 * @return 0 after composition, or -1 for malformed annotations, unsupported bounds,
1347 * cache failures or capacity limits.
1348 * @details Bounds are computed before tile access; only intersecting tiles are
1349 * assembled, heat pixels are projected individually, then crisp evidence layers
1350 * are drawn on top. No step feeds back into acoustic measurements or navigation.
1351 */
1352static int build_output(const struct options *options, const struct ear_heatmap_georef *geo,
1353 const struct rgb_image *heat, struct rgb_image *output)
1354{
1355 double search_lat = 0.0, search_lon = 0.0, search_radius = 25.0;
1356 bool has_search = options->search_text != NULL;
1357 if (has_search && !parse_location(options->search_text, true, &search_lat, &search_lon, &search_radius)) {
1358 fprintf(stderr, "--search expects LAT,LON[,RADIUS_M]\n"); return -1;
1359 }
1360 double truth_lat = 0.0, truth_lon = 0.0, unused_radius = 0.0;
1361 bool has_truth = options->truth_text != NULL;
1362 if (has_truth && !parse_location(options->truth_text, false, &truth_lat, &truth_lon, &unused_radius)) {
1363 fprintf(stderr, "--truth expects LAT,LON\n"); return -1;
1364 }
1365 double m_per_deg_lat = DEG_TO_RAD * EARTH_RADIUS_M;
1366 double m_per_deg_lon = m_per_deg_lat * cos(geo->lat_center * DEG_TO_RAD);
1367 if (m_per_deg_lon <= 1e-6) { fprintf(stderr, "Heatmap is too close to a pole.\n"); return -1; }
1368 // Keep the field's local equirectangular origin explicit; basemap pixels are Mercator.
1369 double east0 = (geo->lon_west - geo->lon_center) * m_per_deg_lon;
1370 double north0 = (geo->lat_north - geo->lat_center) * m_per_deg_lat;
1371 double width_m = geo->width_px * geo->m_per_px;
1372 double height_m = geo->height_px * geo->m_per_px;
1373 // Expand map bounds far enough to include the full optional search circle.
1374 double margin = options->margin_m;
1375 if (has_search) {
1376 double east = (search_lon - geo->lon_center) * m_per_deg_lon;
1377 double north = (search_lat - geo->lat_center) * m_per_deg_lat;
1378 double needed[4] = {east + search_radius - (east0 + width_m) + 5.0,
1379 east0 - (east - search_radius) + 5.0,
1380 north + search_radius - north0 + 5.0,
1381 (north0 - height_m) - (north - search_radius) + 5.0};
1382 for (unsigned int index = 0; index < 4; index++) { if (needed[index] > margin) { margin = needed[index]; } }
1383 }
1384 double lat_north = geo->lat_center + (north0 + margin) / m_per_deg_lat;
1385 double lat_south = geo->lat_center + (north0 - height_m - margin) / m_per_deg_lat;
1386 double lon_west = geo->lon_center + (east0 - margin) / m_per_deg_lon;
1387 double lon_east = geo->lon_center + (east0 + width_m + margin) / m_per_deg_lon;
1388 if (lat_north > 85.0 || lat_south < -85.0 || lon_west < -180.0 || lon_east > 180.0) {
1389 fprintf(stderr, "Requested overlay crosses supported map bounds.\n"); return -1;
1390 }
1391 unsigned int zoom = options->zoom == 0 ? choose_zoom(geo, options->max_zoom) : options->zoom;
1392 double x_w, y_n, x_e, y_s;
1393 mercator_xy(lat_north, lon_west, zoom, &x_w, &y_n);
1394 mercator_xy(lat_south, lon_east, zoom, &x_e, &y_s);
1395 if (!(x_e > x_w && y_s > y_n)) { return -1; }
1396 int tx0 = (int)floor(x_w), ty0 = (int)floor(y_n);
1397 int tx1 = (int)floor(x_e), ty1 = (int)floor(y_s);
1398 if (tx0 < 0 || ty0 < 0 || tx1 < tx0 || ty1 < ty0
1399 || tx1 >= (int)ldexp(1.0, (int)zoom) || ty1 >= (int)ldexp(1.0, (int)zoom)) {
1400 fprintf(stderr, "Tile bounds are outside Web Mercator.\n"); return -1;
1401 }
1402 // Reject oversized requests before touching cache/network or output storage.
1403 uint64_t tile_count = (uint64_t)(tx1 - tx0 + 1) * (uint64_t)(ty1 - ty0 + 1);
1404 if (tile_count > MAX_TILE_COUNT) { fprintf(stderr, "Overlay requires too many map tiles (%llu).\n", (unsigned long long)tile_count); return -1; }
1405 int crop_x = (int)floor((x_w - tx0) * TILE_SIZE);
1406 int crop_y = (int)floor((y_n - ty0) * TILE_SIZE);
1407 int end_x = (int)ceil((x_e - tx0) * TILE_SIZE);
1408 int end_y = (int)ceil((y_s - ty0) * TILE_SIZE);
1409 if (end_x <= crop_x || end_y <= crop_y) { return -1; }
1410 output->width = (unsigned int)(end_x - crop_x);
1411 output->height = (unsigned int)(end_y - crop_y);
1412 uint64_t pixels = (uint64_t)output->width * output->height;
1413 if (pixels > MAX_OUTPUT_PIXELS) {
1414 fprintf(stderr, "Overlay output exceeds the %u-pixel memory limit. Increase margin less or choose a lower zoom.\n", MAX_OUTPUT_PIXELS);
1415 return -1;
1416 }
1417 // One bounded mosaic buffer avoids a second full-resolution assembly surface.
1418 output->pixels = output_pixels;
1419 output->capacity_bytes = sizeof(output_pixels);
1420 for (size_t index = 0; index < (size_t)pixels * 3U; index++) { output->pixels[index] = 0; }
1421 for (int ty = ty0; ty <= ty1; ty++) {
1422 for (int tx = tx0; tx <= tx1; tx++) {
1423 struct rgb_image tile = {.pixels = tile_pixels, .capacity_bytes = sizeof(tile_pixels)};
1424 if (fetch_tile(options, (unsigned int)tx, (unsigned int)ty, zoom, &tile) != 0) { return -1; }
1425 copy_tile_to_output(&tile, output, tx, ty, crop_x, crop_y);
1426 image_free(&tile);
1427 }
1428 }
1429 int crop_end_x = crop_x + (int)output->width;
1430 int crop_end_y = crop_y + (int)output->height;
1431 // All later field/marker transforms share the crop's pixel-aligned XYZ origin.
1432 double origin_x = tx0 + (double)crop_x / TILE_SIZE;
1433 double origin_y = ty0 + (double)crop_y / TILE_SIZE;
1434 (void)crop_end_x;
1435 (void)crop_end_y;
1436 composite_heatmap(output, heat, geo, zoom, crop_x, crop_y, options->alpha);
1437
1438 // Draw evidence after the translucent field so sample/track colors stay legible.
1439 struct point_list samples = {.items = session_points, .capacity = MAX_CSV_POINTS};
1440 struct point_list track = {.items = track_points, .capacity = MAX_CSV_POINTS};
1441 if (options->log_path != NULL && read_points(options->log_path, true, &samples) != 0) { return -1; }
1442 if (options->track_path != NULL && read_points(options->track_path, false, &track) != 0) { return -1; }
1443 draw_log_points(output, &samples, origin_x, origin_y, zoom);
1444 struct obstacle_list obstacles = {.items = obstacle_cells, .capacity = MAX_CSV_POINTS};
1445 if (options->obstacles_path != NULL) {
1446 double cell_size = 0.0;
1447 if (read_obstacles(options->obstacles_path, &obstacles, &cell_size) != 0) {
1448 return -1;
1449 }
1450 draw_obstacles(output, &obstacles, cell_size, m_per_deg_lat, m_per_deg_lon, origin_x, origin_y, zoom);
1451 draw_text(output, 4, 4, "TREES 3-6M ORANGE 6M+ RED", 255, 170, 90);
1452 }
1453 double output_m_per_px = mercator_m_per_pixel(geo->lat_center, zoom);
1454 int bar_length = (int)fmin(50.0 / output_m_per_px, 0.6 * output->width);
1455 int bar_x = (int)(0.04 * output->width);
1456 int bar_y = (int)(0.94 * output->height);
1457 draw_line(output, bar_x, bar_y, bar_x + bar_length, bar_y, 5, 0, 0, 0, 1.0);
1458 draw_line(output, bar_x, bar_y, bar_x + bar_length, bar_y, 2, 255, 255, 255, 1.0);
1459 draw_line(output, bar_x, bar_y - 6, bar_x, bar_y + 6, 2, 255, 255, 255, 1.0);
1460 draw_line(output, bar_x + bar_length, bar_y - 6, bar_x + bar_length, bar_y + 6, 2, 255, 255, 255, 1.0);
1461 draw_text(output, bar_x, bar_y - 19, "50 M", 255, 255, 255);
1462 draw_track(output, &track, origin_x, origin_y, zoom, options->track_gap_s);
1463 if (geo->has_spot) {
1464 int x, y;
1465 pixel_location(geo->spot_lat, geo->spot_lon, origin_x, origin_y, zoom, &x, &y);
1466 draw_crosshair(output, x, y, 255, 40, 255);
1467 draw_text(output, x + 12, y + 10, "LOUDEST SPOT", 255, 40, 255);
1468 }
1469 if (has_search) {
1470 int x, y;
1471 pixel_location(search_lat, search_lon, origin_x, origin_y, zoom, &x, &y);
1472 int radius = (int)(search_radius / output_m_per_px + 0.5);
1473 draw_circle(output, x, y, radius, 2, 255, 255, 255, 1.0);
1474 draw_line(output, x - 6, y, x + 6, y, 2, 255, 255, 255, 1.0);
1475 draw_line(output, x, y - 6, x, y + 6, 2, 255, 255, 255, 1.0);
1476 char radius_label[48];
1477 snprintf(radius_label, sizeof(radius_label), "R=%.0f M", search_radius);
1478 draw_text(output, x + 8, y - radius - 20, "GIVEN POINT", 255, 255, 255);
1479 draw_text(output, x - 12, y - radius - 4, radius_label, 255, 255, 255);
1480 }
1481 if (has_truth) {
1482 int x, y;
1483 pixel_location(truth_lat, truth_lon, origin_x, origin_y, zoom, &x, &y);
1484 draw_diamond(output, x, y, 9, 255, 40, 40);
1485 draw_text(output, x + 12, y - 24, "SOUND SOURCE", 255, 70, 70);
1486 if (geo->has_spot) {
1487 double offset_m = haversine_m(truth_lat, truth_lon, geo->spot_lat, geo->spot_lon);
1488 char offset_label[48];
1489 snprintf(offset_label, sizeof(offset_label), "%.1f M OFF", offset_m);
1490 draw_text(output, x + 12, y - 8, offset_label, 255, 70, 70);
1491 fprintf(stderr, "truth-to-estimated-spot=%.1f m\n", offset_m);
1492 }
1493 }
1494 if (!options->quiet) {
1495 printf("overlay %ux%u, %s tiles z%u, %.3f m/px\n", output->width, output->height,
1496 options->source, zoom, output_m_per_px);
1497 }
1498 return 0;
1499}
1500
1501/**
1502 * @brief Validate replay artifacts, compose the map context and write a JPEG.
1503 * @param argc Command-line argument count.
1504 * @param argv Process arguments; option strings are borrowed for this invocation.
1505 * @return 0 on success, 2 for usage/policy errors, or 1 for I/O/data failure.
1506 * @details Prefer the matching undecorated field because reusing the decorated
1507 * heatmap would blend its original dots/marker into the basemap a second time.
1508 * The sidecar dimensions are checked before any map data is read.
1509 */
1510int main(int argc, char **argv)
1511{
1512 if (argc == 2 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)) {
1514 return 0;
1515 }
1516 if (argc == 2 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) {
1517 print_help(argv[0]);
1518 return 0;
1519 }
1520 struct options options;
1521 if (!parse_options(argc, argv, &options)) {
1522 print_help(argv[0]);
1523 return 2;
1524 }
1525 if (options.source == NULL || (strcmp(options.source, "google") != 0 && strcmp(options.source, "esri") != 0)
1526 || options.max_zoom < 12 || options.max_zoom > 22 || options.zoom > 22
1527 || options.alpha < 0.0 || options.alpha > 1.0 || options.margin_m < 0.0
1528 || options.track_gap_s < 0.0) {
1529 fprintf(stderr, "Invalid source, zoom, alpha, margin or track gap.\n");
1530 return 2;
1531 }
1534 if (options.geo_path == NULL) {
1535 if (make_stem_path(options.input, ".geo", geo_path, sizeof(geo_path)) != 0) { return 2; }
1537 }
1538 if (make_stem_path(options.input, "_field.jpg", field_path, sizeof(field_path)) != 0) { return 2; }
1539 if (options.output_path == NULL) {
1540 if (make_stem_path(options.input, "_sat.jpg", output_path, sizeof(output_path)) != 0) { return 2; }
1542 }
1543 if (options.cache_path == NULL) {
1544 if (default_cache_path(cache_path, sizeof(cache_path)) != 0) {
1545 fprintf(stderr, "Set HOME or pass --cache.\n"); return 2;
1546 }
1548 }
1549 struct ear_heatmap_georef geo = {0};
1550 if (ear_heatmap_read_georef(options.geo_path, &geo) != 0) {
1551 fprintf(stderr, "%s: cannot read valid EAR heatmap georeference\n", options.geo_path); return 1;
1552 }
1553 // Decode exactly one raster into the fixed input buffer, avoiding a duplicate image copy.
1554 struct rgb_image field = {.pixels = input_pixels, .capacity_bytes = sizeof(input_pixels)};
1555 struct rgb_image output = {0};
1556 const char *field_input = access(field_path, R_OK) == 0 ? field_path : options.input;
1557 if (image_read_jpeg(field_input, &field) != 0) {
1558 fprintf(stderr, "Cannot read heatmap JPEG: %s\n", field_input); return 1;
1559 }
1560 if (field.width != geo.width_px || field.height != geo.height_px
1561 || field.width > MAX_INPUT_PIXELS || field.height > MAX_INPUT_PIXELS) {
1562 fprintf(stderr, "Heatmap dimensions do not match its .geo sidecar.\n");
1563 image_free(&field);
1564 return 1;
1565 }
1566 int status = build_output(&options, &geo, &field, &output);
1567 if (status == 0 && image_write_jpeg(options.output_path, &output) != 0) {
1568 perror(options.output_path);
1569 status = -1;
1570 }
1571 if (status == 0) { printf("wrote %s\n", options.output_path); }
1573 image_free(&field);
1574 return status == 0 ? 0 : 1;
1575}
static unsigned capacity[COVERAGE_CAMERAS]
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
static pid_t child
static FILE * session_log
#define DEG_TO_RAD
Definition ear_fusion.c:34
#define EARTH_RADIUS_M
Definition ear_fusion.c:33
int ear_heatmap_read_georef(const char *filename, struct ear_heatmap_georef *georef)
Read the georeference sidecar emitted by the heatmap renderer.
Render geotagged acoustic measurements into north-up JPEG heatmaps.
#define EAR_HEATMAP_NO_DATA_GREEN
Definition ear_heatmap.h:30
#define EAR_HEATMAP_NO_DATA_RED
Definition ear_heatmap.h:29
#define EAR_HEATMAP_NO_DATA_BLUE
Definition ear_heatmap.h:31
static void draw_log_points(struct rgb_image *image, const struct point_list *points, double origin_x, double origin_y, unsigned int zoom)
Redraw sample locations as crisp dots over the blended sound field.
static uint8_t output_pixels[(size_t) MAX_OUTPUT_PIXELS *3U]
static void draw_obstacles(struct rgb_image *image, const struct obstacle_list *obstacles, double cell_size, double m_per_deg_lat, double m_per_deg_lon, double origin_x, double origin_y, unsigned int zoom)
Paint optional height-above-terrain cells over the output map.
static int header_column(const char *header, const char *name)
Locate an exact field name in a CSV header without mutating the source.
static int default_cache_path(char *path, size_t capacity)
Resolve the Paparazzi GCS map-cache root from XDG environment settings.
static bool csv_number(const char *line, unsigned int column, double *value)
Parse one complete numeric field from a bounded CSV row.
static double obstacle_eastings[MAX_CSV_POINTS]
static double mercator_m_per_pixel(double lat, unsigned int zoom)
Estimate ground metres per tile pixel at a latitude.
static bool parse_location(const char *text, bool with_radius, double *lat, double *lon, double *radius)
Parse LAT,LON or LAT,LON,RADIUS_M into bounded geographic values.
static uint8_t tile_pixels[(size_t) TILE_SIZE *TILE_SIZE *3U]
static int build_output(const struct options *options, const struct ear_heatmap_georef *geo, const struct rgb_image *heat, struct rgb_image *output)
Assemble basemap tiles, heatfield and optional annotations into one output raster.
int main(int argc, char **argv)
Validate replay artifacts, compose the map context and write a JPEG.
static void gcs_key(unsigned int x, unsigned int y, unsigned int zoom, char *key, size_t capacity)
Encode an XYZ address using Paparazzi's legacy Google quadkey alphabet.
static void print_help(const char *program)
Print command synopsis and defaults from the same option vocabulary parsed below.
static int image_read_jpeg(const char *path, struct rgb_image *image)
Decode one JPEG into the caller's bounded RGB workspace.
static struct obstacle obstacle_cells[MAX_CSV_POINTS]
static int append_obstacle(struct obstacle_list *list, const struct obstacle *obstacle)
Append one obstacle cell when fixed storage has room.
static void draw_line(struct rgb_image *image, int x0, int y0, int x1, int y1, int width, uint8_t red, uint8_t green, uint8_t blue, double alpha)
Draw a raster line with an integer Bresenham walk.
static bool parse_options(int argc, char **argv, struct options *options)
Parse one positional heatmap and the supported optional controls.
static struct point track_points[MAX_CSV_POINTS]
#define DEFAULT_TRACK_GAP_S
static void draw_crosshair(struct rgb_image *image, int x, int y, uint8_t red, uint8_t green, uint8_t blue)
Draw a distinct, high-contrast marker for the estimated loudest spot.
static struct point session_points[MAX_CSV_POINTS]
#define TILE_SIZE
static int make_stem_path(const char *path, const char *suffix, char *output, size_t capacity)
Derive a sibling .geo, _field.jpg or _sat.jpg path from an image.
#define MAX_TILE_COUNT
static int fetch_tile(const struct options *options, unsigned int x, unsigned int y, unsigned int zoom, struct rgb_image *tile)
Read a local hit, fetch a miss if permitted, and decode one 256x256 tile.
static void pixel_location(double lat, double lon, double origin_x, double origin_y, unsigned int zoom, int *x, int *y)
Convert a geographic annotation to pixels in the cropped tile mosaic.
#define MAX_INPUT_PIXELS
static int tile_path(const struct options *options, unsigned int x, unsigned int y, unsigned int zoom, char *path, size_t capacity)
Select the first known local filename for an XYZ source tile.
static void draw_track(struct rgb_image *image, const struct point_list *points, double origin_x, double origin_y, unsigned int zoom, double gap_s)
Draw aircraft-track segments, breaking where fixes are too far apart.
#define DEFAULT_MAX_ZOOM
static unsigned int choose_zoom(const struct ear_heatmap_georef *geo, unsigned int max_zoom)
Select the first basemap zoom at least as detailed as the heatmap.
static uint8_t input_pixels[(size_t) MAX_INPUT_PIXELS *3U]
Reused input, tile and final RGB workspaces; avoid per-image allocator churn.
static void draw_text(struct rgb_image *image, int x, int y, const char *text, uint8_t red, uint8_t green, uint8_t blue)
Draw a small outlined label over arbitrary imagery.
#define MAX_PATH_LENGTH
static void put_blended_pixel(struct rgb_image *image, int x, int y, uint8_t red, uint8_t green, uint8_t blue, double alpha)
Blend one annotation pixel while clipping out-of-image coordinates.
static bool parse_unsigned(const char *text, unsigned int *value)
Parse an unsigned integer option without accepting suffix characters.
static double mercator_latitude(double tile_y, unsigned int zoom)
Invert fractional Web Mercator tile Y into a geographic latitude.
#define MAX_OUTPUT_PIXELS
static void draw_circle(struct rgb_image *image, int cx, int cy, int radius, int width, uint8_t red, uint8_t green, uint8_t blue, double alpha)
Draw a filled disc or clipped ring with a fixed-width stroke.
static bool csv_column(const char *line, unsigned int column, double *value)
Read one required numeric column from a LiDAR CSV row.
static int make_directories(const char *path)
Create parent directories for a tile file without treating the file as a directory.
#define MAX_CSV_POINTS
static void draw_diamond(struct rgb_image *image, int x, int y, int radius, uint8_t red, uint8_t green, uint8_t blue)
Draw the known simulation source as a shape distinct from the estimate.
#define DEFAULT_ALPHA
static void jpeg_error_exit(j_common_ptr info)
Convert libjpeg's fatal callback into a jump to the active operation.
static void draw_brush(struct rgb_image *image, int x, int y, int width, uint8_t red, uint8_t green, uint8_t blue, double alpha)
Stamp a square brush centered at an integer pixel.
static const uint8_t * glyph_rows(char character)
Return one embedded 5x7 uppercase bitmap glyph.
static void composite_heatmap(struct rgb_image *base, const struct rgb_image *field, const struct ear_heatmap_georef *geo, unsigned int zoom, int crop_x, int crop_y, double alpha)
Resample the local equirectangular heat field onto the Mercator tile mosaic.
static bool parse_double(const char *text, double *value)
Parse a finite floating-point token in full.
#define MAX_CSV_LINE
#define JPEG_QUALITY
static void mercator_xy(double lat, double lon, unsigned int zoom, double *x, double *y)
Project latitude/longitude into fractional Web Mercator tile coordinates.
static int read_points(const char *path, bool session_log, struct point_list *points)
Read geographic points from an EAR session or aircraft-track CSV.
#define DEFAULT_MARGIN_M
static int append_point(struct point_list *list, const struct point *point)
Append a point into caller-owned bounded storage.
static int image_write_jpeg(const char *path, const struct rgb_image *image)
Encode a bounded RGB view to a JPEG file.
static void image_free(struct rgb_image *image)
Invalidate an RGB view before its shared workspace is reused.
static int compare_double(const void *left, const void *right)
Order projected eastings so adjacent positive deltas reveal cell pitch.
static double haversine_m(double lat_a, double lon_a, double lat_b, double lon_b)
Compute great-circle distance between two latitude/longitude points.
static int copy_tile_to_output(const struct rgb_image *tile, struct rgb_image *output, int tile_x, int tile_y, int crop_x, int crop_y)
Copy only the part of a source tile intersecting the cropped output.
static int download_tile(const struct options *options, unsigned int x, unsigned int y, unsigned int zoom, const char *path)
Download one cache miss with the existing curl executable.
static int read_obstacles(const char *path, struct obstacle_list *obstacles, double *cell_size)
Read the optional regular LiDAR height grid and infer its cell width.
static void draw_text_pass(struct rgb_image *image, int x, int y, const char *text, unsigned int scale, uint8_t red, uint8_t green, uint8_t blue)
Paint one foreground or outline pass of bitmap text.
static struct ear_sample samples[EAR_MAX_SAMPLES]
#define PI
Definition earcam.c:90
struct jpeg_compress_struct encoder
Definition lwir_image.c:59
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
struct jpeg_decompress_struct decoder
Definition lwir_mock.c:55
static uint8_t glyph(char character, unsigned row)
One row of a built-in 5x7 bitmap font.
static void color(unsigned intensity, enum lwir_palette palette, unsigned *red, unsigned *green, unsigned *blue)
Map a window intensity to RGB for the selected palette.
static const char header[]
Definition pose_log.c:87
static FILE * output
Definition pose_log.c:77
Compile-time build identity strings for USHER executables.
#define EAR_HEATMAP_OVERLAY_BUILD_VERSION
Definition version.h:82
Validated geographic placement metadata shared by heatmap consumers.
Definition ear_heatmap.h:38
unsigned int width_px
Definition ear_heatmap.h:39
unsigned int height_px
Definition ear_heatmap.h:40
struct jpeg_error_mgr manager
Bounded view over LiDAR cells and their inferred regular spacing.
struct obstacle * items
One optional terrain-height cell supplied for visual context.
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
const char * truth_text
const char * obstacles_path
unsigned int max_zoom
const char * geo_path
const char * track_path
const char * log_path
const char * cache_path
const char * search_text
const char * input
const char * output_path
unsigned int zoom
const char * source
Fixed-capacity, non-owning view over parsed session/track points.
struct point * items
One timestamped geographic position for a replay annotation.
Non-owning view of a bounded interleaved RGB workspace.
unsigned int width
unsigned int height
bool valid
Definition usher.c:537
struct captured_image image
Definition usher.c:371