Rise
The Vieneo Province
Loading...
Searching...
No Matches
LandingLights.h
Go to the documentation of this file.
1#pragma once
3#include "BeamProfile.h"
4#include <array>
5#include <cstdint>
6#include <limits>
7
8namespace LandingLights
9{
10 inline constexpr unsigned MaxLights = 2;
11 // Slot 2 belongs to cockpit radiosity.
12 inline constexpr unsigned DeviceSlots[MaxLights] = {1, 3};
13 inline const char* BodySide(float x)
14 {
15 // The forward projection is rolled by pi: +X is the driver's left.
16 return x > 0 ? "left" : x < 0 ? "right" : "center";
17 }
18 // Below half health the contact becomes intermittent. When conducting it
19 // retains half brightness; deterioration reduces the time spent lit.
20 // Absolute transition times keep flicker independent of render frame rate.
21 struct Condition
22 {
23 int previousHealth = -128;
24 uint32_t random = 1, seed = 0;
25 bool conducting = true, simulatorTiming = false;
26 double nextTransition = 0, lastTime = 0;
27 double meanOn = 0, meanOff = 0;
28
29 double Duration()
30 {
32 const double jitter = .5 + double(random) / 4294967296.0;
33 return (conducting ? meanOn : meanOff) * jitter;
34 }
35 float Sample(int health, double seconds, uint32_t lampSeed, bool simulator = false)
36 {
37 health = (std::clamp)(health, -1, 127);
38 if (!std::isfinite(seconds)) return 0;
39 if (health != previousHealth || seed != lampSeed || seconds < lastTime || simulator != simulatorTiming)
40 {
41 previousHealth = health; seed = lampSeed;
42 simulatorTiming = simulator;
43 random = lampSeed ? lampSeed : 1;
44 conducting = health >= 32;
45 if (health > 0 && health < 63)
46 {
47 // Visible electrical intermittence: 62 is on ~3 s / off
48 // ~0.2 s; 1 reverses those times. Artistic timing, not a
49 // measured bulb failure rate or atmospheric correction.
50 // Simulator training retains its original long intervals.
51 meanOn = .2 * std::pow(simulator ? 900.0 : 15.0, (health - 1) / 61.0);
52 meanOff = (simulator ? 36.0 : .6) / meanOn;
53 nextTransition = seconds + Duration();
54 }
55 }
56 lastTime = seconds;
57 if (health <= 0) return 0;
58 if (health >= 63) return .5f + (health - 63) / 128.f;
59 unsigned transitions = 0;
60 while (seconds >= nextTransition && transitions++ < 1024)
61 {
64 }
65 // Bound catch-up after a long suspension of the application.
66 if (seconds >= nextTransition) nextTransition = seconds + Duration();
67 return conducting ? .5f : 0.f;
68 }
69 };
70 inline unsigned InstallationMismatch(unsigned modelCount, const char* health)
71 {
72 unsigned mask = 0;
73 for (unsigned i = 0; i < MaxLights; ++i)
74 if ((i < modelCount) != (health[i] >= 0)) mask |= 1u << i;
75 return mask;
76 }
77 // Gameplay tuning, in meters/second: harmless contact below 0.75 m/s;
78 // a direct ~12 m/s strike takes a healthy lamp into intermittent failure,
79 // and ~16.7 m/s can break it. Clearance includes a 15 cm lamp housing margin.
80 // Use impact speed rather than per-frame acceleration to avoid FPS bias.
81 inline int ImpactHealth(int health, float clearanceKm, float closingMps,
82 float damageScale = 1, int damageLimit = 127)
83 {
84 if (health <= 0 || !std::isfinite(clearanceKm) || !std::isfinite(closingMps)
85 || clearanceKm > .00015f || closingMps <= .75f) return health;
86 const float severity = (closingMps - .75f) * (closingMps - .75f) * .5f * damageScale;
87 const int damage = static_cast<int>((std::min)(float(damageLimit), std::ceil(severity)));
88 return (std::max)(0, health - damage);
89 }
91 {
92 double lastContact = -1;
94
95 int Apply(int health, float clearanceKm, float closingMps, double seconds)
96 {
97 if (!std::isfinite(seconds)) return health;
98 // Identical response for both lamps: geometry determines exposure.
99 const int damage = 127 - ImpactHealth(127, clearanceKm, closingMps);
100 if (damage == 0 || health <= 0) return health;
101 if (lastContact < 0 || seconds < lastContact || seconds - lastContact > .5)
102 appliedDamage = 0;
103 lastContact = seconds;
104 // Collision solvers can report the same contact repeatedly (and
105 // through multiple paths). Charge only the strongest shock until
106 // there has been half a second without damaging contact.
107 const int additionalDamage = (std::max)(0, damage - appliedDamage);
108 appliedDamage = (std::max)(appliedDamage, damage);
109 return (std::max)(0, health - additionalDamage);
110 }
111
112 int ApplyFrameDamage(int health, int hullLoss, double seconds)
113 {
114 if (health <= 0 || hullLoss <= 0 || !std::isfinite(seconds) || lastContact < 0 ||
115 seconds < lastContact || seconds - lastContact > .5) return health;
116 // A lamp already struck in this crash is also crushed with its
117 // supporting structure. IIHS documents headlight damage even in
118 // minor collisions: https://www.iihs.org/api/datastoredocument/status-report/pdf/53/8
119 // Two lamp points per hull point is an explicit gameplay proxy,
120 // not an empirical material coefficient. Losing half the frame's
121 // full-scale health destroys the contacted assembly. Do not add
122 // the initial surface strike twice or transfer damage across sides.
123 const int damage = (std::min)(127, (std::min)(127, hullLoss) * 2);
124 const int additionalDamage = (std::max)(0, damage - appliedDamage);
125 appliedDamage = (std::max)(appliedDamage, damage);
126 return (std::max)(0, health - additionalDamage);
127 }
128 };
129 struct Light
130 {
133 RiseMath::Color color{1, 1, .75f, 1};
136 };
137 // Four-lamp meshes share their two vdat circuits with the nearest selected
138 // beam, so the lamp sprites and projected illumination fail together.
139 inline unsigned NearestLamp(const RiseMath::Vector3& origin,
140 const std::array<Light, MaxLights>& lights, unsigned count)
141 {
142 unsigned nearest = 0;
143 float distance = (std::numeric_limits<float>::max)();
144 for (unsigned i = 0; i < count && i < MaxLights; ++i)
145 {
146 const auto delta = origin - lights[i].origin;
147 const float candidate = RiseMath::Vec3LengthSq(&delta);
148 if (candidate < distance) { nearest = i; distance = candidate; }
149 }
150 return nearest;
151 }
152 inline bool Valid(const RiseMath::Vector3& origin, const RiseMath::Vector3& direction)
153 {
154 const float length = RiseMath::Vec3LengthSq(&direction);
155 return std::isfinite(origin.x) && std::isfinite(origin.y) && std::isfinite(origin.z)
156 && std::isfinite(length) && length > 1e-12f;
157 }
158 // Model-space definitions; the exterior model matrix supplies both the
159 // model's authored axis conversion and the vehicle's current attitude.
160 template<class Effects>
161 unsigned FromModel(const Effects& effects, std::array<Light, MaxLights>& lights)
162 {
163 lights = {};
164 int first = -1, second = -1;
165 float separation = -1;
166 for (int i = 0; i < static_cast<int>(effects.size()); ++i)
167 {
168 const auto& a = effects[i];
169 if (a.power != 2.f || !Valid(a.position, a.normal)) continue;
170 if (first < 0) first = i;
171 for (int j = i + 1; j < static_cast<int>(effects.size()); ++j)
172 {
173 const auto& b = effects[j];
174 if (b.power != 2.f || !Valid(b.position, b.normal)) continue;
175 const auto delta = a.position - b.position;
176 const float distance = RiseMath::Vec3LengthSq(&delta);
177 // Four-lamp models retain a beam on each side, rather than
178 // taking the first two records, which can be on the same side.
179 if (distance > separation) { first = i; second = j; separation = distance; }
180 }
181 }
182 unsigned count = 0;
183 for (const int index : {first, second})
184 {
185 if (index < 0) continue;
186 const auto& effect = effects[index];
187 auto& light = lights[count++];
188 light.origin = effect.position;
189 RiseMath::Vec3Normalize(&light.direction, &effect.normal);
190 light.color = effect.diffuse;
191 }
192 return count;
193 }
194 inline Light Transform(const Light& source, const RiseMath::Matrix& modelToWorld)
195 {
196 Light light = source;
197 RiseMath::Vec3TransformCoord(&light.origin, &source.origin, &modelToWorld);
198 RiseMath::Vec3TransformNormal(&light.direction, &source.direction, &modelToWorld);
200 RiseMath::Vec3TransformNormal(&light.up, &source.up, &modelToWorld);
201 light.up = OrthonormalUp(light.up, light.direction);
202 return light;
203 }
204 inline std::array<RiseMath::Vector4, MaxLights> EmissionSources(
205 const std::array<Light, MaxLights>& lights, unsigned count,
206 const std::array<float, MaxLights>& brightness, const RiseMath::Matrix& modelToWorld)
207 {
208 std::array<RiseMath::Vector4, MaxLights> sources{};
209 for (unsigned i = 0; i < count && i < MaxLights; ++i)
210 {
211 RiseMath::Vector3 origin;
212 RiseMath::Vec3TransformCoord(&origin, &lights[i].origin, &modelToWorld);
213 // Keep dead emitters in their authored slots so their lens pixels
214 // cannot borrow the surviving lamp's light after beam compaction.
215 sources[i] = {origin.x, origin.y, origin.z, brightness[i]};
216 }
217 return sources;
218 }
219 inline constexpr unsigned FogSegments = 24, FogRings = 8;
220 inline constexpr unsigned FogVertexCount = FogSegments * FogRings * 6;
221 // Fog fallback only; cloud volumes use the full angular scattering shader.
222 template<class Vertex> void FogMesh(const Light& light, Vertex* output, bool spill)
223 {
224 const auto angles = light.profile.Angles<RiseMath::Vector4>();
225 const float horizontal = spill ? angles.z : angles.x;
226 const float vertical = spill ? angles.w : angles.y;
227 const float weight = spill ? light.profile.spill : 1-light.profile.spill;
228 static const auto circle = [] {
229 std::array<RiseMath::Vector2,FogSegments+1> values{};
230 for (unsigned i=0;i<=FogSegments;++i)
231 {
232 const float angle=RiseMath::Tau*i/FogSegments;
233 values[i]={std::sin(angle),std::cos(angle)};
234 }
235 return values;
236 }();
237 for (unsigned ring=0;ring<FogRings;++ring)
238 {
239 const float a=float(ring)/FogRings, b=float(ring+1)/FogRings;
240 const float nearDistance=.001f+(light.profile.rangeKm-.001f)*a*a;
241 const float farDistance=.001f+(light.profile.rangeKm-.001f)*b*b;
242 uint32_t colors[2]{};
243 for (unsigned end=0;end<2;++end)
244 {
245 const float distance=end ? farDistance : nearDistance;
246 colors[end]=RiseMath::Color(1,1,1,weight*RiseMath::Min(1.f,IlluminanceLux(light.profile,distance)/20)
247 *std::exp(-light.extinctionPerKm*distance));
248 }
249 for (unsigned segment=0;segment<FogSegments;++segment)
250 {
251 Vertex corners[4]{};
252 for (unsigned corner=0;corner<4;++corner)
253 {
254 const float distance=corner<2 ? nearDistance : farDistance;
255 const auto point=circle[segment+(corner%2)];
256 auto& vertex=corners[corner];
257 vertex.x=point.x*horizontal*distance;
258 vertex.y=RiseMath::Min(point.y*vertical,light.profile.cutoffSlope)*distance;
259 vertex.z=-distance;
260 vertex.diffuse=colors[corner/2];
261 }
262 for (unsigned corner : {0u,1u,2u,1u,3u,2u}) *output++=corners[corner];
263 }
264 }
265 }
266 inline float Intensity(const Light& light, const RiseMath::Vector3& delta)
267 {
268 const float axial = RiseMath::Vec3Dot(&delta, &light.direction);
269 if (axial <= 0) return 0;
270 RiseMath::Vector3 right;
271 RiseMath::Vec3Cross(&right, &light.direction, &light.up);
272 const float distance = RiseMath::Vec3Length(&delta);
273 return Angular(light.profile, RiseMath::Vec3Dot(&delta, &right)/axial,
274 RiseMath::Vec3Dot(&delta, &light.up)/axial, axial)
275 * RiseMath::Min(4.f, IlluminanceLux(light.profile, distance)/20)
276 * std::exp(-light.extinctionPerKm*distance);
277 }
278}
unsigned FromModel(const Effects &effects, std::array< Light, MaxLights > &lights)
constexpr unsigned MaxLights
bool Valid(const RiseMath::Vector3 &origin, const RiseMath::Vector3 &direction)
unsigned InstallationMismatch(unsigned modelCount, const char *health)
float IlluminanceLux(const Profile &profile, float distanceKm)
Definition BeamProfile.h:81
int ImpactHealth(int health, float clearanceKm, float closingMps, float damageScale=1, int damageLimit=127)
float Intensity(const Light &light, const RiseMath::Vector3 &delta)
constexpr unsigned FogVertexCount
Vector OrthonormalUp(Vector up, const Vector &direction)
Definition BeamProfile.h:43
std::array< RiseMath::Vector4, MaxLights > EmissionSources(const std::array< Light, MaxLights > &lights, unsigned count, const std::array< float, MaxLights > &brightness, const RiseMath::Matrix &modelToWorld)
constexpr unsigned FogRings
constexpr unsigned DeviceSlots[MaxLights]
constexpr unsigned FogSegments
float Angular(const Profile &profile, float horizontalSlope, float verticalSlope, float axialDistanceKm)
Definition BeamProfile.h:66
void FogMesh(const Light &light, Vertex *output, bool spill)
const char * BodySide(float x)
unsigned NearestLamp(const RiseMath::Vector3 &origin, const std::array< Light, MaxLights > &lights, unsigned count)
Light Transform(const Light &source, const RiseMath::Matrix &modelToWorld)
float Vec3Length(const Vector3 *a)
Definition ClientMath.h:95
Vector3 * Vec3Cross(Vector3 *out, const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:105
constexpr auto Min(A first, B second)
Definition ClientMath.h:15
Vector3 * Vec3TransformCoord(Vector3 *out, const Vector3 *a, const Matrix *m)
Definition ClientMath.h:109
float Vec3LengthSq(const Vector3 *a)
Definition ClientMath.h:94
Vector3 * Vec3TransformNormal(Vector3 *out, const Vector3 *a, const Matrix *m)
Definition ClientMath.h:107
constexpr float Tau
Definition ClientMath.h:12
float Vec3Dot(const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:93
Vector3 * Vec3Normalize(Vector3 *out, const Vector3 *a)
Definition ClientMath.h:103
float Sample(int health, double seconds, uint32_t lampSeed, bool simulator=false)
int Apply(int health, float clearanceKm, float closingMps, double seconds)
int ApplyFrameDamage(int health, int hullLoss, double seconds)
RiseMath::Vector3 origin
RiseMath::Vector3 up
RiseMath::Vector3 direction
RiseMath::Color color
PackedVector Angles() const
Definition BeamProfile.h:18