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

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

1#include "../Viewscreen/SpatialFogWeather.h"
2
3// Real native scene/depth tests: clear observer, directional storm, visibility,
4// terrain/base clipping, lightning, and original cockpit/MSAA samples.
5namespace
6{
7 void TestRainCurtains(Device11& gpu,CloudRenderer11& renderer,UINT samples)
8 {
9 if(!gpu.SupportsSamples(samples))return;
10 Pipeline pipeline(gpu.Device(),samples);Scene scene(gpu.Device(),samples),reference(gpu.Device(),samples);
11 CloudVolume::Parameters cloud;cloud.base=80;cloud.top=90;
12 XMFLOAT4X4 view,projection;
13 XMStoreFloat4x4(&view,XMMatrixIdentity());
14 XMStoreFloat4x4(&projection,XMMatrixPerspectiveFovRH(1.f,float(Width)/Height,.001f,384));
15 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};
16 auto grid=std::make_unique<CloudRenderer11::RainGrid>();
17 grid->cube=0;grid->u=grid->v=1019;grid->revision=1;
18 grid->cells.fill({0,3,42.16f,2});
19 constexpr char slopeSource[]=R"(
20float4 RainSlope(uint vertex:SV_VertexID):SV_Position
21{
22 float4 p=float4(vertex==2 ? 3 : -1,vertex==1 ? 3 : -1,0,1);
23 p.z=.99984+.0001*p.y;
24 return p;
25})";
26 ComPtr<ID3DBlob> slopeCode;
27 HR(D3DCompile(slopeSource,strlen(slopeSource),"RainSlope",nullptr,nullptr,"RainSlope","vs_5_0",
28 D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&slopeCode,nullptr),"rain slope compile");
29 ComPtr<ID3D11VertexShader> slope;
30 HR(gpu.Device()->CreateVertexShader(slopeCode->GetBufferPointer(),slopeCode->GetBufferSize(),nullptr,&slope),"rain slope VS");
31 const auto render=[&](Scene& target,float distance,float background,bool flash=false,bool sloped=false,
32 float altitude=1.f,XMFLOAT3 bolt={7,3,-14},float strength=1.f)
33 {
34 target.Clear(gpu.Context());
35 const float color[]={background,background,background,1};
36 gpu.Context()->ClearRenderTargetView(target.target.Get(),color);
37 gpu.Context()->ClearDepthStencilView(target.depth.WriteView(),D3D11_CLEAR_DEPTH,
38 -projection._33+projection._43/distance,0);
39 if(sloped)
40 {
41 auto* context=gpu.Context();auto* output=target.target.Get();context->ClearState();
42 context->OMSetRenderTargets(1,&output,target.depth.WriteView());
43 context->RSSetState(pipeline.raster.Get());context->RSSetViewports(1,&viewport);
44 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
45 context->VSSetShader(slope.Get(),nullptr,0);context->PSSetShader(pipeline.black.Get(),nullptr,0);
46 context->OMSetDepthStencilState(pipeline.foreground.Get(),0);context->Draw(3,0);
47 context->OMSetRenderTargets(0,nullptr,nullptr);
48 }
49 renderer.SetRainGrid(grid.get());renderer.SetLightningEnabled(flash);
50 renderer.SetLocalLightning({bolt.x,cloud.radius+bolt.y,bolt.z},{strength,strength,strength,1},12,
51 {bolt.x,cloud.radius,bolt.z});
52 HR(renderer.Render(gpu.Context(),target.target.Get(),target.depth,viewport,view,projection,
53 {0,cloud.radius+altitude,0},cloud,{0,-1,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{.3f,.3f,.3f,42.16f}),
54 "rain scene draw");
55 return pipeline.Pixels(gpu,target,samples);
56 };
57 const auto center=(Height/2*Width+Width/2)*samples;
58 // The predicted CPU field must move actual fog pixels, while fresh
59 // snapshots preserve the visible field and then converge smoothly.
60 auto fogSource=std::make_shared<SpatialFogWeather::Grid>();
61 fogSource->cube=0;fogSource->u=fogSource->v=1019;fogSource->revision=1;
62 for(int y=0;y<64;++y)for(int x=0;x<64;++x)
63 fogSource->cells[y*64+x]={x<=30 ? 1.5f : 42.16f,2};
64 SpatialFogWeather::Store moving;moving.Accept(fogSource,true);
65 const auto pack=[&] {
66 for(int y=0;y<64;++y)for(int x=0;x<64;++x)
67 {
68 const auto fog=moving.Sample(SpatialFogWeather::Direction(0,1019+x-31,1019+y-31));
69 grid->cells[y*64+x]={0,3,fog.visibility,fog.precipitation};
70 }
71 };
72 pack();const auto beforeMotion=render(scene,20,1);
73 moving.Advance(120,{0,-(cloud.radius+1),0},{.06,0,0});
74 pack();const auto afterMotion=render(scene,20,1);
75 Check(beforeMotion[center].color[0]-afterMotion[center].color[0]>.2f,
76 "Weather1 prediction must move spatial fog through a stationary view");
77 auto clearSnapshot=std::make_shared<SpatialFogWeather::Grid>(*fogSource);
78 clearSnapshot->cells.fill({42.16f,2});clearSnapshot->revision=2;
79 moving.Accept(clearSnapshot,true);pack();const auto arrival=render(scene,20,1);
80 Check(std::abs(arrival[center].color[0]-afterMotion[center].color[0])<1.01f/255,
81 "full snapshot caused a visible fog jump");
82 moving.Advance(5,{0,-(cloud.radius+1),0},{});pack();const auto middle=render(scene,20,1);
83 moving.Advance(5,{0,-(cloud.radius+1),0},{});pack();const auto settled=render(scene,20,1);
84 Check(middle[center].color[0]>arrival[center].color[0]+.01f &&
85 middle[center].color[0]<settled[center].color[0]-.01f,
86 "fog snapshot did not reconcile progressively in native rendering");
87 if(samples==1)
88 {
89 std::filesystem::create_directories("Output");
90 std::ofstream preview("Output/spatial-fog-motion.ppm",std::ios::binary);
91 preview<<"P6\n"<<Width*3<<" "<<Height<<"\n255\n";
92 for(UINT y=0;y<Height;++y)for(const auto* frame:{&beforeMotion,&afterMotion,&settled})
93 for(UINT x=0;x<Width;++x)for(unsigned c=0;c<3;++c)
94 preview.put(char(std::lround(std::clamp((*frame)[y*Width+x].color[c],0.f,1.f)*255)));
95 std::cout<<"Spatial fog motion/reconciliation: "<<beforeMotion[center].color[0]<<" -> "
96 <<afterMotion[center].color[0]<<" -> "<<middle[center].color[0]<<" -> "<<settled[center].color[0]<<std::endl;
97 }
98 // A zero ceiling is valid ground-level cloud, not absent weather.
99 // Automatic visibility must follow the uniform VIS distance ramp near
100 // the surface and remain effective while climbing through clear gaps
101 // below the separately rendered cloud deck. The manual path applies
102 // that ramp in the geometry shader, absent from this depth-only scene.
103 double overrideDifference=0;
104 const auto horizon=((Height/2-1)*Width+Width/2)*samples;
105 const double centerRayLength=sqrt(1+pow(1./Width/projection._11,2)+pow(1./Height/projection._22,2));
106 for(float surface:{0.f,.048f,2.f})for(float ceiling:{0.f,.02f})for(float agl:{0.f,.006f,.162f,.4f})
107 {
108 const float altitude=surface+agl;
109 grid->cells.fill({surface,surface+ceiling,.75f,2});
110 const float visibility=CloudVolume::AtmosphericVisibility(.75f,altitude,surface,10);
111 for(float fraction:{.25f,.75f,1.2f})
112 {
113 const auto automatic=render(scene,visibility*fraction,1,false,false,altitude);
114 const double distance=double(projection._43)/double(automatic[horizon].depth+projection._33)*centerRayLength;
115 const double expected=1-.7*std::min(1.,distance/visibility);
116 overrideDifference=std::max(overrideDifference,
117 std::abs(automatic[horizon].color[0]-expected));
118 }
119 }
120 std::cout<<"Reported visibility ramp maximum error: "<<overrideDifference*255<<"/255"<<std::endl;
121 Check(overrideDifference<2.01/255,"zero/low ceilings must preserve reported visibility on the ground and during climb");
122 grid->cells.fill({0,0,.75f,2});
123 const auto aboveAtmosphere=render(scene,20,1,false,false,11);
124 Check(aboveAtmosphere[center].color[0]>254.f/255,"weather fog must clear above the atmosphere");
125 // A nearby BOLT must light 750 m fog even without rainfall. A low/zero
126 // weather ceiling does not remove the air between observer and strike.
127 for(float ceiling:{0.f,.02f,3.f})for(float precipitation:{2.f,16.f})
128 {
129 grid->cells.fill({0,ceiling,.75f,precipitation});
130 const XMFLOAT3 bolt{.3f,3,-1};
131 const auto dark=render(scene,4,0,false,false,.006f,bolt,.4f);
132 const auto bright=render(scene,4,0,true,false,.006f,bolt,.4f);
133 const auto white=render(scene,4,1,true,false,.006f,bolt,.4f);
134 Check(bright[center].color[0]-dark[center].color[0]>.04f,
135 "750 m dry and wet fog must scatter a nearby lightning flash");
136 Check(std::abs(white[center].color[0]-bright[center].color[0])<1.01f/255,
137 "illuminated fog must still hide terrain beyond visibility");
138 const auto foregroundDark=render(scene,.003f,0,false,false,.006f,bolt,.4f);
139 const auto foregroundBright=render(scene,.003f,0,true,false,.006f,bolt,.4f);
140 Check(foregroundBright[center].color[0]-foregroundDark[center].color[0]<1.01f/255,
141 "lightning fog must stop at nearby opaque surfaces");
142 const auto distantFog=render(scene,4,0,true,false,.006f,{0,3,-40},.4f);
143 Check(std::abs(distantFog[center].color[0]-dark[center].color[0])<1.01f/255,
144 "dense fog must extinguish incoming light from distant strikes");
145 Check(render(scene,4,0,false,false,.006f,bolt,.4f)[center].color[0]==dark[center].color[0],
146 "fog returns to its original color when the flash ends");
147 if(samples==1 && ceiling==3 && precipitation==2)
148 {
149 std::filesystem::create_directories("outputs/rain-curtains");
150 std::ofstream preview("outputs/rain-curtains/lightning-fog-750.ppm",std::ios::binary);
151 preview<<"P6\n"<<Width*2<<" "<<Height<<"\n255\n";
152 for(UINT y=0;y<Height;++y)for(const auto* frame:{&dark,&bright})
153 for(UINT x=0;x<Width;++x)for(unsigned c=0;c<3;++c)
154 preview.put(char(std::lround(std::clamp((*frame)[y*Width+x].color[c],0.f,1.f)*255)));
155 std::cout<<"750 m dry fog flash: "<<dark[center].color[0]<<" -> "<<bright[center].color[0]<<std::endl;
156 }
157 }
158 grid->cells.fill({0,3,42.16f,2});
159 auto clear=render(scene,20,1);
160 // Reconstructed forward Z is slightly quantized; compute the actual ray.
161 const float z=-projection._33+projection._43/20;
162 const float actual=projection._43/(z+projection._33);
163 const float expected=1-.7f*actual/CloudVolume::AtmosphericVisibility(42.16f,1,0,10);
164 Check(std::abs(clear[center].color[0]-expected)<2.f/255,"uniform visibility is applied once");
165 auto clearNear=render(scene,4,1);
166 for(int v=34;v<=46;++v)for(int u=22;u<=29;++u)grid->cells[v*64+u]={0,3,3,16};
167 auto storm=render(scene,20,1);
168 auto foregroundRain=render(scene,4,1);
169 const auto right=(Height/2*Width+Width*3/4)*samples;
170 const auto left=(Height/2*Width+Width/4)*samples;
171 Check(clear[right].color[0]-storm[right].color[0]>.25f,"right-hand storm must hide distant terrain");
172 Check(std::abs(clear[left].color[0]-storm[left].color[0])<1.01f/255,"storm must not fog opposite bearing");
173 Check(std::abs(clearNear[right].color[0]-foregroundRain[right].color[0])<1.01f/255,"foreground before storm stays clear");
174 auto lit=render(scene,20,1,true);
175 if(samples==1)
176 {
177 const auto directory=std::filesystem::path("outputs/rain-curtains");
178 std::filesystem::create_directories(directory);
179 std::ofstream preview(directory/"clear-storm-lightning.ppm",std::ios::binary);
180 preview<<"P6"<<char(10)<<Width*3<<" "<<Height<<char(10)<<"255"<<char(10);
181 for(UINT y=0;y<Height;++y)for(const auto* frame:{&clear,&storm,&lit})
182 for(UINT x=0;x<Width;++x)for(unsigned c=0;c<3;++c)
183 preview.put(char(std::lround(std::clamp((*frame)[y*Width+x].color[c],0.f,1.f)*255)));
184 }
185 Check(lit[right].color[0]-storm[right].color[0]>.03f,"lightning must illuminate storm curtain");
186 Check(lit[right].color[0]-storm[right].color[0]>lit[left].color[0]-storm[left].color[0]+.02f,
187 "lightning glow must preserve storm bearing");
188 // Keep every sampled surface above the ray: interpolating between a
189 // 0 km and 5 km floor would include genuinely exposed weather cells.
190 for(auto& cell:grid->cells){cell.x=5;cell.y=8;}
191 auto elevated=render(scene,20,1);
192 Check(std::abs(elevated[right].color[0]-clear[right].color[0])<1.01f/255,"curtain must not extend below cell surface");
193 for(auto& cell:grid->cells){cell.x=0;cell.y=.1f;}
194 auto low=render(scene,20,1);
195 for(auto& cell:grid->cells){cell.y=3;cell.w=2;}
196 auto dryStorm=render(scene,20,1);
197 Check(std::abs(low[right].color[0]-dryStorm[right].color[0])<1.01f/255,
198 "cloud base stops precipitation tint, not weather visibility");
199 Check(clear[right].color[0]-low[right].color[0]>.25f,"low ceilings must retain distant storm obscuration");
200 // Compare transmission with identical visibility but different rain.
201 grid->cells.fill({0,3,10,2});
202 const auto dryWhite=render(scene,4,1),dryBlack=render(scene,4,0);
203 grid->cells.fill({0,3,10,16});
204 const auto wetWhite=render(scene,4,1),wetBlack=render(scene,4,0);
205 Check(std::abs((dryWhite[center].color[0]-dryBlack[center].color[0])-
206 (wetWhite[center].color[0]-wetBlack[center].color[0]))<2.01f/255,"rain must not add a second visibility penalty");
207 for(UINT x=Width/4;x<Width/2;++x)
208 Check(std::abs(wetBlack[(Height/2*Width+x)*samples].color[0]-
209 wetBlack[(Height/2*Width+Width-1-x)*samples].color[0])<1.01f/255,
210 "uniform rain must not paint repeated directional stripes");
211 // Missing controls are clear fallback; they never divide by zero.
212 grid->cells.fill({});
213 const auto unavailable=render(scene,20,1);
214 Check(std::abs(unavailable[center].color[0]-clear[center].color[0])<1.01f/255,"unavailable weather uses clear fallback");
215
216 // Grazing terrain exposes integration slices as horizontal ribbons.
217 // Compare real depth-limited rendering to fine independent quadrature,
218 // including terrain crossings and the continuous altitude profile.
219 grid->cells.fill({.9f,1.1f,3,2});
220 const auto shallow=render(scene,8,0,false,true);
221 if(samples==1)
222 {
223 std::ofstream preview("outputs/rain-curtains/shallow-layer.ppm",std::ios::binary);
224 preview<<"P6\n"<<Width<<" "<<Height<<"\n255\n";
225 for(const auto& pixel:shallow)for(unsigned c=0;c<3;++c)
226 preview.put(char(std::lround(std::clamp(pixel.color[c],0.f,1.f)*255)));
227 }
228 const auto smooth=[](double low,double high,double value) {
229 const double t=std::clamp((value-low)/(high-low),0.,1.);
230 return t*t*(3-2*t);
231 };
232 const auto visibility=[&](double ground,double altitude,double surface) {
233 return ground+(168.64-ground)*smooth(surface,10,altitude);
234 };
235 double maximumError=0;
236 for(UINT y=12;y<Height-12;++y)
237 {
238 const UINT x=Width/2;
239 const auto& pixel=shallow[(y*Width+x)*samples];
240 const double dx=(2*(x+.5)/Width-1)/projection._11;
241 const double dy=(1-2*(y+.5)/Height)/projection._22;
242 const double rayLength=sqrt(dx*dx+dy*dy+1);
243 const double distance=double(projection._43)/double(pixel.depth+projection._33)*rayLength;
244 constexpr unsigned steps=8192;
245 const double ds=distance/steps;
246 double opacity=0;
247 for(unsigned i=0;i<steps;++i)
248 {
249 const double along=(i+.5)*ds/rayLength;
250 const double radius=double(cloud.radius)+1+dy*along;
251 const double altitude=sqrt(radius*radius+(dx*dx+1)*along*along)-cloud.radius;
252 const double column=smooth(.875,.9,altitude);
253 opacity+=ds*((1-column)/visibility(42.16,altitude,0)+column/visibility(3,altitude,.9));
254 }
255 maximumError=std::max(maximumError,std::abs(pixel.color[0]-.3*std::min(1.,opacity)));
256 }
257 std::cout<<"Terrain weather boundary maximum error: "<<maximumError*255<<"/255"<<std::endl;
258 Check(maximumError<2.5/255,"weather must fade continuously without horizontal sampling ribbons");
259
260 grid->cells.fill({0,3,10,16});renderer.SetRainGrid(grid.get());
261 renderer.SetLocalLightning({.3f,cloud.radius+3,-1},{.4f,.4f,.4f,1},12,{.3f,cloud.radius,-1});
262 const auto draw=[&](Scene& target)
263 {
264 HR(renderer.Render(gpu.Context(),target.target.Get(),target.depth,viewport,view,projection,
265 {0,cloud.radius+1,0},cloud,{0,-1,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{.3f,.3f,.3f,42.16f}),"rain masking draw");
266 };
267 for(bool flash:{false,true})
268 {
269 renderer.SetLightningEnabled(flash);
270 scene.Clear(gpu.Context());reference.Clear(gpu.Context());
271 pipeline.Occlude(gpu,scene);const auto before=pipeline.Pixels(gpu,scene,samples);
272 draw(reference);const auto referencePixels=pipeline.Pixels(gpu,reference,samples);
273 draw(scene);const auto after=pipeline.Pixels(gpu,scene,samples);
274 Protected(before,after,referencePixels,samples);
275 }
276 renderer.SetLightningEnabled(false);
277 renderer.SetRainGrid(nullptr);
278 Check(!renderer.HasRainGrid(1,0,1019,1019),"disabled grid must not retain render generation");
279 DebugMessages(gpu);
280 std::cout<<"PASS: spatial rain, direct visibility, surface/ceiling, lightning, foreground/cockpit "<<samples<<"x"<<std::endl;
281 }
282}
283
284namespace
285{
286 void BenchmarkRainCurtains(Device11& gpu,CloudRenderer11& renderer)
287 {
288 constexpr UINT width=1920,height=1080,samples=4,batch=8;
289 Scene scene(gpu.Device(),samples,width,height);
290 CloudVolume::Parameters cloud;cloud.base=1.8f;
291 XMFLOAT4X4 view,projection;
292 XMStoreFloat4x4(&view,XMMatrixIdentity());
293 XMStoreFloat4x4(&projection,XMMatrixPerspectiveFovRH(1.f,float(width)/height,.001f,384));
294 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};
295 auto grid=std::make_unique<CloudRenderer11::RainGrid>();
296 grid->cube=0;grid->u=grid->v=1019;grid->revision=1;grid->cells.fill({0,3,42.16f,2});
297 for(int v=34;v<=46;++v)for(int u=22;u<=29;++u)grid->cells[v*64+u]={0,3,3,16};
298 ComPtr<ID3D11Query> disjoint,begin,end;
299 D3D11_QUERY_DESC description{D3D11_QUERY_TIMESTAMP_DISJOINT,0};
300 HR(gpu.Device()->CreateQuery(&description,&disjoint),"rain timer");
301 description.Query=D3D11_QUERY_TIMESTAMP;
302 HR(gpu.Device()->CreateQuery(&description,&begin),"rain timer begin");
303 HR(gpu.Device()->CreateQuery(&description,&end),"rain timer end");
304 auto* context=gpu.Context();
305 renderer.SetLightningEnabled(false);
306 for(int mode=0;mode<2;++mode)
307 {
308 renderer.SetRainGrid(mode ? grid.get() : nullptr);
309 scene.Clear(context);
310 context->ClearDepthStencilView(scene.depth.WriteView(),D3D11_CLEAR_DEPTH,
311 -projection._33+projection._43/20,0);
312 const auto draw=[&] {
313 HR(renderer.Render(context,scene.target.Get(),scene.depth,viewport,view,projection,
314 {0,cloud.radius+1,0},cloud,{0,-1,0},{1,1,1,1},{.3f,.4f,.5f,1},
315 {.125f,.375f,.25f,1},{.3f,.3f,.3f,42.16f}),"rain benchmark draw");
316 };
317 for(unsigned warm=0;warm<3;++warm)draw();
318 context->Begin(disjoint.Get());context->End(begin.Get());
319 for(unsigned frame=0;frame<batch;++frame)draw();
320 context->End(end.Get());context->End(disjoint.Get());context->Flush();
321 const auto read=[&](ID3D11Query* query,void* data,UINT bytes) {
322 const auto deadline=GetTickCount64()+30000;HRESULT hr;
323 while((hr=context->GetData(query,data,bytes,0))==S_FALSE) {
324 if(GetTickCount64()>deadline)throw std::runtime_error("rain timer timeout");
325 Sleep(1);
326 }
327 HR(hr,"rain timer read");
328 };
329 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT frequency{};UINT64 first=0,last=0;
330 read(disjoint.Get(),&frequency,sizeof(frequency));read(begin.Get(),&first,sizeof(first));read(end.Get(),&last,sizeof(last));
331 Check(!frequency.Disjoint,"rain timer disjoint");
332 std::cout<<"1920x1080 4x cloud+fog "<<(mode ? "spatial" : "uniform")<<" "<<
333 double(last-first)*1000/frequency.Frequency/batch<<" ms"<<std::endl;
334 }
335 renderer.SetRainGrid(nullptr);
336 }
337}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
void Advance(double elapsed, Point physicalPosition, Point physicalWindKms)
void Accept(GridPtr next, bool full)
Cell Sample(Point renderPosition) const
Definition grid.h:14
char cube
Definition grid.h:45
float AtmosphericVisibility(float surfaceVisibility, float altitude, float surfaceAltitude, float clearAltitude)
constexpr float Width
constexpr float Height
Point Direction(int cube, double u, double v)