Rise
The Vieneo Province
Loading...
Searching...
No Matches
WeatherRadarModel.h
Go to the documentation of this file.
1#pragma once
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <cstdint>
7#include <vector>
8
9// Ticket 0000434. All acquisition, attenuation, memory and display preparation
10// live in the WeatherRadar module. This header is independent of the GPU/network.
11namespace WeatherRadarModel
12{
13 constexpr double Pi = 3.14159265358979323846;
14 constexpr int Bearings = 121, Gates = 128;
15 constexpr double MaxRangeKm = 64; // Rise scan limit; each source footprint can end earlier
16 constexpr double HalfSweepDegrees = 60, TraverseSeconds = 4;
17 constexpr double MemorySeconds = TraverseSeconds * 2 + .25;
18 // Rise tuning, not measured N2/SO2 microwave absorption or Earth rainfall/dBZ.
19 constexpr double WeatherExtinctionPerKm = .12;
20 constexpr double RangeExtinctionPerKm = .0015;
21 constexpr double ShadowTransmission = .06;
22 constexpr double SourceTimeoutSeconds = 360; // five-minute weather epoch + margin
23 // Assumed 18-inch X-band installation: Honeywell's 5.6 degree weather
24 // beam / 10 degree ground beam. Gaussian two-way antenna response, not
25 // an Earth atmosphere correction. See docs/WeatherRadar.md for limits.
26 constexpr double WeatherBeamDegrees = 5.6, GroundHalfBeamDegrees = 5;
27 constexpr std::array<double,9> ElevationDegrees{{-5,-4,-2.8,-1.4,0,1.4,2.8,4,5}};
28 constexpr int CenterRay = 4;
29 // Installation choices for Rise's automatic weather search, not atmospheric
30 // constants: park the lower weather-beam edge at the terrain horizon out to
31 // 80% range, with a +/-15 degree commanded tilt envelope. A separate level
32 // look retains nearby/flight-level weather when the search beam tilts down.
33 constexpr double AutoTiltRangeFraction = .8, MaxTiltDegrees = 15;
34
35 inline double AntennaIntegral(double lowDegrees,double highDegrees)
36 {
37 // One-way half power at +/- beamwidth/2; transmit * receive squares it.
38 const double scale=std::sqrt(8*std::log(2.))/WeatherBeamDegrees;
39 return .5*(std::erf(highDegrees*scale)-std::erf(lowDegrees*scale));
40 }
41 inline double GroundLevel(double illuminatedFraction,double gateKm,double waterFraction)
42 {
43 // Constant-gamma-style diffuse surface proxy. Projected footprint and
44 // grazing factor cancel; slope/range enter through visible solid angle
45 // per range gate. These scales are Rise display tuning, NOT measured
46 // rock/brackish-water gamma, dBZ, or an Earth sea-state coefficient.
47 const double responseKm=24*(1-waterFraction)+.08*waterFraction;
48 const double power=(std::max)(0.,(std::min)(1.,responseKm*illuminatedFraction/gateKm));
49 return 2+12*std::sqrt(power); // ground uses green/yellow/red; no synthetic turbulence
50 }
51
52 inline double PathExtinctionPerKm(double level)
53 {
54 const double intensity=(std::max)(0.,(level-2.5)/13.5);
55 const double squared=intensity*intensity;
56 // Rise tuning: light/moderate (green/yellow) paths remain usable over
57 // the full 64 km scan; deep heavy/extreme cells can exhaust the signal.
58 // Fourth power preserves the existing peak loss, without treating the
59 // ordinal weather level as measured microwave power or Earth rainfall.
60 return RangeExtinctionPerKm+WeatherExtinctionPerKm*squared*squared;
61 }
62
63 inline double Dot(Point a, Point b) { return a.x*b.x+a.y*b.y+a.z*b.z; }
64 inline double Length(Point a) { return std::sqrt(Dot(a,a)); }
65 inline bool Finite(Point a) { return std::isfinite(a.x)&&std::isfinite(a.y)&&std::isfinite(a.z); }
66 inline Point Unit(Point a) { const double n=Length(a); return n>1e-9 ? a*(1/n) : Point{}; }
67 inline Point Cross(Point a, Point b) { return {a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x}; }
68 inline void MapFrame(Point position,double headingDegrees,Point& forward,Point& right)
69 {
70 const auto up=Unit(position);
71 // Match MovingMap's planet/sign and clockwise-heading convention.
72 // Its physical forward at heading zero is the negative-Z tangent.
73 auto north=Unit(Point{0,0,-1}+up*up.z);
74 if(Length(north)<.9) north=Unit(Point{0,-1,0}+up*up.y);
75 const auto east=Unit(Cross(up,north));
76 const double heading=headingDegrees*Pi/180;
77 forward=north*std::cos(heading)+east*std::sin(heading);
78 right=east*std::cos(heading)-north*std::sin(heading);
79 }
80
81 enum class Echo : uint8_t { Clear, Green, Yellow, Red, Purple, Shadow, Missing, TerrainShadow, OutsideCoverage };
82 inline Echo Classify(double level)
83 {
84 return level < 2.5 ? Echo::Clear : level < 7 ? Echo::Green :
85 level < 11 ? Echo::Yellow : level < 15 ? Echo::Red : Echo::Purple;
86 }
87 inline uint32_t Color(Echo echo)
88 {
89 switch(echo)
90 {
91 case Echo::Green: return 0xff00d040;
92 case Echo::Yellow: return 0xffffff00;
93 case Echo::Red: return 0xffff2020;
94 case Echo::Purple: return 0xffc040ff;
95 case Echo::Shadow: case Echo::TerrainShadow: return 0xff202028;
96 case Echo::Missing: case Echo::OutsideCoverage: return 0xff101c24;
97 default: return 0xff000000;
98 }
99 }
100 struct Sample
101 {
102 bool available=false;
103 double level=2, surfaceKm=0, topKm=0;
104 bool outsideCoverage=false; // normal source footprint edge, not an interior data failure
105 double waterFraction=0; // terrain landform coverage, NOT elevation or standing-water depth
106 };
107 inline bool ValidSample(const Sample& cell)
108 {
109 return cell.available && std::isfinite(cell.level) && cell.level>=2 && cell.level<=16 &&
110 std::isfinite(cell.surfaceKm) && std::isfinite(cell.topKm) &&
111 std::isfinite(cell.waterFraction) && cell.waterFraction>=0 && cell.waterFraction<=1;
112 }
114 {
115 // A measured weather return wins over an obscured part of the beam.
116 // An empty upper look does not certify the hidden lower volume clear.
117 const auto weather=[](Echo e) { return e>=Echo::Green && e<=Echo::Purple; };
118 if(weather(a) || weather(b)) return weather(a) && weather(b) ? (std::max)(a,b) : weather(a) ? a : b;
120 if(a==e || b==e) return e;
121 return Echo::Clear;
122 }
123 struct Input
124 {
125 bool equipped=false, power=false, simulator=false, dataAvailable=false;
127 int vehicle=-1;
128 uint64_t generation=0, revision=0;
129 Point position{}, forward{}, right{}; // physical planet coordinates, local horizontal
130 double radiusKm=0, rangeKm=0;
131 double maxFrameSeconds=0; // scheduler's largest frame; zero for direct callers
132 };
133 inline bool AboveWeatherCoverage(double mslKm,bool feedSuspended,double topKm,double resumeKm)
134 {
135 // Use the weather service's MSL limits and existing hysteresis latch.
136 // Guard a stale latch during a teleport/descent; invalid altitude is not clear air.
137 return std::isfinite(mslKm) && std::isfinite(topKm) && std::isfinite(resumeKm) && resumeKm<=topKm &&
138 (mslKm>topKm || (feedSuspended && mslKm>=resumeKm));
139 }
140 struct Beam
141 {
142 bool valid=false;
143 double time=0, rangeKm=0;
144 double tiltDegrees=0;
145 bool tiltValid=false;
147 std::array<Echo,Gates> echoes{};
148 std::array<Echo,Gates> groundEchoes{}; // rejected clutter, retained for diagnostics/tests only
149 bool attenuated=false, limited=false; // independent of a visible return at another elevation
150 };
152 {
153 std::array<Beam,Bearings> beams{};
154 bool running=false;
156 double clock=0, pending=0, sourceAge=0;
158
159 static Point Direction(const Input& in,double degrees)
160 { const double a=degrees*Pi/180; return in.forward*std::cos(a)+in.right*std::sin(a); }
161 static Quad Geometry(const Beam& beam,int begin,int end,double radius,uint32_t color)
162 {
163 const double nearKm=beam.rangeKm*(begin ? double(begin) : .1)/Gates;
164 const double farKm=beam.rangeKm*end/Gates;
165 // A tiny inner edge avoids a degenerate sprite homography at ownship.
166 return {{{Unit(beam.origin+beam.left*nearKm)*-radius,
167 Unit(beam.origin+beam.left*farKm)*-radius,
168 Unit(beam.origin+beam.right*farKm)*-radius,
169 Unit(beam.origin+beam.right*nearKm)*-radius}},color};
170 }
171 template<class Sampler> void Acquire(const Input& in,Sampler& sample)
172 {
173 auto& beam=beams[bearing]; beam.valid=true; beam.time=clock;
174 beam.origin=in.position; beam.rangeKm=in.rangeKm;
175 const double angle=-HalfSweepDegrees+bearing;
176 beam.left=Direction(in,(std::max)(-HalfSweepDegrees,angle-.5));
177 beam.right=Direction(in,(std::min)(HalfSweepDegrees,angle+.5));
178 const auto ray=Direction(in,angle), up=Unit(in.position);
179 const double step=in.rangeKm/Gates;
180 // Reuse this surface profile for tilt selection and both looks.
181 // No terrain is extrapolated through a missing sample or footprint.
182 std::array<Sample,Gates> profile{};
183 double horizon=-90;
184 bool profileKnown=true;
185 const int aimGate=int(AutoTiltRangeFraction*Gates);
186 for(int g=0;g<Gates;++g)
187 {
188 const auto point=in.position+ray*((g+.5)*step);
189 profile[g]=sample(point);
190 if(g>aimGate) continue;
191 profileKnown&=ValidSample(profile[g]) && !profile[g].outsideCoverage;
192 if(profileKnown)
193 {
194 const auto delta=Unit(point)*(in.radiusKm+profile[g].surfaceKm)-in.position;
195 horizon=(std::max)(horizon,std::atan2(Dot(delta,up),Dot(delta,ray))*180/Pi);
196 }
197 }
198 beam.tiltValid=profileKnown;
199 beam.tiltDegrees=profileKnown ? std::clamp(horizon+WeatherBeamDegrees*.5,-MaxTiltDegrees,MaxTiltDegrees) : 0;
200 beam.echoes={}; beam.groundEchoes={};
201 beam.attenuated=beam.limited=false;
202 // Two elevation looks form one displayed bearing. This is bounded
203 // multi-elevation acquisition, not a complete volumetric radar.
204 AcquireLook(in,sample,beam,ray,up,profile,0);
205 if(std::fabs(beam.tiltDegrees)>.01)
206 AcquireLook(in,sample,beam,ray,up,profile,beam.tiltDegrees);
207 }
208 template<class Sampler> void AcquireLook(const Input& in,Sampler& sample,Beam& beam,
209 Point ray,Point up,const std::array<Sample,Gates>& profile,double tilt)
210 {
211 const double step=in.rangeKm/Gates;
212 std::array<Point,ElevationDegrees.size()> rays{};
213 std::array<double,ElevationDegrees.size()> opticalDepth{};
214 std::array<Echo,ElevationDegrees.size()> blocked{};
215 for(size_t n=0;n<rays.size();++n)
216 {
217 const double elevation=(tilt+ElevationDegrees[n])*Pi/180;
218 rays[n]=ray*std::cos(elevation)+up*std::sin(elevation);
219 }
220 double terrainHorizon=-90;
221 double groundOpticalDepth=0;
222 bool groundPathKnown=true;
223 for(int g=0;g<Gates;++g)
224 {
225 const double distance=(g+.5)*step;
226 const auto centerPoint=in.position+ray*distance;
227 const auto& center=profile[g];
228 Echo echo=Echo::Clear;
229 // Integrate the newly visible surface's angular footprint. A
230 // continuous horizon avoids painting one isolated ring per ray
231 // on flat ground. Hidden slopes cannot return through a ridge.
232 if(groundPathKnown && ValidSample(center) && !center.outsideCoverage)
233 {
234 const auto surface=Unit(centerPoint)*(in.radiusKm+center.surfaceKm);
235 const auto delta=surface-in.position;
236 // With both endpoints below the column top the entire
237 // straight ground path stays in that column. Integrate its
238 // loss independently: a lower quadrature ray may already
239 // have hit the ground and stopped accumulating weather.
240 const double groundLoss=step*PathExtinctionPerKm(center.level);
241 const double groundTransmission=std::exp(-2*(groundOpticalDepth+groundLoss*.5)*Length(delta)/distance);
242 groundOpticalDepth+=groundLoss;
243 const bool withinColumn=Length(in.position)-in.radiusKm<=center.topKm && center.surfaceKm<=center.topKm;
244 const double elevation=std::atan2(Dot(delta,up),Dot(delta,ray))*180/Pi;
245 const double low=(std::max)(terrainHorizon-tilt,-GroundHalfBeamDegrees);
246 const double high=(std::min)(elevation-tilt,GroundHalfBeamDegrees);
247 double illuminated=0;
248 if(high>low && Length(delta)<=in.rangeKm) for(size_t n=0;n<rays.size();++n)
249 {
250 const double a=n ? (ElevationDegrees[n-1]+ElevationDegrees[n])*.5 : -GroundHalfBeamDegrees;
251 const double b=n+1<rays.size() ? (ElevationDegrees[n]+ElevationDegrees[n+1])*.5 : GroundHalfBeamDegrees;
252 const double lo=(std::max)(low,a), hi=(std::min)(high,b);
253 // The terrain echo must survive the weather path too.
254 if(hi>lo && blocked[n]!=Echo::Missing && blocked[n]!=Echo::OutsideCoverage &&
255 (withinColumn ? groundTransmission : std::exp(-2*opticalDepth[n]))>=ShadowTransmission)
256 illuminated+=AntennaIntegral(lo,hi);
257 }
258 // Terrain-database clutter rejection removes the SURFACE
259 // echo, never the precipitation in the same range gate.
260 beam.groundEchoes[g]=(std::max)(beam.groundEchoes[g],
261 Classify(GroundLevel(illuminated,step,center.waterFraction)));
262 terrainHorizon=(std::max)(terrainHorizon,elevation);
263 }
264 else groundPathKnown=false; // no surface extrapolation through missing coverage
265
266 bool missing=false;
267 for(size_t n=0;n<rays.size();++n)
268 {
269 const bool mainLobe=std::fabs(ElevationDegrees[n])<=WeatherBeamDegrees*.5;
270 if(blocked[n]==Echo::Clear)
271 {
272 const auto point=in.position+rays[n]*distance;
273 const auto cell=n==CenterRay && tilt==0 ? center : sample(point);
274 if(cell.outsideCoverage) blocked[n]=Echo::OutsideCoverage;
275 else if(!ValidSample(cell)) blocked[n]=Echo::Missing;
276 else if(Length(point)-in.radiusKm<cell.surfaceKm) blocked[n]=Echo::TerrainShadow;
277 else
278 {
279 // Existing uniform precipitation column, sampled at
280 // each elevation using geometric MSL and slant range.
281 const double level=Length(point)-in.radiusKm<=cell.topKm ? cell.level : 2;
282 const double loss=step*PathExtinctionPerKm(level);
283 const double transmission=std::exp(-2*(opticalDepth[n]+loss*.5));
284 opticalDepth[n]+=loss;
285 if(transmission<ShadowTransmission) blocked[n]=Echo::Shadow;
286 else if(mainLobe && int(Classify(level))>int(echo)) echo=Classify(level);
287 }
288 }
289 missing|=mainLobe && blocked[n]==Echo::Missing;
290 }
291 beam.attenuated|=blocked[CenterRay]==Echo::Shadow;
292 beam.limited|=missing;
293 // Preserve any real return from the unobstructed beam above a
294 // ridge. With no return, keep the central path's unknown/shadow
295 // state; an empty upper ray must not assert clear weather below.
296 if(echo==Echo::Clear) echo=missing ? Echo::Missing : blocked[CenterRay];
297 beam.echoes[g]=MergeEcho(beam.echoes[g],echo);
298 }
299 }
300 void Prepare(const Input& in,Display& out) const
301 {
302 out.echoes.clear(); out.limited=false; out.attenuated=false;
303 int count=0; bool known=false;
304 for(const auto& beam:beams)
305 {
306 if(!beam.valid || clock-beam.time>MemorySeconds) continue;
307 ++count;
308 out.attenuated|=beam.attenuated;
309 out.limited|=beam.limited;
310 for(int begin=0;begin<Gates;)
311 {
312 const auto echo=beam.echoes[begin]; int end=begin+1;
313 while(end<Gates && beam.echoes[end]==echo) ++end;
314 out.limited|=echo==Echo::Missing; out.attenuated|=echo==Echo::Shadow;
315 known|=echo!=Echo::Missing && echo!=Echo::OutsideCoverage;
316 if(echo!=Echo::Clear) out.echoes.push_back(Geometry(beam,begin,end,in.radiusKm,Color(echo)));
317 begin=end;
318 }
319 }
321 // A normal empty high-altitude sweep commands level, not an invalid
322 // antenna. Keep command validity separate from measured weather.
323 out.tiltValid=in.aboveWeatherCoverage || (beams[bearing].valid && beams[bearing].tiltValid);
324 out.tiltDegrees=out.tiltValid && !in.aboveWeatherCoverage ? beams[bearing].tiltDegrees : 0;
325 out.scanning=!in.aboveWeatherCoverage && count<Bearings;
327 out.sweepDegrees=(std::max)(-HalfSweepDegrees,(std::min)(HalfSweepDegrees,out.sweepDegrees));
328 Beam sweep; sweep.origin=in.position; sweep.rangeKm=in.rangeKm;
329 sweep.left=Direction(in,out.sweepDegrees-.08); sweep.right=Direction(in,out.sweepDegrees+.08);
330 out.sweep=Geometry(sweep,0,Gates,in.radiusKm,0xff508d99);
331 }
332 public:
333 void Reset() { beams={}; running=false; previous={}; clock=pending=sourceAge=0; bearing=0; direction=1; }
334 const std::array<Beam,Bearings>& Beams() const { return beams; }
335 int Bearing() const { return bearing; }
336 int Direction() const { return direction; }
337 template<class Sampler> void Update(Input in,double elapsed,Sampler sample,Display& out)
338 {
339 const bool enabled=in.equipped&&in.power&&!in.simulator;
340 const bool valid=Finite(in.position)&&Finite(in.forward)&&Finite(in.right)&&
341 std::isfinite(in.radiusKm)&&in.radiusKm>0&&Length(in.position)>in.radiusKm*.9&&
342 Length(in.forward)>.9&&Length(in.right)>.9&&std::isfinite(in.rangeKm)&&in.rangeKm>0;
343 if(!enabled || !valid || (!in.dataAvailable && !in.aboveWeatherCoverage) || !std::isfinite(elapsed) || elapsed<0 ||
344 !std::isfinite(in.maxFrameSeconds) || in.maxFrameSeconds<0)
345 { Reset(); out={}; out.enabled=enabled; return; }
346 in.rangeKm=(std::min)(MaxRangeKm,in.rangeKm);
347 const bool changed=running&&(in.vehicle!=previous.vehicle||in.generation!=previous.generation||
349 std::fabs(in.rangeKm-previous.rangeKm)>.001||
350 Length(in.position-previous.position)>(std::max)(1.,in.rangeKm*.25)||
352 // Distinguish a normal multi-frame scheduled turn from an actual
353 // frozen frame. Direct callers retain the original elapsed guard.
354 const double frameGap=in.maxFrameSeconds>0 ? in.maxFrameSeconds : elapsed;
355 if(changed || frameGap>.5) Reset();
356 if(running && !in.aboveWeatherCoverage && in.revision==previous.revision) sourceAge+=elapsed; else sourceAge=0;
358 { beams={}; out={}; out.enabled=true; previous=in; return; }
359 out.enabled=true; out.rangeKm=in.rangeKm;
360 clock+=elapsed;
361 // Outside the modeled weather volume, only advance the antenna.
362 // Do not manufacture valid clear samples or retain old ground/weather returns.
363 if(!running) { running=true; if(!in.aboveWeatherCoverage) Acquire(in,sample); }
364 pending+=frameGap<=.5 ? elapsed : 0;
365 constexpr double interval=TraverseSeconds/(Bearings-1);
366 while(pending+1e-9>=interval)
367 {
368 pending-=interval;
369 if(bearing==Bearings-1) direction=-1;
370 else if(bearing==0) direction=1;
372 if(!in.aboveWeatherCoverage) Acquire(in,sample);
373 }
374 previous=in;
375 Prepare(in,out);
376 }
377 };
378}
SCRIPT_CONTROL SCRIPT_STATE const void int
const std::array< Beam, Bearings > & Beams() const
static Quad Geometry(const Beam &beam, int begin, int end, double radius, uint32_t color)
void AcquireLook(const Input &in, Sampler &sample, Beam &beam, Point ray, Point up, const std::array< Sample, Gates > &profile, double tilt)
void Prepare(const Input &in, Display &out) const
std::array< Beam, Bearings > beams
void Update(Input in, double elapsed, Sampler sample, Display &out)
static Point Direction(const Input &in, double degrees)
void Acquire(const Input &in, Sampler &sample)
weather(Viewscreen *ptr)
Definition weather.cpp:11
Point Cross(Point a, Point b)
constexpr double TraverseSeconds
constexpr double ShadowTransmission
constexpr double MaxTiltDegrees
constexpr double Pi
constexpr double AutoTiltRangeFraction
constexpr int Bearings
double Length(Point a)
Echo MergeEcho(Echo a, Echo b)
constexpr std::array< double, 9 > ElevationDegrees
Echo Classify(double level)
double PathExtinctionPerKm(double level)
constexpr double WeatherExtinctionPerKm
constexpr int CenterRay
bool ValidSample(const Sample &cell)
double Dot(Point a, Point b)
uint32_t Color(Echo echo)
constexpr double WeatherBeamDegrees
constexpr double HalfSweepDegrees
constexpr double RangeExtinctionPerKm
Point Unit(Point a)
constexpr double GroundHalfBeamDegrees
constexpr double MaxRangeKm
constexpr double MemorySeconds
bool AboveWeatherCoverage(double mslKm, bool feedSuspended, double topKm, double resumeKm)
double AntennaIntegral(double lowDegrees, double highDegrees)
void MapFrame(Point position, double headingDegrees, Point &forward, Point &right)
double GroundLevel(double illuminatedFraction, double gateKm, double waterFraction)
constexpr double SourceTimeoutSeconds
std::array< Echo, Gates > echoes
std::array< Echo, Gates > groundEchoes