-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathparseobject.cpp
More file actions
1859 lines (1621 loc) · 64.2 KB
/
Copy pathparseobject.cpp
File metadata and controls
1859 lines (1621 loc) · 64.2 KB
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
// parseobject.cpp
//
// Copyright (C) 2004-2009, the Celestia Development Team
// Original version by Chris Laurel <claurel@gmail.com>
//
// Functions for parsing objects common to star, solar system, and
// deep sky catalogs.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
#include "parseobject.h"
#include <cassert>
#include <cmath>
#include <string>
#include <vector>
#include <Eigen/Core>
#include <celastro/astro.h>
#include <celastro/date.h>
#include <celcompat/numbers.h>
#include <celephem/customorbit.h>
#include <celephem/customrotation.h>
#include <celephem/orbit.h>
#include <celephem/rotation.h>
#include <celephem/samporbit.h>
#include <celmath/geomutil.h>
#include <celmath/mathlib.h>
#include <celutil/associativearray.h>
#include <celutil/fsutils.h>
#include <celutil/logger.h>
#include <celutil/stringutils.h>
#include "body.h"
#include "rotationmanager.h"
#include "selection.h"
#include "trajmanager.h"
#include "universe.h"
#ifdef CELX
#include <celephem/scriptorbit.h>
#include <celephem/scriptrotation.h>
#endif
#ifdef USE_SPICE
#include <celephem/spiceorbit.h>
#include <celephem/spicerotation.h>
#endif
using celestia::ephem::TrajectoryInterpolation;
using celestia::ephem::TrajectoryPrecision;
using celestia::util::AssociativeArray;
using celestia::util::GetLogger;
using celestia::util::Value;
using celestia::util::ValueArray;
namespace astro = celestia::astro;
namespace engine = celestia::engine;
namespace ephem = celestia::ephem;
namespace math = celestia::math;
namespace numbers = celestia::numbers;
namespace util = celestia::util;
namespace
{
/**
* Returns the default units scale for orbits.
*
* If the usePlanetUnits flag is set, this returns a distance scale of AU and a
* time scale of years. Otherwise the distace scale is kilometers and the time
* scale is days.
*
* @param[in] usePlanetUnits Controls whether to return planet units or satellite units.
* @param[out] distanceScale The default distance scale in kilometers.
* @param[out] timeScale The default time scale in days.
*/
void
GetDefaultUnits(bool usePlanetUnits, double& distanceScale, double& timeScale)
{
if(usePlanetUnits)
{
distanceScale = astro::KM_PER_AU<double>;
timeScale = astro::DAYS_PER_YEAR;
}
else
{
distanceScale = 1.0;
timeScale = 1.0;
}
}
/**
* Returns the default distance scale for orbits.
*
* If the usePlanetUnits flag is set, this returns AU, otherwise it returns
* kilometers.
*
* @param[in] usePlanetUnits Controls whether to return planet units or satellite units.
* @param[out] distanceScale The default distance scale in kilometers.
*/
void
GetDefaultUnits(bool usePlanetUnits, double& distanceScale)
{
distanceScale = usePlanetUnits ? astro::KM_PER_AU<double> : 1.0;
}
/*!
* Create a new Keplerian orbit from an ssc property table:
*
* \code EllipticalOrbit
* {
* # One of the following is required to specify orbit size:
* SemiMajorAxis <number>
* PericenterDistance <number>
*
* # One of the following is required:
* Period <number>
* AnomalisticPeriod <number>
*
* Eccentricity <number> (default: 0.0)
* Inclination <degrees> (default: 0.0)
* AscendingNode <degrees> (default: 0.0)
*
* # One or none of the following:
* ArgOfPericenter <degrees> (default: 0.0)
* LongOfPericenter <degrees> (default: 0.0)
*
* Epoch <date> (default J2000.0)
*
* # One or none of the following:
* MeanAnomaly <degrees> (default: 0.0)
* MeanLongitude <degrees> (default: 0.0)
*
* # One or both of the following for a precessing orbit:
* # Default values result in no precession
* NodalPrecessionPeriod <number> (default: 0.0)
* ApsidalPrecessionPeriod <number> (default: 0.0)
* } \endcode
*
* If usePlanetUnits is true:
* Period or AnomalisticPeriod is in Julian years
* SemiMajorAxis or PericenterDistance is in AU
* Otherwise:
* Period or AnomalisticPeriod is in Julian days
* SemiMajorAxis or PericenterDistance is in kilometers.
* The default unit for precession periods is Julian years.
*/
std::shared_ptr<const ephem::Orbit>
CreateKeplerianOrbit(const AssociativeArray* orbitData,
bool usePlanetUnits)
{
// default units for planets are AU and years, otherwise km and days
double distanceScale;
double timeScale;
GetDefaultUnits(usePlanetUnits, distanceScale, timeScale);
astro::KeplerElements elements;
elements.eccentricity = orbitData->getNumber<double>("Eccentricity").value_or(0.0);
if (elements.eccentricity < 0.0)
{
GetLogger()->error("Negative eccentricity is invalid.\n");
return nullptr;
}
else if (elements.eccentricity == 1.0)
{
GetLogger()->error("Parabolic orbits are not supported.\n");
return nullptr;
}
// SemiMajorAxis and Period are absolutely required; everything
// else has a reasonable default.
if (auto semiMajorAxisValue = orbitData->getLength<double>("SemiMajorAxis", 1.0, distanceScale); semiMajorAxisValue.has_value())
{
elements.semimajorAxis = *semiMajorAxisValue;
}
else if (auto pericenter = orbitData->getLength<double>("PericenterDistance", 1.0, distanceScale); pericenter.has_value())
{
elements.semimajorAxis = *pericenter / (1.0 - elements.eccentricity);
}
else
{
GetLogger()->error("SemiMajorAxis/PericenterDistance missing from orbit definition.\n");
return nullptr;
}
elements.nodalPeriod = orbitData->getTime<double>("NodalPrecessionPeriod", 1.0, astro::DAYS_PER_YEAR).value_or(0.0);
elements.apsidalPeriod = orbitData->getTime<double>("ApsidalPrecessionPeriod", 1.0, astro::DAYS_PER_YEAR).value_or(0.0);
if (auto periodValue = orbitData->getTime<double>("Period", 1.0, timeScale); periodValue.has_value())
{
elements.period = *periodValue;
if (elements.period == 0.0)
{
GetLogger()->error("Period cannot be zero.\n");
return nullptr;
}
}
else if (auto anomPeriodValue = orbitData->getTime<double>("AnomalisticPeriod", 1.0, timeScale); anomPeriodValue.has_value())
{
double periodCorrection = 0.0;
if (elements.nodalPeriod != 0.0)
periodCorrection -= 1.0 / elements.nodalPeriod;
if (elements.apsidalPeriod != 0.0)
periodCorrection += 1.0 / elements.apsidalPeriod;
elements.period = 1.0 / (1.0 / *anomPeriodValue + periodCorrection);
if (elements.period == 0.0)
{
GetLogger()->error("AnomalisticPeriod cannot be zero.\n");
return nullptr;
}
}
else
{
GetLogger()->error("Period must be specified in EllipticalOrbit.\n");
return nullptr;
}
elements.inclination = orbitData->getAngle<double>("Inclination").value_or(0.0);
elements.longAscendingNode = orbitData->getAngle<double>("AscendingNode").value_or(0.0);
if (auto argPeri = orbitData->getAngle<double>("ArgOfPericenter"); argPeri.has_value())
{
elements.argPericenter = *argPeri;
}
else if (auto longPeri = orbitData->getAngle<double>("LongOfPericenter"); longPeri.has_value())
{
elements.argPericenter = *longPeri - elements.longAscendingNode;
}
double epoch = astro::J2000;
ParseDate(orbitData, "Epoch", epoch);
// Accept either the mean anomaly or mean longitude--use mean anomaly
// if both are specified.
if (auto meanAnomaly = orbitData->getAngle<double>("MeanAnomaly"); meanAnomaly.has_value())
elements.meanAnomaly = *meanAnomaly;
else if (auto meanLongitude = orbitData->getAngle<double>("MeanLongitude"); meanLongitude.has_value())
elements.meanAnomaly = *meanLongitude - (elements.argPericenter + elements.longAscendingNode);
elements.inclination = math::degToRad(elements.inclination);
elements.longAscendingNode = math::degToRad(elements.longAscendingNode);
elements.argPericenter = math::degToRad(elements.argPericenter);
elements.meanAnomaly = math::degToRad(elements.meanAnomaly);
if (elements.eccentricity < 1.0)
{
if (elements.nodalPeriod == 0.0 && elements.apsidalPeriod == 0.0)
return std::make_shared<ephem::EllipticalOrbit>(elements, epoch);
return std::make_shared<ephem::PrecessingOrbit>(elements, epoch);
}
return std::make_shared<ephem::HyperbolicOrbit>(elements, epoch);
}
/*!
* Create a new sampled orbit from an ssc property table:
*
* \code SampledTrajectory
* {
* Source <string>
* Interpolation "Cubic" | "Linear"
* DoublePrecision <boolean>
* } \endcode
*
* Source is the only required field. Interpolation defaults to cubic, and
* DoublePrecision defaults to true.
*/
std::shared_ptr<const ephem::Orbit>
CreateSampledTrajectory(const AssociativeArray* trajData, const std::filesystem::path& path)
{
const std::string* source = trajData->getString("Source");
if (source == nullptr)
{
GetLogger()->error("SampledTrajectory is missing a source.\n");
return nullptr;
}
auto sourceFile = util::U8FileName(*source);
if (!sourceFile.has_value())
{
GetLogger()->error("Invalid Source filename for SampledTrajectory\n");
return nullptr;
}
// Read interpolation type; string value must be either "Linear" or "Cubic"
// Default interpolation type is cubic.
TrajectoryInterpolation interpolation = TrajectoryInterpolation::Cubic;
if (const std::string* interpolationString = trajData->getString("Interpolation"); interpolationString != nullptr)
{
if (!compareIgnoringCase(*interpolationString, "linear"))
interpolation = TrajectoryInterpolation::Linear;
else if (!compareIgnoringCase(*interpolationString, "cubic"))
interpolation = TrajectoryInterpolation::Cubic;
else
GetLogger()->warn("Unknown interpolation type {}\n", *interpolationString); // non-fatal error
}
// Double precision is true by default
bool useDoublePrecision = trajData->getBoolean("DoublePrecision").value_or(true);
TrajectoryPrecision precision = useDoublePrecision ? TrajectoryPrecision::Double : TrajectoryPrecision::Single;
GetLogger()->verbose("Attempting to load sampled trajectory from source '{}'\n", *source);
auto orbit = engine::GetTrajectoryManager()->find(*sourceFile, path, interpolation, precision);
if (orbit == nullptr)
GetLogger()->error("Could not load sampled trajectory from '{}'\n", *source);
return orbit;
}
/** Create a new FixedPosition trajectory.
*
* A FixedPosition is a property list with one of the following 3-vector properties:
*
* - \c Rectangular
* - \c Planetographic
* - \c Planetocentric
*
* Planetographic and planetocentric coordinates are given in the order longitude,
* latitude, altitude. Units of altitude are kilometers. Planetographic and
* and planetocentric coordinates are only practical when the coordinate system
* is BodyFixed.
*/
std::shared_ptr<const ephem::Orbit>
CreateFixedPosition(const AssociativeArray* trajData, const Selection& centralObject, bool usePlanetUnits)
{
double distanceScale;
GetDefaultUnits(usePlanetUnits, distanceScale);
Eigen::Vector3d position = Eigen::Vector3d::Zero();
if (auto rectangular = trajData->getLengthVector<double>("Rectangular", 1.0, distanceScale); rectangular.has_value())
{
// Convert to Celestia's coordinate system
position = Eigen::Vector3d(rectangular->x(), rectangular->z(), -rectangular->y());
}
else if (auto planetographic = trajData->getSphericalTuple("Planetographic"); planetographic.has_value())
{
if (centralObject.getType() != SelectionType::Body)
{
GetLogger()->error("FixedPosition planetographic coordinates are not valid for stars.\n");
return nullptr;
}
// TODO: Need function to calculate planetographic coordinates
// TODO: Change planetocentricToCartesian so that 180 degree offset isn't required
position = centralObject.body()->planetocentricToCartesian(180.0 + planetographic->x(),
planetographic->y(),
planetographic->z());
}
else if (auto planetocentric = trajData->getSphericalTuple("Planetocentric"); planetocentric.has_value())
{
if (centralObject.getType() != SelectionType::Body)
{
GetLogger()->error("FixedPosition planetocentric coordinates aren't valid for stars.\n");
return nullptr;
}
// TODO: Change planetocentricToCartesian so that 180 degree offset isn't required
position = centralObject.body()->planetocentricToCartesian(180.0 + planetocentric->x(),
planetocentric->y(),
planetocentric->z());
}
else
{
GetLogger()->error("Missing coordinates for FixedPosition\n");
return nullptr;
}
return std::make_shared<ephem::FixedOrbit>(position);
}
#ifdef USE_SPICE
/**
* Parse a string list--either a single string or an array of strings is permitted.
*/
bool
ParseStringList(const AssociativeArray* table,
std::string_view propertyName,
std::vector<std::string>& stringList)
{
const Value* v = table->getValue(propertyName);
if (v == nullptr)
return false;
// Check for a single string first.
if (const std::string* str = v->getString(); str != nullptr)
{
stringList.emplace_back(*str);
return true;
}
if (const ValueArray* array = v->getArray(); array != nullptr)
{
// Verify that all array entries are strings
if (std::any_of(array->begin(), array->end(),
[](const Value& val)
{
return val.getType() != util::ValueType::StringType;
}))
{
return false;
}
// Add strings to stringList
for (const auto& val : *array)
stringList.emplace_back(*val.getString());
return true;
}
return false;
}
/*! Create a new SPICE orbit. This is just a Celestia wrapper for a trajectory specified
* in a SPICE SPK file.
*
* \code SpiceOrbit
* {
* Kernel <string|string array> # optional
* Target <string>
* Origin <string>
* BoundingRadius <number>
* Period <number> # optional
* Beginning <number> # optional
* Ending <number> # optional
* } \endcode
*
* The Kernel property specifies one or more SPK files that must be loaded. Any
* already loaded kernels will also be used if they contain trajectories for
* the target or origin.
* Target and origin are strings that give NAIF IDs for the target and origin
* objects. Either names or integer IDs are valid, but integer IDs still must
* be quoted.
* BoundingRadius gives a conservative estimate of the maximum distance between
* the target and origin objects. It is required by Celestia for visibility
* culling when rendering.
* Beginning and Ending specify the valid time range of the SPICE orbit. It is
* an error to specify Beginning without Ending, and vice versa. If neither is
* specified, the valid range is computed from the coverage window in the SPICE
* kernel pool. If the coverage window is noncontiguous, the first interval is
* used.
*/
std::shared_ptr<const ephem::Orbit>
CreateSpiceOrbit(const AssociativeArray* orbitData,
const std::filesystem::path& path,
bool usePlanetUnits)
{
std::vector<std::string> kernelList;
double distanceScale;
double timeScale;
GetDefaultUnits(usePlanetUnits, distanceScale, timeScale);
if (orbitData->getValue("Kernel") != nullptr)
{
// Kernel list is optional; a SPICE orbit may rely on kernels already loaded into
// the kernel pool.
if (!ParseStringList(orbitData, "Kernel", kernelList))
{
GetLogger()->error("Kernel list for SPICE orbit is neither a string nor array of strings\n");
return nullptr;
}
}
const std::string* targetBodyName = orbitData->getString("Target");
if (targetBodyName == nullptr)
{
GetLogger()->error("Target name missing from SPICE orbit\n");
return nullptr;
}
const std::string* originName = orbitData->getString("Origin");
if (originName == nullptr)
{
GetLogger()->error("Origin name missing from SPICE orbit\n");
return nullptr;
}
// A bounding radius for culling is required for SPICE orbits
double boundingRadius = 0.0;
if (auto bounding = orbitData->getLength<double>("BoundingRadius", 1.0, distanceScale); bounding.has_value())
{
boundingRadius = *bounding;
}
else
{
GetLogger()->error("Bounding Radius missing from SPICE orbit\n");
return nullptr;
}
// The period of the orbit may be specified if appropriate; a value
// of zero for the period (the default), means that the orbit will
// be considered aperiodic.
auto period = orbitData->getTime<double>("Period", 1.0, timeScale).value_or(0.0);
// Either a complete time interval must be specified with Beginning/Ending, or
// else neither field can be present.
const Value* beginningDate = orbitData->getValue("Beginning");
const Value* endingDate = orbitData->getValue("Ending");
if (beginningDate != nullptr && endingDate == nullptr)
{
GetLogger()->error("Beginning specified for SPICE orbit, but ending is missing.\n");
return nullptr;
}
if (endingDate != nullptr && beginningDate == nullptr)
{
GetLogger()->error("Ending specified for SPICE orbit, but beginning is missing.\n");
return nullptr;
}
std::shared_ptr<ephem::SpiceOrbit> orbit = nullptr;
if (beginningDate != nullptr && endingDate != nullptr)
{
double beginningTDBJD = 0.0;
if (!ParseDate(orbitData, "Beginning", beginningTDBJD))
{
GetLogger()->error("Invalid beginning date specified for SPICE orbit.\n");
return nullptr;
}
double endingTDBJD = 0.0;
if (!ParseDate(orbitData, "Ending", endingTDBJD))
{
GetLogger()->error("Invalid ending date specified for SPICE orbit.\n");
return nullptr;
}
orbit = std::make_shared<ephem::SpiceOrbit>(*targetBodyName,
*originName,
period,
boundingRadius,
beginningTDBJD,
endingTDBJD);
}
else
{
// No time interval given; we'll use whatever coverage window is given
// in the SPICE kernel.
orbit = std::make_shared<ephem::SpiceOrbit>(*targetBodyName,
*originName,
period,
boundingRadius);
}
if (!orbit->init(path, kernelList.cbegin(), kernelList.cend()))
{
// Error using SPICE library; destroy the orbit; hopefully a
// fallback is defined in the SSC file.
orbit = nullptr;
}
return orbit;
}
/*! Create a new rotation model based on a SPICE frame.
*
* \code SpiceRotation
* {
* Kernel <string|string array> # optional
* Frame <string>
* BaseFrame <string> # optional (defaults to ecliptic)
* Period <number> # optional (units are hours)
* Beginning <number> # optional
* Ending <number> # optional
* } \endcode
*
* The Kernel property specifies one or more SPICE kernel files that must be
* loaded in order for the frame to be defined over the required range. Any
* already loaded kernels will be used if they contain information relevant
* for defining the frame.
* Frame and base name are strings that give SPICE names for the frames. The
* orientation of the SpiceRotation is the orientation of the frame relative to
* the base frame. By default, the base frame is eclipj2000.
* Beginning and Ending specify the valid time range of the SPICE rotation.
* If the Beginning and Ending are omitted, the rotation model is assumed to
* be valid at any time. It is an error to specify Beginning without Ending,
* and vice versa.
* Period specifies the principal rotation period; it defaults to 0 indicating
* that the rotation is aperiodic. It is not essential to provide the rotation
* period; it is only used by Celestia for displaying object information such
* as sidereal day length.
*/
std::shared_ptr<ephem::SpiceRotation>
CreateSpiceRotation(const Value& value,
const std::filesystem::path& path)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect spice rotation syntax.\n");
return nullptr;
}
std::vector<std::string> kernelList;
if (rotationData->getValue("Kernel") != nullptr)
{
// Kernel list is optional; a SPICE rotation may rely on kernels already loaded into
// the kernel pool.
if (!ParseStringList(rotationData, "Kernel", kernelList))
{
GetLogger()->warn("Kernel list for SPICE rotation is neither a string nor array of strings\n");
return nullptr;
}
}
const std::string* frameName = rotationData->getString("Frame");
if (frameName == nullptr)
{
GetLogger()->error("Frame name missing from SPICE rotation\n");
return nullptr;
}
std::string baseFrameName;
if (auto baseFrame = rotationData->getString("BaseFrame"); baseFrame == nullptr)
baseFrameName = "eclipj2000";
else
baseFrameName = *baseFrame;
// The period of the rotation may be specified if appropriate; a value
// of zero for the period (the default), means that the rotation will
// be considered aperiodic.
auto period = rotationData->getTime<double>("Period", 1.0, 1.0 / astro::HOURS_PER_DAY).value_or(0.0);
// Either a complete time interval must be specified with Beginning/Ending, or
// else neither field can be present.
const Value* beginningDate = rotationData->getValue("Beginning");
const Value* endingDate = rotationData->getValue("Ending");
if (beginningDate != nullptr && endingDate == nullptr)
{
GetLogger()->error("Beginning specified for SPICE rotation, but ending is missing.\n");
return nullptr;
}
if (endingDate != nullptr && beginningDate == nullptr)
{
GetLogger()->error("Ending specified for SPICE rotation, but beginning is missing.\n");
return nullptr;
}
std::shared_ptr<ephem::SpiceRotation> rotation = nullptr;
if (beginningDate != nullptr && endingDate != nullptr)
{
double beginningTDBJD = 0.0;
if (!ParseDate(rotationData, "Beginning", beginningTDBJD))
{
GetLogger()->error("Invalid beginning date specified for SPICE rotation.\n");
return nullptr;
}
double endingTDBJD = 0.0;
if (!ParseDate(rotationData, "Ending", endingTDBJD))
{
GetLogger()->error("Invalid ending date specified for SPICE rotation.\n");
return nullptr;
}
rotation = std::make_shared<ephem::SpiceRotation>(*frameName,
baseFrameName,
period,
beginningTDBJD,
endingTDBJD);
}
else
{
// No time interval given; rotation is valid at any time.
rotation = std::make_shared<ephem::SpiceRotation>(*frameName,
baseFrameName,
period);
}
if (!rotation->init(path, kernelList.cbegin(), kernelList.cend()))
{
// Error using SPICE library; destroy the rotation.
rotation = nullptr;
}
return rotation;
}
#endif
std::shared_ptr<const ephem::Orbit>
CreateScriptedOrbit(const AssociativeArray* orbitData,
const std::filesystem::path& path)
{
#ifdef CELX
// Function name is required
const std::string* funcName = orbitData->getString("Function");
if (funcName == nullptr)
{
GetLogger()->error("Function name missing from script orbit definition.\n");
return nullptr;
}
// Module name is optional
const std::string* moduleName = orbitData->getString("Module");
//Value* pathValue = new Value(path.string());
//orbitData->addValue("AddonPath", *pathValue);
return ephem::CreateScriptedOrbit(moduleName, *funcName, *orbitData, path);
#else
GetLogger()->warn("ScriptedOrbit not usable without scripting support.\n");
return nullptr;
#endif
}
std::shared_ptr<const ephem::ConstantOrientation>
CreateFixedRotationModel(double offset,
double inclination,
double ascendingNode)
{
Eigen::Quaterniond q = math::YRotation(-numbers::pi - offset) *
math::XRotation(-inclination) *
math::YRotation(-ascendingNode);
return std::make_shared<ephem::ConstantOrientation>(q);
}
std::shared_ptr<const ephem::RotationModel>
CreateUniformRotationModel(const Value& value,
double syncRotationPeriod)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect UniformRotation syntax.\n");
return nullptr;
}
// Default to synchronous rotation
auto period = rotationData->getTime<double>("Period", 1.0, 1.0 / astro::HOURS_PER_DAY).value_or(syncRotationPeriod);
auto offset = math::degToRad(rotationData->getAngle<double>("MeridianAngle").value_or(0.0));
double epoch = astro::J2000;
ParseDate(rotationData, "Epoch", epoch);
auto inclination = math::degToRad(rotationData->getAngle<double>("Inclination").value_or(0.0));
auto ascendingNode = math::degToRad(rotationData->getAngle<double>("AscendingNode").value_or(0.0));
// No period was specified, and the default synchronous
// rotation period is zero, indicating that the object
// doesn't have a periodic orbit. Default to a constant
// orientation instead.
if (period == 0.0)
return CreateFixedRotationModel(offset, inclination, ascendingNode);
return std::make_shared<ephem::UniformRotationModel>(period,
static_cast<float>(offset),
epoch,
static_cast<float>(inclination),
static_cast<float>(ascendingNode));
}
std::shared_ptr<const ephem::RotationModel>
CreateFixedRotationModel(const Value& value)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect FixedRotation syntax.\n");
return nullptr;
}
auto offset = math::degToRad(rotationData->getAngle<double>("MeridianAngle").value_or(0.0));
auto inclination = math::degToRad(rotationData->getAngle<double>("Inclination").value_or(0.0));
auto ascendingNode = math::degToRad(rotationData->getAngle<double>("AscendingNode").value_or(0.0));
Eigen::Quaterniond q = math::YRotation(-numbers::pi - offset) *
math::XRotation(-inclination) *
math::YRotation(-ascendingNode);
return std::make_shared<ephem::ConstantOrientation>(q);
}
std::shared_ptr<const ephem::RotationModel>
CreateFixedAttitudeRotationModel(const Value& value)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect FixedAttitude syntax.\n");
return nullptr;
}
auto heading = math::degToRad(rotationData->getAngle<double>("Heading").value_or(0.0));
auto tilt = math::degToRad(rotationData->getAngle<double>("Tilt").value_or(0.0));
auto roll = math::degToRad(rotationData->getAngle<double>("Roll").value_or(0.0));
Eigen::Quaterniond q = math::YRotation(-numbers::pi - heading) *
math::XRotation(-tilt) *
math::ZRotation(-roll);
return std::make_shared<ephem::ConstantOrientation>(q);
}
std::shared_ptr<const ephem::RotationModel>
CreatePrecessingRotationModel(const Value& value,
double syncRotationPeriod)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect syntax for precessing rotation.\n");
return nullptr;
}
// Default to synchronous rotation
double period = rotationData->getTime<double>("Period", 1.0, 1.0 / astro::HOURS_PER_DAY).value_or(syncRotationPeriod);
auto offset = math::degToRad(rotationData->getAngle<double>("MeridianAngle").value_or(0.0));
double epoch = astro::J2000;
ParseDate(rotationData, "Epoch", epoch);
auto inclination = math::degToRad(rotationData->getAngle<double>("Inclination").value_or(0.0));
auto ascendingNode = math::degToRad(rotationData->getAngle<double>("AscendingNode").value_or(0.0));
// The default value of 0 is handled specially, interpreted to indicate
// that there's no precession.
auto precessionPeriod = rotationData->getTime<double>("PrecessionPeriod", 1.0, astro::DAYS_PER_YEAR).value_or(0.0);
// No period was specified, and the default synchronous
// rotation period is zero, indicating that the object
// doesn't have a periodic orbit. Default to a constant
// orientation instead.
if (period == 0.0)
return CreateFixedRotationModel(offset, inclination, ascendingNode);
return std::make_shared<ephem::PrecessingRotationModel>(period,
static_cast<float>(offset),
epoch,
static_cast<float>(inclination),
static_cast<float>(ascendingNode),
precessionPeriod);
}
#ifdef CELX
std::shared_ptr<const ephem::RotationModel>
CreateScriptedRotation(const Value& value,
const std::filesystem::path& path)
{
const AssociativeArray* rotationData = value.getHash();
if (rotationData == nullptr)
{
GetLogger()->error("Object has incorrect scripted rotation syntax.\n");
return nullptr;
}
// Function name is required
const std::string* funcName = rotationData->getString("Function");
if (funcName == nullptr)
{
GetLogger()->error("Function name missing from scripted rotation definition.\n");
return nullptr;
}
// Module name is optional
const std::string* moduleName = rotationData->getString("Module");
//Value* pathValue = new Value(path.string());
//rotationData->addValue("AddonPath", *pathValue);
return ephem::CreateScriptedRotation(moduleName, *funcName, *rotationData, path);
}
#endif
std::shared_ptr<const ephem::RotationModel>
CreateSampledRotation(std::string_view filename, const std::filesystem::path& path)
{
auto filePath = util::U8FileName(filename);
if (!filePath.has_value())
{
GetLogger()->error("Invalid filename in SampledOrientation\n");
return nullptr;
}
GetLogger()->verbose("Attempting to load orientation file '{}'\n", filename);
auto rotationModel = engine::GetRotationModelManager()->find(*filePath, path);
if (rotationModel == nullptr)
GetLogger()->error("Could not load rotation model file '{}'\n", filename);
return rotationModel;
}
/**
* Get the center object of a frame definition. Return an empty selection
* if it's missing or refers to an object that doesn't exist.
*/
Selection
getFrameCenter(const Universe& universe, const AssociativeArray* frameData, const Selection& defaultCenter)
{
const std::string* centerName = frameData->getString("Center");
if (centerName == nullptr)
{
if (defaultCenter.empty())
GetLogger()->warn("No center specified for reference frame.\n");
return defaultCenter;
}
Selection centerObject = universe.findPath(*centerName, {});
if (centerObject.empty())
{
GetLogger()->error("Center object '{}' of reference frame not found.\n", *centerName);
return Selection();
}
// Should verify that center object is a star or planet, and
// that it is a member of the same star system as the body in which
// the frame will be used.
return centerObject;
}
BodyFixedFrame::SharedConstPtr
CreateBodyFixedFrame(const Universe& universe,
const AssociativeArray* frameData,
const Selection& defaultCenter)
{
Selection center = getFrameCenter(universe, frameData, defaultCenter);
if (center.empty())
return nullptr;
return std::make_shared<BodyFixedFrame>(center, center);
}
BodyMeanEquatorFrame::SharedConstPtr
CreateMeanEquatorFrame(const Universe& universe,
const AssociativeArray* frameData,
const Selection& defaultCenter)
{
Selection center = getFrameCenter(universe, frameData, defaultCenter);
if (center.empty())
return nullptr;
Selection obj = center;
if (const std::string* objName = frameData->getString("Object"); objName != nullptr)
{
obj = universe.findPath(*objName, {});
if (obj.empty())
{
GetLogger()->error("Object '{}' for mean equator frame not found.\n", *objName);
return nullptr;
}
}
if (double freezeEpoch = 0.0; ParseDate(frameData, "Freeze", freezeEpoch))
return std::make_shared<BodyMeanEquatorFrame>(center, obj, freezeEpoch);
return std::make_shared<BodyMeanEquatorFrame>(center, obj);
}
/**
* Convert a string to an axis label. Permitted axis labels are
* x, y, z, -x, -y, and -z. +x, +y, and +z are allowed as synonyms for
* x, y, z. Case is ignored.
*/
int
parseAxisLabel(const std::string& label)
{
if (compareIgnoringCase(label, "x") == 0 ||
compareIgnoringCase(label, "+x") == 0)
{
return 1;
}
if (compareIgnoringCase(label, "y") == 0 ||
compareIgnoringCase(label, "+y") == 0)
{
return 2;
}
if (compareIgnoringCase(label, "z") == 0 ||
compareIgnoringCase(label, "+z") == 0)
{
return 3;
}
if (compareIgnoringCase(label, "-x") == 0)
{
return -1;
}
if (compareIgnoringCase(label, "-y") == 0)