Rise
The Vieneo Province
Loading...
Searching...
No Matches
WindshieldRain11.cpp
Go to the documentation of this file.
1#include "WindshieldRain11.h"
2#include "ShaderBytecode11.h"
3#include "FrameProfiler11.h"
5#include <cstring>
6
7using Microsoft::WRL::ComPtr;
9namespace Rendering
10{
11using namespace Math11;
12namespace
13{
14void PackFilm(const WindshieldRain::Surface::Field& residue, std::vector<uint32_t>& filmUpload)
15{
16 constexpr int size = WindshieldRain::Surface::Resolution;
17 filmUpload.resize(size*size);
18 const auto height = [&](int x,int y) {
19 return (std::clamp)(residue[(std::clamp)(y,0,size-1)*size+(std::clamp)(x,0,size-1)],0.f,1.f);
20 };
21 // The encoded slope is positive (64.5..191.5). Round by truncating
22 // after adding half, avoiding two expensive Win32 lround calls per texel.
23 const auto encodeSlope = [](float slope) { return uint32_t(int(128.5f+127.f*slope)); };
24 for (int y = 0; y < size; ++y) for (int x = 0; x < size; ++x)
25 {
26 const uint32_t film = uint32_t(int(height(x,y)*255));
27 const uint32_t dx = encodeSlope((height(x+1,y)-height(x-1,y))*.5f);
28 const uint32_t dy = encodeSlope((height(x,y+1)-height(x,y-1))*.5f);
29 // G: runoff height; R/B: signed central slopes, with 128 exactly flat.
30 // Filtering these normals removes texel facets without a larger field.
31 filmUpload[y*size+x] = 0xff000000u | (dx<<16) | (film<<8) | dy;
32 }
33}
34Vector Position(const WindshieldRain11::Vertex& v) { return {v.x,v.y,v.z}; }
35Point Project(const Vector& p, const Vector& origin,
36 const Vector& u, const Vector& v)
37{
38 const auto delta = p-origin;
39 return {Dot(delta,u)*1000.f, Dot(delta,v)*1000.f};
40}
41}
43{
44 // Undo the ANSI screen half-turn, then change the RH view's -Z forward
45 // to propulsion's +Z forward. Keeping view Z made headwind run DOWN glass.
46 Matrix viewToPhysics;
47 DirectX::XMStoreFloat4x4(&viewToPhysics,DirectX::XMMatrixScaling(-1.f,-1.f,-1.f));
48 return cockpitToView*viewToPhysics;
49}
51 const Matrix& inverse, const Vector& normal,
52 const Vector& u, const Vector& v)
53{
54 const auto right=TransformVector({1,0,0},inverse);
55 const auto forward=TransformVector({0,0,1},inverse);
56 Vector vertical(0,acceleration.y,0), lateral(acceleration.x,0,acceleration.z);
57 vertical=TransformVector(vertical,inverse);
58 lateral=TransformVector(lateral,inverse);
59 Vector down;
60 // Front/rear panes drain in an aircraft-longitudinal vertical section;
61 // side panes use a transverse vertical section. Using aircraft-right for
62 // side glass turns its inward rake into a large fore/aft runoff slant.
63 const auto across=std::abs(Dot(normal,right))>std::abs(Dot(normal,forward)) ? forward : right;
64 down=Cross(normal,across);
65 if (LengthSquared(down) > .000001f)
66 {
67 down=Normalize(down);
68 // Follow the pane's vertical section. A compound windshield rake must
69 // not turn vertical loading into the fanning pattern of forward airflow.
70 vertical = down * Dot(vertical,down);
71 }
72 const auto force = vertical + lateral;
73 return {Dot(force,u),Dot(force,v)};
74}
80{
81 if (value && !simulator)
82 {
83 for (auto& pane:panes) pane.water.Clear();
85 previousTransforms.clear();
86 }
87 simulator=value;
88}
90{
91 glassCondition=simulator ? 127 : (std::clamp)(condition,0,127);
92 if(glassCondition>95)for(auto& pane:panes){pane.fractures={};pane.uploadedCondition=-1;}
93}
100{
102 parameters=Parameters11{};samplers.clear();isolated.Reset();
103 unifiedDepth.Reset();noDepth.Reset();worldDepth.Reset();cockpitDepth.Reset();opaque.Reset();alpha.Reset();alphaWithAdMask.Reset();device.Reset();
104 for(auto& pane:panes){pane.film={};pane.beads={};pane.wakes={};pane.fractures={};pane.uploadedCondition=-1;
105 pane.geometry.Reset();pane.uploadedRevision=uint64_t(-1);}
106 status="native windshield rain not initialized";
107}
108void WindshieldRain11::AddGlass(int component, const Vertex* vertices, size_t count)
109{
110 // Split curved/multi-window components into coplanar patches. Never use the
111 // material UV atlas: it can overlap, rotate, or mirror different windows.
112 for (size_t i = 0; i+2 < count; i += 3)
113 {
114 const auto a = Position(vertices[i]);
115 // D3DX's Win32 normalization can return zero for tiny km-squared
116 // cross products. Metre-scale edges keep small quarter panes valid.
117 const auto e1 = (Position(vertices[i+1])-a)*1000.f, e2 = (Position(vertices[i+2])-a)*1000.f;
118 Vector n;
119 n=Cross(e1,e2);
120 if (LengthSquared(n) < 1.e-8f) continue;
121 n=Normalize(n);
122 auto found = std::find_if(panes.begin(),panes.end(),[&](const Pane& p) {
123 const auto delta = a-p.origin;
124 return p.component == component && Dot(n,p.normal) > .999f
125 && std::abs(Dot(delta,p.normal)) < .000005f;
126 });
127 if (found == panes.end())
128 {
129 // Bound CPU/texture cost even on unexpectedly tessellated assets.
130 if (panes.size() >= 64) continue;
131 Pane pane{}; pane.component = component; pane.origin = a; pane.normal = n;
132 pane.u=Normalize(e1);
133 pane.v=Cross(n,pane.u);
134 panes.push_back(std::move(pane)); found = panes.end()-1;
135 }
136 found->vertices.insert(found->vertices.end(),vertices+i,vertices+i+3);
137 found->geometry.Reset();
138 }
139}
140void WindshieldRain11::AddWiper(int component, const Vertex* vertices, size_t count)
141{
142 wipers.push_back({component, {vertices,vertices+count}});
143}
145{
146 // Adjacent facets of one gently bent window share a projected water chart.
147 // Keep the authored mesh for drawing: the same bead continues over the bend.
148 // Joining bends requires a shared edge, not just proximity across a bezel.
149 const auto same = [](const Vector& a, const Vector& b) {
150 const auto d = a-b; return LengthSquared(d) < 1.e-16f;
151 };
152 const auto connected = [&](const Pane& a, const Pane& b) {
153 for (size_t i=0;i<a.vertices.size();i+=3) for (int e=0;e<3;++e)
154 for (size_t j=0;j<b.vertices.size();j+=3) for (int f=0;f<3;++f)
155 {
156 const auto a0=Position(a.vertices[i+e]), a1=Position(a.vertices[i+(e+1)%3]);
157 const auto b0=Position(b.vertices[j+f]), b1=Position(b.vertices[j+(f+1)%3]);
158 if ((same(a0,b0) && same(a1,b1)) || (same(a0,b1) && same(a1,b0))) return true;
159 }
160 return false;
161 };
162 for (size_t i=0;i<panes.size();++i) for (size_t j=i+1;j<panes.size();)
163 {
164 auto& a=panes[i]; const auto& b=panes[j];
165 Vector normal(0,0,0);
166 const Pane* parts[]={&a,&b};
167 for (const auto* p : parts) for (size_t t=0;t<p->vertices.size();t+=3)
168 {
169 const auto e1=(Position(p->vertices[t+1])-Position(p->vertices[t]))*1000.f;
170 const auto e2=(Position(p->vertices[t+2])-Position(p->vertices[t]))*1000.f;
171 Vector n; n=Cross(e1,e2); normal+=n;
172 }
173 normal=Normalize(normal);
174 bool shallow = Dot(a.normal,b.normal) > .866f;
175 for (const auto* p : parts) for (size_t t=0;t<p->vertices.size();t+=3)
176 {
177 const auto e1=(Position(p->vertices[t+1])-Position(p->vertices[t]))*1000.f;
178 const auto e2=(Position(p->vertices[t+2])-Position(p->vertices[t]))*1000.f;
179 Vector n; n=Cross(e1,e2); n=Normalize(n);
180 shallow &= Dot(n,normal) > .866f;
181 }
182 if (a.component!=b.component || !shallow || !connected(a,b)) { ++j; continue; }
183 a.vertices.insert(a.vertices.end(),b.vertices.begin(),b.vertices.end());
184 a.normal=normal; a.u-=normal*Dot(a.u,normal);
185 a.u=Normalize(a.u); a.v=Cross(normal,a.u);
186 panes.erase(panes.begin()+j); j=i+1; // joining can expose another shared edge
187 }
188 uint32_t seed = 9;
189 for (auto& pane : panes)
190 {
191 Point lo{1.e10f,1.e10f}, hi{-1.e10f,-1.e10f};
192 for (const auto& vertex : pane.vertices)
193 {
194 const auto p = Project(Position(vertex),pane.origin,pane.u,pane.v);
195 lo.x = (std::min)(lo.x,p.x); lo.y = (std::min)(lo.y,p.y);
196 hi.x = (std::max)(hi.x,p.x); hi.y = (std::max)(hi.y,p.y);
197 }
198 pane.origin += (pane.u*lo.x + pane.v*lo.y)*.001f;
199 pane.fractures={};pane.uploadedCondition=-1;
200 pane.water = WindshieldRain::Surface(hi.x-lo.x,hi.y-lo.y,seed++);
201 pane.fractureNetwork=WindshieldFractures::Network(pane.water.Width(),pane.water.Height(),seed-1);
202 pane.uploadedRevision = uint64_t(-1);
203 pane.geometry.Reset();
204 pane.facets.clear();
205 for(size_t t=0;t<pane.vertices.size();t+=3)
206 {
207 const auto origin=Position(pane.vertices[t]);
208 const auto e1=(Position(pane.vertices[t+1])-origin)*1000.f;
209 const auto e2=(Position(pane.vertices[t+2])-origin)*1000.f;
210 Vector normal; normal=Cross(e1,e2); normal=Normalize(normal);
211 pane.facets.push_back({origin,normal});
212 }
213 }
214}
216{
217 return std::any_of(panes.begin(),panes.end(),[](const Pane& p) { return p.water.Wet(); });
218}
220{
221 float wetness = 0.f;
222 for (const auto& pane : panes) wetness = (std::max)(wetness, pane.water.Wetness());
223 return wetness;
224}
225void WindshieldRain11::Update(float elapsed, float rain, const Vector& acceleration,
226 const Vector& relativeWind, const std::vector<Matrix>& transforms, float airDensity, bool wiping, float rainAir)
227{
228 if (simulator || elapsed <= 0) return;
229 const float airSpeed = Length(relativeWind);
230 for (auto& pane : panes)
231 {
232 if (size_t(pane.component) >= transforms.size()) continue;
233 Matrix inverse;
234 if (!Inverse(inverse,transforms[pane.component])) continue;
235 Vector localWind;
236 localWind=TransformVector(relativeWind,inverse);
237 const Point force = ProjectAcceleration(acceleration,inverse,pane.normal,pane.u,pane.v);
238 const Point wind{Dot(localWind,pane.u),Dot(localWind,pane.v)};
240 if (rainAir>0)
241 {
242 // Transforms are cockpit-to-aircraft physics, not head/camera space.
243 // Only forward-facing glass ahead of the seat has rain-air nozzles;
244 // leave side/rear/roof glass and other vehicles on their usual path.
245 const auto normal=Normalize(TransformVector(pane.normal,transforms[pane.component]));
246 const auto center=TransformPoint(pane.origin+(pane.u*pane.water.Width()
247 +pane.v*pane.water.Height())*.0005f,transforms[pane.component]);
248 if (center.z>0 && std::abs(normal.z)>.25f && std::abs(normal.z)>std::abs(normal.x))
249 {
250 const auto up=TransformVector({0,1,0},inverse);
251 const Point tangent{Dot(up,pane.u),Dot(up,pane.v)};
252 const float length=std::hypot(tangent.x,tangent.y);
253 if (length>.1f)
254 {
255 jet.direction={tangent.x/length,tangent.y/length};
256 jet.speed=75.f*(std::clamp)(rainAir,0.f,1.f);
257 jet.bottom=1.e10f;jet.top=-1.e10f;
258 // Bounds follow physical aircraft-up, even with rotated or
259 // mirrored chart axes and trapezoidal/bent front glass.
260 for (const auto& vertex:pane.vertices)
261 {
262 const auto p=Project(Position(vertex),pane.origin,pane.u,pane.v);
263 const float height=p.x*jet.direction.x+p.y*jet.direction.y;
264 jet.bottom=(std::min)(jet.bottom,height);
265 jet.top=(std::max)(jet.top,height);
266 }
267 }
268 }
269 }
270 // Impacts still land. Local air speed moves/breaks up water afterward;
271 // the weaker upper curtain must not reject rain across the whole pane.
272 pane.water.Update(elapsed,rain,force,wind,airDensity,airSpeed,jet);
273 if (!wiping || !pane.water.Wet()) continue;
274 std::vector<WindshieldRain::Surface::BladeSweep> sweeps;
275 Matrix previousInverse;
276 if(previousTransforms.size()!=transforms.size()
277 || !Inverse(previousInverse,previousTransforms[pane.component])) continue;
278 for (const auto& wiper : wipers)
279 {
280 if (size_t(wiper.component) >= transforms.size()) continue;
281 // Compare in each frame's glass space. A seat/cockpit translation
282 // must not turn a parked blade into a sweep across the windshield.
283 const auto oldMatrix = previousTransforms[wiper.component]*previousInverse;
284 const auto newMatrix = transforms[wiper.component]*inverse;
285 // A parked blade does not keep its entire sweep area permanently dry.
286 if (std::memcmp(&oldMatrix,&newMatrix,sizeof(oldMatrix)) == 0) continue;
287 for (size_t i = 0; i+2 < wiper.vertices.size(); i += 3)
288 {
290 bool nearGlass = true;
291 for (int j = 0; j < 3; ++j)
292 {
293 const auto vertex = Position(wiper.vertices[i+j]);
294 Vector a,b;
295 a=TransformPoint(vertex,oldMatrix);
296 b=TransformPoint(vertex,newMatrix);
297 // Check the actual facets, not the chart's average plane.
298 float distance=1.f;
299 for (const auto& facet:pane.facets)
300 {
301 const auto delta=b-facet.origin;
302 distance=(std::min)(distance,std::abs(Dot(delta,facet.normal)));
303 }
304 nearGlass &= distance < .00008f;
305 sweep.previous[j] = Project(a,pane.origin,pane.u,pane.v);
306 sweep.current[j] = Project(b,pane.origin,pane.u,pane.v);
307 }
308 if (!nearGlass) continue;
309 sweeps.push_back(sweep);
310 }
311 }
312 pane.water.SweepBlades(sweeps,elapsed);
313 }
314 previousTransforms = transforms;
315}
316
317HRESULT WindshieldRain11::Initialize(ID3D11Device* native,const std::filesystem::path& directory)
318{
319 ResetDevice();if(!native)return E_INVALIDARG;device=native;
320 ComPtr<ID3D11Device1> device1;HRESULT hr=device.As(&device1);if(FAILED(hr))return hr;
321 const auto level=device->GetFeatureLevel();
322 if(FAILED(hr=device1->CreateDeviceContextState(0,&level,1,D3D11_SDK_VERSION,__uuidof(ID3D11Device),nullptr,&isolated)))return hr;
323 const D3D11_INPUT_ELEMENT_DESC position{"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0};
324 const auto create=[&](Program11& program,const char* vsName,const char* psName) {
325 const auto vs=ReadShaderBytecode11(directory/(std::string("CustomUI-")+vsName+"-1.cso"));
326 const auto ps=ReadShaderBytecode11(directory/(std::string("CustomUI-")+psName+"-1.cso"));
327 return program.Create(device.Get(),vs.data(),vs.size(),ps.data(),ps.size(),&position,1);
328 };
329 if(FAILED(hr=create(water,"RainVS","RainPS"))){status=water.Status();return hr;}
330 const auto adVs=ReadShaderBytecode11(directory/"CustomUI-RainVS-1.cso");
331 const auto adPs=ReadShaderBytecode11(directory/"AdViewability-AdRainPixel-1.cso");
332 if(FAILED(hr=waterWithAdMask.Create(device.Get(),adVs.data(),adVs.size(),adPs.data(),adPs.size(),&position,1)))
333 {status=waterWithAdMask.Status();return hr;}
334 if(FAILED(hr=create(visibilityProgram,"RainVisibilityVS","RainVisibilityPS"))){status=visibilityProgram.Status();return hr;}
335 const auto damagePs=ReadShaderBytecode11(directory/"WindshieldDamage-DamagePS-1.cso");
336 const auto damageAdPs=ReadShaderBytecode11(directory/"WindshieldDamage-DamageAdPS-1.cso");
337 if(FAILED(hr=damage.Create(device.Get(),adVs.data(),adVs.size(),damagePs.data(),damagePs.size(),&position,1)))
338 {status=damage.Status();return hr;}
339 if(FAILED(hr=damageWithAdMask.Create(device.Get(),adVs.data(),adVs.size(),damageAdPs.data(),damageAdPs.size(),&position,1)))
340 {status=damageWithAdMask.Status();return hr;}
341 for(const auto& entry:CustomUISamplers)
342 {
343 if(strncmp(entry.name,"Rain",4))continue;
344 ComPtr<ID3D11SamplerState> sampler;
345 if(FAILED(hr=device->CreateSamplerState(&entry.description,&sampler)))return hr;
346 parameters.Sampler(entry.name,sampler.Get());samplers.push_back(std::move(sampler));
347 }
348 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ZERO;ds.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;
349 ds.FrontFace=ds.BackFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_ALWAYS};
350 if(FAILED(hr=device->CreateDepthStencilState(&ds,&unifiedDepth)))return hr;
351 ds.DepthEnable=FALSE;if(FAILED(hr=device->CreateDepthStencilState(&ds,&noDepth)))return hr;
352 ds.DepthEnable=TRUE;ds.StencilEnable=TRUE;ds.StencilReadMask=255;ds.StencilWriteMask=0;
353 ds.DepthFunc=D3D11_COMPARISON_ALWAYS;ds.FrontFace.StencilFunc=ds.BackFace.StencilFunc=D3D11_COMPARISON_GREATER;
354 if(FAILED(hr=device->CreateDepthStencilState(&ds,&worldDepth)))return hr;
355 ds.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;ds.FrontFace.StencilFunc=ds.BackFace.StencilFunc=D3D11_COMPARISON_EQUAL;
356 if(FAILED(hr=device->CreateDepthStencilState(&ds,&cockpitDepth)))return hr;
357 D3D11_BLEND_DESC bs{};
358 bs.RenderTarget[0]={FALSE,D3D11_BLEND_SRC_ALPHA,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,
359 D3D11_BLEND_SRC_ALPHA,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,D3D11_COLOR_WRITE_ENABLE_ALL};
360 if(FAILED(hr=device->CreateBlendState(&bs,&opaque)))return hr;
361 bs.RenderTarget[0].BlendEnable=TRUE;if(FAILED(hr=device->CreateBlendState(&bs,&alpha)))return hr;
362 bs.IndependentBlendEnable=TRUE;
363 // Union exclusions from overlapping panes without altering scene blending.
364 bs.RenderTarget[1]={TRUE,D3D11_BLEND_ONE,D3D11_BLEND_ONE,D3D11_BLEND_OP_MAX,
365 D3D11_BLEND_ONE,D3D11_BLEND_ONE,D3D11_BLEND_OP_MAX,D3D11_COLOR_WRITE_ENABLE_RED};
366 if(FAILED(hr=device->CreateBlendState(&bs,&alphaWithAdMask)))return hr;
367 status="native windshield rain ready";return S_OK;
368}
369
370HRESULT WindshieldRain11::CreateImage(Image& image,UINT width,UINT height,DXGI_FORMAT format,bool dynamic,DXGI_SAMPLE_DESC samples)
371{
372 Image next;D3D11_TEXTURE2D_DESC desc{};desc.Width=width;desc.Height=height;desc.ArraySize=desc.MipLevels=1;
373 desc.Format=format;desc.SampleDesc=samples;desc.Usage=dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
374 desc.BindFlags=D3D11_BIND_SHADER_RESOURCE|(dynamic ? 0 : D3D11_BIND_RENDER_TARGET);
375 desc.CPUAccessFlags=dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
376 HRESULT hr=device->CreateTexture2D(&desc,nullptr,&next.texture);if(FAILED(hr))return hr;
377 if(FAILED(hr=device->CreateShaderResourceView(next.texture.Get(),nullptr,&next.srv)))return hr;
378 if(!dynamic && FAILED(hr=device->CreateRenderTargetView(next.texture.Get(),nullptr,&next.rtv)))return hr;
379 image=std::move(next);return S_OK;
380}
381
382HRESULT WindshieldRain11::PrepareTargets(const D3D11_TEXTURE2D_DESC& desc)
383{
384 if(scene.texture && desc.Width==targetDescription.Width && desc.Height==targetDescription.Height
385 && desc.Format==targetDescription.Format && desc.SampleDesc.Count==targetDescription.SampleDesc.Count
386 && desc.SampleDesc.Quality==targetDescription.SampleDesc.Quality)return S_OK;
387 Image nextScene,nextVisibility,nextSamples;
388 HRESULT hr=CreateImage(nextScene,desc.Width,desc.Height,desc.Format);if(FAILED(hr))return hr;
389 DXGI_FORMAT maskFormat=desc.Format;
390 // The mask uses only red. For linear 8-bit UNORM scenes, R8 retains the
391 // identical normalized coverage and filtering with one quarter the bytes.
392 // Preserve other formats and devices without matching MSAA/resolve support.
393 if(compactVisibility && (desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM))
394 {
395 UINT support=0,quality=0;
396 const UINT required=D3D11_FORMAT_SUPPORT_RENDER_TARGET|D3D11_FORMAT_SUPPORT_SHADER_SAMPLE
397 | (desc.SampleDesc.Count>1 ? D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET|D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE : 0);
398 if(SUCCEEDED(device->CheckFormatSupport(DXGI_FORMAT_R8_UNORM,&support)) && (support&required)==required
399 && (desc.SampleDesc.Count==1 || (SUCCEEDED(device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8_UNORM,desc.SampleDesc.Count,&quality))
400 && desc.SampleDesc.Quality<quality)))maskFormat=DXGI_FORMAT_R8_UNORM;
401 }
402 if(FAILED(hr=CreateImage(nextVisibility,desc.Width,desc.Height,maskFormat)))return hr;
403 if(desc.SampleDesc.Count>1)
404 {
405 if(FAILED(hr=CreateImage(nextSamples,desc.Width,desc.Height,maskFormat,false,desc.SampleDesc)))return hr;
406 }
407 else nextSamples=nextVisibility;
408 parameters.ClearTextures();scene=std::move(nextScene);visibility=std::move(nextVisibility);visibilitySamples=std::move(nextSamples);
409 targetDescription=desc;visibilityFormat=maskFormat;return S_OK;
410}
411
412HRESULT WindshieldRain11::Upload(ID3D11DeviceContext* context,Pane& pane)
413{
414 ProfileScope11 timing("Windshield water upload",false);
415 constexpr UINT size=WindshieldRain::Surface::Resolution;
416 HRESULT hr;
417 if(!pane.film.texture && FAILED(hr=CreateImage(pane.film,size,size,DXGI_FORMAT_B8G8R8A8_UNORM,true)))return hr;
418 if(!pane.beads.texture && FAILED(hr=CreateImage(pane.beads,size,size,DXGI_FORMAT_R32G32B32A32_FLOAT,true)))return hr;
419 if(!pane.wakes.texture && FAILED(hr=CreateImage(pane.wakes,size,size,DXGI_FORMAT_R32G32B32A32_FLOAT,true)))return hr;
420 if(pane.uploadedRevision==pane.water.Revision())return S_OK;
421 {ProfileScope11 mapTiming("Windshield bead and wake map",false);
423 {ProfileScope11 filmTiming("Windshield film packing",false);
424 PackFilm(pane.water.Residue(),filmUpload);}
425 ProfileScope11 transferTiming("Windshield texture transfer",false);
426 const auto upload=[&](Image& image,const void* data,UINT stride) {
427 D3D11_MAPPED_SUBRESOURCE mapped{};const HRESULT result=context->Map(image.texture.Get(),0,D3D11_MAP_WRITE_DISCARD,0,&mapped);
428 if(FAILED(result))return result;
429 for(UINT y=0;y<size;++y)memcpy(static_cast<char*>(mapped.pData)+size_t(y)*mapped.RowPitch,static_cast<const char*>(data)+size_t(y)*stride,stride);
430 context->Unmap(image.texture.Get(),0);
431 FrameProfiler11::Get().TextureUpload(UINT64(size)*stride);return S_OK;
432 };
433 if(FAILED(hr=upload(pane.wakes,wakeUpload.data(),size*sizeof(wakeUpload[0]))))return hr;
434 if(FAILED(hr=upload(pane.beads,beadUpload.data(),size*sizeof(beadUpload[0]))))return hr;
435 if(FAILED(hr=upload(pane.film,filmUpload.data(),size*sizeof(filmUpload[0]))))return hr;
436 pane.uploadedRevision=pane.water.Revision();return S_OK;
437}
438
439HRESULT WindshieldRain11::Render(ID3D11DeviceContext* caller,ID3D11RenderTargetView* target,ID3D11DepthStencilView* depth,
440 const D3D11_VIEWPORT& viewport,const std::vector<Matrix>& world,const Matrix& viewProjection,
441 float opacity,DepthLayout layout,float cockpitLight,ID3D11RenderTargetView* adExclusion)
442{
443 ProfileScope11 timing("Windshield water render");
444 opacity=(std::clamp)(opacity,0.f,1.f);
445 const bool damaged=glassCondition<=95;
446 const bool wet=opacity>0 && Wet();
447 if(simulator || (!damaged && !wet))return S_FALSE;
448 if(!device || !isolated || !caller || !target || caller->GetType()!=D3D11_DEVICE_CONTEXT_IMMEDIATE)return E_UNEXPECTED;
449 if(!std::isfinite(viewport.Width) || !std::isfinite(viewport.Height) || viewport.Width<1 || viewport.Height<1
450 || !std::isfinite(viewport.MinDepth) || !std::isfinite(viewport.MaxDepth)
451 || viewport.MinDepth<0 || viewport.MaxDepth>1 || viewport.MinDepth>viewport.MaxDepth
452 || !std::isfinite(opacity) || !std::isfinite(cockpitLight))return E_INVALIDARG;
453 ComPtr<ID3D11Device> callerDevice;caller->GetDevice(&callerDevice);if(callerDevice!=device)return E_INVALIDARG;
454 std::vector<bool> visible(panes.size(),false);bool visibleWater=false;
455 for(size_t i=0;i<panes.size();++i)
456 {
457 const auto& pane=panes[i];if(size_t(pane.component)>=world.size())continue;
458 const auto wvp=world[pane.component]*viewProjection;unsigned outside=63;
459 for(const auto& vertex:pane.vertices)
460 {
461 const auto clip=TransformClip(Position(vertex),wvp);unsigned mask=0;
462 if(clip.x < -clip.w)mask|=1;if(clip.x > clip.w)mask|=2;
463 if(clip.y < -clip.w)mask|=4;if(clip.y > clip.w)mask|=8;
464 if(clip.z<0)mask|=16;if(clip.z>clip.w)mask|=32;
465 outside&=mask;
466 }
467 visible[i]=outside==0;visibleWater|=visible[i] && (damaged || (wet && pane.water.Wet()));
468 }
469 if(!visibleWater)return S_FALSE;
470 ComPtr<ID3D11Resource> resource;target->GetResource(&resource);ComPtr<ID3D11Texture2D> color;
471 HRESULT hr=resource.As(&color);if(FAILED(hr))return hr;
472 ComPtr<ID3D11Device> targetDevice;color->GetDevice(&targetDevice);if(targetDevice!=device)return E_INVALIDARG;
473 D3D11_TEXTURE2D_DESC desc{};color->GetDesc(&desc);D3D11_RENDER_TARGET_VIEW_DESC view{};target->GetDesc(&view);
474 if(desc.ArraySize!=1 || (view.ViewDimension!=D3D11_RTV_DIMENSION_TEXTURE2D && view.ViewDimension!=D3D11_RTV_DIMENSION_TEXTURE2DMS)
475 || (view.ViewDimension==D3D11_RTV_DIMENSION_TEXTURE2D && view.Texture2D.MipSlice!=0)
476 || !std::isfinite(viewport.TopLeftX) || !std::isfinite(viewport.TopLeftY) || viewport.TopLeftX<0 || viewport.TopLeftY<0
477 || viewport.TopLeftX+viewport.Width>desc.Width || viewport.TopLeftY+viewport.Height>desc.Height)return E_INVALIDARG;
478 desc.Format=view.Format;
479 if(adExclusion)
480 {
481 ComPtr<ID3D11Resource> adResource;adExclusion->GetResource(&adResource);
482 ComPtr<ID3D11Texture2D> adTexture;if(FAILED(hr=adResource.As(&adTexture)))return hr;
483 ComPtr<ID3D11Device> adDevice;adTexture->GetDevice(&adDevice);
484 D3D11_TEXTURE2D_DESC adDesc{};adTexture->GetDesc(&adDesc);
485 D3D11_RENDER_TARGET_VIEW_DESC adView{};adExclusion->GetDesc(&adView);
486 if(adDevice!=device || adTexture==color || adDesc.Width!=desc.Width || adDesc.Height!=desc.Height
487 || adDesc.SampleDesc.Count!=desc.SampleDesc.Count || adDesc.SampleDesc.Quality!=desc.SampleDesc.Quality
488 || adDesc.ArraySize!=1 || adView.Format!=DXGI_FORMAT_R8_UNORM || adView.ViewDimension!=view.ViewDimension
489 || (adView.ViewDimension==D3D11_RTV_DIMENSION_TEXTURE2D && adView.Texture2D.MipSlice!=0))return E_INVALIDARG;
490 }
491 ComPtr<ID3D11DepthStencilView> readOnly;
492 if(depth)
493 {
494 D3D11_DEPTH_STENCIL_VIEW_DESC depthView{};depth->GetDesc(&depthView);
495 ComPtr<ID3D11Resource> depthResource;depth->GetResource(&depthResource);ComPtr<ID3D11Texture2D> depthTexture;
496 if(FAILED(hr=depthResource.As(&depthTexture)))return hr;
497 ComPtr<ID3D11Device> depthDevice;depthTexture->GetDevice(&depthDevice);if(depthDevice!=device)return E_INVALIDARG;
498 D3D11_TEXTURE2D_DESC depthDesc{};depthTexture->GetDesc(&depthDesc);
499 if(depthDesc.Width!=desc.Width || depthDesc.Height!=desc.Height || depthDesc.SampleDesc.Count!=desc.SampleDesc.Count
500 || depthDesc.SampleDesc.Quality!=desc.SampleDesc.Quality || depthDesc.ArraySize!=1
501 || (depthView.ViewDimension!=D3D11_DSV_DIMENSION_TEXTURE2D && depthView.ViewDimension!=D3D11_DSV_DIMENSION_TEXTURE2DMS)
502 || (depthView.ViewDimension==D3D11_DSV_DIMENSION_TEXTURE2D && depthView.Texture2D.MipSlice!=0))return E_INVALIDARG;
503 const bool stencil=depthView.Format==DXGI_FORMAT_D24_UNORM_S8_UINT || depthView.Format==DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
504 if(layout==DepthLayout::CockpitAndWorld && !stencil)return E_INVALIDARG;
505 depthView.Flags|=D3D11_DSV_READ_ONLY_DEPTH|(stencil ? D3D11_DSV_READ_ONLY_STENCIL : 0);
506 if(FAILED(hr=device->CreateDepthStencilView(depthTexture.Get(),&depthView,&readOnly)))return hr;
507 }
508 if(FAILED(hr=PrepareTargets(desc)))return hr;
509 ComPtr<ID3D11RasterizerState> raster;caller->RSGetState(&raster);
510 D3D11_RECT scissors[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]{};UINT scissorCount=UINT(std::size(scissors));
511 caller->RSGetScissorRects(&scissorCount,scissors);
512 ComPtr<ID3D11DepthStencilState> inheritedDepth;UINT reference=0;caller->OMGetDepthStencilState(&inheritedDepth,&reference);
513 if(depth && layout==DepthLayout::Unified && inheritedDepth)
514 {
515 D3D11_DEPTH_STENCIL_DESC inherited{};inheritedDepth->GetDesc(&inherited);
516 inherited.DepthEnable=TRUE;inherited.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;inherited.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ZERO;
517 inherited.StencilWriteMask=0;
518 inherited.FrontFace.StencilFailOp=inherited.FrontFace.StencilDepthFailOp=inherited.FrontFace.StencilPassOp=D3D11_STENCIL_OP_KEEP;
519 inherited.BackFace.StencilFailOp=inherited.BackFace.StencilDepthFailOp=inherited.BackFace.StencilPassOp=D3D11_STENCIL_OP_KEEP;
520 ComPtr<ID3D11DepthStencilState> next;if(FAILED(hr=device->CreateDepthStencilState(&inherited,&next)))return hr;
521 inheritedDepth=std::move(next);
522 }
523 struct Restore
524 {
525 ComPtr<ID3D11DeviceContext1> context;
526 ComPtr<ID3DDeviceContextState> previous;
528 ~Restore(){parameters.ClearTextures();if(previous){context->ClearState();context->SwapDeviceContextState(previous.Get(),nullptr);}}
529 } restore{{},{},parameters};
530 if(FAILED(hr=caller->QueryInterface(IID_PPV_ARGS(&restore.context))))return hr;
531 auto* context=restore.context.Get();context->SwapDeviceContextState(isolated.Get(),&restore.previous);
532 context->RSSetState(raster.Get());context->RSSetViewports(1,&viewport);
533 context->RSSetScissorRects(scissorCount,scissors);
534 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
535 // Only color is resolved/copied. Every mask and water draw tests the original
536 // scene depth/stencil samples through the read-only view.
537 if(desc.SampleDesc.Count>1)context->ResolveSubresource(scene.texture.Get(),0,color.Get(),0,desc.Format);
538 else context->CopySubresourceRegion(scene.texture.Get(),0,0,0,0,color.Get(),0,nullptr);
539 parameters.Set("_risePixelCenterOffset",DirectX::XMFLOAT2(1/viewport.Width,-1/viewport.Height));
540 const auto draw=[&](Pane& pane,Program11& program) -> HRESULT {
541 if(!pane.geometry)
542 {
543 if(pane.vertices.size()>UINT_MAX/sizeof(Vertex))return E_INVALIDARG;
544 D3D11_BUFFER_DESC buffer{};buffer.ByteWidth=UINT(pane.vertices.size()*sizeof(Vertex));buffer.Usage=D3D11_USAGE_IMMUTABLE;buffer.BindFlags=D3D11_BIND_VERTEX_BUFFER;
545 const D3D11_SUBRESOURCE_DATA initial{pane.vertices.data(),0,0};
546 const HRESULT created=device->CreateBuffer(&buffer,&initial,&pane.geometry);if(FAILED(created))return created;
547 }
548 auto* buffer=pane.geometry.Get();const UINT stride=sizeof(Vertex),offset=0;
549 context->IASetVertexBuffers(0,1,&buffer,&stride,&offset);
550 const HRESULT bound=program.Bind(context,parameters);if(FAILED(bound))return bound;
551 if(depth && layout==DepthLayout::CockpitAndWorld)
552 {
553 context->OMSetDepthStencilState(worldDepth.Get(),3);context->Draw(UINT(pane.vertices.size()),0);
554 context->OMSetDepthStencilState(cockpitDepth.Get(),3);context->Draw(UINT(pane.vertices.size()),0);
555 }
556 else
557 {
558 context->OMSetDepthStencilState(!depth ? noDepth.Get() : inheritedDepth ? inheritedDepth.Get() : unifiedDepth.Get(),reference);
559 context->Draw(UINT(pane.vertices.size()),0);
560 }
561 return S_OK;
562 };
563 auto* mask=visibilitySamples.rtv.Get();context->OMSetRenderTargets(1,&mask,readOnly.Get());
564 const float clear[4]{};context->ClearRenderTargetView(mask,clear);context->OMSetBlendState(opaque.Get(),nullptr,0xffffffff);
565 for(size_t i=0;i<panes.size();++i)if(visible[i])
566 {
567 parameters.Set("matWorldViewProj",world[panes[i].component]*viewProjection);
568 if(FAILED(hr=draw(panes[i],visibilityProgram)))return hr;
569 }
570 context->OMSetRenderTargets(0,nullptr,nullptr);
571 if(desc.SampleDesc.Count>1)context->ResolveSubresource(visibility.texture.Get(),0,visibilitySamples.texture.Get(),0,visibilityFormat);
572 ID3D11RenderTargetView* targets[]={target,adExclusion};
573 context->OMSetRenderTargets(adExclusion ? 2 : 1,targets,readOnly.Get());
574 context->OMSetBlendState(adExclusion ? alphaWithAdMask.Get() : alpha.Get(),nullptr,0xffffffff);
575 parameters.Texture("RainScene",scene.srv.Get());parameters.Texture("RainVisibility",visibility.srv.Get());
576 parameters.Set("RainOpacity",opacity);parameters.Set("RainCockpitLight",(std::clamp)(cockpitLight,0.f,1.f));
577 parameters.Set("RainSceneTexel",Vector4(1.f/desc.Width,1.f/desc.Height,0,0));
578 for(size_t i=0;i<panes.size();++i)
579 {
580 auto& pane=panes[i];if(!wet || !visible[i] || !pane.water.Wet())continue;
581 if(FAILED(hr=Upload(context,pane)))return hr;
582 const auto u=pane.u*(1000/pane.water.Width()),v=pane.v*(1000/pane.water.Height());
583 parameters.Set("matWorldViewProj",world[pane.component]*viewProjection);
584 parameters.Set("RainU",Vector4(u.x,u.y,u.z,-Dot(pane.origin,u)));
585 parameters.Set("RainV",Vector4(v.x,v.y,v.z,-Dot(pane.origin,v)));
587 parameters.Texture("RainWater",pane.film.srv.Get());parameters.Texture("RainBeads",pane.beads.srv.Get());parameters.Texture("RainWakes",pane.wakes.srv.Get());
588 if(FAILED(hr=draw(pane,adExclusion ? waterWithAdMask : water)))return hr;
589 }
590 if(damaged)
591 {
592 // Fractures transmit the rendered exterior AND any water on the glass.
593 // Unbind the snapshot before updating it; the original depth stays read-only.
594 if(wet)
595 {
596 ID3D11ShaderResourceView* empty[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]{};
597 context->PSSetShaderResources(0,UINT(std::size(empty)),empty);
598 context->OMSetRenderTargets(0,nullptr,nullptr);
599 if(desc.SampleDesc.Count>1)context->ResolveSubresource(scene.texture.Get(),0,color.Get(),0,desc.Format);
600 else context->CopySubresourceRegion(scene.texture.Get(),0,0,0,0,color.Get(),0,nullptr);
601 context->OMSetRenderTargets(adExclusion ? 2 : 1,targets,readOnly.Get());
602 }
603 for(size_t i=0;i<panes.size();++i)
604 {
605 auto& pane=panes[i];if(!visible[i])continue;
606 constexpr UINT size=WindshieldFractures::Resolution;
607 if(!pane.fractures.texture && FAILED(hr=CreateImage(pane.fractures,size,size,DXGI_FORMAT_R32G32B32A32_FLOAT,true)))return hr;
609 {
611 D3D11_MAPPED_SUBRESOURCE map{};
612 if(FAILED(hr=context->Map(pane.fractures.texture.Get(),0,D3D11_MAP_WRITE_DISCARD,0,&map)))return hr;
613 for(UINT y=0;y<size;++y)memcpy(static_cast<char*>(map.pData)+size_t(y)*map.RowPitch,
614 field.data()+size_t(y)*size,size*sizeof(field[0]));
615 context->Unmap(pane.fractures.texture.Get(),0);pane.uploadedCondition=glassCondition;
616 FrameProfiler11::Get().TextureUpload(UINT64(size)*size*sizeof(field[0]));
617 }
618 const auto u=pane.u*(1000/pane.water.Width()),v=pane.v*(1000/pane.water.Height());
619 parameters.Set("matWorldViewProj",world[pane.component]*viewProjection);
620 parameters.Set("RainU",Vector4(u.x,u.y,u.z,-Dot(pane.origin,u)));
621 parameters.Set("RainV",Vector4(v.x,v.y,v.z,-Dot(pane.origin,v)));
622 parameters.Set("RainExtent",Vector4(pane.water.Width(),pane.water.Height(),0,0));
623 parameters.Texture("DamageSegments",pane.fractures.srv.Get());
624 if(FAILED(hr=draw(pane,adExclusion ? damageWithAdMask : damage)))return hr;
625 }
626 }
627 return S_OK;
628}
629}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
void TextureUpload(UINT64 bytes)
static FrameProfiler11 & Get()
void Set(const std::string &name, const void *data, size_t bytes)
Definition Program11.cpp:45
void Texture(const std::string &name, ID3D11ShaderResourceView *value)
Definition Program11.cpp:55
void Sampler(const std::string &name, ID3D11SamplerState *value)
Definition Program11.cpp:66
HRESULT Create(ID3D11Device *device, const void *vertexCode, size_t vertexSize, const void *pixelCode, size_t pixelSize, const D3D11_INPUT_ELEMENT_DESC *elements=nullptr, UINT elementCount=0, UINT bgraColorMask=0)
const std::string & Status() const
Definition Program11.h:67
std::vector< Microsoft::WRL::ComPtr< ID3D11SamplerState > > samplers
Microsoft::WRL::ComPtr< ID3D11Device > device
std::vector< Wiper > wipers
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
std::vector< WindshieldRain::Surface::BeadSample > beadUpload
HRESULT CreateImage(Image &image, UINT width, UINT height, DXGI_FORMAT format, bool dynamic=false, DXGI_SAMPLE_DESC samples={1, 0})
HRESULT Render(ID3D11DeviceContext *context, ID3D11RenderTargetView *target, ID3D11DepthStencilView *depth, const D3D11_VIEWPORT &viewport, const std::vector< Matrix > &world, const Matrix &viewProjection, float opacity=1, DepthLayout depthLayout=DepthLayout::Unified, float cockpitLight=0, ID3D11RenderTargetView *adExclusion=nullptr)
void SetGlassCondition(int condition)
static Matrix ToPhysicsTransform(const Matrix &cockpitToView)
Microsoft::WRL::ComPtr< ID3DDeviceContextState > isolated
Microsoft::WRL::ComPtr< ID3D11BlendState > alphaWithAdMask
std::vector< float > distanceUpload
D3D11_TEXTURE2D_DESC targetDescription
std::vector< WindshieldRain::Surface::WakeSample > wakeUpload
HRESULT PrepareTargets(const D3D11_TEXTURE2D_DESC &description)
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > worldDepth
void Update(float elapsed, float rain, const Vector &acceleration, const Vector &relativeWind, const std::vector< Matrix > &transforms, float airDensity, bool wiping, float rainAir=0)
static WindshieldRain::Point ProjectAcceleration(const Vector &acceleration, const Matrix &inverse, const Vector &normal, const Vector &u, const Vector &v)
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > cockpitDepth
std::vector< uint32_t > filmUpload
std::vector< Matrix > previousTransforms
void AddWiper(int component, const Vertex *vertices, size_t count)
void AddGlass(int component, const Vertex *vertices, size_t count)
HRESULT Upload(ID3D11DeviceContext *context, Pane &pane)
Microsoft::WRL::ComPtr< ID3D11BlendState > alpha
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > unifiedDepth
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > noDepth
Microsoft::WRL::ComPtr< ID3D11BlendState > opaque
void BeadMap(std::vector< BeadSample > &map, std::vector< WakeSample > *wakes=nullptr, std::vector< float > *scratchDistances=nullptr) const
std::vector< float > Field
static constexpr int Resolution
const Field & Residue() const
uint64_t Revision() const
Vector Position(int cube, int u, int v, float radius)
Vector TransformPoint(const Vector &a, const Matrix &matrix)
Definition Math11.h:25
DirectX::XMFLOAT4 Vector4
Definition Math11.h:8
float Length(const Vector &a)
Definition Math11.h:18
float LengthSquared(const Vector &a)
Definition Math11.h:17
Vector Normalize(const Vector &a)
Definition Math11.h:21
Vector TransformVector(const Vector &a, const Matrix &matrix)
Definition Math11.h:23
bool Inverse(Matrix &result, const Matrix &matrix)
Definition Math11.h:31
Vector Cross(const Vector &a, const Vector &b)
Definition Math11.h:19
DirectX::XMFLOAT3 Vector
Definition Math11.h:7
Vector4 TransformClip(const Vector &a, const Matrix &matrix)
Definition Math11.h:27
float Dot(const Vector &a, const Vector &b)
Definition Math11.h:15
const ShaderSampler11 CustomUISamplers[]
std::vector< char > ReadShaderBytecode11(const std::filesystem::path &path, HMODULE resourceModule=nullptr)
Model.
RiseMath::Vector2 Project(const RiseMath::Vector3 &terrainPosition, float radius, const RiseMath::Matrix &mapView, float pixelsPerKmX, float pixelsPerKmY, RiseMath::Vector2 center)
std::vector< Texel > Field(const std::vector< Segment > &cuts, float width, float height, int condition)
std::vector< Segment > Network(float width, float height, uint32_t seed)
Microsoft::WRL::ComPtr< ID3D11Texture2D > texture
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > rtv
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > srv
std::vector< WindshieldFractures::Segment > fractureNetwork
Microsoft::WRL::ComPtr< ID3D11Buffer > geometry