/
4D_api.cpp
2890 lines (2561 loc) · 109 KB
/
4D_api.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Project: PROJ.4
* Purpose: Implement a (currently minimalistic) proj API based primarily
* on the PJ_COORD 4D geodetic spatiotemporal data type.
*
* Author: Thomas Knudsen, thokn@sdfe.dk, 2016-06-09/2016-11-06
*
******************************************************************************
* Copyright (c) 2016, 2017 Thomas Knudsen/SDFE
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************/
#define FROM_PROJ_CPP
#include <assert.h>
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _MSC_VER
#include <strings.h>
#endif
#include <algorithm>
#include <limits>
#include "filemanager.hpp"
#include "geodesic.h"
#include "grids.hpp"
#include "proj.h"
#include "proj_experimental.h"
#include "proj_internal.h"
#include <cmath> /* for isnan */
#include <math.h>
#include "proj/common.hpp"
#include "proj/coordinateoperation.hpp"
#include "proj/internal/internal.hpp"
#include "proj/internal/io_internal.hpp"
using namespace NS_PROJ::internal;
/* Initialize PJ_COORD struct */
PJ_COORD proj_coord(double x, double y, double z, double t) {
PJ_COORD res;
res.v[0] = x;
res.v[1] = y;
res.v[2] = z;
res.v[3] = t;
return res;
}
static PJ_DIRECTION opposite_direction(PJ_DIRECTION dir) {
return static_cast<PJ_DIRECTION>(-dir);
}
/*****************************************************************************/
int proj_angular_input(PJ *P, enum PJ_DIRECTION dir) {
/******************************************************************************
Returns 1 if the operator P expects angular input coordinates when
operating in direction dir, 0 otherwise.
dir: {PJ_FWD, PJ_INV}
******************************************************************************/
if (PJ_FWD == dir)
return pj_left(P) == PJ_IO_UNITS_RADIANS;
return pj_right(P) == PJ_IO_UNITS_RADIANS;
}
/*****************************************************************************/
int proj_angular_output(PJ *P, enum PJ_DIRECTION dir) {
/******************************************************************************
Returns 1 if the operator P provides angular output coordinates when
operating in direction dir, 0 otherwise.
dir: {PJ_FWD, PJ_INV}
******************************************************************************/
return proj_angular_input(P, opposite_direction(dir));
}
/*****************************************************************************/
int proj_degree_input(PJ *P, enum PJ_DIRECTION dir) {
/******************************************************************************
Returns 1 if the operator P expects degree input coordinates when
operating in direction dir, 0 otherwise.
dir: {PJ_FWD, PJ_INV}
******************************************************************************/
if (PJ_FWD == dir)
return pj_left(P) == PJ_IO_UNITS_DEGREES;
return pj_right(P) == PJ_IO_UNITS_DEGREES;
}
/*****************************************************************************/
int proj_degree_output(PJ *P, enum PJ_DIRECTION dir) {
/******************************************************************************
Returns 1 if the operator P provides degree output coordinates when
operating in direction dir, 0 otherwise.
dir: {PJ_FWD, PJ_INV}
******************************************************************************/
return proj_degree_input(P, opposite_direction(dir));
}
/* Geodesic distance (in meter) + fwd and rev azimuth between two points on the
* ellipsoid */
PJ_COORD proj_geod(const PJ *P, PJ_COORD a, PJ_COORD b) {
PJ_COORD c;
if (!P->geod) {
return proj_coord_error();
}
/* Note: the geodesic code takes arguments in degrees */
geod_inverse(P->geod, PJ_TODEG(a.lpz.phi), PJ_TODEG(a.lpz.lam),
PJ_TODEG(b.lpz.phi), PJ_TODEG(b.lpz.lam), c.v, c.v + 1,
c.v + 2);
// cppcheck-suppress uninitvar
return c;
}
/* Geodesic distance (in meter) between two points with angular 2D coordinates
*/
double proj_lp_dist(const PJ *P, PJ_COORD a, PJ_COORD b) {
double s12, azi1, azi2;
/* Note: the geodesic code takes arguments in degrees */
if (!P->geod) {
return HUGE_VAL;
}
geod_inverse(P->geod, PJ_TODEG(a.lpz.phi), PJ_TODEG(a.lpz.lam),
PJ_TODEG(b.lpz.phi), PJ_TODEG(b.lpz.lam), &s12, &azi1, &azi2);
return s12;
}
/* The geodesic distance AND the vertical offset */
double proj_lpz_dist(const PJ *P, PJ_COORD a, PJ_COORD b) {
if (HUGE_VAL == a.lpz.lam || HUGE_VAL == b.lpz.lam)
return HUGE_VAL;
return hypot(proj_lp_dist(P, a, b), a.lpz.z - b.lpz.z);
}
/* Euclidean distance between two points with linear 2D coordinates */
double proj_xy_dist(PJ_COORD a, PJ_COORD b) {
return hypot(a.xy.x - b.xy.x, a.xy.y - b.xy.y);
}
/* Euclidean distance between two points with linear 3D coordinates */
double proj_xyz_dist(PJ_COORD a, PJ_COORD b) {
return hypot(proj_xy_dist(a, b), a.xyz.z - b.xyz.z);
}
static bool inline coord_is_all_nans(PJ_COORD coo) {
return std::isnan(coo.v[0]) && std::isnan(coo.v[1]) &&
std::isnan(coo.v[2]) && std::isnan(coo.v[3]);
}
static bool inline coord_has_nans(PJ_COORD coo) {
return std::isnan(coo.v[0]) || std::isnan(coo.v[1]) ||
std::isnan(coo.v[2]) || std::isnan(coo.v[3]);
}
/* Measure numerical deviation after n roundtrips fwd-inv (or inv-fwd) */
double proj_roundtrip(PJ *P, PJ_DIRECTION direction, int n, PJ_COORD *coord) {
int i;
PJ_COORD t, org;
if (nullptr == P)
return HUGE_VAL;
if (n < 1) {
proj_log_error(P, _("n should be >= 1"));
proj_errno_set(P, PROJ_ERR_OTHER_API_MISUSE);
return HUGE_VAL;
}
/* in the first half-step, we generate the output value */
org = *coord;
*coord = proj_trans(P, direction, org);
t = *coord;
/* now we take n-1 full steps in inverse direction: We are */
/* out of phase due to the half step already taken */
for (i = 0; i < n - 1; i++)
t = proj_trans(P, direction,
proj_trans(P, opposite_direction(direction), t));
/* finally, we take the last half-step */
t = proj_trans(P, opposite_direction(direction), t);
/* if we start with any NaN, we expect all NaN as output */
if (coord_has_nans(org) && coord_is_all_nans(t)) {
return 0.0;
}
/* checking for angular *input* since we do a roundtrip, and end where we
* begin */
if (proj_angular_input(P, direction))
return proj_lpz_dist(P, org, t);
return proj_xyz_dist(org, t);
}
/**************************************************************************************/
int pj_get_suggested_operation(PJ_CONTEXT *,
const std::vector<PJCoordOperation> &opList,
const int iExcluded[2], bool skipNonInstantiable,
PJ_DIRECTION direction, PJ_COORD coord)
/**************************************************************************************/
{
const auto normalizeLongitude = [](double x) {
if (x > 180.0) {
x -= 360.0;
if (x > 180.0)
x = fmod(x + 180.0, 360.0) - 180.0;
} else if (x < -180.0) {
x += 360.0;
if (x < -180.0)
x = fmod(x + 180.0, 360.0) - 180.0;
}
return x;
};
// Select the operations that match the area of use
// and has the best accuracy.
int iBest = -1;
double bestAccuracy = std::numeric_limits<double>::max();
const int nOperations = static_cast<int>(opList.size());
for (int i = 0; i < nOperations; i++) {
if (i == iExcluded[0] || i == iExcluded[1]) {
continue;
}
const auto &alt = opList[i];
bool spatialCriterionOK = false;
if (direction == PJ_FWD) {
if (coord.xyzt.x >= alt.minxSrc && coord.xyzt.y >= alt.minySrc &&
coord.xyzt.x <= alt.maxxSrc && coord.xyzt.y <= alt.maxySrc) {
spatialCriterionOK = true;
} else if (alt.srcIsLonLatDegree && coord.xyzt.y >= alt.minySrc &&
coord.xyzt.y <= alt.maxySrc) {
const double normalizedLon = normalizeLongitude(coord.xyzt.x);
if (normalizedLon >= alt.minxSrc &&
normalizedLon <= alt.maxxSrc) {
spatialCriterionOK = true;
}
} else if (alt.srcIsLatLonDegree && coord.xyzt.x >= alt.minxSrc &&
coord.xyzt.x <= alt.maxxSrc) {
const double normalizedLon = normalizeLongitude(coord.xyzt.y);
if (normalizedLon >= alt.minySrc &&
normalizedLon <= alt.maxySrc) {
spatialCriterionOK = true;
}
}
} else {
if (coord.xyzt.x >= alt.minxDst && coord.xyzt.y >= alt.minyDst &&
coord.xyzt.x <= alt.maxxDst && coord.xyzt.y <= alt.maxyDst) {
spatialCriterionOK = true;
} else if (alt.dstIsLonLatDegree && coord.xyzt.y >= alt.minyDst &&
coord.xyzt.y <= alt.maxyDst) {
const double normalizedLon = normalizeLongitude(coord.xyzt.x);
if (normalizedLon >= alt.minxDst &&
normalizedLon <= alt.maxxDst) {
spatialCriterionOK = true;
}
} else if (alt.dstIsLatLonDegree && coord.xyzt.x >= alt.minxDst &&
coord.xyzt.x <= alt.maxxDst) {
const double normalizedLon = normalizeLongitude(coord.xyzt.y);
if (normalizedLon >= alt.minyDst &&
normalizedLon <= alt.maxyDst) {
spatialCriterionOK = true;
}
}
}
if (spatialCriterionOK) {
// The offshore test is for the "Test bug 245 (use +datum=carthage)"
// of testvarious. The long=10 lat=34 point belongs both to the
// onshore and offshore Tunisia area of uses, but is slightly
// onshore. So in a general way, prefer a onshore area to a
// offshore one.
if (iBest < 0 || (alt.accuracy >= 0 &&
(alt.accuracy < bestAccuracy ||
// If two operations have the same accuracy, use
// the one that is contained within a larger one
(alt.accuracy == bestAccuracy &&
alt.minxSrc >= opList[iBest].minxSrc &&
alt.minySrc >= opList[iBest].minySrc &&
alt.maxxSrc <= opList[iBest].maxxSrc &&
alt.maxySrc <= opList[iBest].maxySrc &&
// check that this is not equality
!(alt.minxSrc == opList[iBest].minxSrc &&
alt.minySrc == opList[iBest].minySrc &&
alt.maxxSrc == opList[iBest].maxxSrc &&
alt.maxySrc == opList[iBest].maxySrc) &&
!opList[iBest].isPriorityOp)) &&
!alt.isOffshore)) {
if (skipNonInstantiable && !alt.isInstantiable()) {
continue;
}
iBest = i;
bestAccuracy = alt.accuracy;
}
}
}
return iBest;
}
//! @cond Doxygen_Suppress
/**************************************************************************************/
bool PJCoordOperation::isInstantiable() const {
/**************************************************************************************/
if (isInstantiableCached == INSTANTIABLE_STATUS_UNKNOWN)
isInstantiableCached = proj_coordoperation_is_instantiable(pj->ctx, pj);
return bool(isInstantiableCached);
}
//! @endcond
/**************************************************************************************/
static void warnAboutMissingGrid(PJ *P)
/**************************************************************************************/
{
std::string msg("Attempt to use coordinate operation ");
msg += proj_get_name(P);
msg += " failed.";
int gridUsed = proj_coordoperation_get_grid_used_count(P->ctx, P);
for (int i = 0; i < gridUsed; ++i) {
const char *gridName = "";
int available = FALSE;
if (proj_coordoperation_get_grid_used(P->ctx, P, i, &gridName, nullptr,
nullptr, nullptr, nullptr,
nullptr, &available) &&
!available) {
msg += " Grid ";
msg += gridName;
msg += " is not available. "
"Consult https://proj.org/resource_files.html for guidance.";
}
}
if (!P->errorIfBestTransformationNotAvailable &&
P->warnIfBestTransformationNotAvailable) {
msg += " This might become an error in a future PROJ major release. "
"Set the ONLY_BEST option to YES or NO. "
"This warning will no longer be emitted (for the current "
"transformation instance).";
P->warnIfBestTransformationNotAvailable = false;
}
pj_log(P->ctx,
P->errorIfBestTransformationNotAvailable ? PJ_LOG_ERROR
: PJ_LOG_DEBUG,
msg.c_str());
}
/**************************************************************************************/
PJ_COORD proj_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coord) {
/***************************************************************************************
Apply the transformation P to the coordinate coord, preferring the 4D
interfaces if available.
See also pj_approx_2D_trans and pj_approx_3D_trans in pj_internal.c, which
work similarly, but prefers the 2D resp. 3D interfaces if available.
***************************************************************************************/
if (nullptr == P || direction == PJ_IDENT)
return coord;
if (P->inverted)
direction = opposite_direction(direction);
if (P->iso_obj != nullptr && !P->iso_obj_is_coordinate_operation) {
pj_log(P->ctx, PJ_LOG_ERROR, "Object is not a coordinate operation");
proj_errno_set(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE);
return proj_coord_error();
}
if (!P->alternativeCoordinateOperations.empty()) {
constexpr int N_MAX_RETRY = 2;
int iExcluded[N_MAX_RETRY] = {-1, -1};
bool skipNonInstantiable = P->skipNonInstantiable &&
!P->warnIfBestTransformationNotAvailable &&
!P->errorIfBestTransformationNotAvailable;
const int nOperations =
static_cast<int>(P->alternativeCoordinateOperations.size());
// We may need several attempts. For example the point at
// long=-111.5 lat=45.26 falls into the bounding box of the Canadian
// ntv2_0.gsb grid, except that it is not in any of the subgrids, being
// in the US. We thus need another retry that will select the conus
// grid.
for (int iRetry = 0; iRetry <= N_MAX_RETRY; iRetry++) {
// Do a first pass and select the operations that match the area of
// use and has the best accuracy.
int iBest = pj_get_suggested_operation(
P->ctx, P->alternativeCoordinateOperations, iExcluded,
skipNonInstantiable, direction, coord);
if (iBest < 0) {
break;
}
if (iRetry > 0) {
const int oldErrno = proj_errno_reset(P);
if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) {
pj_log(P->ctx, PJ_LOG_DEBUG,
proj_context_errno_string(P->ctx, oldErrno));
}
pj_log(P->ctx, PJ_LOG_DEBUG,
"Did not result in valid result. "
"Attempting a retry with another operation.");
}
const auto &alt = P->alternativeCoordinateOperations[iBest];
if (P->iCurCoordOp != iBest) {
if (proj_log_level(P->ctx, PJ_LOG_TELL) >= PJ_LOG_DEBUG) {
std::string msg("Using coordinate operation ");
msg += alt.name;
pj_log(P->ctx, PJ_LOG_DEBUG, msg.c_str());
}
P->iCurCoordOp = iBest;
}
PJ_COORD res = coord;
if (alt.pj->hasCoordinateEpoch)
coord.xyzt.t = alt.pj->coordinateEpoch;
if (direction == PJ_FWD)
pj_fwd4d(res, alt.pj);
else
pj_inv4d(res, alt.pj);
if (proj_errno(alt.pj) == PROJ_ERR_OTHER_NETWORK_ERROR) {
return proj_coord_error();
}
if (res.xyzt.x != HUGE_VAL) {
return res;
} else if (P->errorIfBestTransformationNotAvailable ||
P->warnIfBestTransformationNotAvailable) {
warnAboutMissingGrid(alt.pj);
if (P->errorIfBestTransformationNotAvailable)
return res;
P->warnIfBestTransformationNotAvailable = false;
skipNonInstantiable = true;
}
if (iRetry == N_MAX_RETRY) {
break;
}
iExcluded[iRetry] = iBest;
}
// In case we did not find an operation whose area of use is compatible
// with the input coordinate, then goes through again the list, and
// use the first operation that does not require grids.
NS_PROJ::io::DatabaseContextPtr dbContext;
try {
if (P->ctx->cpp_context) {
dbContext =
P->ctx->cpp_context->getDatabaseContext().as_nullable();
}
} catch (const std::exception &) {
}
for (int i = 0; i < nOperations; i++) {
const auto &alt = P->alternativeCoordinateOperations[i];
auto coordOperation =
dynamic_cast<NS_PROJ::operation::CoordinateOperation *>(
alt.pj->iso_obj.get());
if (coordOperation) {
if (coordOperation->gridsNeeded(dbContext, true).empty()) {
if (P->iCurCoordOp != i) {
if (proj_log_level(P->ctx, PJ_LOG_TELL) >=
PJ_LOG_DEBUG) {
std::string msg("Using coordinate operation ");
msg += alt.name;
msg += " as a fallback due to lack of more "
"appropriate operations";
pj_log(P->ctx, PJ_LOG_DEBUG, msg.c_str());
}
P->iCurCoordOp = i;
}
if (direction == PJ_FWD) {
pj_fwd4d(coord, alt.pj);
} else {
pj_inv4d(coord, alt.pj);
}
return coord;
}
}
}
proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_NO_OPERATION);
return proj_coord_error();
}
P->iCurCoordOp =
0; // dummy value, to be used by proj_trans_get_last_used_operation()
if (P->hasCoordinateEpoch)
coord.xyzt.t = P->coordinateEpoch;
if (coord_has_nans(coord))
coord.v[0] = coord.v[1] = coord.v[2] = coord.v[3] =
std::numeric_limits<double>::quiet_NaN();
else if (direction == PJ_FWD)
pj_fwd4d(coord, P);
else
pj_inv4d(coord, P);
return coord;
}
/*****************************************************************************/
PJ *proj_trans_get_last_used_operation(PJ *P)
/******************************************************************************
Return the operation used during the last invocation of proj_trans().
This is especially useful when P has been created with
proj_create_crs_to_crs() and has several alternative operations. The returned
object must be freed with proj_destroy().
******************************************************************************/
{
if (nullptr == P || P->iCurCoordOp < 0)
return nullptr;
if (P->alternativeCoordinateOperations.empty())
return proj_clone(P->ctx, P);
return proj_clone(P->ctx,
P->alternativeCoordinateOperations[P->iCurCoordOp].pj);
}
/*****************************************************************************/
int proj_trans_array(PJ *P, PJ_DIRECTION direction, size_t n, PJ_COORD *coord) {
/******************************************************************************
Batch transform an array of PJ_COORD.
Performs transformation on all points, even if errors occur on some
points.
Individual points that fail to transform will have their components set
to HUGE_VAL
Returns 0 if all coordinates are transformed without error, otherwise
returns a precise error number if all coordinates that fail to transform
for the same reason, or a generic error code if they fail for different
reasons.
******************************************************************************/
size_t i;
int retErrno = 0;
bool hasSetRetErrno = false;
bool sameRetErrno = true;
for (i = 0; i < n; i++) {
proj_context_errno_set(P->ctx, 0);
coord[i] = proj_trans(P, direction, coord[i]);
int thisErrno = proj_errno(P);
if (thisErrno != 0) {
if (!hasSetRetErrno) {
retErrno = thisErrno;
hasSetRetErrno = true;
} else if (sameRetErrno && retErrno != thisErrno) {
sameRetErrno = false;
retErrno = PROJ_ERR_COORD_TRANSFM;
}
}
}
proj_context_errno_set(P->ctx, retErrno);
return retErrno;
}
/*************************************************************************************/
size_t proj_trans_generic(PJ *P, PJ_DIRECTION direction, double *x, size_t sx,
size_t nx, double *y, size_t sy, size_t ny, double *z,
size_t sz, size_t nz, double *t, size_t st,
size_t nt) {
/**************************************************************************************
Transform a series of coordinates, where the individual coordinate
dimension may be represented by an array that is either
1. fully populated
2. a null pointer and/or a length of zero, which will be treated as
a fully populated array of zeroes
3. of length one, i.e. a constant, which will be treated as a fully
populated array of that constant value
The strides, sx, sy, sz, st, represent the step length, in bytes,
between consecutive elements of the corresponding array. This makes it
possible for proj_transform to handle transformation of a large class of
application specific data structures, without necessarily understanding the
data structure format, as in:
typedef struct {double x, y; int quality_level; char
surveyor_name[134];} XYQS; XYQS survey[345]; double height = 23.45; PJ *P =
{...}; size_t stride = sizeof (XYQS);
...
proj_transform (
P, PJ_INV, sizeof(XYQS),
&(survey[0].x), stride, 345, (* We have 345 eastings *)
&(survey[0].y), stride, 345, (* ...and 345 northings. *)
&height, 1, (* The height is the
constant 23.45 m *) 0, 0 (* and the time is the
constant 0.00 s *)
);
This is similar to the inner workings of the pj_transform function, but
the stride functionality has been generalized to work for any size of basic
unit, not just a fixed number of doubles.
In most cases, the stride will be identical for x, y,z, and t, since
they will typically be either individual arrays (stride = sizeof(double)),
or strided views into an array of application specific data structures
(stride = sizeof (...)).
But in order to support cases where x, y, z, and t come from
heterogeneous sources, individual strides, sx, sy, sz, st, are used.
Caveat: Since proj_transform does its work *in place*, this means that
even the supposedly constants (i.e. length 1 arrays) will return from the
call in altered state. Hence, remember to reinitialize between repeated
calls.
Return value: Number of transformations completed.
**************************************************************************************/
PJ_COORD coord = {{0, 0, 0, 0}};
size_t i, nmin;
double null_broadcast = 0;
double invalid_time = HUGE_VAL;
if (nullptr == P)
return 0;
if (P->inverted)
direction = opposite_direction(direction);
/* ignore lengths of null arrays */
if (nullptr == x)
nx = 0;
if (nullptr == y)
ny = 0;
if (nullptr == z)
nz = 0;
if (nullptr == t)
nt = 0;
/* and make the nullities point to some real world memory for broadcasting
* nulls */
if (0 == nx)
x = &null_broadcast;
if (0 == ny)
y = &null_broadcast;
if (0 == nz)
z = &null_broadcast;
if (0 == nt)
t = &invalid_time;
/* nothing to do? */
if (0 == nx + ny + nz + nt)
return 0;
/* arrays of length 1 are constants, which we broadcast along the longer
* arrays */
/* so we need to find the length of the shortest non-unity array to figure
* out
*/
/* how many coordinate pairs we must transform */
nmin = (nx > 1) ? nx : (ny > 1) ? ny : (nz > 1) ? nz : (nt > 1) ? nt : 1;
if ((nx > 1) && (nx < nmin))
nmin = nx;
if ((ny > 1) && (ny < nmin))
nmin = ny;
if ((nz > 1) && (nz < nmin))
nmin = nz;
if ((nt > 1) && (nt < nmin))
nmin = nt;
/* Check validity of direction flag */
switch (direction) {
case PJ_FWD:
case PJ_INV:
break;
case PJ_IDENT:
return nmin;
}
/* Arrays of length==0 are broadcast as the constant 0 */
/* Arrays of length==1 are broadcast as their single value */
/* Arrays of length >1 are iterated over (for the first nmin values) */
/* The slightly convolved incremental indexing is used due */
/* to the stride, which may be any size supported by the platform */
for (i = 0; i < nmin; i++) {
coord.xyzt.x = *x;
coord.xyzt.y = *y;
coord.xyzt.z = *z;
coord.xyzt.t = *t;
coord = proj_trans(P, direction, coord);
/* in all full length cases, we overwrite the input with the output, */
/* and step on to the next element. */
/* The casts are somewhat funky, but they compile down to no-ops and */
/* they tell compilers and static analyzers that we know what we do */
if (nx > 1) {
*x = coord.xyzt.x;
x = (double *)((void *)(((char *)x) + sx));
}
if (ny > 1) {
*y = coord.xyzt.y;
y = (double *)((void *)(((char *)y) + sy));
}
if (nz > 1) {
*z = coord.xyzt.z;
z = (double *)((void *)(((char *)z) + sz));
}
if (nt > 1) {
*t = coord.xyzt.t;
t = (double *)((void *)(((char *)t) + st));
}
}
/* Last time around, we update the length 1 cases with their transformed
* alter egos */
if (nx == 1)
*x = coord.xyzt.x;
if (ny == 1)
*y = coord.xyzt.y;
if (nz == 1)
*z = coord.xyzt.z;
if (nt == 1)
*t = coord.xyzt.t;
return i;
}
/*************************************************************************************/
PJ_COORD pj_geocentric_latitude(const PJ *P, PJ_DIRECTION direction,
PJ_COORD coord) {
/**************************************************************************************
Convert geographical latitude to geocentric (or the other way round if
direction = PJ_INV)
The conversion involves a call to the tangent function, which goes
through the roof at the poles, so very close (the last centimeter) to the
poles no conversion takes place and the input latitude is copied directly to
the output.
Fortunately, the geocentric latitude converges to the geographical at
the poles, so the difference is negligible.
For the spherical case, the geographical latitude equals the geocentric,
and consequently, the input is copied directly to the output.
**************************************************************************************/
const double limit = M_HALFPI - 1e-9;
PJ_COORD res = coord;
if ((coord.lp.phi > limit) || (coord.lp.phi < -limit) || (P->es == 0))
return res;
if (direction == PJ_FWD)
res.lp.phi = atan(P->one_es * tan(coord.lp.phi));
else
res.lp.phi = atan(P->rone_es * tan(coord.lp.phi));
return res;
}
double proj_torad(double angle_in_degrees) {
return PJ_TORAD(angle_in_degrees);
}
double proj_todeg(double angle_in_radians) {
return PJ_TODEG(angle_in_radians);
}
double proj_dmstor(const char *is, char **rs) { return dmstor(is, rs); }
char *proj_rtodms(char *s, double r, int pos, int neg) {
// 40 is the size used for the buffer in proj.cpp
size_t arbitrary_size = 40;
return rtodms(s, arbitrary_size, r, pos, neg);
}
char *proj_rtodms2(char *s, size_t sizeof_s, double r, int pos, int neg) {
return rtodms(s, sizeof_s, r, pos, neg);
}
/*************************************************************************************/
static PJ *skip_prep_fin(PJ *P) {
/**************************************************************************************
Skip prepare and finalize function for the various "helper operations" added
to P when in cs2cs compatibility mode.
**************************************************************************************/
P->skip_fwd_prepare = 1;
P->skip_fwd_finalize = 1;
P->skip_inv_prepare = 1;
P->skip_inv_finalize = 1;
return P;
}
/*************************************************************************************/
static int cs2cs_emulation_setup(PJ *P) {
/**************************************************************************************
If any cs2cs style modifiers are given (axis=..., towgs84=..., ) create the
4D API equivalent operations, so the preparation and finalization steps in
the pj_inv/pj_fwd invocators can emulate the behavior of pj_transform and
the cs2cs app.
Returns 1 on success, 0 on failure
**************************************************************************************/
PJ *Q;
paralist *p;
int do_cart = 0;
if (nullptr == P)
return 0;
/* Don't recurse when calling proj_create (which calls us back) */
if (pj_param_exists(P->params, "break_cs2cs_recursion"))
return 1;
/* Swap axes? */
p = pj_param_exists(P->params, "axis");
const bool disable_grid_presence_check =
pj_param_exists(P->params, "disable_grid_presence_check") != nullptr;
/* Don't axisswap if data are already in "enu" order */
if (p && (0 != strcmp("enu", p->param))) {
size_t def_size = 100 + strlen(P->axis);
char *def = static_cast<char *>(malloc(def_size));
if (nullptr == def)
return 0;
snprintf(def, def_size,
"break_cs2cs_recursion proj=axisswap axis=%s", P->axis);
Q = pj_create_internal(P->ctx, def);
free(def);
if (nullptr == Q)
return 0;
P->axisswap = skip_prep_fin(Q);
}
/* Geoid grid(s) given? */
p = pj_param_exists(P->params, "geoidgrids");
if (!disable_grid_presence_check && p &&
strlen(p->param) > strlen("geoidgrids=")) {
char *gridnames = p->param + strlen("geoidgrids=");
size_t def_size = 100 + 2 * strlen(gridnames);
char *def = static_cast<char *>(malloc(def_size));
if (nullptr == def)
return 0;
snprintf(def, def_size,
"break_cs2cs_recursion proj=vgridshift grids=%s",
pj_double_quote_string_param_if_needed(gridnames).c_str());
Q = pj_create_internal(P->ctx, def);
free(def);
if (nullptr == Q)
return 0;
P->vgridshift = skip_prep_fin(Q);
}
/* Datum shift grid(s) given? */
p = pj_param_exists(P->params, "nadgrids");
if (!disable_grid_presence_check && p &&
strlen(p->param) > strlen("nadgrids=")) {
char *gridnames = p->param + strlen("nadgrids=");
size_t def_size = 100 + 2 * strlen(gridnames);
char *def = static_cast<char *>(malloc(def_size));
if (nullptr == def)
return 0;
snprintf(def, def_size,
"break_cs2cs_recursion proj=hgridshift grids=%s",
pj_double_quote_string_param_if_needed(gridnames).c_str());
Q = pj_create_internal(P->ctx, def);
free(def);
if (nullptr == Q)
return 0;
P->hgridshift = skip_prep_fin(Q);
}
/* We ignore helmert if we have grid shift */
p = P->hgridshift ? nullptr : pj_param_exists(P->params, "towgs84");
while (p) {
char *def;
char *s = p->param;
double *d = P->datum_params;
size_t n = strlen(s);
/* We ignore null helmert shifts (common in auto-translated resource
* files, e.g. epsg) */
if (0 == d[0] && 0 == d[1] && 0 == d[2] && 0 == d[3] && 0 == d[4] &&
0 == d[5] && 0 == d[6]) {
/* If the current ellipsoid is not WGS84, then make sure the */
/* change in ellipsoid is still done. */
if (!(fabs(P->a_orig - 6378137.0) < 1e-8 &&
fabs(P->es_orig - 0.0066943799901413) < 1e-15)) {
do_cart = 1;
}
break;
}
if (n <= 8) /* 8==strlen ("towgs84=") */
return 0;
size_t def_size = 100 + n;
def = static_cast<char *>(malloc(def_size));
if (nullptr == def)
return 0;
snprintf(def, def_size,
"break_cs2cs_recursion proj=helmert exact %s "
"convention=position_vector",
s);
Q = pj_create_internal(P->ctx, def);
free(def);
if (nullptr == Q)
return 0;
pj_inherit_ellipsoid_def(P, Q);
P->helmert = skip_prep_fin(Q);
break;
}
/* We also need cartesian/geographical transformations if we are working in
*/
/* geocentric/cartesian space or we need to do a Helmert transform. */
if (P->is_geocent || P->helmert || do_cart) {
char def[150];
snprintf(def, sizeof(def),
"break_cs2cs_recursion proj=cart a=%40.20g es=%40.20g",
P->a_orig, P->es_orig);
{
/* In case the current locale does not use dot but comma as decimal
*/
/* separator, replace it with dot, so that proj_atof() behaves */
/* correctly. */
/* TODO later: use C++ ostringstream with
* imbue(std::locale::classic()) */
/* to be locale unaware */
char *next_pos;
for (next_pos = def; (next_pos = strchr(next_pos, ',')) != nullptr;
next_pos++) {
*next_pos = '.';
}
}
Q = pj_create_internal(P->ctx, def);
if (nullptr == Q)
return 0;
P->cart = skip_prep_fin(Q);
if (!P->is_geocent) {
snprintf(def, sizeof(def),
"break_cs2cs_recursion proj=cart ellps=WGS84");
Q = pj_create_internal(P->ctx, def);
if (nullptr == Q)
return 0;
P->cart_wgs84 = skip_prep_fin(Q);
}
}
return 1;
}
/*************************************************************************************/
PJ *pj_create_internal(PJ_CONTEXT *ctx, const char *definition) {
/*************************************************************************************/
/**************************************************************************************
Create a new PJ object in the context ctx, using the given definition.
If ctx==0, the default context is used, if definition==0, or invalid, a
null-pointer is returned. The definition may use '+' as argument start
indicator, as in
"+proj=utm +zone=32", or leave it out, as in "proj=utm zone=32".
It may even use free formatting "proj = utm; zone =32 ellps=
GRS80". Note that the semicolon separator is allowed, but not required.
**************************************************************************************/
char *args, **argv;
size_t argc, n;
if (nullptr == ctx)
ctx = pj_get_default_ctx();
/* Make a copy that we can manipulate */
n = strlen(definition);
args = (char *)malloc(n + 1);
if (nullptr == args) {
proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/);
return nullptr;
}
strcpy(args, definition);
argc = pj_trim_argc(args);
if (argc == 0) {
free(args);
proj_context_errno_set(ctx, PROJ_ERR_INVALID_OP_MISSING_ARG);
return nullptr;
}
argv = pj_trim_argv(argc, args);
if (!argv) {
free(args);
proj_context_errno_set(ctx, PROJ_ERR_OTHER /*ENOMEM*/);
return nullptr;