Rise
The Vieneo Province
Loading...
Searching...
No Matches
ProceduralLightning11.cpp
Go to the documentation of this file.
2#include "ShaderBytecode11.h"
4using namespace DirectX;
5using Microsoft::WRL::ComPtr;
6namespace Rendering
7{
8 namespace
9 {
10 void Unbind(ID3D11DeviceContext* context)
11 {
12 ID3D11ShaderResourceView* empty[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]{};
13 context->PSSetShaderResources(0,UINT(std::size(empty)),empty);
14 context->VSSetShaderResources(0,UINT(std::size(empty)),empty);
15 context->OMSetRenderTargets(0,nullptr,nullptr);
16 }
17 struct Restore
18 {
19 ComPtr<ID3D11DeviceContext1> context;ComPtr<ID3DDeviceContextState> previous;
20 ~Restore(){if(previous){Unbind(context.Get());context->SwapDeviceContextState(previous.Get(),nullptr);}}
21 };
22 }
24 {
25 vertices.Reset();indices.Reset();program.Reset();state.Reset();raster.Reset();
26 depthState.Reset();blend.Reset();sampler.Reset();device.Reset();indexCount=builds=0;
31 }
32 HRESULT ProceduralLightning11::Initialize(ID3D11Device* native,const std::filesystem::path& directory)
33 {
34 Reset();if(!native)return E_INVALIDARG;device=native;
35 ComPtr<ID3D11Device1> device1;HRESULT hr=device.As(&device1);if(FAILED(hr))return hr;
36 const auto level=device->GetFeatureLevel();
37 if(FAILED(hr=device1->CreateDeviceContextState(0,&level,1,D3D11_SDK_VERSION,__uuidof(ID3D11Device),nullptr,&state)))return hr;
38 const auto vs=ReadShaderBytecode11(directory/"ProceduralLightning-boltVertex-1.cso");
39 const auto ps=ReadShaderBytecode11(directory/"ProceduralLightning-boltPixel-1.cso");
40 const D3D11_INPUT_ELEMENT_DESC layout[]={
41 {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0},
42 {"NORMAL",0,DXGI_FORMAT_R32G32B32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA,0},
43 {"TEXCOORD",0,DXGI_FORMAT_R32G32B32_FLOAT,0,24,D3D11_INPUT_PER_VERTEX_DATA,0}};
44 if(FAILED(hr=program.Create(device.Get(),vs.data(),vs.size(),ps.data(),ps.size(),layout,3)))return hr;
45 const auto capturePS=ReadShaderBytecode11(directory/"ProceduralLightning-boltCapturePixel-1.cso");
46 if(FAILED(hr=captureProgram.Create(device.Get(),vs.data(),vs.size(),capturePS.data(),capturePS.size(),layout,3)))return hr;
47 const auto screenVS=ReadShaderBytecode11(directory/"ProceduralLightning-Fullscreen11-1.cso");
48 const auto historyPS=ReadShaderBytecode11(directory/"ProceduralLightning-afterimageHistory-1.cso");
49 const auto ghostPS=ReadShaderBytecode11(directory/"ProceduralLightning-afterimageGhost-1.cso");
50 if(FAILED(hr=historyProgram.Create(device.Get(),screenVS.data(),screenVS.size(),historyPS.data(),historyPS.size())))return hr;
51 if(FAILED(hr=ghostProgram.Create(device.Get(),screenVS.data(),screenVS.size(),ghostPS.data(),ghostPS.size())))return hr;
52 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=TRUE;rs.MultisampleEnable=TRUE;
53 if(FAILED(hr=device->CreateRasterizerState(&rs,&raster)))return hr;
54 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ZERO;ds.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;
55 ds.StencilEnable=TRUE;ds.StencilReadMask=255;ds.StencilWriteMask=0;
56 ds.FrontFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_GREATER};ds.BackFace=ds.FrontFace;
57 if(FAILED(hr=device->CreateDepthStencilState(&ds,&depthState)))return hr;
58 ds.DepthEnable=ds.StencilEnable=FALSE;
59 if(FAILED(hr=device->CreateDepthStencilState(&ds,&noDepth)))return hr;
60 D3D11_BLEND_DESC bs{};
61 bs.RenderTarget[0]={TRUE,D3D11_BLEND_ONE,D3D11_BLEND_ONE,D3D11_BLEND_OP_ADD,
62 D3D11_BLEND_ZERO,D3D11_BLEND_ONE,D3D11_BLEND_OP_ADD,D3D11_COLOR_WRITE_ENABLE_RED|D3D11_COLOR_WRITE_ENABLE_GREEN|D3D11_COLOR_WRITE_ENABLE_BLUE};
63 if(FAILED(hr=device->CreateBlendState(&bs,&blend)))return hr;
64 bs.IndependentBlendEnable=TRUE;
65 bs.RenderTarget[1]={TRUE,D3D11_BLEND_ONE,D3D11_BLEND_ONE,D3D11_BLEND_OP_MAX,
66 D3D11_BLEND_ONE,D3D11_BLEND_ONE,D3D11_BLEND_OP_MAX,D3D11_COLOR_WRITE_ENABLE_RED};
67 if(FAILED(hr=device->CreateBlendState(&bs,&captureBlend)))return hr;
68 bs={};bs.RenderTarget[0]={TRUE,D3D11_BLEND_ONE,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,
69 D3D11_BLEND_ZERO,D3D11_BLEND_ONE,D3D11_BLEND_OP_ADD,
70 D3D11_COLOR_WRITE_ENABLE_RED|D3D11_COLOR_WRITE_ENABLE_GREEN|D3D11_COLOR_WRITE_ENABLE_BLUE};
71 if(FAILED(hr=device->CreateBlendState(&bs,&ghostBlend)))return hr;
72 D3D11_SAMPLER_DESC sd{};sd.Filter=D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
73 sd.AddressU=sd.AddressV=sd.AddressW=D3D11_TEXTURE_ADDRESS_CLAMP;sd.MaxLOD=0;sd.MaxAnisotropy=1;sd.ComparisonFunc=D3D11_COMPARISON_NEVER;
74 return device->CreateSamplerState(&sd,&sampler);
75 }
76 void ProceduralLightning11::BeginAfterimage(double now,bool enabled,float ambient,uint64_t viewer)
77 {
78 if(afterimage.Begin(now,enabled,ambient,viewer))historyClear=true;
79 captured=false;
80 }
81 bool ProceduralLightning11::AfterimageSizeMatches(const SceneDepth11& depth,const D3D11_VIEWPORT& viewport) const
82 {
83 const auto& d=depth.Description();
84 return capture.texture && d.Width==captureDescription.Width && d.Height==captureDescription.Height
85 && d.SampleDesc.Count==captureDescription.SampleDesc.Count && d.SampleDesc.Quality==captureDescription.SampleDesc.Quality
86 && viewport.TopLeftX==captureViewport.TopLeftX && viewport.TopLeftY==captureViewport.TopLeftY
87 && viewport.Width==captureViewport.Width && viewport.Height==captureViewport.Height;
88 }
89 HRESULT ProceduralLightning11::AfterimageTargets(const SceneDepth11& depth,const D3D11_VIEWPORT& viewport)
90 {
91 if(AfterimageSizeMatches(depth,viewport))return S_OK;
92 Target next[4];auto desc=depth.Description();
93 desc.Format=DXGI_FORMAT_R16_FLOAT;desc.Usage=D3D11_USAGE_DEFAULT;desc.CPUAccessFlags=desc.MiscFlags=0;
94 desc.MipLevels=desc.ArraySize=1;
95 for(unsigned i=0;i<4;++i)
96 {
97 desc.BindFlags=D3D11_BIND_RENDER_TARGET;
98 if(i){desc.SampleDesc={1,0};desc.BindFlags|=D3D11_BIND_SHADER_RESOURCE;}
99 HRESULT hr=device->CreateTexture2D(&desc,nullptr,&next[i].texture);if(FAILED(hr))return hr;
100 if(FAILED(hr=device->CreateRenderTargetView(next[i].texture.Get(),nullptr,&next[i].rtv)))return hr;
101 if(i && FAILED(hr=device->CreateShaderResourceView(next[i].texture.Get(),nullptr,&next[i].srv)))return hr;
102 }
103 capture=std::move(next[0]);resolved=std::move(next[1]);history[0]=std::move(next[2]);history[1]=std::move(next[3]);
105 historyClear=true;captured=false;afterimage.active=false;historyIndex=0;return S_OK;
106 }
107 HRESULT ProceduralLightning11::CompositeAfterimage(ID3D11DeviceContext* context,ID3D11RenderTargetView* scene,
108 const SceneDepth11& depth,const D3D11_VIEWPORT& viewport)
109 {
110 if(!afterimage.active || afterimage.gain<=0)return S_OK;
111 if(!AfterimageSizeMatches(depth,viewport)){historyClear=true;afterimage.active=false;return S_OK;}
112 if(!context || !scene)return E_INVALIDARG;
113 HRESULT hr;Restore restore;if(FAILED(hr=context->QueryInterface(IID_PPV_ARGS(&restore.context))))return hr;
114 restore.context->SwapDeviceContextState(state.Get(),&restore.previous);Unbind(context);
115 if(captured)
116 {
117 if(captureDescription.SampleDesc.Count>1)
118 context->ResolveSubresource(resolved.texture.Get(),0,capture.texture.Get(),0,DXGI_FORMAT_R16_FLOAT);
119 else context->CopyResource(resolved.texture.Get(),capture.texture.Get());
120 }
121 const float black[4]{};
122 if(historyClear){context->ClearRenderTargetView(history[historyIndex].rtv.Get(),black);historyClear=false;}
123 Parameters11 values;
124 values.Set("afterimageFrame",XMFLOAT4(afterimage.decay,captured ? 1.f : 0.f,
126 values.Sampler("afterimageSampler",sampler.Get());values.Sampler("afterimageCaptureSampler",sampler.Get());
127 values.Texture("afterimagePrevious",history[historyIndex].srv.Get());
128 values.Texture("afterimageCapture",resolved.srv.Get());
129 const D3D11_VIEWPORT full{0,0,float(captureDescription.Width),float(captureDescription.Height),0,1};
130 context->RSSetState(raster.Get());context->RSSetViewports(1,&full);
131 context->OMSetDepthStencilState(noDepth.Get(),0);context->OMSetBlendState(nullptr,nullptr,UINT_MAX);
132 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
133 const unsigned next=1-historyIndex;auto* target=history[next].rtv.Get();
134 context->OMSetRenderTargets(1,&target,nullptr);
135 if(FAILED(hr=historyProgram.Bind(context,values)))return hr;
136 context->Draw(3,0);Unbind(context);historyIndex=next;
137 values.Texture("afterimagePrevious",history[historyIndex].srv.Get());
138 values.Set("afterimageViewport",XMFLOAT4(viewport.TopLeftX/full.Width,viewport.TopLeftY/full.Height,
139 viewport.Width/full.Width,viewport.Height/full.Height));
140 context->RSSetViewports(1,&viewport);context->OMSetRenderTargets(1,&scene,nullptr);
141 context->OMSetBlendState(ghostBlend.Get(),nullptr,UINT_MAX);
142 if(FAILED(hr=ghostProgram.Bind(context,values)))return hr;
143 context->Draw(3,0);captured=false;return S_OK;
144 }
146 {
147 for(const auto& entry:geometryCache)
148 if(entry.vertices && seed==entry.seed && offset.x==entry.offset.x && offset.y==entry.offset.y && offset.z==entry.offset.z)
149 {vertices=entry.vertices;indices=entry.indices;indexCount=entry.indexCount;return S_OK;}
150 const auto mesh=ProceduralLightning::Generate(offset,seed);
151 if(mesh.indices.empty()){vertices.Reset();indices.Reset();indexCount=0;return S_FALSE;}
152 D3D11_BUFFER_DESC desc{};desc.Usage=D3D11_USAGE_IMMUTABLE;desc.BindFlags=D3D11_BIND_VERTEX_BUFFER;
153 desc.ByteWidth=UINT(mesh.vertices.size()*sizeof(ProceduralLightning::Vertex));
154 D3D11_SUBRESOURCE_DATA data{mesh.vertices.data(),0,0};
155 ComPtr<ID3D11Buffer> nextVertices,nextIndices;
156 HRESULT hr=device->CreateBuffer(&desc,&data,&nextVertices);if(FAILED(hr))return hr;
157 desc.BindFlags=D3D11_BIND_INDEX_BUFFER;desc.ByteWidth=UINT(mesh.indices.size()*sizeof(uint16_t));data.pSysMem=mesh.indices.data();
158 if(FAILED(hr=device->CreateBuffer(&desc,&data,&nextIndices)))return hr;
159 vertices=std::move(nextVertices);indices=std::move(nextIndices);indexCount=UINT(mesh.indices.size());
160 auto& entry=geometryCache[nextGeometry];nextGeometry=(nextGeometry+1)%unsigned(geometryCache.size());
161 entry={offset,seed,indexCount,vertices,indices};++builds;return S_OK;
162 }
163 HRESULT ProceduralLightning11::Render(ID3D11DeviceContext* context,ID3D11RenderTargetView* scene,const SceneDepth11& depth,
164 const D3D11_VIEWPORT& viewport,const Matrix& view,const Matrix& projection,
165 Vector origin,Vector ground,Vector cloud,uint32_t seed,const RiseMath::Color& color,
166 float pulse,float visibilityKm,CloudRenderer11* atmosphere,float growth)
167 {
168 if(!std::isfinite(pulse) || pulse<=0 || !std::isfinite(growth) || growth<=0)return S_OK;
169 if(!device || !context || !scene || !depth.ReadView() || !ProceduralLightning::Finite(origin)
170 || !ProceduralLightning::Finite(ground) || !ProceduralLightning::Finite(cloud))return E_INVALIDARG;
171 HRESULT hr=Geometry(cloud-ground,seed);if(hr!=S_OK)return hr;
172 XMVECTOR determinant;XMFLOAT4X4 inverse;
173 XMStoreFloat4x4(&inverse,XMMatrixInverse(&determinant,XMLoadFloat4x4(&view)));
174 if(std::abs(XMVectorGetX(determinant))<1e-20f)return E_INVALIDARG;
175 Parameters11 values=atmosphere && atmosphere->Ready() ? atmosphere->Parameters() : Parameters11{};
176 const auto relative=ground-origin;
177 values.Set("boltView",view);values.Set("boltProjection",projection);
178 values.Set("boltOrigin",XMFLOAT4(relative.x,relative.y,relative.z,0));
179 values.Set("boltCamera",XMFLOAT4(inverse._41,inverse._42,inverse._43,0));
180 const bool imprint=afterimage.gain>0;
181 if(imprint && FAILED(hr=AfterimageTargets(depth,viewport)))return hr;
182 values.Set("boltDisplay",XMFLOAT4(viewport.Width,viewport.Height,visibilityKm,afterimage.gain));
183 values.Set("afterimageTuning",XMFLOAT4(LightningAfterimage::CaptureThreshold,LightningAfterimage::FullExposure,0,0));
184 values.Set("boltColor",XMFLOAT4(color.r,color.g,color.b,LocalLightning::Radiance(pulse)));
185 const auto axis=cloud-ground;
186 const float lengthSquared=axis.x*axis.x+axis.y*axis.y+axis.z*axis.z;
187 values.Set("boltGrowth",XMFLOAT4(axis.x/lengthSquared,axis.y/lengthSquared,axis.z/lengthSquared,
188 (std::min)(growth,1.f)*1.03f));
189 values.Set("eye",XMFLOAT4(origin.x+inverse._41,origin.y+inverse._42,origin.z+inverse._43,1));
190 if(!atmosphere || !atmosphere->Ready())values.Set("rainInfo",XMFLOAT4(0,42.16f,0,0));
191 values.Sampler("rainSampler",sampler.Get());
192 Restore restore;if(FAILED(hr=context->QueryInterface(IID_PPV_ARGS(&restore.context))))return hr;
193 restore.context->SwapDeviceContextState(state.Get(),&restore.previous);Unbind(context);
194 context->RSSetState(raster.Get());context->RSSetViewports(1,&viewport);
195 if(imprint && !captured){const float black[4]{};context->ClearRenderTargetView(capture.rtv.Get(),black);}
196 ID3D11RenderTargetView* targets[]={scene,capture.rtv.Get()};
197 context->OMSetRenderTargets(imprint ? 2 : 1,targets,depth.ReadView());context->OMSetDepthStencilState(depthState.Get(),3);
198 context->OMSetBlendState(imprint ? captureBlend.Get() : blend.Get(),nullptr,UINT_MAX);
199 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
200 const UINT stride=sizeof(ProceduralLightning::Vertex),offset=0;
201 context->IASetVertexBuffers(0,1,vertices.GetAddressOf(),&stride,&offset);context->IASetIndexBuffer(indices.Get(),DXGI_FORMAT_R16_UINT,0);
202 if(FAILED(hr=(imprint ? captureProgram : program).Bind(context,values)))return hr;
203 context->DrawIndexed(indexCount,0,0);
204 if(imprint){captured=true;afterimage.Capture();}
205 return S_OK;
206 }
207}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
const Parameters11 & Parameters() const
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
Microsoft::WRL::ComPtr< ID3DDeviceContextState > state
HRESULT CompositeAfterimage(ID3D11DeviceContext *context, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport)
void BeginAfterimage(double now, bool enabled, float ambient, uint64_t viewer)
Microsoft::WRL::ComPtr< ID3D11SamplerState > sampler
Microsoft::WRL::ComPtr< ID3D11BlendState > ghostBlend
Microsoft::WRL::ComPtr< ID3D11Buffer > vertices
std::array< GeometryEntry, LightningTiming::MaxChainedBolts+1 > geometryCache
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &directory={})
HRESULT Render(ID3D11DeviceContext *context, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, const Matrix &view, const Matrix &projection, Vector observerOrigin, Vector ground, Vector cloud, uint32_t seed, const RiseMath::Color &color, float pulse, float visibilityKm, CloudRenderer11 *atmosphere=nullptr, float growth=1.f)
Microsoft::WRL::ComPtr< ID3D11BlendState > blend
LightningAfterimage::State afterimage
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > noDepth
Microsoft::WRL::ComPtr< ID3D11Buffer > indices
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > depthState
Microsoft::WRL::ComPtr< ID3D11Device > device
bool AfterimageSizeMatches(const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport) const
Microsoft::WRL::ComPtr< ID3D11RasterizerState > raster
HRESULT AfterimageTargets(const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport)
HRESULT Geometry(Vector offset, uint32_t seed)
Microsoft::WRL::ComPtr< ID3D11BlendState > captureBlend
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)
HRESULT Bind(ID3D11DeviceContext *context, const Parameters11 &parameters)
const D3D11_TEXTURE2D_DESC & Description() const
Definition Device11.h:22
ID3D11DepthStencilView * ReadView() const
Definition Device11.h:19
Definition DDS.h:24
constexpr float FullExposure
constexpr float CaptureThreshold
constexpr float PeakOpacity
float Radiance(float pulse)
Mesh Generate(Vector3 cloudOffset, uint32_t seed)
std::vector< char > ReadShaderBytecode11(const std::filesystem::path &path, HMODULE resourceModule=nullptr)
Model.
bool Begin(double now, bool enabled, float ambient, uint64_t view)
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > rtv
Microsoft::WRL::ComPtr< ID3D11Texture2D > texture
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > srv