1#include "../Viewscreen/LightningStrike.h"
2#include "../Viewscreen/LightningChain.h"
3#include "LightningStrikeAnimationTests.h"
4namespace
5{
6 void TestAfterimageTiming()
7 {
11 for(int fps:{30,60,144})
12 {
13 State state;Check(state.
Begin(0,
true,0,1),
"first afterimage frame must clear");state.
Capture();
14 double decay=1;
15 for(
int i=1;i<=fps*3;++i){state.
Begin(
double(i)/fps,
true,0,1);decay*=state.
decay;}
16 Check(std::abs(decay-std::exp(-3/
DecaySeconds))<1e-6,
"afterimage fade depends on frame rate");
17 Check(state.
active,
"ghost expired before its tail");
19 }
21 Check(state.
Begin(10.1,
false,0,1) && !state.
active && state.
gain==0,
"simulator/disabled view retained ghost");
22 state.
Begin(10.2,
true,0,1);Check(!state.
active,
"disabled ghost replayed on exit");
23 state.
Capture();Check(state.
Begin(10.3,
true,0,2) && !state.
active,
"camera/vehicle switch retained ghost");
24 state.
Capture();Check(state.
Begin(10.4,
true,1,2) && !state.
active,
"daylight retained ghost");
26 Check(state.
Begin(20,
true,0,2) && !state.
active,
"pause retained expired ghost");
27 state.
Capture();Check(state.
Begin(19,
true,0,2) && !state.
active,
"backwards clock retained ghost");
28 }
29 void TestBoltGeometry()
30 {
31 TestBoltAnimation();
32 TestAfterimageTiming();
33 for(uint32_t seed=0;seed<100;++seed) {
35 Check(a.indices==b.indices && a.vertices.size()==b.vertices.size(),"seeded topology changed");
36 Check(a.branches>=7 && a.branches<=15 && a.vertices.size()<1400 && a.indices.size()<5000,"geometry budget/branch count");
37 Check(a.vertices.front().position.y==3 && a.vertices[256].position.y==0,"channel endpoint attachment");
38 for(size_t i=0;i<a.vertices.size();++i) {
39 const auto& v=a.vertices[i];const auto& same=b.vertices[i];
40 Check(v.position.x==same.position.x && v.position.y==same.position.y && v.position.z==same.position.z,
41 "flash regenerated unstable channel positions");
43 && v.width>0 && v.energy>=0 && v.energy<=1 && v.position.y>=0 && v.position.y<=3,
44 "invalid vertex or branch crossed surface/deck");
45 }
46 for(auto index:a.indices)Check(index<a.vertices.size(),"ribbon index out of bounds");
47 }
51 Check(a.vertices[128].position.x!=b.vertices[128].position.x,"different seeds repeat the same bolt");
52 }
53 void SaveBoltPreview(Device11& gpu,Scene& scene,const std::filesystem::path& file)
54 {
55 D3D11_TEXTURE2D_DESC desc{};scene.color->GetDesc(&desc);
56 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
57 ComPtr<ID3D11Texture2D> copy;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,©),"preview readback");
58 gpu.Context()->ClearState();gpu.Context()->CopyResource(copy.Get(),scene.color.Get());
59 D3D11_MAPPED_SUBRESOURCE mapped{};HR(gpu.Context()->Map(copy.Get(),0,D3D11_MAP_READ,0,&mapped),"preview map");
60 std::filesystem::create_directories(file.parent_path());std::ofstream
output(file,std::ios::binary);
61 output<<
"P6\n"<<desc.Width<<
" "<<desc.Height<<
"\n255\n";
62 for(UINT y=0;y<desc.Height;++y)for(UINT x=0;x<desc.Width;++x) {
63 const auto* p=static_cast<unsigned char*>(mapped.pData)+y*mapped.RowPitch+x*4;
64 output.write(
reinterpret_cast<const char*
>(p),3);
65 }
66 gpu.Context()->Unmap(copy.Get(),0);Check(bool(output),"preview save");
67 }
68 void TestProceduralBolt(Device11& gpu,CloudRenderer11& atmosphere,const std::filesystem::path& shaders,UINT samples)
69 {
70 if(!gpu.SupportsSamples(samples))return;
71 ProceduralLightning11 bolt;HR(bolt.Initialize(gpu.Device(),shaders),"bolt initialize");
72 Pipeline pipeline(gpu.Device(),samples);Scene scene(gpu.Device(),samples),reference(gpu.Device(),samples);
73 XMFLOAT4X4 view,projection;XMStoreFloat4x4(&view,XMMatrixIdentity());
74 XMStoreFloat4x4(&projection,XMMatrixPerspectiveFovRH(1.f,float(Width)/Height,.001f,128));
75 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};
77 float strikeTop=3003;
78 const auto draw=[&](Scene&
target,
float pulse=1,CloudRenderer11* fog=
nullptr,
float growth=1.f,uint32_t seed=123) {
79 for(float x:{-4.5f,-2.25f,0.f,2.25f,4.5f})
80 HR(bolt.Render(gpu.Context(),
target.target.Get(),
target.depth,viewport,view,projection,
81 origin,{x,3000,-8},{x,strikeTop,-8},seed,{.9f,.95f,1,1},pulse,42.16f,fog,growth),"bolt draw");
82 };
83 scene.Clear(gpu.Context());draw(scene);
84 const auto first=pipeline.Pixels(gpu,scene,samples);
85 Check(bolt.GeometryBuilds()==1 && bolt.IndexCount()>1000,"one mesh should serve camera/pulse/position changes");
86 const auto energy=[](const std::vector<Sample>& pixels) {
87 double value=0;for(const auto& p:pixels)value+=p.color[0]+p.color[1]+p.color[2];return value;
88 };
89 Check(energy(first)>30,"procedural bolt not visible");
90 scene.Clear(gpu.Context());draw(scene);const auto repeat=pipeline.Pixels(gpu,scene,samples);
91 for(size_t i=0;i<first.size();++i)for(unsigned c=0;c<4;++c)
92 Check(first[i].color[c]==repeat[i].color[c],"unchanged strike frame flickers");
93 scene.Clear(gpu.Context());draw(scene,0);const auto off=pipeline.Pixels(gpu,scene,samples);
94 Check(energy(off)==0 && bolt.GeometryBuilds()==1,"zero pulse emits light or rebuilds geometry");
95 double previousEnergy=0;
96 for(float growth:{0.f,.25f,.5f,.75f,1.f})
97 {
98 scene.Clear(gpu.Context());draw(scene,1,nullptr,growth);
99 const auto growing=pipeline.Pixels(gpu,scene,samples);
100 const double currentEnergy=energy(growing);
101 Check(growth==0 ? currentEnergy==0 : currentEnergy>previousEnergy,"leader failed to grow down the fixed channel");
102 for(size_t i=0;i<first.size();++i)for(unsigned c=0;c<3;++c)
103 Check(growing[i].color[c]<=first[i].color[c],"growing leader appeared outside the established branches");
104 previousEnergy=currentEnergy;
105 }
107 while(animation.
inuse)
108 {
111 Check(bolt.GeometryBuilds()==1,"production animation regenerated geometry between frames/strokes");
112 }
113 scene.Clear(gpu.Context());reference.Clear(gpu.Context());pipeline.Occlude(gpu,scene);
114 const auto before=pipeline.Pixels(gpu,scene,samples);draw(reference);draw(scene);
115 const auto expected=pipeline.Pixels(gpu,reference,samples),after=pipeline.Pixels(gpu,scene,samples);
116 unsigned changed=0;
117 for(UINT y=0;y<
Height;++y)
for(UINT x=0;x<
Width;++x)
for(UINT s=0;s<samples;++s) {
118 const auto i=(y*
Width+x)*samples+s;
119 const bool protectedSample=before[i].depth<1 || x/(
Width/5)>=3;
120 const auto&
target=protectedSample?before[i]:expected[i];
121 Check(before[i].depth==after[i].depth,"bolt wrote original scene depth");
122 for(
unsigned c=0;c<4;++c)Check(std::abs(after[i].color[c]-
target.color[c])<1.01f/255,
"bolt crossed foreground or cockpit mask");
123 if(!protectedSample && after[i].color[2]>before[i].color[2]+.01f)++changed;
124 }
125 Check(changed>10,"masked fixture did not expose any bolt samples");
126
127
130 const auto throughRain=[&](float visibility,float precip) {
131 grid->cells.fill({0,4,visibility,precip});++
grid->revision;atmosphere.SetRainGrid(
grid.get());
132 scene.Clear(gpu.Context());
133 HR(atmosphere.Render(gpu.Context(),scene.target.Get(),scene.depth,viewport,view,projection,
134 {origin.x,origin.y,origin.z},cloud,{0,-1,0},{},{},{},{0,0,0,42.16f}),"bolt fog setup");
135 scene.Clear(gpu.Context());draw(scene,.04f,&atmosphere);return pipeline.Pixels(gpu,scene,samples);
136 };
137 const auto clear=throughRain(42.16f,2),rain=throughRain(10,16),dry=throughRain(10,2),dense=throughRain(1,16);
138
139
140 Check(energy(clear)>energy(rain)*1.2 && energy(dense)<energy(rain)*.75,
141 "altitude-adjusted spatial visibility must attenuate bolts along their rays");
142 for(size_t i=0;i<rain.size();++i)for(unsigned c=0;c<3;++c)
143 Check(rain[i].color[c]==dry[i].color[c],"precipitation applied a second bolt visibility penalty");
144
145 origin.y=3000.3f;strikeTop=3000.6f;
146 const auto lowRain=throughRain(10,16),lowOpaque=throughRain(1,16);
147 Check(energy(lowRain)>1 && energy(lowOpaque)<energy(lowRain)*.01,
148 "dense near-ground fog must hide distant bolts");
149 origin.y=3002;strikeTop=3003;
150 atmosphere.SetRainGrid(nullptr);
151
152
153 scene.Clear(gpu.Context());
154 HR(bolt.Render(gpu.Context(),scene.target.Get(),scene.depth,viewport,view,projection,
155 {0,3000.4f,0},{0,3000,-1},{0,3001.8f,-1},123,{.9f,.95f,1,1},1,42.16f),"1 km diagnostic bolt");
156 const auto nearby=pipeline.Pixels(gpu,scene,samples);
157 Check(energy(nearby)>100,"1 km cloud-to-ground channel is not visible in front of the camera");
158
159
160 bolt.BeginAfterimage(0,true,0,1);
161 scene.Clear(gpu.Context());pipeline.Occlude(gpu,scene);draw(scene);
162 const auto capturedScene=pipeline.Pixels(gpu,scene,samples);
163 for(size_t i=0;i<after.size();++i)for(unsigned c=0;c<4;++c)
164 Check(std::abs(capturedScene[i].color[c]-after[i].color[c])<1.01f/255,"capture changed real bolt emission");
165 scene.Clear(gpu.Context());
166 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),"initial afterimage composite");
167 const auto ghost=pipeline.Pixels(gpu,scene,samples);
168 Check(energy(ghost)>1 && energy(ghost)<energy(first)*.5,"ghost absent or too bright");
169 for(UINT y=0;y<
Height;++y)
for(UINT x=0;x<
Width;++x)
170 {
171 bool visible=false;
172 for(UINT s=0;s<samples;++s) {
173 const auto i=(y*
Width+x)*samples+s;
174 visible|=before[i].depth==1 && x/(
Width/5)<3 && after[i].color[2]>0;
175 }
176 for(UINT s=0;s<samples;++s) {
177 const auto i=(y*
Width+x)*samples+s;
178 Check(ghost[i].depth==1 && ghost[i].color[3]==1,"ghost modified depth or scene alpha");
179 if(!visible)Check(ghost[i].color[0]==0 && ghost[i].color[1]==0 && ghost[i].color[2]==0,
180 "afterimage imprinted an occluded/off-channel fragment");
181 }
182 }
183
184
185 double previousGhost=energy(ghost);
186 for(double time:{.5,1.,2.}) {
187 bolt.BeginAfterimage(time,true,0,1);scene.Clear(gpu.Context());
188 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),"decaying ghost");
189 const auto fading=pipeline.Pixels(gpu,scene,samples);const auto fadedEnergy=energy(fading);
190 Check(fadedEnergy>0 && fadedEnergy<previousGhost,"afterimage failed to fade gradually");
191 for(size_t i=0;i<fading.size();++i)for(unsigned c=0;c<3;++c)
192 Check(fading[i].color[c]<=ghost[i].color[c],"afterimage moved or generated new branches");
193 previousGhost=fadedEnergy;
194 }
195 const auto expectNoGhost=[&](const char* reason) {
196 scene.Clear(gpu.Context());
197 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),reason);
198 Check(energy(pipeline.Pixels(gpu,scene,samples))==0,reason);
199 };
200 bolt.BeginAfterimage(4,true,0,1);expectNoGhost("afterimage lifetime exceeded");
201 bolt.BeginAfterimage(5,true,0,1);scene.Clear(gpu.Context());draw(scene);
202 bolt.BeginAfterimage(5.1,false,0,1);expectNoGhost("simulator/optics suppression failed");
203 bolt.BeginAfterimage(5.2,true,0,1);expectNoGhost("simulator exit replayed history");
204 scene.Clear(gpu.Context());draw(scene);
205 bolt.BeginAfterimage(5.3,true,0,2);expectNoGhost("view change retained history");
206 scene.Clear(gpu.Context());draw(scene);
207 bolt.BeginAfterimage(5.4,true,1,2);expectNoGhost("daylight retained history");
208 draw(scene);expectNoGhost("daylight recorded a new afterimage");
209 bolt.BeginAfterimage(6,true,0,2);scene.Clear(gpu.Context());draw(scene,0);
210 expectNoGhost("zero pulse imprinted a ghost");
211
212 bolt.BeginAfterimage(7,true,0,2);origin.y=3000.3f;strikeTop=3000.6f;
213 throughRain(1,16);expectNoGhost("opaque fog left a visible afterimage");
214 origin.y=3002;strikeTop=3003;atmosphere.SetRainGrid(nullptr);
215 bolt.ClearAfterimage();bolt.BeginAfterimage(8,true,0,2);
216 scene.Clear(gpu.Context());draw(scene);
217 const D3D11_VIEWPORT smaller{0,0,float(Width-1),float(Height),0,1};
218 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,smaller),"resized view");
219 expectNoGhost("viewport resize retained a displaced ghost");
220 bolt.ClearAfterimage();
221
223 const auto chainedDraw=[&](float growth=1.f) {
224 for(int i=0;i<connected.count;++i) {
225 const auto& segment=connected.segments[i];
226 HR(bolt.Render(gpu.Context(),scene.target.Get(),scene.depth,viewport,view,projection,
227 origin,segment.end,segment.start,segment.seed,
228 {.9f,.95f,1,1},1,42.16f,nullptr,segment.Growth(growth)),"connected bolt draw");
229 }
230 };
231 const unsigned chainBuilds=bolt.GeometryBuilds();
232 bolt.BeginAfterimage(10,true,0,1);scene.Clear(gpu.Context());chainedDraw();
233 const auto chainedPixels=pipeline.Pixels(gpu,scene,samples);
234 Check(bolt.GeometryBuilds()==chainBuilds+3,"chained flash failed to create three distinct meshes");
235 scene.Clear(gpu.Context());chainedDraw();
236 const auto repeatedChains=pipeline.Pixels(gpu,scene,samples);
237 Check(bolt.GeometryBuilds()==chainBuilds+3,"chained return strokes rebuilt geometry every frame");
238 for(size_t i=0;i<chainedPixels.size();++i)for(unsigned c=0;c<4;++c)
239 Check(chainedPixels[i].color[c]==repeatedChains[i].color[c],"chained channels changed shape between strokes");
240 scene.Clear(gpu.Context());chainedDraw(connected.segments[0].finish*.5f);
241 const auto earlyChain=pipeline.Pixels(gpu,scene,samples);
242 Check(energy(earlyChain)>0 && energy(earlyChain)<energy(chainedPixels),"connected leader failed to reveal in stages");
243 scene.Clear(gpu.Context());
244 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),"chained afterimage");
245 const auto chainedGhost=pipeline.Pixels(gpu,scene,samples);
246 for(int i=0;i<connected.count;++i)
247 {
248 const auto& segment=connected.segments[i];reference.Clear(gpu.Context());
249 HR(bolt.Render(gpu.Context(),reference.target.Get(),reference.depth,viewport,view,projection,
250 origin,segment.end,segment.start,segment.seed,{.9f,.95f,1,1},1,42.16f),"individual chain section");
251 const auto section=pipeline.Pixels(gpu,reference,samples);
252 double glow=0;
253 for(size_t p=0;p<section.size();++p)if(section[p].color[2]>.1f)glow+=chainedGhost[p].color[2];
254 Check(energy(section)>0 && glow>0,"connected afterimage lost a visible section");
255 }
256 bolt.ClearAfterimage();
258 for(int section=0;section<connected.count;++section)
259 {
263 const auto& active=connected.segments[sequenceTest.
activeSegment];
264 scene.Clear(gpu.Context());reference.Clear(gpu.Context());bolt.BeginAfterimage(now,true,0,1);
265 HR(bolt.Render(gpu.Context(),scene.target.Get(),scene.depth,viewport,view,projection,
268 const auto actual=pipeline.Pixels(gpu,scene,samples);
269 const auto& expectedSection=connected.segments[section];
270 HR(bolt.Render(gpu.Context(),reference.target.Get(),reference.depth,viewport,view,projection,
271 origin,expectedSection.end,expectedSection.start,expectedSection.seed,{.9f,.95f,1,1},1,42.16f),"expected isolated section");
272 const auto isolatedPixels=pipeline.Pixels(gpu,reference,samples);
273 Check(energy(actual)>0,"sequential section invisible");
274 for(size_t p=0;p<actual.size();++p)for(unsigned c=0;c<4;++c)
275 Check(actual[p].color[c]==isolatedPixels[p].color[c],"sequence flashed more than its active section");
276 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),"sequential imprint");
277 }
278 scene.Clear(gpu.Context());bolt.BeginAfterimage(sequenceTest.
sequenceAge+.05,
true,0,1);
279 HR(bolt.CompositeAfterimage(gpu.Context(),scene.target.Get(),scene.depth,viewport),"sequential ghost persistence");
280 Check(energy(pipeline.Pixels(gpu,scene,samples))>0,"sequence lost its retinal afterimage");
282 bolt.ClearAfterimage();
283 if(samples==1) {
284 Scene preview(gpu.Device(),1,1024,768);preview.Clear(gpu.Context());
285 const float background[]={.018f,.026f,.047f,1};gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
286 const D3D11_VIEWPORT large{0,0,1024,768,0,1};
288 for(int section=0;section<connected.count;++section)
289 {
293 preview.Clear(gpu.Context());gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
294 bolt.BeginAfterimage(now,true,0,1);
296 HR(bolt.Render(gpu.Context(),preview.target.Get(),preview.depth,large,view,projection,
297 origin,active.end,active.start,active.seed,{.9f,.95f,1,1},sequence.
flashBrightness,42.16f,
nullptr,sequence.
growth),
"sequence preview");
298 HR(bolt.CompositeAfterimage(gpu.Context(),preview.target.Get(),preview.depth,large),"sequence afterimage preview");
299 SaveBoltPreview(gpu,preview,"outputs/procedural-lightning/sequential-section-"+std::to_string(section)+".ppm");
300 }
301 bolt.ClearAfterimage();
302 preview.Clear(gpu.Context());gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
303 for(int i=0;i<connected.count;++i) {
304 const auto& segment=connected.segments[i];
305 HR(bolt.Render(gpu.Context(),preview.target.Get(),preview.depth,large,view,projection,
306 origin,segment.end,segment.start,segment.seed,{.9f,.95f,1,1},1,42.16f),"connected preview");
307 }
308 SaveBoltPreview(gpu,preview,"outputs/procedural-lightning/connected-chain.ppm");
309 preview.Clear(gpu.Context());gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
310 for(int i=0;i<3;++i)
311 HR(bolt.Render(gpu.Context(),preview.target.Get(),preview.depth,large,view,projection,
312 origin,{float(i-1)*3.4f,3000,-8},{float(i-1)*3.4f,3003,-8},uint32_t(173+i*391),
313 {.9f,.95f,1,1},i==1?.4f:1,42.16f),"preview bolt");
314 SaveBoltPreview(gpu,preview,"outputs/procedural-lightning/channels.ppm");
315
316 animation.
Start(123);
317 for(int frame=0;frame<66;++frame)
318 {
319 preview.Clear(gpu.Context());gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
320 HR(bolt.Render(gpu.Context(),preview.target.Get(),preview.depth,large,view,projection,
321 origin,{0,3000,-8},{0,3003,-8},animation.
seed,{.9f,.95f,1,1},
323 SaveBoltPreview(gpu,preview,"outputs/procedural-lightning/animation/frame-"+std::to_string(frame)+".ppm");
325 }
326
327 bolt.BeginAfterimage(0,true,0,1);preview.Clear(gpu.Context());
328 HR(bolt.Render(gpu.Context(),preview.target.Get(),preview.depth,large,view,projection,
329 origin,{0,3000,-8},{0,3003,-8},123,{.9f,.95f,1,1},1,42.16f),"afterimage preview capture");
330 for(int frame=0;frame<=4;++frame) {
331 if(frame)bolt.BeginAfterimage(double(frame),true,0,1);
332 preview.Clear(gpu.Context());gpu.Context()->ClearRenderTargetView(preview.target.Get(),background);
333 HR(bolt.CompositeAfterimage(gpu.Context(),preview.target.Get(),preview.depth,large),"afterimage preview");
334 SaveBoltPreview(gpu,preview,"outputs/procedural-lightning/afterimage-"+std::to_string(frame)+"s.ppm");
335 }
336 }
337 bolt.Reset();DebugMessages(gpu);std::cout<<"PASS: procedural channel, stable pulses, rain, depth/cockpit "<<samples<<"x\n";
338 }
339}
float NightGain(float ambient)
constexpr float DayLuminance
constexpr double LifetimeSeconds
constexpr double DecaySeconds
Path Build(Vector3 ground, Vector3 cloud, uint32_t seed, int chains, float cloudTopRadius)
Mesh Generate(Vector3 cloudOffset, uint32_t seed)
bool Begin(double now, bool enabled, float ambient, uint64_t view)
double SegmentStart(int index) const
void Update(double elapsed)
void Start(uint32_t packetSeed, const Path &geometry)
std::array< Segment, LightningTiming::MaxChainedBolts+1 > segments
void Start(uint32_t strikeSeed, double durationSeconds=0)
std::array< Stroke, Timing::MaxStrokes > strokes
void Update(double elapsed)
std::vector< Vertex > vertices