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

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

1// Exercise the production ground texture, cloud marcher and haze together.
2// Capture both shader versions with the same camera, weather and plot lights.
3static std::vector<float> CloudCityDistances(Device11& gpu,ID3D11ShaderResourceView* view,UINT width,UINT height)
4{
5 ComPtr<ID3D11Resource> resource;view->GetResource(&resource);
6 ComPtr<ID3D11Texture2D> texture;HR(resource.As(&texture),"city distance texture");
7 D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
8 Check(desc.Width==width && desc.Height==height && desc.Format==DXGI_FORMAT_R32G32_FLOAT,"city distance dimensions");
9 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=desc.MiscFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
10 ComPtr<ID3D11Texture2D> staging;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"city distance staging");
11 gpu.Context()->CopyResource(staging.Get(),texture.Get());
12 D3D11_MAPPED_SUBRESOURCE mapped{};HR(gpu.Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"city distance readback");
13 std::vector<float> result(size_t(width)*height);
14 for(UINT y=0;y<height;++y)
15 {
16 const auto* row=reinterpret_cast<const float*>(static_cast<const char*>(mapped.pData)+size_t(y)*mapped.RowPitch);
17 for(UINT x=0;x<width;++x)result[size_t(y)*width+x]=row[x*2];
18 }
19 gpu.Context()->Unmap(staging.Get(),0);return result;
20}
21
22static void CloudCityLighting(Device11& gpu,const fs::path& shaders,const fs::path& reference,const fs::path& output,const fs::path& capture={})
23{
24 using namespace DirectX;
25 // The CPU horizon is fed back into the shader. Its blend must be
26 // idempotent and let different sources win in different RGB channels.
27 const auto natural=CloudVolume::WithAirglow({},{.125f,.375f,.25f},-1,1.8f,1.8f,10);
28 const auto twice=CloudVolume::WithAirglow(natural,{.125f,.375f,.25f},-1,1.8f,1.8f,10);
29 Check(natural.x==twice.x && natural.y==twice.y && natural.z==twice.z,"horizon must not add airglow twice");
30 const auto mixed=CloudVolume::WithAirglow({.5f,0,.5f},{.125f,.375f,.25f},-1,1.8f,1.8f,10);
31 Check(mixed.x==.5f && mixed.y==natural.y && mixed.z==.5f,"horizon chooses the strongest source per channel");
32 const auto bright=CloudVolume::WithAirglow({.8f,.8f,.8f},{.125f,.375f,.25f},-1,1.8f,1.8f,10);
33 Check(bright.x==.8f && bright.y==.8f && bright.z==.8f,"weaker airglow must not brighten bcllight");
34 fs::create_directories(output);
35 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS","1");SetEnvironmentVariableA("RISE_CLOUD_SEED","0x52495345");
36 CloudRenderer11 candidate,baseline;
37 HR(candidate.Initialize(gpu.Device(),shaders),"city candidate renderer");
38 HR(baseline.Initialize(gpu.Device(),reference),"city baseline renderer");
39 candidate.SetLightningEnabled(false);baseline.SetLightningEnabled(false);
40 const bool captured=!capture.empty();
41 const UINT width=captured ? 1280 : 960,height=captured ? 502 : 540;
42 D3D11_TEXTURE2D_DESC desc{};desc.Width=width;desc.Height=height;desc.MipLevels=desc.ArraySize=1;
43 desc.SampleDesc={1,0};desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
44 ComPtr<ID3D11Texture2D> image;ComPtr<ID3D11RenderTargetView> target;
45 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&image),"city fixture image");
46 HR(gpu.Device()->CreateRenderTargetView(image.Get(),nullptr,&target),"city fixture target");
47 SceneDepth11 depth;HR(depth.Create(gpu.Device(),width,height,desc.SampleDesc),"city fixture depth");
48 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};
49 XMFLOAT4X4 view,projection;
50 XMStoreFloat4x4(&view,XMMatrixLookAtRH(XMVectorZero(),XMVectorSet(1,.08f,0,0),XMVectorSet(0,1,0,0)));
51 XMStoreFloat4x4(&projection,XMMatrixPerspectiveFovRH(XMConvertToRadians(60),float(width)/height,.0001f,100000));
53 XMFLOAT3 eye{0,params.radius+.05f,0},capturedSun{};
54 XMFLOAT4 capturedHaze{},capturedAmbient{},capturedHorizon{},capturedDirect{};
55 CloudVolume::GroundLighting capturedGround;
56 float capturedVisibility=0;
57 if(captured)
58 {
59 std::ifstream inputs(capture/"deois-view.bin",std::ios::binary);
60 const auto read=[&](auto& value){inputs.read(reinterpret_cast<char*>(&value),sizeof(value));};
61 read(eye);read(params.radius);read(params.base);read(params.top);read(params.activity);read(params.noiseOffset);
62 read(capturedSun);read(view);read(projection);read(capturedHaze);read(capturedAmbient);
63 read(capturedVisibility);read(capturedHorizon);read(capturedDirect);
64 Check(inputs.good() && inputs.peek()==std::char_traits<char>::eof(),"complete captured cloud inputs");
65 const float attenuation=std::exp(-.5f*std::exp(-params.top/7.5f));
66 capturedDirect.x*=attenuation;capturedDirect.y*=attenuation;capturedDirect.z*=attenuation;
67 capturedHaze.w=capturedVisibility;capturedHorizon.w=CloudVolume::AtmosphericHazeDistanceKm(params.top);
68 std::ifstream groundFile(capture/"deois-ground.bin",std::ios::binary);
69 std::array<uint32_t,64*64> packedGround{};
70 groundFile.read(reinterpret_cast<char*>(packedGround.data()),sizeof(packedGround));
71 for(size_t i=0;i<packedGround.size();++i)
72 {
73 const auto rgb=packedGround[i];
74 capturedGround.pixels[i]={float((rgb>>16)&255)/255,float((rgb>>8)&255)/255,float(rgb&255)/255};
75 }
76 groundFile.read(reinterpret_cast<char*>(&capturedGround.cube),sizeof(int));
77 groundFile.read(reinterpret_cast<char*>(&capturedGround.u),sizeof(int));
78 groundFile.read(reinterpret_cast<char*>(&capturedGround.v),sizeof(int));
79 Check(groundFile.good() && groundFile.peek()==std::char_traits<char>::eof(),"complete captured ground inputs");
80 if(fs::exists(capture/"deois-radiance.bin"))
81 {
82 std::ifstream radianceFile(capture/"deois-radiance.bin",std::ios::binary);
83 radianceFile.read(reinterpret_cast<char*>(capturedGround.pixels.data()),sizeof(capturedGround.pixels));
84 Check(radianceFile.good() && radianceFile.peek()==std::char_traits<char>::eof(),"complete unquantized source lights");
85 }
86 if(fs::exists(capture/"deois-height.bin"))
87 {
88 std::ifstream heightFile(capture/"deois-height.bin",std::ios::binary);
89 heightFile.read(reinterpret_cast<char*>(capturedGround.sourceAltitudeKm.data()),sizeof(capturedGround.sourceAltitudeKm));
90 Check(heightFile.good() && heightFile.peek()==std::char_traits<char>::eof(),"complete captured terrain heights");
91 }
92 }
93 unsigned comparisons=0;
94 std::ofstream metrics(output/"metrics.csv");
95 metrics<<"fixture,before_added_rgb,after_added_rgb,changed_pixels,unchanged_pixels\n";
96 // The reported dark scene has the sun above the horizon. Cover that case
97 // separately from both solar night and a genuinely bright daytime base.
98 for(unsigned lighting=0;lighting<(captured ? 1u : 3u);++lighting)
99 for(float visibility:(captured ? std::vector<float>{capturedVisibility} : std::vector<float>{0,8,20}))
100 {
101 const bool brightDay=!captured && lighting==2;
102 const char* lightingName=captured ? "deois-overcast" : lighting==0 ? "night" : lighting==1 ? "dark-overcast" : "bright-day";
103 const XMFLOAT3 sun=captured ? capturedSun : XMFLOAT3(0,lighting ? -1.f : 1.f,0);
104 const XMFLOAT4 direct=captured ? capturedDirect : lighting ? XMFLOAT4(.9f,.86f,.8f,1) : XMFLOAT4(0,0,0,1);
105 const XMFLOAT4 ambient=captured ? capturedAmbient : brightDay ? XMFLOAT4(.3f,.32f,.35f,1) : XMFLOAT4(.02f,.03f,.025f,1);
106 const XMFLOAT4 haze=captured ? capturedHaze : XMFLOAT4(ambient.x,ambient.y,ambient.z,visibility);
107 const XMFLOAT4 atmosphere=captured ? capturedHorizon : XMFLOAT4(0,0,0,0);
108 std::vector<uint8_t> unlit,beforeUnlit,previous;
109 std::vector<float> distances;
110 uint64_t distanceHash=0,opacityHash=0;
111 double previousGain=0;
112 for(unsigned level=0;level<=5;++level)
113 {
114 if(captured && level!=0 && level!=5)continue;
115 // All authored nonzero plot strengths are 0.1, 0.2, 0.3, 0.4 or
116 // 0.5 times this shared RGB. Reproduce the grid's 3x3 averaging.
117 CloudVolume::GroundLighting ground;ground.cube=0;ground.u=ground.v=1019;
118 for(int y=1;y<63;++y)for(int x=1;x<63;++x)
119 {
120 unsigned neighbors=0;
121 for(int dy=-1;dy<=1;++dy)for(int dx=-1;dx<=1;++dx)
122 if(x+dx>=26 && x+dx<=29 && y+dy>=29 && y+dy<=32)++neighbors;
123 const float strength=float(level)*.1f*float(neighbors)/9;
124 ground.pixels[size_t(y)*64+x]={.0853626f*strength,.0980091f*strength,.1011710f*strength};
125 }
126 if(captured){ground=capturedGround;if(!level)ground.pixels.fill({});}
127 const auto name=std::string(lightingName)+"-haze"+std::to_string(unsigned(visibility))+"-level"+std::to_string(level);
128 std::vector<uint8_t> before,after;
129 for(unsigned version=0;version<2;++version)
130 {
131 auto& renderer=version ? candidate : baseline;
132 renderer.SetGroundLighting(ground);
133 const float dark[]={.02f,.03f,.025f,1};gpu.Context()->ClearRenderTargetView(target.Get(),dark);
134 gpu.Context()->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
135 HR(renderer.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,eye,params,
136 sun,direct,ambient,{.125f,.375f,.25f,1},haze,atmosphere),"city fixture render");
137 const auto hit=CloudQualityHash(gpu,renderer.Pass().Distance(),false);
138 const auto alpha=CloudQualityHash(gpu,renderer.Pass().Image(),true);
139 if(level==0 && version==0){distanceHash=hit;opacityHash=alpha;}
140 Check(hit==distanceHash && alpha==opacityHash,"city illumination must preserve cloud shape and opacity");
141 (version ? after : before)=Pixels(gpu,image.Get());
142 if(level==0 && version==1)distances=CloudCityDistances(gpu,renderer.Pass().Distance(),width/2,height/2);
143 if(level==0 || level==1 || level==5)
144 HR(SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,
145 (output/(name+(version ? "-after.png" : "-before.png"))).c_str()),"save city preview");
146 }
147 if(level==0){unlit=after;beforeUnlit=before;}
148 if(brightDay)Check(after==unlit,"weaker city light must not brighten a daylight base");
149 if(!captured && lighting==0 && level==1)
150 Check(after==unlit,"weak colonies must not add to stronger airglow and bcllight");
151 double oldGain=0,newGain=0;unsigned changed=0,unchanged=0,beyondCutoff=0,visibleContrast=0;
152 for(size_t p=0;p<after.size();p+=4)
153 {
154 bool differs=false;int peakDelta=0;
155 for(unsigned c=0;c<3;++c)
156 {
157 oldGain+=int(before[p+c])-int(beforeUnlit[p+c]);newGain+=int(after[p+c])-int(unlit[p+c]);
158 differs|=after[p+c]!=unlit[p+c];
159 peakDelta=(std::max)(peakDelta,int(after[p+c])-int(unlit[p+c]));
160 if(!previous.empty())Check(after[p+c]>=previous[p+c],"brighter colony sources must never darken a channel");
161 }
162 if(differs)++changed;else ++unchanged;
163 if(peakDelta>=3)++visibleContrast;
164 const size_t pixel=p/4;
165 if(differs && distances[(pixel/width/2)*(width/2)+(pixel%width)/2]>visibility*1.1f)++beyondCutoff;
166 Check(after[p+3]==before[p+3],"city glow must preserve scene alpha");
167 }
168 if(!brightDay && level)
169 {
170 Check(newGain>=previousGain,"colony glow is monotonic above the ambient threshold");
171 if(level==5)Check(newGain>0 && changed>100,"strong city light must exceed the dark base");
172 if(!captured)Check(unchanged>width*height/2,"city glow must be geographically localized");
173 if(visibility==8 && level==5)Check(beyondCutoff>100,"winning city light must fade through the haze cutoff");
174 if(captured && fs::exists(capture/"deois-height.bin"))
175 Check(visibleContrast>5000,"low Deois deck must show a visible city patch above bcllight");
176 previousGain=newGain;
177 }
178 previous=after;
179 metrics<<name<<','<<oldGain<<','<<newGain<<','<<changed<<','<<unchanged<<'\n';
180 std::cout<<name<<": before="<<oldGain<<" after="<<newGain<<" changed="<<changed<<std::endl;
181 ++comparisons;
182 }
183
184 }
185 if(!captured)
186 {
187 // Isolate AGL attenuation: hold the clouds/camera fixed and vary only
188 // the source elevation carried by the ground texture. This also
189 // checks negative terrain heights and the bounded zero-gap limit.
190 CloudVolume::GroundLighting ground;ground.cube=0;ground.u=ground.v=1019;
191 std::vector<uint8_t> dark,previousHeight;
192 uint64_t distanceHash=0,opacityHash=0;
193 double previousGain=-1;
194 for(float gap:{-1.f,4.f,2.f,1.f,.471f,0.f})
195 {
196 ground.pixels.fill(gap<0 ? CloudVolume::Point{} : CloudVolume::Point{6/255.f,7/255.f,7/255.f});
197 ground.sourceAltitudeKm.fill(params.base-gap);
198 candidate.SetGroundLighting(ground);
199 const float background[]={.055f,.055f,.055f,1};
200 gpu.Context()->ClearRenderTargetView(target.Get(),background);
201 gpu.Context()->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
202 HR(candidate.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,eye,params,
203 {0,-1,0},{0,0,0,1},{.055f,.055f,.055f,1},{0,0,0,1},{0,0,0,0},{0,0,0,0}),"source height render");
204 const auto pixels=Pixels(gpu,image.Get());
205 const auto hit=CloudQualityHash(gpu,candidate.Pass().Distance(),false);
206 const auto alpha=CloudQualityHash(gpu,candidate.Pass().Image(),true);
207 if(gap<0){dark=pixels;distanceHash=hit;opacityHash=alpha;continue;}
208 Check(hit==distanceHash && alpha==opacityHash,"terrain height changes illumination only");
209 double gain=0;unsigned visible=0;
210 for(size_t p=0;p<pixels.size();p+=4)
211 {
212 int peak=0;
213 for(unsigned c=0;c<3;++c)
214 {
215 const int delta=int(pixels[p+c])-int(dark[p+c]);
216 Check(delta>=0,"uplight cannot darken the base");gain+=delta;peak=(std::max)(peak,delta);
217 if(!previousHeight.empty())Check(pixels[p+c]>=previousHeight[p+c],"closer sources cannot dim cloud pixels");
218 Check(pixels[p+c]<200,"near-ground uplight stays bounded");
219 }
220 if(peak>=3)++visible;
221 }
222 Check(gain>=previousGain,"AGL attenuation is monotonic");
223 if(gap>=2)Check(gain==0,"distant source below bcllight is suppressed by max");
224 if(gap==.471f)Check(visible>width*height/10,"471 m cloud gap produces visible uplight");
225 metrics<<"source-gap-"<<gap<<",0,"<<gain<<','<<visible<<",0\n";
226 std::cout<<"source gap "<<gap<<" km: gain="<<gain<<" visible="<<visible<<std::endl;
227 previousGain=gain;previousHeight=pixels;++comparisons;
228 }
229 // A lone 0.1-strength plot contributes less than one UNORM8 step
230 // after smoothing. It must reach the GPU rather than round to black.
231 ground.pixels.fill({});ground.sourceAltitudeKm.fill(params.base-.471f);
232 for(int y=29;y<=31;++y)for(int x=27;x<=29;++x)
233 ground.pixels[y*64+x]={.0853626f*.1f/9,.0980091f*.1f/9,.1011710f*.1f/9};
234 candidate.SetGroundLighting(ground);
235 const float black[]={0,0,0,1};gpu.Context()->ClearRenderTargetView(target.Get(),black);
236 gpu.Context()->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
237 HR(candidate.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,eye,params,
238 {0,-1,0},{0,0,0,1},{0,0,0,1},{0,0,0,1},{0,0,0,0},{0,0,0,0}),"faint colony render");
239 const auto faint=Pixels(gpu,image.Get());unsigned litPixels=0;
240 for(size_t p=0;p<faint.size();p+=4)if(faint[p] || faint[p+1] || faint[p+2])++litPixels;
241 Check(litPixels>100,"unquantized light from a lone faint colony must survive GPU upload");
242 std::cout<<"isolated faint colony: "<<litPixels<<" lit pixels\n";++comparisons;
243 }
244 Check(metrics.good(),"city lighting metrics written");DebugMessages(gpu);
245 std::cout<<"PASS: "<<comparisons<<(captured ? " captured Deois comparisons" : " colony/night/overcast/day/haze comparisons")
246 <<"; cloud shape and opacity unchanged\n";
247}
SCRIPT_CONTROL SCRIPT_STATE const void int
float AtmosphericHazeDistanceKm(float nominalTop)
Point WithAirglow(Point scattered, Point airglow, float sunCosine, float altitude, float base, float top)
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 uint8_t Pixels[262144]
std::array< Point, 64 *64 > pixels
std::array< float, 64 *64 > sourceAltitudeKm