Rise
The Vieneo Province
Loading...
Searching...
No Matches
Sprite11.cpp
Go to the documentation of this file.
1#include "Sprite11.h"
2#include "FrameProfiler11.h"
3#include <algorithm>
4#include <cmath>
5#include <cstring>
6using namespace DirectX;
7using Microsoft::WRL::ComPtr;
8namespace Rendering
9{
11 {
12 if(context && previous)
13 {
14 context->ClearState();
15 context->SwapDeviceContextState(previous.Get(),nullptr);
16 }
17 previous.Reset();context.Reset();queue.clear();order.clear();state.stages[0].texture.Reset();
19 batchRaster.Reset();batchDepth.Reset();batchBlend.Reset();
20 }
22 {
23 Restore();fixed.Reset();vertices.Reset();indices.Reset();isolated.Reset();device.Reset();
24 XMStoreFloat4x4(&transform,XMMatrixIdentity());status="native sprite renderer not initialized";
25 }
26 HRESULT Sprite11::Initialize(ID3D11Device* native,const std::filesystem::path& directory)
27 {
28 Reset();if(!native)return E_INVALIDARG;device=native;
29 HRESULT hr=fixed.Initialize(native,directory);if(FAILED(hr)){status=fixed.Status();return hr;}
30 ComPtr<ID3D11Device1> device1;if(FAILED(hr=device.As(&device1)))return hr;
31 const D3D_FEATURE_LEVEL level=device->GetFeatureLevel();
32 if(FAILED(hr=device1->CreateDeviceContextState(0,&level,1,D3D11_SDK_VERSION,__uuidof(ID3D11Device),nullptr,&isolated)))return hr;
33 D3D11_BUFFER_DESC desc{};desc.ByteWidth=Capacity*4*sizeof(FixedVertex11);desc.Usage=D3D11_USAGE_DYNAMIC;
34 desc.BindFlags=D3D11_BIND_VERTEX_BUFFER;desc.CPUAccessFlags=D3D11_CPU_ACCESS_WRITE;
35 if(FAILED(hr=device->CreateBuffer(&desc,nullptr,&vertices)))return hr;
36 std::vector<uint16_t> data(Capacity*6);
37 for(unsigned i=0;i<Capacity;++i)
38 {
39 const uint16_t base=uint16_t(i*4),quad[]={base,uint16_t(base+1),uint16_t(base+2),uint16_t(base+2),uint16_t(base+1),uint16_t(base+3)};
40 std::copy(std::begin(quad),std::end(quad),data.begin()+i*6);
41 }
42 desc.ByteWidth=UINT(data.size()*sizeof(uint16_t));desc.Usage=D3D11_USAGE_IMMUTABLE;desc.BindFlags=D3D11_BIND_INDEX_BUFFER;desc.CPUAccessFlags=0;
43 const D3D11_SUBRESOURCE_DATA initial{data.data(),0,0};
44 if(FAILED(hr=device->CreateBuffer(&desc,&initial,&indices)))return hr;
45 status="native sprite renderer ready";return S_OK;
46 }
47 HRESULT Sprite11::Begin(ID3D11DeviceContext* caller,const SpriteOptions11& requested)
48 {
49 ProfileDisplayCpu11 timing("Sprite batch begin");
50 if(!device || !isolated || context || !caller || caller->GetType()!=D3D11_DEVICE_CONTEXT_IMMEDIATE)return E_UNEXPECTED;
51 ComPtr<ID3D11Device> callerDevice;caller->GetDevice(&callerDevice);
52 if(callerDevice!=device)return E_INVALIDARG;
53 ComPtr<ID3D11RenderTargetView> target;ComPtr<ID3D11DepthStencilView> depth;
54 caller->OMGetRenderTargets(1,&target,&depth);if(!target)return E_INVALIDARG;
55 D3D11_VIEWPORT viewport{};UINT count=1;caller->RSGetViewports(&count,&viewport);if(count!=1 || viewport.Width<=0 || viewport.Height<=0)return E_INVALIDARG;
56 ComPtr<ID3D11RasterizerState> currentRaster;caller->RSGetState(&currentRaster);
57 D3D11_RASTERIZER_DESC rs{};
58 if(currentRaster)currentRaster->GetDesc(&rs);
59 rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=TRUE;
60 D3D11_RECT scissor{};count=1;caller->RSGetScissorRects(&count,&scissor);
61 ComPtr<ID3D11RasterizerState> raster;HRESULT hr=device->CreateRasterizerState(&rs,&raster);if(FAILED(hr))return hr;
62 ComPtr<ID3D11DepthStencilState> currentDepth;UINT reference=0;caller->OMGetDepthStencilState(&currentDepth,&reference);
63 D3D11_DEPTH_STENCIL_DESC ds{};
64 if(currentDepth)currentDepth->GetDesc(&ds);
65 else {ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ALL;ds.DepthFunc=D3D11_COMPARISON_LESS;
66 ds.FrontFace=ds.BackFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_ALWAYS};}
67 ds.StencilEnable=FALSE;
68 ComPtr<ID3D11DepthStencilState> depthState;if(FAILED(hr=device->CreateDepthStencilState(&ds,&depthState)))return hr;
69 D3D11_BLEND_DESC bs{};
70 bs.RenderTarget[0]={requested.alphaBlend ? TRUE : FALSE,D3D11_BLEND_SRC_ALPHA,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,
71 D3D11_BLEND_SRC_ALPHA,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,D3D11_COLOR_WRITE_ENABLE_ALL};
72 FLOAT blendFactor[4]{1,1,1,1};UINT sampleMask=UINT_MAX;
73 if(requested.inheritBlend)
74 {
75 ComPtr<ID3D11BlendState> currentBlend;caller->OMGetBlendState(&currentBlend,blendFactor,&sampleMask);
76 if(currentBlend)currentBlend->GetDesc(&bs);
77 else bs.RenderTarget[0]={FALSE,D3D11_BLEND_ONE,D3D11_BLEND_ZERO,D3D11_BLEND_OP_ADD,
78 D3D11_BLEND_ONE,D3D11_BLEND_ZERO,D3D11_BLEND_OP_ADD,D3D11_COLOR_WRITE_ENABLE_ALL};
79 }
80 ComPtr<ID3D11BlendState> blend;if(FAILED(hr=device->CreateBlendState(&bs,&blend)))return hr;
81 if(FAILED(hr=caller->QueryInterface(IID_PPV_ARGS(&context))))return hr;
82 batchRaster=raster;batchDepth=depthState;batchBlend=blend;
83 std::copy(std::begin(blendFactor),std::end(blendFactor),batchBlendFactor);
84 batchSampleMask=sampleMask;batchStencilReference=reference;
85 context->SwapDeviceContextState(isolated.Get(),&previous);
86 auto* output=target.Get();context->OMSetRenderTargets(1,&output,depth.Get());context->RSSetViewports(1,&viewport);
87 context->RSSetState(raster.Get());if(count)context->RSSetScissorRects(1,&scissor);
88 context->OMSetDepthStencilState(depthState.Get(),reference);context->OMSetBlendState(blend.Get(),blendFactor,sampleMask);
89 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);context->IASetIndexBuffer(indices.Get(),DXGI_FORMAT_R16_UINT,0);
90 auto* buffer=vertices.Get();const UINT stride=sizeof(FixedVertex11),offset=0;context->IASetVertexBuffers(0,1,&buffer,&stride,&offset);
91 state=FixedState11{};state.viewport={viewport.TopLeftX,viewport.TopLeftY,viewport.Width,viewport.Height};
93 // D3DXSprite's orthographic projection already offsets integer centers.
94 state.legacyPixelCenters=false;state.alphaTest=requested.alphaBlend;state.alphaFunction=D3D11_COMPARISON_GREATER;
95 auto& stage=state.stages[0];stage.color2=stage.alpha2=TextureArg11::Diffuse;stage.alpha=TextureOp11::Modulate;
96 stage.sampler.Filter=D3D11_FILTER_ANISOTROPIC;stage.sampler.MaxAnisotropy=16;stage.sampler.MaxLOD=D3D11_FLOAT32_MAX;
97 stage.sampler.AddressU=stage.sampler.AddressV=stage.sampler.AddressW=D3D11_TEXTURE_ADDRESS_CLAMP;
98 options=requested;return S_OK;
99 }
100 HRESULT Sprite11::Draw(ID3D11ShaderResourceView* texture,const RECT* source,const Vector* center,const Vector* position,uint32_t color)
101 {
102 ProfileDisplayCpu11 timing("Sprite queue");
103 if(!context || !texture)return E_UNEXPECTED;
104 if(sizeTexture.Get()!=texture)
105 {
106 D3D11_SHADER_RESOURCE_VIEW_DESC view{};texture->GetDesc(&view);if(view.ViewDimension!=D3D11_SRV_DIMENSION_TEXTURE2D)return E_INVALIDARG;
107 ComPtr<ID3D11Resource> resource;texture->GetResource(&resource);ComPtr<ID3D11Texture2D> image;
108 const HRESULT hr=resource.As(&image);if(FAILED(hr))return hr;
109 D3D11_TEXTURE2D_DESC desc{};image->GetDesc(&desc);
110 textureWidth=(std::max)(1u,desc.Width>>view.Texture2D.MostDetailedMip);
111 textureHeight=(std::max)(1u,desc.Height>>view.Texture2D.MostDetailedMip);
112 sizeTexture=texture;
113 }
114 const UINT width=textureWidth,height=textureHeight;
115 const RECT rect=source ? *source : RECT{0,0,LONG(width),LONG(height)};
116 if(rect.right<rect.left || rect.bottom<rect.top)return E_INVALIDARG;
117 const Vector origin=center ? *center : Vector{},at=position ? *position : Vector{};
118 Entry entry;entry.texture=texture;
119 // Fonts encode their layer in SetTransform rather than Draw's position.
120 // Sort in transformed space, just as D3DXSprite does, so cockpit text
121 // stays above its background even when texture batching is enabled.
122 entry.depth=XMVectorGetZ(XMVector3TransformCoord(XMLoadFloat3(&at),XMLoadFloat4x4(&transform)));
123 for(unsigned i=0;i<4;++i)
124 {
125 const float x=(i&1) ? float(rect.right-rect.left) : 0,y=(i&2) ? float(rect.bottom-rect.top) : 0;
126 XMFLOAT4 transformed;XMStoreFloat4(&transformed,XMVector4Transform(XMVectorSet(x+at.x-origin.x,y+at.y-origin.y,at.z-origin.z,1),XMLoadFloat4x4(&transform)));
127 if(!std::isfinite(transformed.w) || std::abs(transformed.w)<1e-20f)return E_INVALIDARG;
128 auto& vertex=entry.vertices[i];
129 // D3DXSprite coordinates are absolute render-target pixels, even in an offset viewport.
130 vertex.position={transformed.x/transformed.w,transformed.y/transformed.w,transformed.z/transformed.w,1/transformed.w};
131 vertex.diffuse=color;vertex.uv[0]={float((i&1) ? rect.right : rect.left)/width,float((i&2) ? rect.bottom : rect.top)/height,0};
132 }
133 queue.push_back(std::move(entry));return S_OK;
134 }
135 HRESULT Sprite11::SetScissor(bool enabled,const RECT& rectangle)
136 {
137 if(!context)return E_UNEXPECTED;
138 D3D11_RASTERIZER_DESC description{};if(!batchRaster)return E_UNEXPECTED;batchRaster->GetDesc(&description);
139 if(bool(description.ScissorEnable)!=enabled)
140 {
141 description.ScissorEnable=enabled;ComPtr<ID3D11RasterizerState> next;
142 const HRESULT hr=device->CreateRasterizerState(&description,&next);if(FAILED(hr))return hr;batchRaster=next;
143 }
144 context->RSSetState(batchRaster.Get());context->RSSetScissorRects(1,&rectangle);return S_OK;
145 }
147 {
148 if(!context)return E_UNEXPECTED;
149 ProfileDisplayCpu11 timing("Sprite flush");
150 // Nested dialog controls restore the game's pipeline while this batch
151 // is still open. Restore the sprite pipeline on every flush, including
152 // disabled culling/stencil, before drawing the next dialog or overlay.
153 context->RSSetState(batchRaster.Get());
154 context->OMSetDepthStencilState(batchDepth.Get(),batchStencilReference);
155 context->OMSetBlendState(batchBlend.Get(),batchBlendFactor,batchSampleMask);
156 // Immediate GUI geometry also replaces the sprite's input buffers.
157 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
158 context->IASetIndexBuffer(indices.Get(),DXGI_FORMAT_R16_UINT,0);
159 auto* buffer=vertices.Get();const UINT stride=sizeof(FixedVertex11),offset=0;
160 context->IASetVertexBuffers(0,1,&buffer,&stride,&offset);
162 if(sorted)
163 {
164 ProfileDisplayCpu11 sortTiming("Sprite sort");
165 order.resize(queue.size());
166 for(size_t i=0;i<order.size();++i)order[i]=i;
167 std::stable_sort(order.begin(),order.end(),[&](size_t left,size_t right) {
168 const auto& a=queue[left];const auto& b=queue[right];
169 // Match D3DXSprite's screen-space Z order: larger Z sorts to the front.
170 if(a.depth!=b.depth && options.sort==SpriteSort11::FrontToBack)return a.depth>b.depth;
171 if(a.depth!=b.depth && options.sort==SpriteSort11::BackToFront)return a.depth<b.depth;
172 if(options.sort==SpriteSort11::Texture || options.sortTextures)return std::less<ID3D11ShaderResourceView*>{}(a.texture.Get(),b.texture.Get());
173 return false;
174 });
175 }
176 // Preserve precisely the old stable order, including equal-depth
177 // transparency and texture-address ties, without moving vertex data.
178 const auto entryAt=[&](size_t i)->const Entry& {return queue[sorted ? order[i] : i];};
179 for(size_t first=0;first<queue.size();first+=Capacity)
180 {
181 ProfileDisplayCpu11 uploadTiming("Sprite vertex upload");
182 const UINT count=UINT((std::min)(size_t(Capacity),queue.size()-first));
183 D3D11_MAPPED_SUBRESOURCE mapped{};HRESULT hr=context->Map(vertices.Get(),0,D3D11_MAP_WRITE_DISCARD,0,&mapped);
184 if(FAILED(hr))return hr;
185 auto* output=static_cast<FixedVertex11*>(mapped.pData);
186 for(UINT i=0;i<count;++i)
187 {
188 const auto& entry=entryAt(first+i);
189 std::copy(entry.vertices.begin(),entry.vertices.end(),output+i*4);
190 }
191 context->Unmap(vertices.Get(),0);
192 FrameProfiler11::Get().BufferUpload(UINT64(count)*4*sizeof(FixedVertex11));
193 uploadTiming.Stop();
194 ProfileDisplayCpu11 submitTiming("Sprite draw submission");
195 for(UINT i=0;i<count;)
196 {
197 const auto& entry=entryAt(first+i);
198 UINT end=i+1;while(end<count && entryAt(first+end).texture==entry.texture)++end;
199 state.stages[0].texture=entry.texture;
200 if(FAILED(hr=fixed.Bind(context.Get(),state))){status=fixed.Status();return hr;}
201 context->DrawIndexed((end-i)*6,i*6,0);i=end;
202 }
203 }
204 queue.clear();order.clear();sizeTexture.Reset();textureWidth=textureHeight=0;return S_OK;
205 }
207 {
208 if(!context)return E_UNEXPECTED;
209 const HRESULT hr=Flush();Restore();return hr;
210 }
211}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
const std::string & Status() const
static FrameProfiler11 & Get()
void BufferUpload(UINT64 bytes)
FixedFunction11 fixed
Definition Sprite11.h:44
UINT batchStencilReference
Definition Sprite11.h:43
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > batchDepth
Definition Sprite11.h:40
DirectX::XMFLOAT3 Vector
Definition Sprite11.h:11
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
Definition Sprite11.cpp:26
HRESULT Draw(ID3D11ShaderResourceView *texture, const RECT *source=nullptr, const Vector *center=nullptr, const Vector *position=nullptr, uint32_t color=0xffffffff)
Definition Sprite11.cpp:100
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > sizeTexture
Definition Sprite11.h:53
FLOAT batchBlendFactor[4]
Definition Sprite11.h:42
HRESULT SetScissor(bool enabled, const RECT &rectangle)
Definition Sprite11.cpp:135
SpriteOptions11 options
Definition Sprite11.h:46
Microsoft::WRL::ComPtr< ID3D11RasterizerState > batchRaster
Definition Sprite11.h:39
Microsoft::WRL::ComPtr< ID3D11BlendState > batchBlend
Definition Sprite11.h:41
Microsoft::WRL::ComPtr< ID3D11Buffer > vertices
Definition Sprite11.h:38
std::vector< Entry > queue
Definition Sprite11.h:48
Microsoft::WRL::ComPtr< ID3DDeviceContextState > isolated
Definition Sprite11.h:37
Microsoft::WRL::ComPtr< ID3D11Buffer > indices
Definition Sprite11.h:38
static constexpr UINT Capacity
Definition Sprite11.h:27
std::vector< size_t > order
Definition Sprite11.h:50
HRESULT Begin(ID3D11DeviceContext *context, const SpriteOptions11 &options={})
Definition Sprite11.cpp:47
Microsoft::WRL::ComPtr< ID3D11Device > device
Definition Sprite11.h:35
FixedState11 state
Definition Sprite11.h:45
Microsoft::WRL::ComPtr< ID3D11DeviceContext1 > context
Definition Sprite11.h:36
std::string status
Definition Sprite11.h:55
Microsoft::WRL::ComPtr< ID3DDeviceContextState > previous
Definition Sprite11.h:37
Definition DDS.h:24
Model.
std::array< TextureStage11, 8 > stages
D3D11_COMPARISON_FUNC alphaFunction
DirectX::XMFLOAT4 viewport
Definition Sprite11.h:29
std::array< FixedVertex11, 4 > vertices
Definition Sprite11.h:31
float depth
Definition Sprite11.h:32
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > texture
Definition Sprite11.h:30