Rise
The Vieneo Province
Loading...
Searching...
No Matches
TerrainAwareness.cpp
Go to the documentation of this file.
1#include "Module.h"
6
7namespace
8{
9 float GeometricHeight(RiseMath::Vector3 p)
10 {
11 return float(std::sqrt(double(p.x)*p.x + double(p.y)*p.y + double(p.z)*p.z)-double(radiusC));
12 }
13 bool ValidVertex(const LOCALGRID2& vertex)
14 {
15 return vertex.elevationAvailable && vertex.pri_landform != 255 &&
16 TerrainAwareness::Finite({vertex.position.x,vertex.position.y,vertex.position.z}) &&
18 }
19}
20
22{
23 if (terrainVehicle != playerships[0].vehicleId) terrainStability.Reset();
24 ScanTerrainAwareness(seconds);
25 const auto& state = bus->GPWS.terrain;
27 state.enabled && state.predictionEnabled && !state.onGround && terrainTrackValid &&
29}
30
31void Gpws::ScanTerrainAwareness(float seconds)
32{
33 using namespace TerrainAwareness;
34 auto& state = bus->GPWS.terrain;
35 const auto& ship = playerships[0];
36 const bool airborne = ship.reference == REF_APNMODE || ship.reference == REF_ACLMODE;
37 if (!viewscreen || !bus->GPWS.positionValid || !DisplayAllowed(ship.isSimulator,ship.groundvehicle,ourcockpit.power) ||
38 !std::isfinite(seconds) || seconds <= 0 ||
39 !std::isfinite(ship.mslKm) || ship.mslKm == -1 ||
40 !Finite({ship.position.x,ship.position.y,ship.position.z}))
41 {
42 state.Clear(); terrainTrackValid = false;
43 return;
44 }
45 if (terrainVehicle != ship.vehicleId)
46 {
47 state.Clear(); terrainTrackValid = false;
48 terrainVehicle = ship.vehicleId; terrainDataRevision = 0;
51 }
52 // Re-evaluate the entire 60-second vertical path on each module turn, even while
53 // suspended or waiting for terrain. Fast descents re-arm well above peaks.
54 const bool predictionEnabled = NeedsPrediction(ship.mslKm,bus->VerticalSpeedKms,state.predictionEnabled);
55 // Peaks terrain remains available above the alerting suspension altitude.
56 // No forward corridor is built while suspended; known data can still draw.
58 {
59 if (!predictionEnabled) { state.Clear(); terrainTrackValid = false; return; }
60 state.Clear(); state.enabled = true; state.predictionEnabled = predictionEnabled;
61 state.altitudeKm = ship.mslKm; state.verticalKms = bus->VerticalSpeedKms;
62 state.gearDown = ship.geardown;
63 state.onGround = !airborne;
65 return;
66 }
67 const auto revision = viewscreen->ptrGrid->ElevationRevision();
68 const bool dataChanged = revision != terrainDataRevision;
69 // The shared dispatcher owns cadence; one scan per scheduled GPWS turn.
70 Rendering::ProfileCpuScope11 terrainTiming("GPWS terrain scan");
71 const float elapsed = seconds;
72 if (dataChanged)
73 {
74 // CPU elevation data owns validity; geometryReady only describes the
75 // graphics buffer. Rebuild cached subdivisions from the received data
76 // before sampling, including updates that arrive between GPU rebuilds.
77 for (short u = 16; u < 48; ++u) for (short v = 16; v < 48; ++v)
79 terrainDataRevision = revision;
80 }
81 state.Clear(); state.enabled = true; state.predictionEnabled = predictionEnabled;
82 state.altitudeKm = ship.mslKm;
83 state.verticalKms = bus->VerticalSpeedKms;
84 state.gearDown = ship.geardown;
85 state.onGround = !airborne;
86 if (!airborne) state.verticalKms = 0;
87 // Airport ground decluttering must not remove the higher departure terrain.
88 state.displayRunwayKm = airborne ? -100.f : ship.mslKm;
89 float nearestRunwayKm = MaxRangeKm;
90 for (const auto& runway : bus->waypoint)
91 {
92 if (runway.type != 2 || runway.heading < 0 || runway.heading > 360 ||
93 !std::isfinite(runway.length) || runway.length <= 0 || !std::isfinite(runway.elevationKm)) continue;
94 const auto delta = runway.location-ship.position;
95 const float range = RiseMath::Vec3Length(&delta);
96 if (std::isfinite(range) && range < nearestRunwayKm)
97 {
98 nearestRunwayKm = range;
99 state.displayRunwayKm = runway.elevationKm;
100 }
101 }
102 if (!std::isfinite(state.verticalKms)) { state.Clear(); terrainTrackValid = false; return; }
103
104 RiseMath::Vector3 up, forward, right;
105 RiseMath::Vec3Normalize(&up,&ship.position);
106 // velocity and barycentric use the same world sign; subtract rotation of
107 // Vieneo before removing the radial component. Heading is not ground track.
108 forward = ship.velocity-ship.barycentric;
109 forward -= up*RiseMath::Vec3Dot(&forward,&up);
110 const float speed = RiseMath::Vec3Length(&forward);
111 if (!std::isfinite(speed)) { state.Clear(); terrainTrackValid = false; return; }
112 if (speed >= .001f) forward /= speed;
113 else
114 {
115 // Retain the relative-height display in a hover. Reactive GPWS handles
116 // descent directly below; the predictor does not invent forward travel.
118 if (RiseMath::Vec3LengthSq(&forward) < .001f)
119 {
120 const RiseMath::Vector3 axis = std::fabs(up.z) < .9f ? RiseMath::Vector3(0,0,1) : RiseMath::Vector3(1,0,0);
121 RiseMath::Vec3Cross(&forward,&up,&axis);
122 }
123 RiseMath::Vec3Normalize(&forward,&forward); terrainTrackValid = false;
124 }
125 RiseMath::Vec3Cross(&right,&forward,&up);
126 RiseMath::Vec3Normalize(&right,&right);
127 const auto project = [&](RiseMath::Vector3 renderPosition) {
128 const RiseMath::Vector3 delta = -renderPosition-ship.position;
129 return Point{RiseMath::Vec3Dot(&delta,&right),RiseMath::Vec3Dot(&delta,&forward),GeometricHeight(renderPosition)};
130 };
131 Flight flight;
132 flight.altitudeKm = state.altitudeKm; flight.speedKms = airborne && predictionEnabled && !bus->GPWS.inhibited ? speed : 0; flight.verticalKms = state.verticalKms;
133 if (speed >= .154333f) flight.warningSeconds = (std::max)(WarningSeconds,(std::min)(60.f,14.816f/speed));
134 flight.radiusKm = (std::clamp)(ship.bound,0.f,.1f);
135 if (terrainTrackValid && elapsed < 1)
136 {
137 RiseMath::Vector3 cross;
138 RiseMath::Vec3Cross(&cross,&forward,&oldTerrainForward);
139 flight.turnRadiansPerSecond = std::atan2(RiseMath::Vec3Dot(&cross,&up),
140 RiseMath::Vec3Dot(&forward,&oldTerrainForward))/elapsed;
141 }
142 oldTerrainForward = forward; terrainTrackValid = speed >= .001f;
143 // Low-altitude takeoff and landing use a rising clearance floor. This is
144 // deliberately a Rise approximation, not Honeywell's proprietary ribbon.
145 if ((ship.geardown || flight.verticalKms > .001f) && std::isfinite(bus->RadioAltitudeKm))
146 flight.clearanceKm = (std::clamp)(bus->RadioAltitudeKm*.5f,.005f,ClearanceKm);
147 if (airborne && std::fabs(flight.turnRadiansPerSecond) < .0174533f &&
148 flight.verticalKms <= .001f && flight.verticalKms >= -.02f &&
149 !bus->waypoint.empty())
150 {
151 float bestApproachRange = FLT_MAX;
152 for (size_t targetIndex = 0; targetIndex < bus->waypoint.size(); ++targetIndex)
153 {
154 const auto& target = bus->waypoint[targetIndex];
155 const bool selected = targetIndex == size_t(bus->WPtargetC);
156 const Point site = project(-target.location);
157 // Recognize the selected runway geometrically, including hand-flown
158 // approaches. LOC/G/S capture alone is not permission to ignore hazards.
159 // Reuse the client's 42.6 km guidance range, 3-degree path and Mode 5
160 // 1.3-dot low-path boundary. These are instrument conventions, not a
161 // Vieneo aerodynamic escape model or proprietary Honeywell coefficients.
162 const float height = flight.altitudeKm-site.z;
163 const bool runway = target.heading >= 0 && target.heading <= 360 &&
164 std::isfinite(target.length) && target.length > 0;
165 const float courseError = std::remainder(bus->HeadingTrackDegrees-target.heading,360.f);
166 const bool alignedRunway = runway && Finite(site) &&
167 std::isfinite(bus->HeadingTrackDegrees) && bus->HeadingTrackDegrees >= 0 &&
168 std::fabs(courseError) < 3.f && std::fabs(site.x) < (std::max)(.1f,site.y*.052408f);
169 const bool inbound = alignedRunway && site.y > 0 && site.y < 42.6f &&
170 height >= site.y*std::tan(RiseMath::ToRadian(3.f-1.3f*.35f))-.003f &&
171 height <= (std::max)(ClearanceKm,site.y*std::tan(RiseMath::ToRadian(3.f+2.f*.35f))+.003f) &&
172 // Allow bounded glidepath corrections, not a dive at a selected runway.
173 flight.verticalKms >= -1.5f*height*speed/site.y;
174 const bool overRunway = alignedRunway && ship.geardown && site.y <= 0 &&
175 site.y+(std::min)(target.length,MaxRangeKm) > 0 && height >= -.003f && height < ClearanceKm;
176 const bool runwayApproach = inbound || overRunway;
177 const bool padApproach = selected && ourcockpit.dntranslimit > 0 && !runway && std::isfinite(target.length) && ship.geardown && Finite(site) && site.y > 0 && site.y < 5 &&
178 std::fabs(site.x) < (std::max)(.1f,site.y*.2f) && height >= -.003f && height < .6f;
179 if (target.type == 2 && (runwayApproach || padApproach) && std::fabs(site.y) < bestApproachRange)
180 {
181 flight.landing = true; flight.landingSite = site;
182 flight.landingLengthKm = (std::clamp)(target.length,0.f,runwayApproach ? MaxRangeKm : 5.f);
183 flight.runwayApproach = runwayApproach;
184 bestApproachRange = std::fabs(site.y);
185 }
186 }
187 }
188 state.runwayApproach = flight.runwayApproach;
189 Predictor predictor(flight);
190 state.obstaclesComplete = true;
191 constexpr int fineTriangles[8][3] = {{0,1,3},{1,4,3},{1,2,4},{2,5,4},
192 {3,4,6},{4,7,6},{4,5,7},{5,8,7}};
193 constexpr int coarseTriangles[2][3] = {{0,2,6},{2,8,6}};
194 struct FootprintBounds
195 {
196 float lowX = FLT_MAX, highX = -FLT_MAX, lowY = FLT_MAX, highY = -FLT_MAX;
197 void Include(Point p)
198 {
199 lowX = (std::min)(lowX,p.x); highX = (std::max)(highX,p.x);
200 lowY = (std::min)(lowY,p.y); highY = (std::max)(highY,p.y);
201 }
202 bool Contains(Point p) const
203 { return p.x >= lowX && p.x <= highX && p.y >= lowY && p.y <= highY; }
204 };
205 struct CellGeometry : FootprintBounds
206 {
207 std::array<Point,9> points;
208 bool fine = false;
209 };
210 std::vector<CellGeometry> geometry(GridSize*GridSize);
211 std::array<FootprintBounds,GridSize> rowBounds;
212 for (int u = 0; u < GridSize; ++u) for (int v = 0; v < GridSize; ++v)
213 {
214 auto& cell = state.cells[u*GridSize+v];
215 const auto& source = gridarray[u][v];
216 cell.u = source.tcp.u; cell.v = source.tcp.v;
217 if (!ValidVertex(source) ||
218 !ValidVertex(gridarray[u+1][v]) || !ValidVertex(gridarray[u][v+1]) ||
219 !ValidVertex(gridarray[u+1][v+1])) continue;
220 const bool fine = u >= 16 && u < 47 && v >= 16 && v < 47;
221 // Same two coarse triangles and eight fine triangles as grid::Process,
222 // including the linear seam vertices joining the two resolutions.
223 const auto a = source.position, b = gridarray[u+1][v].position;
224 const auto c = gridarray[u][v+1].position, d = gridarray[u+1][v+1].position;
225 RiseMath::Vector3 vertices[] = {a,(a+b)*.5f,b,(a+c)*.5f,(a+d)*.5f,(b+d)*.5f,c,(c+d)*.5f,d};
226 if (fine)
227 {
228 // Missing interpolation support is genuinely unknown, even if the
229 // four main corners have arrived. Never sample zero/stale support.
230 if (!ValidVertex(gridarray[u-1][v]) || !ValidVertex(gridarray[u][v-1]) ||
231 !ValidVertex(gridarray[u-1][v-1]) || !ValidVertex(gridarray[u+1][v-1]) ||
232 !ValidVertex(gridarray[u-1][v+1])) continue;
233 if (v != 16) vertices[1] = insidearray[u][v][0];
234 if (u != 16) vertices[3] = insidearray[u][v][1];
235 if (u != 16 && u != 46 && v != 16 && v != 46) vertices[4] = insidearray[u][v][2];
236 if (u != 46) vertices[5] = insidearray[u+1][v][1];
237 if (v != 46) vertices[7] = insidearray[u][v+1][0];
238 }
239 Point points[9]; bool valid = true;
240 for (int i = 0; i < 9; ++i)
241 {
242 points[i] = project(vertices[i]);
243 valid &= Finite(points[i]) && RiseMath::Vec3LengthSq(&vertices[i]) > 1;
244 }
245 if (!valid) continue;
246 auto& shape = geometry[u*GridSize+v];
247 shape.fine = fine;
248 std::copy(std::begin(points),std::end(points),shape.points.begin());
249 for (auto p : points)
250 {
251 shape.Include(p);
252 rowBounds[u].Include(p);
253 }
254 cell.valid = true; cell.topKm = points[0].z;
255 for (auto p : points) cell.topKm = (std::max)(cell.topKm,p.z);
256 cell.obstaclesKnown = !(source.type > PlotType::NotZoned && source.type < PlotType::PlotTypeEnum && source.buildzoneOrdinal < 0);
257 for (int i = 0; i < (fine ? 8 : 2); ++i)
258 {
259 const auto& indices = fine ? fineTriangles[i] : coarseTriangles[i];
260 Point triangle[] = {points[indices[0]],points[indices[1]],points[indices[2]]};
261 cell.severity = Max(cell.severity,predictor.Scan(triangle,false,true,&state.terrainTime));
262 if (!cell.obstaclesKnown && predictor.Intersects(triangle)) state.obstaclesComplete = false;
263 }
264 state.terrain = Max(state.terrain,cell.severity);
265 }
266 state.terrainComplete = !airborne || !predictionEnabled || speed < .001f ? state.cells[31*GridSize+31].valid : predictor.Covered();
267 Rendering::ProfileCpuScope11 obstacleTiming("GPWS obstacle classification");
269 else if (bus->GPWS.obstaclesEnabled) state.obstaclesComplete = false;
270 if (!bus->GPWS.obstaclesEnabled) state.obstaclesComplete = true;
271 // Project every component's bounds, retaining its full horizontal footprint.
272 // The convex hull's top is conservative; it cannot miss a narrow tower.
273 std::vector<Obstacle> elevatedObstacles;
274 elevatedObstacles.reserve(state.obstacles.size());
275 for (auto& obstacle : state.obstacles)
276 {
277 std::array<Point,8> points;
278 for (size_t i = 0; i < points.size(); ++i)
279 {
280 const auto p = obstacle.corners[i];
281 points[i] = project({p.x,p.y,p.z});
282 }
283 if (std::any_of(points.begin(),points.end(),[](Point p) { return !Finite(p); })) continue;
284 // The maximum comes from actual emitted mesh vertices. Taking radial
285 // height from a world-axis AABB corner invents tall obstacles on slopes.
286 std::sort(points.begin(),points.end(),[](Point a, Point b) { return a.x == b.x ? a.y < b.y : a.x < b.x; });
287 std::vector<Point> hull;
288 hull.reserve(16);
289 for (auto p : points)
290 {
291 while (hull.size() > 1 && Cross(hull[hull.size()-2],hull.back(),p) <= 0) hull.pop_back();
292 hull.push_back(p);
293 }
294 const auto lower = hull.size();
295 for (int i = int(points.size())-2; i >= 0; --i)
296 {
297 const auto p = points[i];
298 while (hull.size() > lower && Cross(hull[hull.size()-2],hull.back(),p) <= 0) hull.pop_back();
299 hull.push_back(p);
300 }
301 if (hull.size() > 1) hull.pop_back();
302 Point center{};
303 for (auto p : points) { center.x += p.x/8; center.y += p.y/8; }
304 bool surfaceOnly = false;
305 for (int u = 0; u < GridSize && !surfaceOnly; ++u)
306 {
307 // A component can only rest on a cell whose footprint contains its
308 // center. Reject whole rows by their union bounds before searching
309 // cells; this preserves the exact triangle check and scan order.
310 if (!rowBounds[u].Contains(center)) continue;
311 for (int v = 0; v < GridSize && !surfaceOnly; ++v)
312 {
313 if (!state.cells[u*GridSize+v].valid) continue;
314 // Reject flat pavement/foundations using the same terrain triangles.
315 const auto& shape = geometry[u*GridSize+v];
316 if (!shape.Contains(center)) continue;
317 for (int i = 0; i < (shape.fine ? 8 : 2); ++i)
318 {
319 const auto& indices = shape.fine ? fineTriangles[i] : coarseTriangles[i];
320 const Point a = shape.points[indices[0]], b = shape.points[indices[1]], c = shape.points[indices[2]];
321 const float area = Cross(a,b,c);
322 if (std::fabs(area) < 1e-10f) continue;
323 const float wa = Cross(center,b,c)/area, wb = Cross(a,center,c)/area, wc = 1-wa-wb;
324 if (wa >= -.0001f && wb >= -.0001f && wc >= -.0001f &&
325 obstacle.topKm <= wa*a.z+wb*b.z+wc*c.z+.003f) surfaceOnly = true;
326 }
327 }
328 }
329 if (surfaceOnly) continue;
330 for (auto& p : hull) p.z = obstacle.topKm;
331 for (size_t i = 1; i+1 < hull.size(); ++i)
332 {
333 Point triangle[] = {hull[0],hull[i],hull[i+1]};
334 obstacle.severity = Max(obstacle.severity,predictor.Scan(triangle,true,false,&state.obstacleTime));
335 }
336 state.obstacle = Max(state.obstacle,obstacle.severity);
337 elevatedObstacles.push_back(obstacle);
338 }
339 state.obstacles.swap(elevatedObstacles);
340}
@ PlotTypeEnum
@ NotZoned
@ REF_ACLMODE
Definition ServerTypes.h:44
@ REF_APNMODE
Definition ServerTypes.h:42
float HeadingTrackDegrees
Definition Bus.h:303
struct Bus::Gpws GPWS
std::vector< Swaypoint > waypoint
Definition Bus.h:500
float RadioAltitudeKm
Definition Bus.h:157
int WPtargetC
Definition Bus.h:499
float VerticalSpeedKms
Definition Bus.h:451
uint64_t terrainDataRevision
Definition Module.h:49
void UpdateTerrainAwareness(float seconds)
bool terrainTrackValid
Definition Module.h:47
Viewscreen * viewscreen
Definition Module.h:45
float terrainVoiceSeconds
Definition Module.h:50
RiseMath::Vector3 oldTerrainForward
Definition Module.h:46
TerrainAwareness::AlertStability terrainStability
Definition Module.h:54
void ScanTerrainAwareness(float seconds)
Bus::Gpws::GpwsEnum lastTerrainVoice
Definition Module.h:51
int terrainVehicle
Definition Module.h:48
Bus * bus
Definition Module.h:21
void Update(State &state, float seconds, bool active)
Severity Scan(const Point(&triangle)[3], bool obstacle, bool coverage=false, float *firstThreatTime=nullptr)
bool Intersects(const Point(&triangle)[3]) const
std::unique_ptr< grid > ptrGrid
Definition Viewscreen.h:426
std::unique_ptr< buildings > ptrBuildings
Definition Viewscreen.h:428
RiseMath::Vector3 forwardVector
Definition Viewscreen.h:363
void CollectTerrainObstacles(std::vector< TerrainAwareness::Obstacle > &result) const
uint64_t ElevationRevision() const
Definition grid.h:54
bool dataReady
Definition grid.h:36
void CalculateInsideArray(short t, short s) const
Definition grid.cpp:1230
char area[3]
Definition globals.cpp:87
s_network_objects playerships[MAX_SCAN]
Definition globals.cpp:112
RiseMath::Vector3 insidearray[63][63][3]
Definition globals.cpp:102
Scockpit ourcockpit
Definition globals.cpp:114
LOCALGRID2 gridarray[64][64]
Definition globals.cpp:100
#define radiusC
Definition globals.h:87
auto ToRadian(T value)
Definition ClientMath.h:13
float Vec3Length(const Vector3 *a)
Definition ClientMath.h:95
Vector3 * Vec3Cross(Vector3 *out, const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:105
float Vec3LengthSq(const Vector3 *a)
Definition ClientMath.h:94
float Vec3Dot(const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:93
Vector3 * Vec3Normalize(Vector3 *out, const Vector3 *a)
Definition ClientMath.h:103
constexpr float WarningSeconds
constexpr int GridSize
Severity Max(Severity a, Severity b)
float Cross(Point a, Point b, Point c)
bool NeedsPrediction(float altitudeKm, float verticalKms, bool active)
constexpr float ClearanceKm
constexpr float MaxRangeKm
bool DisplayAllowed(bool simulator, bool groundVehicle, float power)
bool Finite(Point p)
bool inhibited
Definition Bus.h:250
bool positionValid
Definition Bus.h:253
unsigned terrainRevision
Definition Bus.h:276
@ NoAlert
Definition Bus.h:190
int testLevel
Definition Bus.h:260
TerrainAwareness::State terrain
Definition Bus.h:264
bool obstaclesEnabled
Definition Bus.h:252
unsigned char pri_landform
Definition globals.h:278
RiseMath::Vector3 position
Definition globals.h:273
VECTOR2SHORT tcp
Definition globals.h:290
bool elevationAvailable
Definition globals.h:291
float dntranslimit
Definition globals.h:601
float power
Definition globals.h:599