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

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

1#pragma once
2#include "CloudOrganicModel.h"
3#include "../Rendering/Shaders/Catalog11.generated.h"
4#include <DirectXPackedVector.h>
5
6// CPU/GPU agreement for the shared organic body and its legacy-layer blend.
7static void CloudOrganicAudit(Device11& gpu,const fs::path& shaders,const fs::path& output)
8{
9 using namespace CloudOrganicPrototype;
10 using namespace DirectX;
11 for(unsigned i=0;i<256;++i)
12 Check(PackedFieldValue(float(i)/255.f)==PackedVector::XMConvertHalfToFloat(
13 PackedVector::XMConvertFloatToHalf(float(i)/255.f)),"organic noise matches uploaded R16 values");
14 for(float value:CloudBillows::Values())
15 Check(PackedFieldValue(value)==PackedVector::XMConvertHalfToFloat(
16 PackedVector::XMConvertFloatToHalf(value)),"organic billows match uploaded R16 values");
17 for(float value:CloudPerlin::Values())
18 Check(PackedFieldValue(value)==PackedVector::XMConvertHalfToFloat(
19 PackedVector::XMConvertFloatToHalf(value)),"organic signed Perlin matches uploaded R16 values");
20 fs::create_directories(output);
21 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS","1");
22 char seedText[32]{};GetEnvironmentVariableA("RISE_ORGANIC_SEED",seedText,32);
23 SetEnvironmentVariableA("RISE_CLOUD_SEED",seedText[0] ? seedText : "0x52495345");
24 CloudRenderer11 renderer;HR(renderer.Initialize(gpu.Device(),shaders),"organic audit renderer");
25 const auto seed=renderer.Seed();
26 renderer.SetLightningEnabled(false);
27 auto& values=const_cast<Parameters11&>(renderer.Parameters());
28 Program11 probe;
29 const bool noiseAudit=GetEnvironmentVariableA("RISE_ORGANIC_NOISE_AUDIT",nullptr,0)>0;
30 const auto vs=ReadShaderBytecode11(shaders/"CloudVolume-Fullscreen11-1.cso");
31 const auto ps=ReadShaderBytecode11(shaders/(noiseAudit ? "CloudOrganic-noise.cso" : "CloudOrganic-probe.cso"));
32 HR(probe.Create(gpu.Device(),vs.data(),vs.size(),ps.data(),ps.size()),"organic probe program");
33 const bool layerAudit=GetEnvironmentVariableA("RISE_ORGANIC_LAYER_AUDIT",nullptr,0)>0;
34 Program11 legacyProbe;
35 if(layerAudit)
36 {
37 const auto code=ReadShaderBytecode11(shaders/"CloudOrganic-legacy-probe.cso");
38 HR(legacyProbe.Create(gpu.Device(),vs.data(),vs.size(),code.data(),code.size()),"organic legacy control probe");
39 }
40 constexpr unsigned width=256,height=64;
41 std::vector<XMFLOAT4> positions(width*height);
42 for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x)
43 {
44 // Include both poles, the longitude seam, many unrelated regions, and
45 // dense altitude coverage of the new upper body and its empty envelope.
46 const float latitude=(float(x%64)/63-.5f)*3.14159265f;
47 const float longitude=(float(x/64)/4+.137f*float(y%7))*6.2831853f;
48 const Point radial{std::cos(latitude)*std::sin(longitude),std::cos(latitude)*std::cos(longitude),std::sin(latitude)};
49 const Point p=Scale(radial,2939.6f+9.f+float(y)*.225f);
50 positions[y*width+x]={p.x,p.y,p.z,1};
51 }
52 D3D11_TEXTURE2D_DESC td{};td.Width=width;td.Height=height;td.MipLevels=td.ArraySize=1;
53 td.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;td.SampleDesc={1,0};td.BindFlags=D3D11_BIND_SHADER_RESOURCE;
54 D3D11_SUBRESOURCE_DATA data{positions.data(),width*sizeof(XMFLOAT4),0};
55 ComPtr<ID3D11Texture2D> positionTexture,result,staging;
56 ComPtr<ID3D11ShaderResourceView> positionView;ComPtr<ID3D11RenderTargetView> target;
57 HR(gpu.Device()->CreateTexture2D(&td,&data,&positionTexture),"organic positions");
58 HR(gpu.Device()->CreateShaderResourceView(positionTexture.Get(),nullptr,&positionView),"organic position SRV");
59 values.Texture("organicPositions",positionView.Get());td.BindFlags=D3D11_BIND_RENDER_TARGET;
60 // This probe binds directly without CloudPass::Render. Use the shipping
61 // sampler catalog, including local-base controls reflected by the field.
62 for(const auto& definition:CloudVolumeSamplers)
63 {
64 ComPtr<ID3D11SamplerState> sampler;
65 HR(gpu.Device()->CreateSamplerState(&definition.description,&sampler),"organic field sampler");
66 values.Sampler(definition.name,sampler.Get());
67 }
68 values.Set("localBaseInfo",XMFLOAT4(0,0,0,0));
69 HR(gpu.Device()->CreateTexture2D(&td,nullptr,&result),"organic output");
70 HR(gpu.Device()->CreateRenderTargetView(result.Get(),nullptr,&target),"organic output RTV");
71 td.BindFlags=0;td.Usage=D3D11_USAGE_STAGING;td.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
72 HR(gpu.Device()->CreateTexture2D(&td,nullptr,&staging),"organic readback");
73 ComPtr<ID3D11DepthStencilState> noDepth;D3D11_DEPTH_STENCIL_DESC ds{};
74 HR(gpu.Device()->CreateDepthStencilState(&ds,&noDepth),"organic depth state");
75 ComPtr<ID3D11RasterizerState> raster;D3D11_RASTERIZER_DESC rd{};
76 rd.FillMode=D3D11_FILL_SOLID;rd.CullMode=D3D11_CULL_NONE;rd.DepthClipEnable=TRUE;
77 HR(gpu.Device()->CreateRasterizerState(&rd,&raster),"organic rasterizer");
78 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};
79 gpu.Context()->RSSetState(raster.Get());gpu.Context()->RSSetViewports(1,&viewport);
80 gpu.Context()->OMSetDepthStencilState(noDepth.Get(),0);gpu.Context()->OMSetBlendState(nullptr,nullptr,UINT_MAX);
81 gpu.Context()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
82 Parameters params;params.organic=true;
83 values.Set("riseOrganicClouds",1u);
84 std::ofstream csv(output/"density-agreement.csv");
85 csv<<"weather,base_km,offset,max_density_error,max_depth_error,max_extinction_error,probes\n";
86 unsigned count=0;
87 for(unsigned weather:{0u,25u,153u,255u,256u,257u})
88 {
89 auto map=ConstantWeather(uint8_t(weather));
90 if(weather>=256)
91 {
92 // Nonuniform weather exercises both the growth remap and the
93 // lower-sheet contour gradient, including seam/pole sampling.
94 auto patterned=std::make_shared<CloudWeather::Map>();
95 patterned->revision=1000+weather;
96 CloudWeather::Mip mip;mip.width=2048;mip.height=1024;
97 mip.pixels.resize(size_t(mip.width)*mip.height);
98 for(unsigned y=0;y<mip.height;++y)for(unsigned x=0;x<mip.width;++x)
99 {
100 const float lon=(float(x)+.5f)*6.2831853f/mip.width;
101 const float lat=(.5f-(float(y)+.5f)/mip.height)*3.14159265f;
102 const float c=std::cos(lat),phase=weather==256 ? 0.f : .6f;
103 const float w=.5f+.23f*std::cos(3*lon+phase)*c*c+.18f*std::sin(4*lat)
104 +.06f*std::sin(11*lon-phase)*c*c*c*c;
105 mip.pixels[y*mip.width+x]=uint8_t(std::round(Saturate(w)*255));
106 }
107 patterned->mips.push_back(std::move(mip));CloudWeather::BuildMips(*patterned);map=patterned;
108 }
109 renderer.UpdateWeather(map,60);
110 for(unsigned i=0;i<256 && renderer.WeatherFrame().current!=map;++i)
111 HR(renderer.PrepareResources(gpu.Context()),"organic weather upload");
112 renderer.UpdateWeather(map,60);HR(renderer.PrepareResources(gpu.Context()),"organic weather blend");
113 params.weather=renderer.WeatherFrame();
114 for(float base:{1.8f,8.f,9.5f})
115 for(float offset:{0.f,3200.f,-3200.f})
116 {
117 if(base!=1.8f && !layerAudit)continue;
118 params.base=base;values.Set("layer",XMFLOAT4(params.radius,params.base,params.top,params.activity));
119 params.noiseOffset={offset,0,0};values.Set("noiseOffset",XMFLOAT4(offset,0,0,0));
120 std::vector<XMFLOAT4> legacyGpu;
121 if(layerAudit)
122 {
123 gpu.Context()->OMSetRenderTargets(1,target.GetAddressOf(),nullptr);
124 HR(legacyProbe.Bind(gpu.Context(),values),"bind legacy control");gpu.Context()->Draw(3,0);
125 gpu.Context()->OMSetRenderTargets(0,nullptr,nullptr);gpu.Context()->CopyResource(staging.Get(),result.Get());
126 D3D11_MAPPED_SUBRESOURCE controlData{};HR(gpu.Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&controlData),"legacy control map");
127 legacyGpu.resize(width*height);
128 for(unsigned y=0;y<height;++y)memcpy(legacyGpu.data()+y*width,static_cast<const char*>(controlData.pData)+y*controlData.RowPitch,width*sizeof(XMFLOAT4));
129 gpu.Context()->Unmap(staging.Get(),0);
130 }
131 gpu.Context()->OMSetRenderTargets(1,target.GetAddressOf(),nullptr);
132 const HRESULT bound=probe.Bind(gpu.Context(),values);HR(bound,probe.Status().c_str());gpu.Context()->Draw(3,0);
133 gpu.Context()->OMSetRenderTargets(0,nullptr,nullptr);
134 gpu.Context()->CopyResource(staging.Get(),result.Get());
135 D3D11_MAPPED_SUBRESOURCE mapped{};HR(gpu.Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"organic map");
136 float densityError=0,depthError=0,extinctionError=0;
137 float newDensityError=0,newDepthError=0,newExtinctionError=0,legacyExtinctionError=0,legacyDifference=0;
138 unsigned mismatches=0;
139 for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x)
140 {
141 const auto& p=positions[y*width+x];const Point point{p.x,p.y,p.z};
142 auto cpu=Evaluate(point,params,seed);
143 if(noiseAudit)
144 {
145 const auto region=Regional(point,params,seed);
146 cpu={region.low,Noise(Add(Scale(region.surface,.04f),Scale({1.5f,-1.1f,.9f},region.low-.5f)),seed),
147 Billow(Scale(region.surface,.19f)),Noise(Scale(Add(point,params.noiseOffset),.71f),seed)};
148 }
149 const auto& actual=reinterpret_cast<const XMFLOAT4*>(static_cast<const char*>(mapped.pData)+y*mapped.RowPitch)[x];
150 if(std::abs(actual.x-cpu.density)>.025f && mismatches++<5)
151 std::cout<<"Mismatch p="<<p.x<<','<<p.y<<','<<p.z<<" CPU="<<cpu.density<<','<<cpu.topDepth
152 <<" GPU="<<actual.x<<','<<actual.y<<std::endl;
153 Check(std::isfinite(actual.x) && std::isfinite(actual.y) && std::isfinite(actual.w),"organic finite GPU result");
154 densityError=(std::max)(densityError,std::abs(actual.x-cpu.density));
155 depthError=(std::max)(depthError,std::abs(actual.y-cpu.topDepth));
156 extinctionError=(std::max)(extinctionError,std::abs(actual.w-cpu.extinction));
157 float expectedDensity=cpu.density,expectedDepth=cpu.topDepth,expectedExtinction=cpu.extinction;
158 if(!legacyGpu.empty())
159 {
160 const auto old=LegacySampleMedium(point,params,seed);
161 const auto& reference=legacyGpu[y*width+x];
162 const float blend=Smooth((Length(point)-params.radius-params.top+.5f)/.5f)*Weight(params);
163 // The old fine extinction pockets also have CPU/GPU filter
164 // error. Measure that control separately; only the newly
165 // introduced contribution must satisfy the new-body budget.
166 expectedExtinction+=(1-blend)*(reference.w-old.extinction);
167 expectedDensity+=(1-blend)*(reference.x-old.density);
168 expectedDepth+=(1-Weight(params))*(reference.y-LegacyDepth(point,params,seed));
169 legacyExtinctionError=(std::max)(legacyExtinctionError,std::abs(reference.w-old.extinction));
170 if(Weight(params)==0)legacyDifference=(std::max)(legacyDifference,
171 (std::max)(std::abs(reference.w-actual.w),(std::max)(std::abs(reference.x-actual.x),std::abs(reference.y-actual.y))));
172 }
173 newDensityError=(std::max)(newDensityError,std::abs(actual.x-expectedDensity));
174 newDepthError=(std::max)(newDepthError,std::abs(actual.y-expectedDepth));
175 newExtinctionError=(std::max)(newExtinctionError,std::abs(actual.w-expectedExtinction));
176 Check(cpu.density>=0 && cpu.density<=1 && actual.x>=0 && actual.x<=1,"organic bounded density");
177 if(!noiseAudit)
178 {
179 const auto dispatched=SampleMedium(point,params,seed);
180 Check(dispatched.density==cpu.density && dispatched.extinction==cpu.extinction,
181 "flight moisture uses the rendered organic body");
182 }
183 Check(Regional(point,params).top<=params.top+MaxTopRiseKm,"organic preserves 22 km envelope");
184 if(!noiseAudit && Length(point)>params.radius+params.top+MaxTopRiseKm)
185 Check(cpu.density==0 && actual.x==0,"organic empty above maximum top");
186 ++count;
187 }
188 gpu.Context()->Unmap(staging.Get(),0);
189 csv<<weather<<','<<base<<','<<offset<<','<<densityError<<','<<depthError<<','<<extinctionError<<','<<width*height<<'\n';csv.flush();
190 std::cout<<"Organic agreement seed="<<seed<<" w="<<weather<<" base="<<base<<" offset="<<offset<<": density "<<densityError
191 <<", depth "<<depthError<<", extinction "<<extinctionError<<std::endl;
192 if(!legacyGpu.empty())std::cout<<"Legacy extinction control "<<legacyExtinctionError<<", new contribution error "<<newExtinctionError
193 <<", density/depth contribution error "<<newDensityError<<'/'<<newDepthError
194 <<", unchanged-layer GPU difference "<<legacyDifference<<std::endl;
195 Check(newDensityError<.025f && newDepthError<.025f && newExtinctionError<.8f,"organic CPU/GPU shape agreement");
196 Check(legacyDifference==0,"high administrative layer retains exact legacy GPU extinction");
197 }
198 }
199 // Guard the old lower deck and the transition independently of GPU noise
200 // quantization. These checks must not depend on a rendered preview looking OK.
201 params.base=1.8f;
202 for(unsigned weather:{0u,153u,255u})
203 {
204 params.weather.current=params.weather.previous=ConstantWeather(uint8_t(weather));params.weather.blend=1;
205 params.noiseOffset={};
206 for(unsigned x=0;x<256;++x)
207 {
208 const Point direction=Scale({float(x)*1.3f,params.radius,37},1/Length({float(x)*1.3f,params.radius,37}));
209 const Point below=Scale(direction,params.radius+9.49f);
210 const auto candidate=Evaluate(below,params);
211 const auto legacy=LegacySampleMedium(below,params);
212 Check(candidate.density==legacy.density && candidate.extinction==legacy.extinction,"organic lower deck unchanged");
213 for(float altitude:{9.5f,10.f})
214 {
215 const auto before=Evaluate(Scale(direction,params.radius+altitude-.001f),params);
216 const auto after=Evaluate(Scale(direction,params.radius+altitude+.001f),params);
217 Check(std::abs(before.density-after.density)<.035f,"organic transition is continuous");
218 }
219 Parameters wrapped=params;params.noiseOffset={3200,0,0};wrapped.noiseOffset={-3200,0,0};
220 const Point p=Scale(direction,params.radius+14);
221 Check(std::abs(Evaluate(p,params).density-Evaluate(p,wrapped).density)<.025f,"organic wind wrap continuous");
222 params.noiseOffset={};
223 }
224 }
225 Check(csv.good(),"organic audit output");DebugMessages(gpu);
226 if(!noiseAudit)
227 {
228 std::ofstream heights(output/"organic-heights.csv");
229 heights<<"weather,minimum_km,mean_km,maximum_km,columns\n";
230 for(unsigned weather:{0u,25u,153u,255u})
231 {
232 params.weather.current=params.weather.previous=ConstantWeather(uint8_t(weather));params.weather.blend=1;
233 params.noiseOffset={};
234 float minimum=100,maximum=0;double sum=0;LONGLONG columnTicks=0;
235 LARGE_INTEGER frequency;QueryPerformanceFrequency(&frequency);
236 float largestColumnDifference=0;
237 for(unsigned z=0;z<32;++z)for(unsigned x=0;x<32;++x)
238 {
239 const Point raw{.438f*params.radius+(float(x)-16)*8, .895f*params.radius,
240 -.073f*params.radius+(float(z)-16)*8};
241 const Point radial=Scale(raw,1/Length(raw));
242 float top=params.top;
243 // Search downward: a full 3D body can contain overhangs and
244 // gaps, so it cannot be treated as one monotone height field.
245 for(float altitude=22;altitude>10;altitude-=.05f)
246 if(Evaluate(Scale(radial,params.radius+altitude),params).density>.001f){top=altitude;break;}
247 LARGE_INTEGER begin,end;QueryPerformanceCounter(&begin);
248 const auto column=SurfaceColumn(Scale(radial,params.radius),params);
249 QueryPerformanceCounter(&end);columnTicks+=end.QuadPart-begin.QuadPart;
250 if(std::abs(column.top-top)>.06f)
251 {
252 // The coarse independent height scan can itself miss a
253 // thin upper lobe. Resolve disagreements at 5 m spacing.
254 float denseTop=params.top;
255 const float start=(std::max)(column.top,top)+.1f;
256 for(unsigned probeIndex=0;probeIndex<2500;++probeIndex)
257 {
258 const float altitude=start-.005f*probeIndex;
259 if(altitude<params.top)break;
260 if(Evaluate(Scale(radial,params.radius+altitude),params).density>.001f){denseTop=altitude;break;}
261 }
262 Check(std::abs(column.top-denseTop)<.02f,"surface query resolves occupied upper lobes");
263 top=denseTop;
264 }
265 largestColumnDifference=(std::max)(largestColumnDifference,std::abs(column.top-top));
266 Check(column.top<=Regional(raw,params).top+.01f,"surface query stays in regional envelope");
267 minimum=(std::min)(minimum,top);maximum=(std::max)(maximum,top);sum+=top;
268 Check(Evaluate(Scale(radial,params.radius+9.49f),params).density>.1f,"organic continuous 10 km core");
269 }
270 heights<<weather<<','<<minimum<<','<<sum/1024<<','<<maximum<<",1024\n";
271 std::cout<<"Organic actual tops w="<<weather<<": "<<minimum<<".."<<maximum
272 <<" km, mean "<<sum/1024<<", column disagreement "<<largestColumnDifference
273 <<" km, query "<<1000.*double(columnTicks)/double(frequency.QuadPart)/1024<<" ms"<<std::endl;
274 if(weather==0)Check(maximum<11.35f,"zero convection retains only shallow cloud relief");
275 // At 25/255 the fixed sqrt envelope allows 3.757 km of growth.
276 if(weather==25)Check(maximum<13.8f,"weak convection exceeded its bounded lift allowance");
277 Check(maximum<=22,"organic actual tops remain in existing envelope");
278 }
279 Check(heights.good(),"organic height audit output");
280 // Use the renderer's real 60-second eased weather transition. Uniform
281 // blend increments are not equal frame times, especially near zero.
282 const auto quiet=ConstantWeather(0),active=ConstantWeather(255);
283 renderer.UpdateWeather(quiet,60);
284 for(unsigned i=0;i<256 && renderer.WeatherFrame().current!=quiet;++i)
285 HR(renderer.PrepareResources(gpu.Context()),"quiet morph weather upload");
286 Check(renderer.WeatherFrame().current==quiet,"quiet morph weather ready");
287 renderer.UpdateWeather(quiet,60);renderer.UpdateWeather(active,0);
288 for(unsigned i=0;i<256 && renderer.WeatherFrame().current!=active;++i)
289 HR(renderer.PrepareResources(gpu.Context()),"active morph weather upload");
290 Check(renderer.WeatherFrame().current==active,"active morph weather ready");
291 std::array<float,3601> frameBlends{};
292 for(unsigned step=0;step<frameBlends.size();++step)
293 {
294 renderer.UpdateWeather(active,step ? 1./60 : 0);
295 frameBlends[step]=renderer.WeatherFrame().blend;
296 }
297 Check(frameBlends.front()==0 && frameBlends.back()==1,"complete 60-second weather morph");
298 float maximumFrameChange=0;
299 for(unsigned x=0;x<32;++x)for(float altitude:{10.7f,11.5f,12.f,14.f,18.f,21.f})
300 {
301 const Point raw{float(x)*8,params.radius,37};
302 const Point point=Scale(raw,(params.radius+altitude)/Length(raw));
303 params.weather.previous=quiet;params.weather.current=active;float previous=0;
304 for(unsigned step=0;step<frameBlends.size();++step)
305 {
306 params.weather.blend=frameBlends[step];const auto sample=Evaluate(point,params);
307 Check(sample.density+1e-5f>=previous,"organic convection grows density monotonically");
308 Check(step==0 || sample.density-previous<.1f,"organic weather morph has no density jump");
309 if(step)maximumFrameChange=(std::max)(maximumFrameChange,sample.density-previous);
310 previous=sample.density;
311 }
312 }
313 std::cout<<"Organic real-time weather morph: 60 seconds at 60 Hz; maximum density/frame "
314 <<maximumFrameChange<<std::endl;
315 }
316 std::cout<<"PASS: organic "<<(noiseAudit ? "noise" : "density")<<" comparison, "<<count
317 <<" CPU/GPU probes plus lower-deck and wrap contracts\n";
318}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
Reason Evaluate(const Observation &value)
const std::vector< float > & Values()
float Weight(float convection)
Column SurfaceColumn(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
Region Regional(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float LegacyDepth(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
const std::vector< float > & Values()
Point Scale(Point p, float s)
Definition CloudVolume.h:93
Point Add(Point a, Point b)
Definition CloudVolume.h:95
float Noise(Point p, uint32_t seed=DefaultSeed, int mask=63)
Medium SampleMedium(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Saturate(float x)
Definition CloudVolume.h:49
Medium LegacySampleMedium(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
void BuildMips(Map &map)
Definition DDS.h:24
BasicParameters< RiseMath::Vector3, RiseMath::Color > Parameters
Definition ExteriorRain.h:7
double Smooth(double t)
double Length(Point a)
std::vector< uint8_t > pixels