Debian Codegraph @

src/cdrizzlemap.c

raw symbols SCIP
1 #include <assert.h>
2 #include <float.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include <Python.h>
8
9 #ifndef NPY_NO_DEPRECATED_API
10 #define NPY_NO_DEPRECATED_API NPY_1_21_API_VERSION
11 #endif
12 #define NO_IMPORT_ARRAY
13 #define PY_ARRAY_UNIQUE_SYMBOL cdrizzle_map_api
14
15 #pragma GCC diagnostic push
16 #pragma GCC diagnostic ignored "-Wpedantic"
17 #include <numpy/npy_math.h>
18 #include <numpy/arrayobject.h>
19 #pragma GCC diagnostic pop
20
21 #include "driz_portability.h"
22 #include "cdrizzlemap.h"
23 #include "cdrizzleutil.h"
24
25 static const double VERTEX_ATOL = 1.0e-12;
26 static const double APPROX_ZERO = 1.0e3 * DBL_MIN;
27 static const double MAX_INV_ERR = 0.03;
28
29 void
30 debug_print_polygon(const struct polygon *p, char *msg)
31 {
32 int i;
33 if (msg) {
34 printf("%s\n", msg);
35 }
36 printf("Polygon with %d vertices:\n", p->npv);
37 for (i = 0; i < p->npv; ++i) {
38 printf(" Vertex %d: (%.20f, %.20f)\n", i, p->v[i].x, p->v[i].y);
39 }
40 printf("\n");
41 fflush(stdout);
42 }
43
44 void
45 rotate_polygon(struct polygon *p, int pos);
46
47 /** ---------------------------------------------------------------------------
48 * Find the tighest bounding box around valid (finite) pixmap values.
49 *
50 * This function takes as input a pixel map array and four values indicating
51 * some given bounding box defined by: xmin, xmax, ymin, ymax. Starting with
52 * these values, this function checks values of pixel map on the border and
53 * if there are no valid values along one or more edges, it will adjust the
54 * values of xmin, xmax, ymin, ymax to find the tightest box that has
55 * at least one valid pixel on every edge of the bounding box.
56 *
57 * @param[in] PyArrayObject *pixmap - pixel map of shape (N, M, 2).
58 * @param[in,out] int xmin - position of the left edge of the bounding box.
59 * @param[in,out] int xmax - position of the right edge of the bounding box.
60 * @param[in,out] int ymin - position of the bottom edge of the bounding box.
61 * @param[in,out] int ymax - position of the top edge of the bounding box.
62 * @return 0 if successul and 1 if there is only one or no valid pixel map
63 * values.
64 *
65 */
66 int
67 shrink_image_section(PyArrayObject *pixmap, int *xmin, int *xmax, int *ymin, int *ymax)
68 {
69 int i, j, imin, imax, jmin, jmax, i1, i2, j1, j2;
70 double *pv;
71
72 j1 = *ymin;
73 j2 = *ymax;
74 i1 = *xmin;
75 i2 = *xmax;
76
77 imin = i2;
78 jmin = j2;
79
80 for (j = j1; j <= j2; ++j) {
81 for (i = i1; i <= i2; ++i) {
82 pv = (double *) PyArray_GETPTR3(pixmap, j, i, 0);
83 if (!(npy_isnan(pv[0]) || npy_isnan(pv[1]))) {
84 if (i < imin) {
85 imin = i;
86 }
87 if (j < jmin) {
88 jmin = j;
89 }
90 break;
91 }
92 }
93 }
94
95 imax = imin;
96 jmax = jmin;
97
98 for (j = j2; j >= j1; --j) {
99 for (i = i2; i >= i1; --i) {
100 pv = (double *) PyArray_GETPTR3(pixmap, j, i, 0);
101 if (!(npy_isnan(pv[0]) || npy_isnan(pv[1]))) {
102 if (i > imax) {
103 imax = i;
104 }
105 if (j > jmax) {
106 jmax = j;
107 }
108 break;
109 }
110 }
111 }
112
113 *xmin = imin;
114 *xmax = imax;
115 *ymin = jmin;
116 *ymax = jmax;
117
118 return (imin >= imax || jmin >= jmax);
119 }
120
121 /** ---------------------------------------------------------------------------
122 * Map a point on the input image to the output image using
123 * a mapping of the pixel centers between the two by interpolating
124 * between the centers in the mapping
125 *
126 * pixmap: The mapping of the pixel centers from input to output image
127 * xyin: An (x,y) point on the input image
128 * xyout: The same (x, y) point on the output image (output)
129 */
130 int
131 interpolate_point(struct driz_param_t *par, double xin, double yin, double *xout, double *yout)
132 {
133 int i0, j0, nx2, ny2;
134 npy_intp *ndim;
135 double x, y, x1, y1, f00, f01, f10, f11, g00, g01, g10, g11;
136 double *p;
137 PyArrayObject *pixmap;
138
139 pixmap = par->pixmap;
140
141 /* Bilinear interpolation from
142 https://en.wikipedia.org/wiki/Bilinear_interpolation#On_the_unit_square
143 */
144 i0 = (int) xin;
145 j0 = (int) yin;
146
147 ndim = PyArray_DIMS(pixmap);
148 nx2 = (int) ndim[1] - 2;
149 ny2 = (int) ndim[0] - 2;
150
151 // point is outside the interpolation range. adjust limits to extrapolate.
152 if (i0 < 0) {
153 i0 = 0;
154 } else if (i0 > nx2) {
155 i0 = nx2;
156 }
157 if (j0 < 0) {
158 j0 = 0;
159 } else if (j0 > ny2) {
160 j0 = ny2;
161 }
162
163 x = xin - i0;
164 y = yin - j0;
165 x1 = 1.0 - x;
166 y1 = 1.0 - y;
167
168 p = get_pixmap(pixmap, i0, j0);
169 f00 = p[0];
170 g00 = p[1];
171
172 p = get_pixmap(pixmap, i0 + 1, j0);
173 f10 = p[0];
174 g10 = p[1];
175
176 p = get_pixmap(pixmap, i0, j0 + 1);
177 f01 = p[0];
178 g01 = p[1];
179
180 p = get_pixmap(pixmap, i0 + 1, j0 + 1);
181 f11 = p[0];
182 g11 = p[1];
183
184 *xout = f00 * x1 * y1 + f10 * x * y1 + f01 * x1 * y + f11 * x * y;
185 *yout = g00 * x1 * y1 + g10 * x * y1 + g01 * x1 * y + g11 * x * y;
186
187 if (npy_isnan(*xout) || npy_isnan(*yout)) {
188 return 1;
189 }
190
191 return 0;
192 }
193
194 /** ---------------------------------------------------------------------------
195 * Map a clockwise grid of four points on the input image to the
196 * output image using a mapping of the pixel centers between the two
197 * by interpolating between the centers in the mapping. This assumes
198 * that we want a square grid in the original coordinates centered on
199 * an integer pixel value, as is used by do_square_kernel.
200 *
201 * pixmap: The mapping of the pixel centers from input to output image
202 * xyin: An (x,y) point on the input image, in integer pixels
203 * h: The x,y distance (<1) from the pixel center to the edges
204 * xyout: Four (x, y) points on the output image (output), given as
205 * four x points, then four y points.
206 */
207 int
208 interpolate_four_points(
209 struct driz_param_t *par, int ixcen, int iycen, double h, double *x1, double *x2, double *x3,
210 double *x4, double *y1, double *y2, double *y3, double *y4)
211 {
212 int i, j;
213 #if !defined(NDEBUG)
214 npy_intp *ndim;
215 int nx2, ny2;
216 #endif
217 double fac;
218 double f[3][3], g[3][3];
219 double *p;
220 PyArrayObject *pixmap = par->pixmap;
221
222 /* Bilinear interpolation from
223 https://en.wikipedia.org/wiki/Bilinear_interpolation#On_the_unit_square
224 */
225
226 #if !defined(NDEBUG)
227 ndim = PyArray_DIMS(pixmap);
228 nx2 = (int) ndim[1] - 2;
229 ny2 = (int) ndim[0] - 2;
230 #endif
231
232 /* This is written specifically for the case where I am enclosed
233 * by nine pixels. Since the increments are the same in x and y,
234 * I can take a shortcut by pre-multiplying by the distances from
235 * center point, given by i=j=1 below. Loop ordered for speed
236 * based on numpy array order.
237 */
238 ixcen -= 1;
239 iycen -= 1;
240 assert(h <= 1);
241 assert(ixcen >= 0 && iycen >= 0 && ixcen < nx2 && iycen < ny2);
242
243 for (j = 0; j <= 2; ++j) {
244 for (i = 0; i <= 2; ++i) {
245 p = get_pixmap(pixmap, i + ixcen, j + iycen);
246 if (i == 1 && j == 1) {
247 fac = (1 - h) * (1 - h);
248 } else if (i == 1 || j == 1) {
249 fac = (1 - h) * h;
250 } else {
251 fac = h * h;
252 }
253 f[i][j] = p[0] * fac;
254 g[i][j] = p[1] * fac;
255 }
256 }
257
258 /* We return the vertices of a square going clockwise in the
259 * original pixel grid.
260 * Order in y: +h, +h, -h, -h; order in x: -h, +h, +h, -h
261 */
262
263 *x1 = f[0][1] + f[1][1] + f[0][2] + f[1][2];
264 *y1 = g[0][1] + g[1][1] + g[0][2] + g[1][2];
265
266 *x2 = f[1][1] + f[2][1] + f[1][2] + f[2][2];
267 *y2 = g[1][1] + g[2][1] + g[1][2] + g[2][2];
268
269 *x3 = f[1][0] + f[2][0] + f[1][1] + f[2][1];
270 *y3 = g[1][0] + g[2][0] + g[1][1] + g[2][1];
271
272 *x4 = f[0][0] + f[1][0] + f[0][1] + f[1][1];
273 *y4 = g[0][0] + g[1][0] + g[0][1] + g[1][1];
274
275 if (npy_isnan(*x1) || npy_isnan(*y1) || npy_isnan(*x2) || npy_isnan(*y2) || npy_isnan(*x3) ||
276 npy_isnan(*y3) || npy_isnan(*x4) || npy_isnan(*y4)) {
277 return 1;
278 }
279
280 return 0;
281 }
282
283 /** ---------------------------------------------------------------------------
284 * Map an integer pixel position from the input to the output image.
285 *
286 * pixmap: The mapping of the pixel centers from input to output image
287 * i - The index of the x coordinate
288 * j - The index of the y coordinate
289 * x - X-coordinate of the point on the output image (output)
290 * y - Y-coordinate of the point on the output image (output)
291 */
292 int
293 map_pixel(PyArrayObject *pixmap, int i, int j, double *x, double *y)
294 {
295 double *pv = (double *) PyArray_GETPTR3(pixmap, j, i, 0);
296 *x = *pv;
297 *y = *(pv + 1);
298 return ((npy_isnan(*x) || npy_isnan(*y)) ? 1 : 0);
299 }
300
301 /** ---------------------------------------------------------------------------
302 * Map a point on the input image to the output image either by interpolation
303 * or direct array access if the input position is integral.
304 *
305 * pixmap: The mapping of the pixel centers from input to output image
306 * xin: X-coordinate of a point on the input image
307 * yin: Y-coordinate of a point on the input image
308 * xout: X-coordinate of the same point on the output image (output)
309 * yout: Y-coordinate of the same point on the output image (output)
310 *
311 */
312 int
313 map_point(struct driz_param_t *par, double xin, double yin, double *xout, double *yout)
314 {
315 int i, j, status;
316
317 i = (int) xin;
318 j = (int) yin;
319
320 if ((double) i == xin && (double) j == yin) {
321 if (i >= par->xmin && i <= par->xmax && j >= par->ymin && j <= par->ymax) {
322 status = map_pixel(par->pixmap, i, j, xout, yout);
323 return status;
324 } else {
325 return 1;
326 }
327 } else {
328 return interpolate_point(par, xin, yin, xout, yout);
329 }
330 }
331
332 /** ---------------------------------------------------------------------------
333 * Evaluate quality of coordinate inversion.
334 *
335 * Given a pair of coordinates (x, y) in the input frame obtained from
336 * a pair of coordinates (xref, yref) in the output frame, this function uses
337 * par->pixmap to perform forward transformation (input to output frame) of
338 * (x, y) back to the output frame (x', y') and then compares interpolated
339 * values with (xref, yref) pair.
340 *
341 * @param[in] struct driz_param_t - drizzle parameters.
342 * @param[in] double x - x-coordinate of the inverted point in the input frame.
343 * @param[in] double y - y-coordinate of the inverted point in the input frame.
344 * @param[in] double xref - x-coordinate of the initial point in the output
345 * frame.
346 * @param[in] double yref - y-coordinate of the initial point in the output
347 * frame.
348 * @param[out] double *dist2 - |(x', y') - (xref, yref)|**2.
349 * @return 0 if successul and 1 if the forward interpolation fails.
350 *
351 */
352 static int
353 eval_inversion(
354 struct driz_param_t *par, double x, double y, double xref, double yref, double *dist2)
355 {
356 double xout, yout, dx, dy;
357
358 if (interpolate_point(par, x, y, &xout, &yout)) {
359 return 1;
360 }
361 dx = xout - xref;
362 dy = yout - yref;
363 *dist2 = dx * dx + dy * dy; // sqrt would be slower
364
365 return 0;
366 }
367
368 /** ---------------------------------------------------------------------------
369 * Inverse mapping of coordinates from the output frame to input frame.
370 *
371 * Inverts input (xout, yout) (output image frame) coordinates iteratively
372 * to the input image image frame (xin, yin) - the output of this function.
373 * Ths function uses the method of Golden-section search - see
374 * https://en.wikipedia.org/wiki/Golden-section_search for the 1D case -
375 * generalized to support planar data.
376 *
377 * @param[in] struct driz_param_t - drizzle parameters.
378 * @param[in] double xout - x-coordinate of a point in the output frame.
379 * @param[in] double yout - y-coordinate of a point in the output frame.
380 * @param[out] double *xin - x-coordinate of the point in the input frame.
381 * @param[out] double *yin - y-coordinate of the point in the input frame.
382 * @return 0 if successul and 1 iterative process fails.
383 *
384 */
385 int
386 invert_pixmap(struct driz_param_t *par, double xout, double yout, double *xin, double *yin)
387 {
388 const double gr = 0.6180339887498948482; // Golden Ratio: (sqrt(5)-1)/2
389 const int nmax_iter = 50;
390 int niter;
391 double xmin, xmax, ymin, ymax, dx, dy, x1, x2, y1, y2;
392 double d11, d12, d21, d22;
393
394 xmin = ((double) par->xmin) - 0.5;
395 xmax = ((double) par->xmax) + 0.5;
396 ymin = ((double) par->ymin) - 0.5;
397 ymax = ((double) par->ymax) + 0.5;
398 dx = xmax - xmin;
399 dy = ymax - ymin;
400
401 niter = 0;
402
403 while ((dx > MAX_INV_ERR || dy > MAX_INV_ERR) && niter < nmax_iter) {
404 niter += 1;
405
406 x1 = xmax - gr * dx;
407 x2 = xmin + gr * dx;
408 y1 = ymax - gr * dy;
409 y2 = ymin + gr * dy;
410
411 if (eval_inversion(par, x1, y1, xout, yout, &d11)) {
412 return 1;
413 }
414 if (eval_inversion(par, x1, y2, xout, yout, &d12)) {
415 return 1;
416 }
417 if (eval_inversion(par, x2, y1, xout, yout, &d21)) {
418 return 1;
419 }
420 if (eval_inversion(par, x2, y2, xout, yout, &d22)) {
421 return 1;
422 }
423
424 if (d11 < d12 && d11 < d21 && d11 < d22) {
425 xmax = x2;
426 ymax = y2;
427 } else if (d12 < d11 && d12 < d21 && d12 < d22) {
428 xmax = x2;
429 ymin = y1;
430 } else if (d21 < d11 && d21 < d12 && d21 < d22) {
431 xmin = x1;
432 ymax = y2;
433 } else {
434 xmin = x1;
435 ymin = y1;
436 }
437
438 dx = xmax - xmin;
439 dy = ymax - ymin;
440 }
441
442 *xin = 0.5 * (xmin + xmax);
443 *yin = 0.5 * (ymin + ymax);
444
445 if (niter == nmax_iter) {
446 return 1;
447 }
448
449 return 0;
450 }
451
452 // computes modulus of a % b (with b > 0) similar to Python. A more robust
453 // approach would be to do this: (((a % b) + b) % b). However the polygon
454 // intersection code will never have a < -1 and so a simplified and faster
455 // version was implemented that works for a >= -b.
456 inline int
457 mod(int a, int b)
458 {
459 return ((a + b) % b);
460 // return (((a % b) + b) % b);
461 }
462
463 // test whether two vertices (points) are equal to within a specified
464 // absolute tolerance
465 static inline int
466 equal_vertices(struct vertex a, struct vertex b, double atol)
467 {
468 return (fabs(a.x - b.x) < atol && fabs(a.y - b.y) < atol);
469 }
470
471 // Z-axis/k-component of the cross product a x b
472 static inline double
473 area(struct vertex a, struct vertex b)
474 {
475 return (a.x * b.y - a.y * b.x);
476 }
477
478 // tests whether a point is in a half-plane of the vector going from
479 // vertex v_ to vertex v (including the case of the point lying on the
480 // vector (v_, v)). Specifically, it tests (v - v_) x (pt - v_) > 0:
481 static inline int
482 is_point_strictly_in_hp(const struct vertex pt, const struct vertex v_, const struct vertex v)
483 {
484 return ((area(v, pt) - area(v_, pt) - area(v, v_)) > 0.0);
485 }
486
487 /**
488 * Rotates the vertices of a polygon by a specified number of positions.
489 *
490 * This function shifts the vertices of the given polygon `p` by `pos`
491 * positions. For each rotation, the first vertex is moved to the end of the
492 * vertex array, effectively rotating the polygon's vertex order. The operation
493 * is performed in-place and repeated `pos` times.
494 *
495 * @param p Pointer to the polygon structure to be rotated. The polygon is
496 * expected to have an array of vertices `v` and a count `npv`.
497 * @param pos Number of positions to rotate the polygon's vertices.
498 */
499 void
500 rotate_polygon(struct polygon *p, int pos)
501 {
502 int i, k, m;
503 double x, y;
504
505 for (i = 0; i < pos; ++i) {
506 // rotate polygon p by pos vertices
507 // (move first pos vertices to the end of the polygon)
508 x = p->v[0].x;
509 y = p->v[0].y;
510 for (k = 0; k < p->npv - 1; ++k) {
511 m = mod(k + 1, p->npv);
512 p->v[k].x = p->v[m].x;
513 p->v[k].y = p->v[m].y;
514 }
515 p->v[p->npv - 1].x = x;
516 p->v[p->npv - 1].y = y;
517 }
518 }
519
520 /**
521 * Append a vertex to a polygon.
522 *
523 * Append a vertex to the polygon's list of vertices and increment
524 * vertex count.
525 *
526 * @param[in,out] p struct polygon* to which the vertex is to be added.
527 * @param[in] v struct vertex to be added to polygon p.
528 * @return 0 on success and 1 if no more storage for vertices is available.
529 */
530 static int
531 append_vertex(struct polygon *p, struct vertex v)
532 {
533 if ((p->npv > 0) && equal_vertices(p->v[p->npv - 1], v, VERTEX_ATOL)) {
534 return 0;
535 }
536 if ((p->npv > 0) && equal_vertices(p->v[0], v, VERTEX_ATOL)) {
537 return 0;
538 }
539 if (p->npv >= 2 * IMAGE_OUTLINE_NPTS) {
540 return 1;
541 }
542 p->v[p->npv++] = v;
543 return 0;
544 }
545
546 /**
547 * Simplify polygon.
548 *
549 * Removes midpoints (if any), i.e., vertices that lie on a line connecting
550 * two adjacent vertices (on each side of the mid-vertex).
551 *
552 * @param[in,out] struct polygon type whose vertices may be re-arranged upon
553 * return.
554 */
555 static void
556 simplify_polygon(struct polygon *p)
557 {
558 struct polygon pqhull;
559 struct vertex dp, dq, *pv, *pv_, *pvnxt;
560 int k;
561
562 if (p->npv < 3) {
563 return;
564 }
565
566 pqhull.npv = 0;
567
568 pv_ = (struct vertex *) (p->v) + (p->npv - 1);
569 pv = (struct vertex *) p->v;
570 pvnxt = ((struct vertex *) p->v) + 1;
571
572 for (k = 0; k < p->npv; k++) {
573 dp.x = pvnxt->x - pv_->x;
574 dp.y = pvnxt->y - pv_->y;
575 dq.x = pv->x - pv_->x;
576 dq.y = pv->y - pv_->y;
577
578 if (fabs(area(dp, dq)) > APPROX_ZERO && sqrt(dp.x * dp.x + dp.y * dp.y) > VERTEX_ATOL) {
579 pqhull.v[pqhull.npv++] = *pv;
580 }
581 pv_ = pv;
582 pv = pvnxt;
583 pvnxt = ((struct vertex *) p->v) + (mod(2 + k, p->npv));
584 }
585
586 p->npv = pqhull.npv;
587 for (k = 0; k < p->npv; k++) {
588 p->v[k] = pqhull.v[k];
589 }
590 }
591
592 /**
593 * Orient a polygon counter-clockwise.
594 *
595 * Reverse the order of the polygon p's vertices in such a way that
596 * polygon p is oriented counter-clockwise.
597 *
598 * @param[in,out] struct polygon type whose vertices may be re-arranged upon
599 * return.
600 */
601 static void
602 orient_ccw(struct polygon *p)
603 {
604 // re-arrange (reverse the order of the) polygon p (input and output)
605 // vertices in such a way that polygon p is oriented counter-clockwise.
606 int k, m;
607 struct vertex v1, v2, cm = {0, 0};
608
609 if (p->npv < 3) {
610 return;
611 }
612
613 // center of mass:
614 for (k = 0; k < p->npv; ++k) {
615 cm.x += p->v[k].x;
616 cm.y += p->v[k].y;
617 }
618 cm.x /= p->npv;
619 cm.y /= p->npv;
620
621 // pick first two polygon vertices and subtract center:
622 v1 = p->v[0];
623 v2 = p->v[1];
624 v1.x -= cm.x;
625 v1.y -= cm.y;
626 v2.x -= cm.x;
627 v2.y -= cm.y;
628
629 if (area(v1, v2) >= 0.0) {
630 return;
631 } else {
632 for (k = 0; k < (p->npv / 2); ++k) {
633 v1 = p->v[k];
634 m = p->npv - 1 - k;
635 p->v[k] = p->v[m];
636 p->v[m] = v1;
637 }
638 }
639 }
640
641 /**
642 * Clip a polygon to a window.
643 *
644 * This function implements the Sutherland-Hodgman polygon-clipping algorithm
645 * as described in
646 * https://www.cs.drexel.edu/~david/Classes/CS430/Lectures/L-05_Polygons.6.pdf
647 *
648 * @param[in] struct polygon p - polygon (last vertex != first)
649 * @param[in] struct polygon wnd - clipping window - must be a a convex polygon
650 * (last vertex != first)
651 * @param[out] struct polygon *cp - intersection polygon
652 *
653 * @returns 0 - success, 1 - failure (input polygons have less than 3 vertices)
654 */
655 int
656 clip_polygon_to_window(const struct polygon *p, const struct polygon *wnd, struct polygon *cp)
657 {
658 int k, j;
659 int v1_inside, v2_inside;
660 struct polygon p1, p2, *ppin, *ppout, *tpp;
661 struct vertex *pv, *pv_, *wv, *wv_, dp, dw, vi;
662 double d, app_, aww_;
663
664 if ((p->npv < 3) || (wnd->npv < 3)) {
665 return 1;
666 }
667
668 orient_ccw((struct polygon *) p);
669 orient_ccw((struct polygon *) wnd);
670
671 p1 = *p;
672
673 ppin = &p2;
674 ppout = &p1;
675
676 wv_ = (struct vertex *) (wnd->v + (wnd->npv - 1));
677 wv = (struct vertex *) wnd->v;
678
679 for (k = 0; k < wnd->npv; k++) {
680 dw.x = wv->x - wv_->x;
681 dw.y = wv->y - wv_->y;
682
683 // use output from previous iteration as input for the current
684 tpp = ppin;
685 ppin = ppout;
686 ppout = tpp;
687 ppout->npv = 0;
688
689 pv_ = (struct vertex *) (ppin->v + (ppin->npv - 1));
690 pv = (struct vertex *) ppin->v;
691
692 for (j = 0; j < ppin->npv; j++) {
693 dp.x = pv->x - pv_->x;
694 dp.y = pv->y - pv_->y;
695
696 v1_inside = is_point_strictly_in_hp(*wv_, *wv, *pv_);
697 v2_inside = is_point_strictly_in_hp(*wv_, *wv, *pv);
698
699 if (v2_inside != v1_inside) {
700 // compute intersection point:
701 // https://en.wikipedia.org/wiki/Line–line_intersection
702 d = area(dp, dw); // d != 0 because (v2_inside != v1_inside)
703
704 app_ = area(*pv, *pv_);
705 aww_ = area(*wv, *wv_);
706
707 vi.x = (app_ * dw.x - aww_ * dp.x) / d;
708 vi.y = (app_ * dw.y - aww_ * dp.y) / d;
709
710 if (isfinite(vi.x) && isfinite(vi.y)) {
711 append_vertex(ppout, vi);
712 }
713 if (v2_inside) {
714 // outside to inside:
715 append_vertex(ppout, *pv);
716 }
717 } else if (v1_inside) {
718 // both edge vertices are inside
719 append_vertex(ppout, *pv);
720 }
721
722 // nothing to do when both edge vertices are outside
723
724 // advance polygon edge:
725 pv_ = pv;
726 pv = pv + 1;
727 }
728
729 // advance window edge:
730 wv_ = wv;
731 wv = wv + 1;
732 }
733
734 orient_ccw(ppout);
735 simplify_polygon(ppout);
736 *cp = *ppout;
737
738 return 0;
739 }
740
741 /**
742 * Initializes an edge structure from two end vertices.
743 *
744 * Initialization includes edge vertices and computing the slope and
745 * the intersect of the line connecting the vertices. Alternative intersect
746 * "c" is computed in such a way that pixels in their entirety fit either
747 * to the left of the right edges or to the right of left edges.
748 *
749 * NOTE: Left edges are the ones to the left (small X) of the line that
750 * connects top and bottom polygon's vertices and the right edges are
751 * to the right of this lighn (high X).
752 *
753 * @param[in] struct edge *e - pointer to the edge structure to be initialized
754 * @param[in] struct vertex v1 - first vertex of the edge
755 * @param[in] struct vertex v2 - second vertex of the edge
756 * @param[in] position: +1 for right edge of the polygon, -1 for left edge
757 *
758 */
759 static void
760 init_edge(struct edge *e, struct vertex v1, struct vertex v2, int position)
761 {
762 e->v1 = v1;
763 e->v2 = v2;
764 e->p = position; // -1 for left-side edge and +1 for right-side edge
765 e->m = (v2.x - v1.x) / (v2.y - v1.y);
766 e->b = (v1.x * v2.y - v1.y * v2.x) / (v2.y - v1.y);
767 e->c = e->b - copysign(0.5 + 0.5 * fabs(e->m), (double) position);
768 }
769
770 /**
771 * Set-up scanner structure for a polygon.
772 *
773 * This function finds minimum and maximum y-coordinates of the polygon
774 * vertices and splits all edges int left and right edges based on their
775 * horizontal position relative to the line connecting the top and bottom
776 * vertices of the polygon. It also copies the bounding box parameters
777 * xmin, xmax, ymin, ymax from the driz_param_t structure.
778 *
779 * @param[in] struct polygon *p.
780 * @param[in] struct driz_param_t - drizzle parameters (bounding box is used).
781 * @param[out] struct scanner *s - scanner structure to be initialized.
782 * @return 0 if successful and 1 if input polygon has only 2 vertices or less.
783 *
784 */
785 int
786 init_scanner(struct polygon *p, struct driz_param_t *par, struct scanner *s)
787 {
788 int k, i1, i2;
789 int min_right, min_left, max_right, max_left;
790 double min_y, max_y;
791
792 s->left = NULL;
793 s->right = NULL;
794 s->nleft = 0;
795 s->nright = 0;
796
797 if (p->npv < 3) {
798 // not a polygon
799 s->overlap_valid = 0;
800 s->bounding_polygon.npv = 0;
801 return 1;
802 }
803
804 s->bounding_polygon = *p;
805
806 // find minimum/minima:
807 min_y = p->v[0].y;
808 min_left = 0;
809 for (k = 1; k < p->npv; k++) {
810 if (p->v[k].y < min_y) {
811 min_left = k;
812 min_y = p->v[k].y;
813 }
814 }
815
816 i1 = mod(min_left - 1, p->npv);
817 i2 = mod(min_left + 1, p->npv);
818 min_right = (p->v[i1].y < p->v[i2].y) ? i1 : i2;
819 if (p->v[min_right].y <= min_y * (1.0 + copysign(VERTEX_ATOL, min_y))) {
820 if (p->v[min_left].x > p->v[min_right].x) {
821 k = min_left;
822 min_left = min_right;
823 min_right = k;
824 }
825 } else {
826 min_right = min_left;
827 }
828
829 // find maximum/maxima:
830 max_y = p->v[0].y;
831 max_right = 0;
832 for (k = 1; k < p->npv; k++) {
833 if (p->v[k].y > max_y) {
834 max_right = k;
835 max_y = p->v[k].y;
836 }
837 }
838
839 i1 = mod(max_right - 1, p->npv);
840 i2 = mod(max_right + 1, p->npv);
841 max_left = (p->v[i1].y > p->v[i2].y) ? i1 : i2;
842 if (p->v[max_left].y >= max_y * (1.0 - copysign(VERTEX_ATOL, max_y))) {
843 if (p->v[max_left].x > p->v[max_right].x) {
844 k = max_left;
845 max_left = max_right;
846 max_right = k;
847 }
848 } else {
849 max_left = max_right;
850 }
851
852 // Left: start with minimum and move clockwise:
853 if (max_left > min_left) {
854 min_left += p->npv;
855 }
856 s->nleft = min_left - max_left;
857
858 for (k = 0; k < s->nleft; k++) {
859 i1 = mod(min_left - k, p->npv); // -k for CW traverse direction
860 i2 = mod(i1 - 1, p->npv); // -1 for CW traverse direction
861 init_edge(s->left_edges + k, p->v[i1], p->v[i2], -1);
862 }
863
864 // Right: start with minimum and move counter-clockwise:
865 if (max_right < min_right) {
866 max_right += p->npv;
867 }
868 s->nright = max_right - min_right;
869
870 for (k = 0; k < s->nright; k++) {
871 i1 = mod(min_right + k, p->npv); // +k for CW traverse direction
872 i2 = mod(i1 + 1, p->npv); // +1 for CW traverse direction
873 init_edge(s->right_edges + k, p->v[i1], p->v[i2], 1);
874 }
875
876 s->left = (struct edge *) s->left_edges;
877 s->right = (struct edge *) s->right_edges;
878 s->min_y = min_y;
879 s->max_y = max_y;
880 s->xmin = par->xmin;
881 s->xmax = par->xmax;
882 s->ymin = par->ymin;
883 s->ymax = par->ymax;
884
885 return 0;
886 }
887
888 /**
889 * Get x-range of pixels in a row that are within the bounds of a polygon.
890 *
891 * get_scanline_limits returns x-limits (integer pixel locations) for an image
892 * row that fit between the edges (of a polygon) specified by the scanner
893 * structure. The limits are computed in such a way that the edge pixels are
894 * entirely inside the polygon.
895 *
896 * This function is intended to be called successively with input
897 * 'y' *increasing* from s->min_y to s->max_y.
898 *
899 * @param[in] struct scanner *s - scanner structure
900 * @param[in] y - integer position of the row along the vertical direction
901 * @param[out] int *x1 - horizontal position of the leftmost pixel within
902 * the bounding polygon
903 * @param[out] int *x2 - horizontal position of the rightmost pixel within
904 * the bounding polygon
905 * @return 0 no errors;
906 * 1 scan ended (y reached the top vertex/edge);
907 * 2 pixel centered on y is outside of scanner's limits or image
908 * [0, height - 1];
909 * 3 limits (x1, x2) are equal (line with is 0).
910 *
911 */
912 int
913 get_scanline_limits(struct scanner *s, int y, int *x1, int *x2)
914 {
915 double pyb, pyt; // pixel top and bottom limits
916 double xlb, xlt, xrb, xrt, edge_ymax, xmin, xmax;
917 struct edge *el_max, *er_max;
918
919 el_max = ((struct edge *) s->left_edges) + (s->nleft - 1);
920 er_max = ((struct edge *) s->right_edges) + (s->nright - 1);
921
922 if (s->ymax >= s->ymin && (y < 0 || y > s->ymax)) {
923 return 2;
924 }
925
926 pyb = (double) y - 0.5;
927 pyt = (double) y + 0.5;
928
929 if (pyt <= s->min_y || pyb >= s->max_y + 1) {
930 return 2;
931 }
932
933 if (s->left == NULL || s->right == NULL) {
934 return 1;
935 }
936
937 while (pyb > s->left->v2.y) {
938 if (s->left == el_max) {
939 s->left = NULL;
940 s->right = NULL;
941 return 1;
942 }
943 ++s->left;
944 }
945
946 while (pyb > s->right->v2.y) {
947 if (s->right == er_max) {
948 s->left = NULL;
949 s->right = NULL;
950 return 1;
951 }
952 ++s->right;
953 }
954
955 xlb = s->left->m * y + s->left->c - MAX_INV_ERR;
956 xrb = s->right->m * y + s->right->c + MAX_INV_ERR;
957
958 edge_ymax = s->left->v2.y + 0.5 + MAX_INV_ERR;
959 while (pyt > edge_ymax) {
960 if (s->left == el_max) {
961 s->left = NULL;
962 s->right = NULL;
963 return 1;
964 }
965 ++s->left;
966 edge_ymax = s->left->v2.y + 0.5 + MAX_INV_ERR;
967 }
968
969 edge_ymax = s->right->v2.y + 0.5 + MAX_INV_ERR;
970 while (pyt > edge_ymax) {
971 if (s->right == er_max) {
972 s->left = NULL;
973 s->right = NULL;
974 return 1;
975 }
976 ++s->right;
977 edge_ymax = s->right->v2.y + 0.5 + MAX_INV_ERR;
978 }
979
980 xlt = s->left->m * y + s->left->c - MAX_INV_ERR;
981 xrt = s->right->m * y + s->right->c + MAX_INV_ERR;
982
983 xmin = s->xmin;
984 xmax = s->xmax;
985 if (s->xmax >= s->xmin) {
986 if (xlb < xmin) {
987 xlb = xmin;
988 }
989 if (xlt < xmin) {
990 xlt = xmin;
991 }
992 if (xrb > xmax) {
993 xrb = xmax;
994 }
995 if (xrt > xmax) {
996 xrt = xmax;
997 }
998 }
999
1000 if (xlt >= xrt) {
1001 *x1 = (int) round(xlb);
1002 *x2 = (int) round(xrb);
1003 if (xlb >= xrb) {
1004 return 3;
1005 }
1006 } else if (xlb >= xrb) {
1007 *x1 = (int) round(xlt);
1008 *x2 = (int) round(xrt);
1009 } else {
1010 *x1 = (int) round((xlb > xlt) ? xlb : xlt);
1011 *x2 = (int) round((xrb < xrt) ? xrb : xrt);
1012 }
1013
1014 return 0;
1015 }
1016
1017 /**
1018 * Map a vertex' coordinates from the input frame to the output frame.
1019 *
1020 * @param[in] struct driz_param_t - drizzle parameters (bounding box is used)
1021 * @param[in] struct vertex vin - vertex' coordinates in the input frame
1022 * @param[out] struct vertex *vout - vertex' coordinates in the output frame
1023 * @return 0 no errors and 1 on errors.
1024 *
1025 */
1026 static int
1027 map_vertex_to_output(struct driz_param_t *par, struct vertex vin, struct vertex *vout)
1028 {
1029 // convert coordinates to the output frame
1030 return map_point(par, vin.x, vin.y, &vout->x, &vout->y);
1031 }
1032
1033 /**
1034 * Map a vertex' coordinates from the output frame to the input frame.
1035 *
1036 * @param[in] struct driz_param_t - drizzle parameters (bounding box is used)
1037 * @param[in] struct vertex vout - vertex' coordinates in the output frame
1038 * @param[out] struct vertex *vin - vertex' coordinates in the input frame
1039 * @return 0 no errors and 1 on errors.
1040 *
1041 */
1042 static int
1043 map_vertex_to_input(struct driz_param_t *par, struct vertex vout, struct vertex *vin)
1044 {
1045 double xin, yin;
1046 char buf[MAX_DRIZ_ERROR_LEN];
1047 int n;
1048 // convert coordinates to the input frame
1049 if (invert_pixmap(par, vout.x, vout.y, &xin, &yin)) {
1050 n = sprintf(buf, "failed to invert pixel map at position (%.2f, %.2f)", vout.x, vout.y);
1051 if (n < 0) {
1052 strcpy(buf, "failed to invert pixel map");
1053 }
1054 driz_error_set_message(par->error, buf);
1055 return 1;
1056 }
1057 vin->x = xin;
1058 vin->y = yin;
1059 return 0;
1060 }
1061
1062 /**
1063 * Set-up image scanner.
1064 *
1065 * This is a the main part of the computation of the bounding polygon in the
1066 * input frame. This function computes the bounding box of the input image,
1067 * maps it the ouput frame, intersects mapped input bounding box with the
1068 * bounding box of the output image. It then maps this intersection polygon
1069 * back to the input frame and then sets up the scanner structure to be used
1070 * by the resampling kernel functions to determine the horizontal scan limits
1071 * for a given input image row.
1072 *
1073 * @param[in] struct driz_param_t - drizzle parameters (bounding box is used).
1074 * @param[out] struct scanner *s - computed from the intersection of polygons.
1075 * @param[out] int *ymin - minimum y of a row in input image with pixels inside
1076 * the intersection polygon
1077 * @param[out] int *ymax - maximum y of a row in input image with pixels inside
1078 * the intersection polygon
1079 * @return see init_scanner for return values.
1080 *
1081 */
1082 int
1083 init_image_scanner(struct driz_param_t *par, struct scanner *s, int *ymin, int *ymax)
1084 {
1085 struct polygon p, q, pq, inpq;
1086 int k, n;
1087 npy_intp *ndim;
1088
1089 // define a polygon bounding the input image:
1090 inpq.npv = 4;
1091 inpq.v[0].x = par->xmin - 0.5;
1092 inpq.v[0].y = par->ymin - 0.5;
1093 inpq.v[1].x = par->xmax + 0.5;
1094 inpq.v[1].y = inpq.v[0].y;
1095 inpq.v[2].x = inpq.v[1].x;
1096 inpq.v[2].y = par->ymax + 0.5;
1097 inpq.v[3].x = inpq.v[0].x;
1098 inpq.v[3].y = inpq.v[2].y;
1099
1100 // convert coordinates of the above polygon to the output frame and
1101 // define a polygon bounding the input image in the output frame:
1102 // inpq will be updated/overwritten later if coordinate mapping, inversion,
1103 // and polygon intersection is successful.
1104 for (k = 0; k < inpq.npv; ++k) {
1105 if (map_vertex_to_output(par, inpq.v[k], p.v + k)) {
1106 s->overlap_valid = 0;
1107 driz_error_set_message(par->error, "error computing input image bounding box");
1108 goto _setup_scanner;
1109 }
1110 }
1111 p.npv = inpq.npv;
1112
1113 // define a polygon bounding the output image:
1114 ndim = PyArray_DIMS(par->output_data);
1115 q.npv = 4;
1116 q.v[0].x = -0.5;
1117 q.v[0].y = -0.5;
1118 q.v[1].x = (double) ndim[1] - 0.5;
1119 q.v[1].y = -0.5;
1120 q.v[2].x = (double) ndim[1] - 0.5;
1121 q.v[2].y = (double) ndim[0] - 0.5;
1122 q.v[3].x = -0.5;
1123 q.v[3].y = (double) ndim[0] - 0.5;
1124
1125 // compute intersection of P and Q (in the output frame):
1126 if (clip_polygon_to_window(&p, &q, &pq)) {
1127 s->overlap_valid = 0;
1128 goto _setup_scanner;
1129 }
1130
1131 // convert coordinates of vertices of the intersection polygon
1132 // back to input image coordinate system:
1133 for (k = 0; k < pq.npv; k++) {
1134 if (map_vertex_to_input(par, pq.v[k], &inpq.v[k])) {
1135 s->overlap_valid = 0;
1136 goto _setup_scanner;
1137 }
1138 }
1139 inpq.npv = pq.npv;
1140
1141 s->overlap_valid = 1;
1142 orient_ccw(&inpq);
1143
1144 _setup_scanner:
1145
1146 // initialize polygon scanner:
1147 driz_error_unset(par->error);
1148 n = init_scanner(&inpq, par, s);
1149 *ymin = MAX(0, (int) (s->min_y + 0.5 + 2.0 * MAX_INV_ERR));
1150 *ymax = MIN(s->ymax, (int) (s->max_y + 2.0 * MAX_INV_ERR));
1151 return n;
1152 }
1153
1154 /**
1155 * Calculates the signed area of a polygon using the shoelace formula.
1156 *
1157 * The polygon is defined by its vertices in the `struct polygon` object.
1158 * The area will be positive if the vertices are ordered counterclockwise,
1159 * and negative if they are ordered clockwise.
1160 *
1161 * @param p Pointer to a `struct polygon` containing the vertices and their
1162 * count.
1163 * @return The signed area of the polygon as a double.
1164 */
1165 static double
1166 polygon_area(const struct polygon *p)
1167 {
1168 int k, j;
1169 double a;
1170
1171 a = 0.0;
1172 j = p->npv - 1;
1173 for (k = 0; k < p->npv; k++) {
1174 a += (p->v[j].x + p->v[k].x) * (p->v[j].y - p->v[k].y);
1175 j = k;
1176 }
1177 return 0.5 * a;
1178 }
1179
1180 /**
1181 * Calculates the centroid (geometric center) of a polygon.
1182 *
1183 * The centroid is computed using the coordinates of the polygon's vertices.
1184 * If the polygon is degenerate (area is approximately zero or has fewer than 3
1185 * vertices), the function returns 1 and sets cx, cy to 0.0.
1186 *
1187 * @param[in] p Pointer to a polygon structure containing the vertices.
1188 * @param[out] cx Pointer to double for centroid x-coordinate.
1189 * @param[out] cy Pointer to double for centroid y-coordinate.
1190 * @return 0 on success, 1 if the polygon is degenerate.
1191 */
1192 int
1193 polygon_centroid(const struct polygon *p, double *cx, double *cy)
1194 {
1195 int k, j;
1196 double a, sum_x = 0.0, sum_y = 0.0, factor;
1197
1198 a = polygon_area(p);
1199 if (fabs(a) < APPROX_ZERO || p->npv < 3) {
1200 *cx = 0.0;
1201 *cy = 0.0;
1202 return 1; // degenerate polygon
1203 }
1204 j = p->npv - 1;
1205 for (k = 0; k < p->npv; k++) {
1206 factor = (p->v[j].x * p->v[k].y - p->v[k].x * p->v[j].y);
1207 sum_x += (p->v[j].x + p->v[k].x) * factor;
1208 sum_y += (p->v[j].y + p->v[k].y) * factor;
1209 j = k;
1210 }
1211 *cx = sum_x / (6.0 * a);
1212 *cy = sum_y / (6.0 * a);
1213 return 0;
1214 }