Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/CloudLightningDiagnosticTests.h

Source at documentation-generation time. See Test catalog for fixture associations.

1#pragma once
2#include <limits>
3
4namespace CloudLightningDiagnosticFixture
5{
8 using DiagnosticClock=CloudLightning::Diagnostic;
9 // Existing geometry/envelope fixtures advance an injected monotonic clock,
10 // rather than depending on CPU test execution speed or production deltas.
11 struct Diagnostic : DiagnosticClock
12 {
13 double fixtureNow=0;
14 void Start(){fixtureNow=0;StartAt(fixtureNow);}
15 void Update(const Parameters& params,double elapsed,uint32_t cloudSeed,const Point& observer)
16 {fixtureNow+=elapsed;UpdateAt(params,fixtureNow,cloudSeed,observer);}
17 };
19
20 inline bool SamePoint(const Point& a,const Point& b)
21 {return a.x==b.x && a.y==b.y && a.z==b.z;}
22
23 inline bool SameVector(const LightningChain::Vector3& a,const LightningChain::Vector3& b)
24 {return a.x==b.x && a.y==b.y && a.z==b.z;}
25
26 inline bool SameFlash(const Flash& a,const Flash& b)
27 {
28 if(!SamePoint(a.position,b.position) || !SamePoint(a.axis,b.axis) || a.width!=b.width
29 || a.radius!=b.radius || a.energy!=b.energy)return false;
30 const auto& x=a.animation;const auto& y=b.animation;
31 if(x.inuse!=y.inuse || x.seed!=y.seed || x.age!=y.age || x.strokeCount!=y.strokeCount
32 || x.flashBrightness!=y.flashBrightness || x.growth!=y.growth
33 || x.growthSeconds!=y.growthSeconds || x.tailSeconds!=y.tailSeconds
34 || x.sequenceAge!=y.sequenceAge || x.boltDuration!=y.boltDuration || x.activeSegment!=y.activeSegment
35 || x.path.count!=y.path.count || !SameVector(x.cloudpos,y.cloudpos) || !SameVector(x.groundpos,y.groundpos))return false;
36 for(size_t i=0;i<x.path.segments.size();++i)
37 {
38 const auto& p=x.path.segments[i];const auto& q=y.path.segments[i];
39 if(!SameVector(p.start,q.start) || !SameVector(p.end,q.end) || p.seed!=q.seed
40 || p.begin!=q.begin || p.finish!=q.finish || p.groundContact!=q.groundContact)return false;
41 }
42 for(size_t i=0;i<x.strokes.size();++i)
43 {
44 const auto& p=x.strokes[i];const auto& q=y.strokes[i];
45 if(p.start!=q.start || p.attack!=q.attack || p.hold!=q.hold
46 || p.decay!=q.decay || p.peak!=q.peak)return false;
47 }
48 return true;
49 }
50
51 inline void CheckCleared(const DiagnosticClock& diagnostic)
52 {
53 Check(!diagnostic.Active(),"cloud diagnostic remained armed after stop");
54 for(const auto& flash:diagnostic.Events())
55 Check(!flash.animation.inuse && flash.Brightness()==0 && flash.energy==0,
56 "stopped cloud diagnostic retained active illumination");
57 }
58
59 inline Point Observer(Point normal,float altitude,const Parameters& params)
60 {return CloudVolume::Scale(normal,(params.radius+altitude)/CloudVolume::Length(normal));}
61
62 inline double SurfaceDistance(Point a,Point b,float radius)
63 {
64 const double crossX=double(a.y)*b.z-double(a.z)*b.y;
65 const double crossY=double(a.z)*b.x-double(a.x)*b.z;
66 const double crossZ=double(a.x)*b.y-double(a.y)*b.x;
67 const double dot=double(a.x)*b.x+double(a.y)*b.y+double(a.z)*b.z;
68 return radius*std::atan2(std::sqrt(crossX*crossX+crossY*crossY+crossZ*crossZ),dot);
69 }
70
71 // Frozen legacy placement expression. Organic placement intentionally now
72 // stays in the uppermost occupied cloud component and is tested separately.
73 inline Point OriginalLegacySourcePosition(Point normal,const Parameters& params,uint32_t seed,float fraction)
74 {
75 const auto column=CloudVolume::Boundaries(CloudVolume::Scale(normal,params.radius),params,seed);
76 return CloudVolume::Scale(normal,params.radius+column.top-.8f-fraction*.8f);
77 }
78
79 inline Point Anchor(const Flash& flash)
80 {
81 const auto& first=flash.animation.path.segments[0].start;
82 return {first.x,first.y,first.z};
83 }
84
85 inline void Prime(Diagnostic& diagnostic,const Parameters& params,const Point& observer)
86 {
87 const auto before=diagnostic.Generated();
88 diagnostic.Start();diagnostic.Update(params,1./128,CloudVolume::DefaultSeed,observer);
89 Check(diagnostic.Active() && diagnostic.Generated()>before,
90 "cloud diagnostic reset fixture did not first create a real flash");
91 bool visible=false;
92 for(const auto& flash:diagnostic.Events())visible|=flash.animation.inuse && flash.Brightness()>0;
93 Check(visible,"cloud diagnostic reset fixture had no active illumination");
94 }
95
96 inline void WallClockTests(Parameters params,const Point& observer,uint32_t seed)
97 {
98 // Isolate clock semantics from the organic source-search fixture.
99 params.organic=false;
100 constexpr double begin=1000000.;
101 DiagnosticClock timed;timed.StartAt(begin);
102 timed.Update(params,1.,seed,observer,begin);
103 Check(timed.Active() && timed.Generated()==0,"start-time duplicate generated a diagnostic event");
104 timed.Update(params,.00277778,seed,observer,begin+1./128);
105 Check(timed.Generated()==1,"wall-time fixture did not generate its initial event");
106 const auto first=timed.Events();
107 for(unsigned duplicate=0;duplicate<2048;++duplicate)
108 {
109 // Deliberately huge/small physics deltas cannot shorten 30 seconds.
110 timed.Update(params,duplicate%2 ? 1. : .00277778,seed,observer,begin+1./128);
111 Check(timed.Active() && timed.Generated()==1,"duplicate timestamps charged the diagnostic clock");
112 }
113 timed.Update(params,1.,seed,observer,begin-1);
114 for(size_t i=0;i<first.size();++i)
115 Check(SameFlash(first[i],timed.Events()[i]),"duplicate or backward time advanced a flash");
116 // Valid wall timestamps control even a negative/zero physics delta;
117 // production can clamp its own delta without changing this deadline.
118 for(unsigned quarter=1;quarter<120;++quarter)
119 {
120 timed.Update(params,quarter%2 ? -1. : 0.,seed,observer,begin+quarter*.25);
121 Check(timed.Active(),"diagnostic expired before 30 wall-clock seconds");
122 }
123 Check(timed.Generated()==60,"wall-clock diagnostic lost its two-per-second schedule");
124 timed.Update(params,.00277778,seed,observer,begin+30);
125 CheckCleared(timed);
126 const auto completed=timed.Generated();
127 timed.UpdateAt(params,begin+31,seed,observer);
128 CheckCleared(timed);
129 Check(timed.Generated()==completed,"expired diagnostic replayed after the deadline");
130
131 DiagnosticClock stalled;stalled.StartAt(begin);
132 stalled.UpdateAt(params,begin+1./128,seed,observer);
133 const auto beforeStall=stalled.Generated();
134 stalled.UpdateAt(params,begin+4,seed,observer);
135 Check(stalled.Active() && stalled.Generated()==beforeStall+1,
136 "a long pause disarmed the test or replayed its missed event backlog");
137 unsigned active=0;
138 for(const auto& flash:stalled.Events())if(flash.animation.inuse)
139 {
140 ++active;
141 Check(flash.animation.sequenceAge==0,"pause recovery kept an old or backdated chain");
142 }
143 Check(active==1,"pause recovery did not leave exactly one fresh chain");
144 const auto fresh=stalled.Events();
145 stalled.UpdateAt(params,begin+4,seed,observer);
146 for(size_t i=0;i<fresh.size();++i)
147 Check(SameFlash(fresh[i],stalled.Events()[i]),"pause recovery duplicate generated or advanced a chain");
148 stalled.UpdateAt(params,begin+29.999,seed,observer);
149 Check(stalled.Active() && stalled.Generated()==beforeStall+2,
150 "late pause recovery lost the original deadline or replayed a backlog");
151 stalled.UpdateAt(params,begin+30,seed,observer);
152 CheckCleared(stalled);
153
154 DiagnosticClock suspended;suspended.StartAt(begin);
155 suspended.UpdateAt(params,begin+31,seed,observer);
156 CheckCleared(suspended);
157 Check(suspended.Generated()==0,"resume after the deadline generated a stale diagnostic event");
158
159 DiagnosticClock restarted;restarted.StartAt(begin);
160 restarted.UpdateAt(params,begin+1./128,seed,observer);
161 restarted.StartAt(begin+20);
162 for(const auto& flash:restarted.Events())
163 Check(!flash.animation.inuse && flash.Brightness()==0,"restart retained a previous diagnostic chain");
164 restarted.UpdateAt(params,begin+30,seed,observer);
165 Check(restarted.Active(),"restart retained the old expiration deadline");
166 restarted.UpdateAt(params,begin+49.999,seed,observer);
167 Check(restarted.Active(),"restarted test expired before its new 30-second deadline");
168 restarted.UpdateAt(params,begin+50,seed,observer);CheckCleared(restarted);
169 for(double invalid:{std::numeric_limits<double>::infinity(),std::numeric_limits<double>::quiet_NaN()})
170 {
171 restarted.StartAt(begin);restarted.StartAt(invalid);CheckCleared(restarted);
172 }
173 }
174}
175
176static void CloudLightningDiagnosticTests()
177{
178 using namespace CloudLightningDiagnosticFixture;
179 constexpr auto seed=CloudVolume::DefaultSeed;
180 Parameters params;params.weather.current=ConstantWeather(80,64);
181 const Point observer=Observer({0,1,0},117,params);
182 const std::array<Point,5> normals{{{0,1,0},{0,0,1},{0,0,-1},{.00001f,-1,0},{-.00001f,-1,0}}};
183 WallClockTests(params,observer,seed);
184
185 // Legacy placement must retain its original expression,
186 // including poles, the longitude seam, wind offset and weather strength.
187 for(uint8_t weather:{uint8_t(80),uint8_t(153),uint8_t(255)})
188 {
189 auto sample=params;sample.organic=false;sample.weather.current=ConstantWeather(weather,64);
190 sample.noiseOffset={31.25f,-12.5f,7.125f};
191 for(auto normal:normals)for(float fraction:{0.f,.25f,.999999f})
192 {
193 normal=CloudVolume::Scale(normal,1/CloudVolume::Length(normal));
194 Check(SamePoint(CloudLightning::SourcePosition(normal,sample,seed,fraction),
195 OriginalLegacySourcePosition(normal,sample,seed,fraction)),
196 "source placement changed the legacy flash position");
197 }
198 }
199
200 Diagnostic idle;
201 idle.Update(params,.5,seed,observer);CheckCleared(idle);
202 Check(idle.Generated()==0,"unarmed cloud diagnostic generated a flash");
203
204 unsigned positioned=0;double farthest=0;
205 // The quiet map is below natural lightning eligibility. Diagnostic mode
206 // may supply test energy, but every source must still occupy real clouds.
207 for(bool organic:{false,true})for(float altitude:{117.f,500.f,1000.f,3000.f})for(auto normal:normals)
208 {
209 auto sample=params;sample.organic=organic;
210 const auto eye=Observer(normal,altitude,sample);
211 Diagnostic diagnostic;diagnostic.Start();
212 std::array<uint32_t,Diagnostic::MaxEvents> seen{};
213 std::array<bool,Diagnostic::MaxEvents> hasSeen{};
214 unsigned localPositions=0;
215 for(unsigned frame=0;frame<96;++frame)
216 {
217 diagnostic.Update(sample,1./32,seed,eye);
218 unsigned active=0;
219 for(size_t i=0;i<diagnostic.Events().size();++i)
220 {
221 const auto& flash=diagnostic.Events()[i];
222 if(!flash.animation.inuse)continue;
223 ++active;
224 if(hasSeen[i] && seen[i]==flash.animation.seed)continue;
225 seen[i]=flash.animation.seed;hasSeen[i]=true;++positioned;++localPositions;
226 // The event anchor is inside the spawn cap; later chain nodes
227 // can spread along their density-checked, fixed world path.
228 const double distance=SurfaceDistance(eye,Anchor(flash),sample.radius);
229 farthest=(std::max)(farthest,distance);
230 Check(std::isfinite(distance) && distance<=Diagnostic::RadiusKm+.05,
231 "diagnostic source escaped its 100 km spawn cap or failed at a pole/seam");
232 Check(CloudVolume::Density(flash.position,sample,seed)>=.01f,
233 "diagnostic manufactured illumination outside actual cloud density");
234 Check(flash.radius>=7 && flash.radius<=20 && flash.energy>=1.4f && flash.energy<=3.6f,
235 "diagnostic changed the existing strong-storm energy/radius envelope");
236 Check(flash.animation.strokeCount>=LightningTiming::MinStrokes
237 && flash.animation.strokeCount<=LightningTiming::MaxStrokes
238 && flash.animation.boltDuration>=LightningTiming::MinDurationSeconds
239 && flash.animation.boltDuration<=LightningTiming::MaxDurationSeconds
240 && flash.animation.path.count>=1
241 && flash.animation.path.count<=LightningTiming::MaxChainedBolts+1
242 && flash.animation.Duration()==flash.animation.boltDuration*flash.animation.path.count,
243 "diagnostic diverged from the shared lightning animation");
244 Check(CloudLightning::Weight(CloudWeather::Sample(sample.weather,
245 flash.position.x,flash.position.y,flash.position.z))==0,
246 "quiet diagnostic fixture accidentally contained natural storm eligibility");
247 }
248 Check(active<=Diagnostic::MaxEvents,"diagnostic exceeded its four-event cap");
249 }
250 Check(localPositions>0,"diagnostic geometry case was vacuous");
251 }
252 Check(positioned>=40 && farthest>20,"diagnostic cap checks did not exercise displaced sources");
253
254 // Binary-exact steps and an off-boundary final time avoid confusing a
255 // floating-point half-second crossing with a scheduling regression.
256 Diagnostic fine,coarse;fine.Start();coarse.Start();
257 for(unsigned i=0;i<840;++i)fine.Update(params,1./128,seed,observer);
258 for(unsigned i=0;i<105;++i)coarse.Update(params,1./16,seed,observer);
259 Check(fine.Generated()==14 && coarse.Generated()==fine.Generated(),
260 "diagnostic did not produce the immediate event plus two events per second");
261 bool cadenceActive=false;
262 for(size_t i=0;i<fine.Events().size();++i)
263 {
264 Check(SameFlash(fine.Events()[i],coarse.Events()[i]),"diagnostic event depends on frame cadence");
265 cadenceActive|=fine.Events()[i].animation.inuse;
266 }
267 Check(cadenceActive,"diagnostic cadence comparison contained no active flash");
268
269 Diagnostic moving;Prime(moving,params,observer);
270 const auto initial=moving.Events();
271 const auto elsewhere=Observer({1,0,0},117,params);
272 moving.Update(params,1./128,seed,elsewhere);
273 bool retained=false;
274 for(size_t i=0;i<initial.size();++i)if(initial[i].animation.inuse)
275 {
276 auto expected=initial[i];expected.Update(1./128);
277 Check(SameFlash(moving.Events()[i],expected),
278 "moving the ship changed an existing flash beyond its own fixed-path animation");
279 retained=true;
280 }
281 Check(retained,"planet-fixed movement check contained no active source");
282 moving.Update(params,.5,seed,elsewhere);
283 bool followed=false;
284 for(const auto& flash:moving.Events())if(flash.animation.inuse)
285 {
286 bool old=false;
287 for(const auto& previous:initial)old|=previous.animation.inuse && previous.animation.seed==flash.animation.seed;
288 if(old)continue;
289 Check(SurfaceDistance(elsewhere,Anchor(flash),params.radius)<=Diagnostic::RadiusKm+.05,
290 "new diagnostic flash did not follow the new ship subpoint");
291 followed=true;
292 }
293 Check(followed,"movement fixture did not produce a flash at the new subpoint");
294
295 // Stop and all automatically-invalidating conditions clear active flashes
296 // and require explicit re-arming. Renderer/simulator hooks call Reset;
297 // their invocation is an integration responsibility, not a CPU-only claim.
298 const auto staysStopped=[&](Diagnostic& diagnostic)
299 {
300 CheckCleared(diagnostic);const auto before=diagnostic.Generated();
301 diagnostic.Update(params,.5,seed,observer);
302 CheckCleared(diagnostic);Check(diagnostic.Generated()==before,"diagnostic re-armed itself");
303 };
304 Diagnostic stopped;Prime(stopped,params,observer);stopped.Reset();staysStopped(stopped);
305 for(double elapsed:{std::numeric_limits<double>::infinity(),
306 std::numeric_limits<double>::quiet_NaN()})
307 {
308 Diagnostic diagnostic;Prime(diagnostic,params,observer);
309 diagnostic.Update(params,elapsed,seed,observer);staysStopped(diagnostic);
310 }
311 const float nan=std::numeric_limits<float>::quiet_NaN(),infinity=std::numeric_limits<float>::infinity();
312 const std::array<Point,5> invalidPositions{{{0,0,0},{nan,1,0},{infinity,0,0},
313 Observer({0,1,0},params.top+CloudVolume::MaxTopRiseKm,params),Observer({0,1,0},.5f,params)}};
314 for(const auto& position:invalidPositions)
315 {
316 Diagnostic diagnostic;Prime(diagnostic,params,observer);
317 diagnostic.Update(params,.01,seed,position);staysStopped(diagnostic);
318 }
319 Diagnostic disconnected;Prime(disconnected,params,observer);
320 auto missing=params;missing.weather={};
321 disconnected.Update(missing,.01,seed,observer);staysStopped(disconnected);
322 Diagnostic paused;Prime(paused,params,observer);const auto beforePause=paused.Events();
323 paused.Update(params,0,seed,observer);
324 Check(paused.Active(),"zero elapsed time disarmed the diagnostic");
325 for(size_t i=0;i<beforePause.size();++i)
326 Check(SameFlash(beforePause[i],paused.Events()[i]),"zero elapsed time advanced a diagnostic flash");
327 Diagnostic expires;expires.Start();
328 for(unsigned i=0;i<119;++i)expires.Update(params,.25,seed,observer);
329 Check(expires.Active(),"diagnostic expired before its 30-second lifetime");
330 expires.Update(params,.25,seed,observer);staysStopped(expires);
331
332 // Deliberately empty administrative layer: its base is above the existing
333 // outer density shell. A valid weather object alone must not create light.
334 auto empty=params;empty.base=40;
335 Diagnostic noMoisture;noMoisture.Start();
336 for(unsigned i=0;i<16;++i)noMoisture.Update(empty,.125,seed,observer);
337 Check(noMoisture.Generated()==0,"diagnostic created a flash in an empty density envelope");
338 for(const auto& flash:noMoisture.Events())
339 Check(!flash.animation.inuse && flash.Brightness()==0,"empty layer retained diagnostic illumination");
340
341 // Interleaving diagnostic work, restarts and cancellation cannot consume
342 // the natural scheduler RNG or alter natural event count/properties.
343 for(bool organic:{false,true})
344 {
345 auto storm=params;storm.organic=organic;storm.weather.current=ConstantWeather(255,64);
346 CloudLightning::System untouched(0x12345678u),interleaved(0x12345678u);
347 Diagnostic diagnostic;diagnostic.Start();
348 for(unsigned frame=0;frame<192;++frame)
349 {
350 untouched.Update(storm,1./64,seed);
351 if(frame==48)diagnostic.Reset();
352 if(frame==96)diagnostic.Start();
353 diagnostic.Update(storm,1./64,seed,observer);
354 interleaved.Update(storm,1./64,seed);
355 Check(untouched.Generated()==interleaved.Generated(),"diagnostic changed natural event counts");
356 for(size_t i=0;i<untouched.Events().size();++i)
357 Check(SameFlash(untouched.Events()[i],interleaved.Events()[i]),
358 "diagnostic changed natural RNG, source, strength or animation");
359 }
360 Check(untouched.Generated()>200,"natural independence comparison was vacuous");
361 }
362 std::cout<<"Cloud diagnostic: "<<positioned<<" occupied polar/seam/altitude sources; farthest "
363 <<farthest<<" km; private 2/s schedule, 30 wall-second expiry, duplicate/stall/restart clocks and natural-stream independence\n";
364}
float Weight(float convection)
Point SourcePosition(const Point &normal, const CloudVolume::Parameters &params, uint32_t cloudSeed, float depthFraction)
constexpr float MaxTopRiseKm
Definition CloudVolume.h:23
Point Scale(Point p, float s)
Definition CloudVolume.h:93
constexpr uint32_t DefaultSeed
Definition CloudVolume.h:19
Column Boundaries(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Density(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Length(Point p)
Definition CloudVolume.h:94
float Sample(const MapPtr &map, float u, float v)
BasicParameters< RiseMath::Vector3, RiseMath::Color > Parameters
Definition ExteriorRain.h:7
constexpr int MaxStrokes
constexpr int MinStrokes
constexpr int MaxChainedBolts
constexpr double MaxDurationSeconds
constexpr double MinDurationSeconds