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

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

1// Deterministic lightning illumination comparisons through the shipping cloud
2// pass. No production test switches, live client, weather server or scheduling.
3static uint64_t CloudLightningGpuHash(Device11& gpu,ID3D11ShaderResourceView* view,bool opacity)
4{
5 ComPtr<ID3D11Resource> resource;view->GetResource(&resource);
6 ComPtr<ID3D11Texture2D> texture;HR(resource.As(&texture),"lightning hash texture");
7 D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
8 Check(desc.SampleDesc.Count==1 && desc.MipLevels==1 && desc.ArraySize==1,"lightning hash dimensions");
9 UINT stride=0,offset=0,bytes=0;
10 if(!opacity && desc.Format==DXGI_FORMAT_R32G32_FLOAT){stride=bytes=8;}
11 else if(opacity && desc.Format==DXGI_FORMAT_R16G16B16A16_FLOAT){stride=8;offset=6;bytes=2;}
12 else if(opacity && (desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM))
13 {stride=4;offset=3;bytes=1;}
14 else throw std::runtime_error("unsupported lightning hash format: "+std::to_string(unsigned(desc.Format)));
15 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=desc.MiscFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
16 ComPtr<ID3D11Texture2D> staging;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"lightning hash staging");
17 gpu.Context()->CopyResource(staging.Get(),texture.Get());
18 D3D11_MAPPED_SUBRESOURCE mapped{};HR(gpu.Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"lightning hash readback");
19 uint64_t hash=14695981039346656037ull;
20 for(UINT y=0;y<desc.Height;++y)
21 {
22 const auto* row=static_cast<const uint8_t*>(mapped.pData)+size_t(y)*mapped.RowPitch;
23 for(UINT x=0;x<desc.Width;++x)for(UINT b=0;b<bytes;++b)
24 hash=(hash^row[size_t(x)*stride+offset+b])*1099511628211ull;
25 }
26 gpu.Context()->Unmap(staging.Get(),0);return hash;
27}
28
29static void CloudLightningGpu(Device11& gpu,const fs::path& shaders,const fs::path& reference,const fs::path& output)
30{
31 using namespace DirectX;
33 fs::create_directories(output);
34 constexpr UINT width=3440,height=1331,samples=4;
35 constexpr uint32_t seed=0x52495345u;
36 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS","1");
37 SetEnvironmentVariableA("RISE_CLOUD_SEED","0x52495345");
38 CloudVolume::Parameters params;params.organic=true;
39 auto weather=std::make_shared<CloudWeather::Map>();
40 weather->mips.push_back({64,32,std::vector<uint8_t>(64*32,255)});CloudWeather::BuildMips(*weather);
41 params.weather.previous=params.weather.current=weather;params.weather.blend=1;
42 const auto point=[](FXMVECTOR v){XMFLOAT3 f;XMStoreFloat3(&f,v);return Point{f.x,f.y,f.z};};
43 const auto oldSource=[&](const Point& normal) {
44 const auto column=CloudVolume::Boundaries(CloudVolume::Scale(normal,params.radius),params,seed);
45 auto source=CloudVolume::Scale(normal,params.radius+column.top-.8f-1.f*.8f);
46 float altitude=CloudVolume::Length(source)-params.radius;
47 for(int i=0;i<440 && altitude>column.base+.25f && CloudVolume::Density(source,params,seed)<.01f;++i)
48 {altitude-=.05f;source=CloudVolume::Scale(normal,params.radius+altitude);}
49 return source;
50 };
51 Point chosen{},before{},sourceNormal{};float occupiedTop=0,occupiedBottom=0;
52 bool found=false;unsigned selectedColumn=0;
53 // Same bounded Fibonacci-sphere strategy as the CPU placement regression.
54 // Independently identify an upper occupied component that the old 1.6 km
55 // subtraction skipped, then require a meaningful source lift (>1 km).
56 constexpr unsigned columns=1024;
57 for(unsigned i=0;i<columns && !found;++i)
58 {
59 const double z=1-2*(double(i)+.5)/columns,azimuth=double(i)*2.399963229728653;
60 const double equator=std::sqrt(1-z*z);
61 const Point normal{float(equator*std::cos(azimuth)),float(equator*std::sin(azimuth)),float(z)};
62 const auto at=[&](float altitude){return CloudVolume::Scale(normal,params.radius+altitude);};
63 const auto density=[&](float altitude){return CloudVolume::Density(at(altitude),params,seed);};
64 const auto column=CloudVolume::Boundaries(at(0),params,seed);
65 if(column.top<params.top+2)continue;
66 float top=column.top;
67 for(unsigned step=0;step<20 && density(top)<.01f;++step)top-=.025f;
68 if(density(top)<.01f)continue;
69 float bottom=top;unsigned depthSteps=0;
70 while(depthSteps<64 && density(bottom)>=.01f){bottom-=.025f;++depthSteps;}
71 if(depthSteps==64 || top-bottom<.075f)continue;
72 const float skipped=column.top-1.6f;
73 if(skipped>=bottom-.05f || density(skipped)>=.01f)continue;
74 const auto candidate=CloudLightning::SourcePosition(normal,params,seed,1.f),previous=oldSource(normal);
75 const float newAltitude=CloudVolume::Length(candidate)-params.radius,oldAltitude=CloudVolume::Length(previous)-params.radius;
76 if(oldAltitude>=bottom-.1f || CloudVolume::Density(previous,params,seed)<.01f
77 || newAltitude-oldAltitude<=1.f || newAltitude<=bottom-.025f)continue;
78 chosen=candidate;before=previous;sourceNormal=normal;occupiedTop=top;occupiedBottom=bottom;selectedColumn=i;found=true;
79 }
80 Check(found,"bounded sphere search finds a skipped thin crown with more than 1 km placement lift");
81 Check(CloudVolume::Density(chosen,params,seed)>=.01f,"lightning source occupies organic cloud");
82 Check(CloudVolume::Length(chosen)-params.radius>occupiedBottom-.025f,"lightning source stays in the upper occupied component");
83 const auto sourceUp=XMVectorSet(sourceNormal.x,sourceNormal.y,sourceNormal.z,0);
84 const auto sourceEast=XMVector3Normalize(XMVector3Cross(sourceUp,XMVectorSet(0,0,1,0)));
85 // Position the observer 160 km back along a stable surface tangent, then
86 // derive its coordinates rather than hiding a search behind fixed metadata.
87 const auto radial=XMVector3Normalize(sourceUp*params.radius-sourceEast*160.f);
88 const auto east=XMVector3Normalize(XMVector3Cross(radial,XMVectorSet(0,0,1,0)));
89 const auto north=XMVector3Cross(east,radial);
90 const auto eyeNormal=point(radial);
91 const float latitude=XMConvertToDegrees(std::asin(eyeNormal.z));
92 const float longitude=XMConvertToDegrees(std::atan2(-eyeNormal.x,eyeNormal.y));
93 XMFLOAT3 eye,sun;XMStoreFloat3(&eye,radial*(params.radius+117.f));XMStoreFloat3(&sun,radial);
94 const auto center=XMVectorSet(chosen.x,chosen.y,chosen.z,0);
95 const auto direction=XMVector3Normalize(center-XMLoadFloat3(&eye));
96 XMFLOAT4X4 view,projection,inverse;
97 XMStoreFloat4x4(&view,XMMatrixLookAtRH(XMVectorZero(),direction,radial));
98 const float nearZ=.0001f,nearWidth=nearZ*std::tan(XMConvertToRadians(115.f)*.5f);
99 XMStoreFloat4x4(&projection,XMMatrixPerspectiveRH(nearWidth,nearWidth*height/width,nearZ,100000.f));
100 XMStoreFloat4x4(&inverse,XMMatrixInverse(nullptr,XMLoadFloat4x4(&view)));
101 const float incident=std::exp(-.5f*std::exp(-params.top/7.5f));
102 const XMFLOAT4 light(240.f/255*incident,245.f/255*incident,incident,1),ambient(.3f,.4f,.5f,1);
103 const XMFLOAT4 glow(.125f,.375f,.25f,1),horizon(.6f,.7f,.8f,CloudVolume::ClearVisibilityKm);
104 const XMFLOAT4 haze(192.f/255,192.f/255,1,CloudVolume::AtmosphericHazeDistanceKm(params.top));
105 D3D11_TEXTURE2D_DESC description{};
106 description.Width=width;description.Height=height;description.MipLevels=description.ArraySize=1;
107 description.SampleDesc={samples,0};description.Format=DXGI_FORMAT_R8G8B8A8_UNORM;description.BindFlags=D3D11_BIND_RENDER_TARGET;
108 ComPtr<ID3D11Texture2D> image;ComPtr<ID3D11RenderTargetView> target;
109 HR(gpu.Device()->CreateTexture2D(&description,nullptr,&image),"lightning fixture image");
110 HR(gpu.Device()->CreateRenderTargetView(image.Get(),nullptr,&target),"lightning fixture target");
111 SceneDepth11 depth;HR(depth.Create(gpu.Device(),width,height,description.SampleDesc),"lightning fixture depth");
112 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};
113 const auto clear=[&] {
114 const float black[]={.002f,.003f,.006f,1};gpu.Context()->ClearRenderTargetView(target.Get(),black);
115 gpu.Context()->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
116 };
117 CloudRenderer11 renderer;
118 HR(renderer.Initialize(gpu.Device(),shaders),"lightning fixture renderer");renderer.SetLightningEnabled(false);
119 renderer.UpdateWeather(weather,60);
120 for(unsigned i=0;i<256 && renderer.WeatherFrame().current!=weather;++i)HR(renderer.PrepareResources(gpu.Context()),"lightning fixture weather upload");
121 Check(renderer.WeatherFrame().current==weather,"lightning fixture weather publication");
122 renderer.UpdateWeather(weather,60);params.weather=renderer.WeatherFrame();
123 clear();HR(renderer.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,eye,params,sun,
124 light,ambient,glow,horizon,haze),"lightning fixture initialize parameters");
125 Check(renderer.Pass().SelectedOrganicPath()==CloudPass11::OrganicPath::Top,"lightning fixture uses actual organic top path");
126 const Parameters11 base=renderer.Parameters();
127 CloudTemporal11::Frame history;
128 history.view=view;history.projection=projection;history.inverseView=inverse;history.eye=eye;history.sun=sun;
129 history.layer={params.radius,params.base,params.top,params.activity};history.light=light;history.ambient=ambient;
130 history.airglow=glow;history.horizon=horizon;history.atmosphere=haze;
131 history.previousWeather=params.weather.previous.get();history.currentWeather=params.weather.current.get();history.weatherBlend=params.weather.blend;
132 CloudPass11 oldPass;
133 if(!reference.empty())
134 {
135 HR(oldPass.Initialize(gpu.Device(),reference),"lightning reference pass");
136 HR(oldPass.ConfigureOrganic(true,true),"lightning reference organic top");oldPass.SetResolutionScale(renderer.Pass().ResolutionScale());
137 }
138 CloudLightning::Flash flash;flash.position=chosen;flash.radius=14;flash.energy=2.8f;
139 uint32_t eventSeed=1;
140 for(uint32_t s=1;s<=64;++s)
141 {
142 CloudLightning::Flash candidate;candidate.position=chosen;candidate.radius=14;candidate.energy=2.8f;candidate.StartChain(params,seed,s);
143 if(candidate.animation.path.count>=flash.animation.path.count){flash=candidate;eventSeed=s;}
145 }
146 using Color=XMFLOAT4;
147 const auto inputs=[&](Point source,bool shaped,unsigned count,float brightness=2.8f,const Parameters11* scene=nullptr) {
148 Parameters11 p=scene ? *scene : base;std::array<Color,CloudLightning::MaxLights> positions{},colors{},shapes{};
149 for(unsigned i=0;i<count;++i)
150 {
151 // Fixed sources are load cases, not natural-event distributions:
152 // four bound diagnostic slots plus natural overlap up to eight.
153 const auto offset=point(east*(float(i%2)*24.f)+north*(float(i/2)*24.f));
154 const auto location=CloudVolume::Add(source,offset);
155 positions[i]={location.x,location.y,location.z,1/(flash.radius*flash.radius)};
156 colors[i]={brightness*.8f,brightness*.88f,brightness,.18f};
157 if(shaped)shapes[i]={flash.axis.x,flash.axis.y,flash.axis.z,flash.width};
158 }
159 p.Set("lightningCount",int(count));p.Set("lightningPosition",positions);p.Set("lightningColor",colors);p.Set("lightningShape",shapes);
160 return p;
161 };
162 uint64_t clock=0;
163 const auto draw=[&](CloudPass11& pass,Parameters11& p,bool transient) {
164 history.milliseconds=clock;clock+=16;history.transientLight=transient;
165 pass.ConfigureTemporal(history,true);
166 HR(pass.Render(gpu.Context(),p,target.Get(),depth,viewport),"lightning direct cloud pass");
167 };
168 std::vector<uint8_t> unlit;
169 uint64_t distanceHash=0,opacityHash=0;
170 std::ofstream metrics(output/"appearance.csv");metrics<<"view,source_altitude_km,lit_pixels,total_added_rgb,distance_hash,opacity_hash\n";
171 const auto capture=[&](const std::string& name,Point source,bool shaped,unsigned count,float brightness=2.8f) {
172 auto p=inputs(source,shaped,count,brightness);renderer.Pass().ResetCloudHistory();clear();draw(renderer.Pass(),p,true);
173 const auto pixels=Pixels(gpu,image.Get());
174 const auto distances=CloudLightningGpuHash(gpu,renderer.Pass().Distance(),false),opacity=CloudLightningGpuHash(gpu,renderer.Pass().Image(),true);
175 if(unlit.empty()){unlit=pixels;distanceHash=distances;opacityHash=opacity;}
176 Check(distances==distanceHash && opacity==opacityHash,"lightning preserves cloud hit depth and opacity");
177 uint64_t gain=0;unsigned visible=0;
178 for(size_t i=0;i<pixels.size();i+=4)
179 {
180 int maximum=0;
181 for(unsigned c=0;c<3;++c){const int delta=int(pixels[i+c])-int(unlit[i+c]);if(delta>0)gain+=uint64_t(delta);maximum=(std::max)(maximum,delta);}
182 if(maximum>=3)++visible;
183 }
184 if(count && brightness>.5f)Check(visible>100,"flash visibly illuminates occupied cloud pixels");
185 HR(SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,(output/(name+".png")).c_str()),"lightning fixture capture");
186 metrics<<name<<','<<CloudVolume::Length(source)-params.radius<<','<<visible<<','<<gain<<','<<distances<<','<<opacity<<'\n';
187 if(!reference.empty() && !shaped)
188 {
189 auto oldInputs=p;oldPass.ResetCloudHistory();clear();draw(oldPass,oldInputs,true);
190 const auto expected=Pixels(gpu,image.Get());
191 Check(expected==pixels,count ? "zeroShape retains old local-light shader output" : "no-light output is byte-identical to reference");
192 }
193 };
194 capture("night-no-light",chosen,false,0);
195 capture("night-old-placement-circular",before,false,1);
196 capture("night-new-placement-circular",chosen,false,1);
197 capture("night-new-placement-shaped",chosen,true,1);
198 capture("night-new-placement-shaped-dim",chosen,true,1,.6f);
199 std::ofstream chain(output/"chain.csv");chain<<"segment,time_s,source_altitude_km,x_km,y_km,z_km,brightness\n";
200 for(int segment=0;segment<flash.animation.path.count;++segment)
201 {
202 CloudLightning::Flash peak=flash;double peakTime=0;
203 for(unsigned sample=1;sample<=100;++sample)
204 {
205 auto current=flash;const double time=current.animation.SegmentStart(segment)+current.animation.boltDuration*sample/101;
206 current.Update(time);if(current.Brightness()>peak.Brightness()){peak=current;peakTime=time;}
207 }
208 capture("night-chain-"+std::to_string(segment),peak.position,true,1,peak.Brightness());
209 chain<<segment<<','<<peakTime<<','<<CloudVolume::Length(peak.position)-params.radius<<','<<peak.position.x<<','<<peak.position.y<<','<<peak.position.z<<','<<peak.Brightness()<<'\n';
210 }
211 // Day context image proves this fixture contains recognizable billows.
212 auto daylight=inputs(chosen,false,0);Color daySun{-sun.x,-sun.y,-sun.z,0};daylight.Set("lightDirection",daySun);
213 renderer.Pass().ResetCloudHistory();clear();const auto nightSun=history.sun;history.sun={daySun.x,daySun.y,daySun.z};draw(renderer.Pass(),daylight,true);history.sun=nightSun;
214 HR(SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,(output/"day-context.png").c_str()),"lightning fixture day context");
215 if(!reference.empty())
216 {
217 // Paired actual shipping passes: a fixed source/camera/density field,
218 // with only sun direction/incident light changed. Compare the added
219 // flash, not absolute image brightness, so a white daytime background
220 // cannot accidentally satisfy the test through output clipping.
221 std::ofstream contrast(output/"daylight-contrast.csv");
222 contrast<<"altitude_km,case,reference_added_rgb,candidate_added_rgb,retained_fraction\n";
223 const auto savedEye=eye;const auto savedView=view;const auto savedHistory=history;
224 CloudPass11 comparison;HR(comparison.Initialize(gpu.Device(),reference),"daylight reference pass");
225 struct LightCase {const char* name;float cosine,incident;bool nvg;};
226 const LightCase cases[]={{"night",-1,1,false},{"night-nvg",-1,1,true},
227 {"unlit-day-geometry",1,0,false},{"dim-incident",1,.02f,false},
228 {"twilight",.03f,1,false},{"sun1",1,1,false}};
229 for(float altitude:{22.f,25.f,117.f,1000.f})
230 {
231 XMStoreFloat3(&eye,sourceUp*(params.radius+altitude));
232 const auto towardSource=XMVector3Normalize(center-XMLoadFloat3(&eye));
233 XMStoreFloat4x4(&view,XMMatrixLookAtRH(XMVectorZero(),towardSource,sourceEast));
234 XMStoreFloat4x4(&inverse,XMMatrixInverse(nullptr,XMLoadFloat4x4(&view)));
235 history.view=view;history.inverseView=inverse;history.eye=eye;
236 double dimRetention=0;
237 for(const auto& c:cases)
238 {
239 XMFLOAT3 incoming;XMStoreFloat3(&incoming,-sourceUp*c.cosine
240 +sourceEast*std::sqrt((std::max)(0.f,1-c.cosine*c.cosine)));
241 const Color incidentLight(light.x*c.incident,light.y*c.incident,light.z*c.incident,1);
242 renderer.Pass().ResetCloudHistory();clear();
243 HR(renderer.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,eye,params,incoming,
244 incidentLight,ambient,glow,horizon,haze),"daylight contrast parameters");
245 auto settings=renderer.Parameters();
246 HR(comparison.ConfigureOrganic(true,renderer.Pass().SelectedOrganicPath()==CloudPass11::OrganicPath::Top),"daylight reference mode");
247 comparison.SetResolutionScale(renderer.Pass().ResolutionScale());
248 history.sun=incoming;history.light=incidentLight;
249 if(c.nvg)settings.Set("nightVisionGain",Color(18.1932316f,23.5441818f,25.6845627f,1));
250 const auto renderFlash=[&](CloudPass11& pass,bool enabled) {
251 auto updated=inputs(chosen,true,enabled ? 1u : 0u,2.8f,&settings);
252 pass.ResetCloudHistory();clear();draw(pass,updated,true);
253 return Pixels(gpu,image.Get());
254 };
255 const auto oldOff=renderFlash(comparison,false),oldOn=renderFlash(comparison,true);
256 const auto off=renderFlash(renderer.Pass(),false),on=renderFlash(renderer.Pass(),true);
257 Check(off==oldOff,"daylight adaptation leaves no-flash cloud appearance byte-identical");
258 uint64_t oldGain=0,newGain=0;unsigned visible=0;
259 for(size_t pixel=0;pixel<on.size();pixel+=4)
260 {
261 Check(on[pixel+3]==off[pixel+3],"daylight flash does not change composite alpha");
262 for(unsigned channel=0;channel<3;++channel)
263 {
264 const int prior=int(oldOn[pixel+channel])-int(oldOff[pixel+channel]);
265 const int now=int(on[pixel+channel])-int(off[pixel+channel]);
266 oldGain+=uint64_t((std::max)(0,prior));newGain+=uint64_t((std::max)(0,now));
267 if(prior>=3)++visible;
268 Check(now<=prior+1,"daylight adaptation cannot increase displayed flash");
269 }
270 }
271 Check(visible>10 && oldGain>100,"contrast fixture contains visible lightning");
272 const double retained=double(newGain)/double(oldGain);
273 if(c.cosine<0 || c.incident==0)Check(on==oldOn,"night and zero solar illumination preserve flash exactly, including NVG");
274 if(c.incident==.02f)dimRetention=retained;
275 if(c.cosine==1 && c.incident==1)
276 {
277 Check(newGain>0 && retained<.35,"direct sun substantially reduces flash without disabling it");
278 Check(dimRetention>retained*1.5,"dim cloud illumination retains more flash contrast than full sun");
279 }
280 const auto label=std::to_string(int(altitude))+"km-"+c.name;
281 contrast<<altitude<<','<<c.name<<','<<oldGain<<','<<newGain<<','<<retained<<'\n';contrast.flush();
282 if(c.cosine==1 && c.incident==1)
283 {
284 HR(SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,(output/(label+"-after.png")).c_str()),"daylight contrast candidate capture");
285 renderFlash(comparison,true);
286 HR(SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,(output/(label+"-before.png")).c_str()),"daylight contrast reference capture");
287 }
288 }
289 }
290 Check(contrast.good(),"daylight contrast evidence saved");
291 eye=savedEye;view=savedView;history=savedHistory;
292 HR(renderer.Pass().ConfigureOrganic(true,true),"restore lightning timing mode");
293 std::cout<<"PASS: paired day/night/NVG cloud-flash contrast at 22, 25, 117 and 1000 km\n";
294 }
295 DebugMessages(gpu);
296 // No screenshot, staging readback, or source search occurs between these
297 // timestamp pairs. Warm up each steady state and collect a queued batch.
298 std::ofstream timing(output/"timings.csv");timing<<"case,width,height,msaa,lights,frames,mean_ms,p95_ms,max_ms,over_12_ms\n";
299 struct Query {ComPtr<ID3D11Query> frequency,begin,end;};
300 for(unsigned count:{0u,1u,4u,8u})
301 {
302 auto p=inputs(chosen,true,count);renderer.Pass().ResetCloudHistory();
303 for(unsigned warm=0;warm<32;++warm){clear();draw(renderer.Pass(),p,count!=0);}
304 std::vector<Query> queries(240);
305 for(auto& q:queries)
306 {
307 D3D11_QUERY_DESC d{D3D11_QUERY_TIMESTAMP_DISJOINT,0};HR(gpu.Device()->CreateQuery(&d,&q.frequency),"lightning timing frequency");
308 d.Query=D3D11_QUERY_TIMESTAMP;HR(gpu.Device()->CreateQuery(&d,&q.begin),"lightning timing begin");HR(gpu.Device()->CreateQuery(&d,&q.end),"lightning timing end");
309 clear();gpu.Context()->Begin(q.frequency.Get());gpu.Context()->End(q.begin.Get());draw(renderer.Pass(),p,count!=0);
310 gpu.Context()->End(q.end.Get());gpu.Context()->End(q.frequency.Get());
311 }
312 gpu.Context()->Flush();std::vector<double> milliseconds;
313 const auto wait=[&](ID3D11Query* q,void* value,UINT bytes) {
314 const auto deadline=GetTickCount64()+30000;HRESULT result;
315 while((result=gpu.Context()->GetData(q,value,bytes,0))==S_FALSE){Check(GetTickCount64()<deadline,"lightning timestamp timeout");Sleep(1);}
316 HR(result,"lightning timestamp readback");
317 };
318 for(const auto& q:queries)
319 {
320 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT f{};UINT64 a=0,b=0;
321 wait(q.frequency.Get(),&f,sizeof(f));wait(q.begin.Get(),&a,sizeof(a));wait(q.end.Get(),&b,sizeof(b));
322 if(!f.Disjoint)milliseconds.push_back(1000.*double(b-a)/double(f.Frequency));
323 }
324 Check(milliseconds.size()>=200,"enough valid lightning timing samples");
325 double sum=0;for(const auto ms:milliseconds)sum+=ms;std::sort(milliseconds.begin(),milliseconds.end());
326 const double mean=sum/milliseconds.size(),p95=milliseconds[size_t(std::ceil(milliseconds.size()*.95)-1)];
327 timing<<"night-fixed-load-"<<count<<"-lights,"<<width<<','<<height<<','<<samples<<','<<count<<','<<milliseconds.size()<<','<<mean<<','<<p95<<','<<milliseconds.back()<<','
328 <<std::count_if(milliseconds.begin(),milliseconds.end(),[](double ms){return ms>12;})<<'\n';
329 std::cout<<"lightning "<<count<<" lights: "<<mean<<" ms mean, "<<p95<<" ms p95\n";
330 }
331 std::ofstream settings(output/"settings.txt");settings.precision(9);
332 settings<<"Deterministic regression fixture; constant 255 convection, not representative live weather.\n"
333 <<"viewport="<<width<<'x'<<height<<" msaa="<<samples<<" cloud_scale="<<renderer.Pass().ResolutionScale()<<"\n"
334 <<"latitude="<<latitude<<" longitude="<<longitude<<" altitude_km=117 seed="<<seed<<" event_seed="<<eventSeed<<"\n"
335 <<"source_old="<<before.x<<','<<before.y<<','<<before.z<<"\nsource_new="<<chosen.x<<','<<chosen.y<<','<<chosen.z<<"\n"
336 <<"source_depth_fraction=1 sphere_column="<<selectedColumn<<" occupied_top="<<occupiedTop<<" occupied_bottom="<<occupiedBottom<<"\n"
337 <<"source_latitude="<<XMConvertToDegrees(std::asin(sourceNormal.z))<<" source_longitude="<<XMConvertToDegrees(std::atan2(-sourceNormal.x,sourceNormal.y))<<"\n"
338 <<"radius_km="<<flash.radius<<" energy="<<flash.energy<<" shape="<<flash.axis.x<<','<<flash.axis.y<<','<<flash.axis.z<<','<<flash.width<<"\n"
339 <<"cloud_base="<<params.base<<" cloud_nominal_top="<<params.top<<" planet_radius="<<params.radius<<"\n"
340 <<"eye="<<eye.x<<','<<eye.y<<','<<eye.z<<"\nsun="<<sun.x<<','<<sun.y<<','<<sun.z<<"\nview=";
341 for(unsigned r=0;r<4;++r)for(unsigned c=0;c<4;++c)settings<<view.m[r][c]<<',';
342 settings<<"\nprojection=";for(unsigned r=0;r<4;++r)for(unsigned c=0;c<4;++c)settings<<projection.m[r][c]<<',';
343 settings<<"\nTiming sources use offsets east=(index%2)*24 km, north=(index/2)*24 km; 0/1/4/8 fixed simultaneous lights.\n"
344 <<"Eight lights exercise natural-plus-diagnostic overlap as a load case, not a natural-event sample or new rate.\n"
345 <<"No screenshot readbacks in measured timestamp regions; setup/first-use excluded.\n";
346 Check(metrics.good() && chain.good() && timing.good() && settings.good(),"lightning fixture evidence saved");
347 DebugMessages(gpu);std::cout<<"PASS: deterministic organic lightning images, invariance checks, and isolated GPU timings\n";
348}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
Point SourcePosition(const Point &normal, const CloudVolume::Parameters &params, uint32_t cloudSeed, float depthFraction)
Point Scale(Point p, float s)
Definition CloudVolume.h:93
float AtmosphericHazeDistanceKm(float nominalTop)
Point Add(Point a, Point b)
Definition CloudVolume.h:95
constexpr float ClearVisibilityKm
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
void BuildMips(Map &map)
Definition DDS.h:24
DIRECTX_TOOLKIT_API HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, _In_ REFGUID guidContainerFormat, _In_z_ const wchar_t *fileName, _In_opt_ const GUID *targetFormat=nullptr, _In_ std::function< void __cdecl(IPropertyBag2 *)> setCustomProps=nullptr, _In_ bool forceSRGB=false)
constexpr int MaxChainedBolts
constexpr uint8_t Pixels[262144]
Distance Query(const Hull &h, const Pose &p, const Triangle &t)
Definition RigidProp.h:116
uint32_t Color(Echo echo)
LightningChain::Animation animation
void StartChain(const CloudVolume::Parameters &params, uint32_t cloudSeed, uint32_t eventSeed, double elapsed=0)
float Brightness() const
CloudWeather::Frame weather
Definition CloudVolume.h:35
double SegmentStart(int index) const