Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/SpriteBatch11Tests.cpp

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

1#include "../Rendering/Device11.h"
2#include "Reference/Sprite11Baseline.h"
3#include <d3d11sdklayers.h>
4#include <algorithm>
5#include <chrono>
6#include <cstring>
7#include <fstream>
8#include <iostream>
9#include <stdexcept>
10using namespace Rendering;
11using namespace DirectX;
12using Microsoft::WRL::ComPtr;
13namespace
14{
15 void Check(bool ok,const char* message){if(!ok)throw std::runtime_error(message);}
16 void HR(HRESULT hr,const char* message){Check(SUCCEEDED(hr),message);}
17 struct Fixture
18 {
19 static constexpr UINT Width=320,Height=240;
20 Device11 gpu;Sprite11 current;Sprite11Baseline baseline;
21 ComPtr<ID3D11Texture2D> target,staging;
22 ComPtr<ID3D11RenderTargetView> rtv;
23 ComPtr<ID3D11DepthStencilState> noDepth;
24 ComPtr<ID3D11RasterizerState> raster;
25 ComPtr<ID3D11ShaderResourceView> textures[3],invalidView;
26 unsigned comparisons=0;
27 Fixture(bool warp,bool debug)
28 {
29 HR(gpu.Create({warp?D3D_DRIVER_TYPE_WARP:D3D_DRIVER_TYPE_HARDWARE,debug}),"device");
30 std::cout<<gpu.Status()<<'\n';
31 HR(current.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"current initialize");
32 HR(baseline.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"baseline initialize");
33 D3D11_TEXTURE2D_DESC desc{};desc.Width=Width;desc.Height=Height;desc.MipLevels=desc.ArraySize=desc.SampleDesc.Count=1;
34 desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
35 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&target),"target");HR(gpu.Device()->CreateRenderTargetView(target.Get(),nullptr,&rtv),"RTV");
36 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
37 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"staging");
38 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;ds.StencilEnable=TRUE;
39 ds.StencilReadMask=ds.StencilWriteMask=255;ds.FrontFace=ds.BackFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_NEVER};
40 HR(gpu.Device()->CreateDepthStencilState(&ds,&noDepth),"hostile stencil");
41 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_FRONT;rs.DepthClipEnable=rs.ScissorEnable=TRUE;
42 HR(gpu.Device()->CreateRasterizerState(&rs,&raster),"raster");
43 std::array<uint32_t,32*32> pixels{};std::array<uint32_t,16*16> mip{};
44 for(unsigned i=0;i<pixels.size();++i)pixels[i]=0x70003080u|((i%32)*5u<<16)|((i/32)*6u<<8);
45 std::fill(mip.begin(),mip.end(),0x90ff0030u);
46 desc.Width=desc.Height=32;desc.MipLevels=2;desc.Usage=D3D11_USAGE_IMMUTABLE;desc.CPUAccessFlags=0;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
47 const D3D11_SUBRESOURCE_DATA data[]={{pixels.data(),32*4,0},{mip.data(),16*4,0}};
48 ComPtr<ID3D11Texture2D> image;HR(gpu.Device()->CreateTexture2D(&desc,data,&image),"image");
49 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&textures[0]),"full view");
50 D3D11_SHADER_RESOURCE_VIEW_DESC view{};view.Format=desc.Format;view.ViewDimension=D3D11_SRV_DIMENSION_TEXTURE2D;view.Texture2D={1,1};
51 HR(gpu.Device()->CreateShaderResourceView(image.Get(),&view,&textures[1]),"mip view");
52 for(auto& pixel:pixels)pixel^=0x00ffffff;
53 image.Reset();HR(gpu.Device()->CreateTexture2D(&desc,data,&image),"alternate image");
54 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&textures[2]),"alternate view");
55 desc.MipLevels=1;desc.ArraySize=2;const D3D11_SUBRESOURCE_DATA arrayData[]={data[0],data[0]};
56 image.Reset();HR(gpu.Device()->CreateTexture2D(&desc,arrayData,&image),"array image");
57 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&invalidView),"array view");
58 }
59 void Setup(unsigned variant)
60 {
61 auto* c=gpu.Context();c->ClearState();auto* view=rtv.Get();c->OMSetRenderTargets(1,&view,nullptr);
62 const D3D11_VIEWPORT viewport{variant%2?11.f:0.f,variant%2?7.f:0.f,variant%2?298.f:float(Width),variant%2?226.f:float(Height),0,1};
63 c->RSSetViewports(1,&viewport);c->OMSetDepthStencilState(noDepth.Get(),17);c->RSSetState(raster.Get());
64 const RECT clip{5,9,310,229};c->RSSetScissorRects(1,&clip);
65 const float clear[]={.1f,.2f,.3f,.8f};c->ClearRenderTargetView(view,clear);
66 }
67 template<class Sprite> void Queue(Sprite& sprite,unsigned count,unsigned variant,bool boundaries)
68 {
69 for(unsigned i=0;i<count;++i)
70 {
71 XMMATRIX matrix=XMMatrixScaling(.17f,.23f,1)*XMMatrixRotationZ(float(variant)*.13f);
72 Sprite11::Matrix transform;XMStoreFloat4x4(&transform,matrix);
73 transform._41=float(i%63)*4-12;transform._42=float((i/63)%63)*3-6;
74 // Same-depth transparent overlaps, transform Z and position Z,
75 // nonzero perspective W, and partially clipped map cells.
76 transform._43=i%3==0 ? .6f : .1f;
77 if(variant==3){transform._14=.0003f;transform._24=-.0002f;}
78 sprite.SetTransform(transform);
79 const Sprite11::Vector at(float(i%5),float(i%7),i%3==1 ? .5f : 0),pivot(3,2,0);
80 const RECT source=variant==2 ? RECT{-4,-3,40,37} : RECT{0,0,32,32};
81 const unsigned texture=variant==4 ? i%3 : (i%97==0 ? 2 : 0);
82 HR(sprite.Draw(textures[texture].Get(),variant==1 ? nullptr : &source,&pivot,&at,0xa0ffffffu-i%8*0x00010101u),"queue");
83 if(boundaries && (i==count/3 || i==count*2/3))
84 {
85 HR(sprite.Flush(),"instrument flush");
86 const RECT clip=i==count/3 ? RECT{70,30,220,165} : RECT{5,9,310,229};
87 HR(sprite.SetScissor(true,clip),"instrument scissor");
88 // Emulate immediate geometry/nested controls disturbing IA.
89 gpu.Context()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
90 gpu.Context()->IASetIndexBuffer(nullptr,DXGI_FORMAT_R16_UINT,0);
91 }
92 }
93 }
94 std::vector<uint32_t> Read()
95 {
96 auto* c=gpu.Context();c->OMSetRenderTargets(0,nullptr,nullptr);c->CopyResource(staging.Get(),target.Get());
97 D3D11_MAPPED_SUBRESOURCE mapped{};HR(c->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"read");
98 std::vector<uint32_t> pixels(Width*Height);
99 for(UINT y=0;y<Height;++y)memcpy(pixels.data()+y*Width,static_cast<char*>(mapped.pData)+y*mapped.RowPitch,Width*4);
100 c->Unmap(staging.Get(),0);return pixels;
101 }
102 template<class Sprite> std::vector<uint32_t> Render(Sprite& sprite,const SpriteOptions11& options,unsigned count,unsigned variant)
103 {
104 Setup(variant);HR(sprite.Begin(gpu.Context(),options),"begin");
105 sprite.Sampler().AddressU=sprite.Sampler().AddressV=variant==2 ? D3D11_TEXTURE_ADDRESS_WRAP : D3D11_TEXTURE_ADDRESS_CLAMP;
106 Queue(sprite,count,variant,variant%2!=0);HR(sprite.Flush(),"screen flush");HR(sprite.Flush(),"empty flush");HR(sprite.End(),"end");
107 ComPtr<ID3D11RasterizerState> restored;gpu.Context()->RSGetState(&restored);Check(restored==raster,"restore caller raster");
108 ComPtr<ID3D11DepthStencilState> depth;UINT reference=0;gpu.Context()->OMGetDepthStencilState(&depth,&reference);
109 Check(depth==noDepth && reference==17,"restore caller stencil");return Read();
110 }
111 void Compare(const SpriteOptions11& options,unsigned count,unsigned variant)
112 {
113 const auto expected=Render(baseline,options,count,variant),actual=Render(current,options,count,variant);
114 if(expected!=actual)
115 {
116 std::cerr<<"PIXEL MISMATCH count="<<count<<" variant="<<variant<<" sort="<<int(options.sort)<<'\n';
117 throw std::runtime_error("optimized sprite pixels differ from frozen renderer");
118 }
119 ++comparisons;
120 }
121 void ErrorsAndLifetime()
122 {
123 Setup(0);HR(current.Begin(gpu.Context()),"error begin");HR(baseline.Begin(gpu.Context()),"nested baseline begin");
124 // Validation must not poison the cached dimensions of a valid SRV.
125 for(auto* texture:{textures[0].Get(),invalidView.Get(),textures[1].Get(),static_cast<ID3D11ShaderResourceView*>(nullptr),textures[0].Get()})
126 {
127 const RECT valid{0,0,16,16},bad{9,0,2,16};
128 for(const RECT* rect:{&valid,&bad})
129 Check(current.Draw(texture,rect)==baseline.Draw(texture,rect),"Draw validation parity");
130 }
131 HR(baseline.End(),"nested baseline end");HR(current.End(),"error end");
132 current.Reset();baseline.Reset();
133 HR(current.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"current reinitialize");
134 HR(baseline.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"baseline reinitialize");
135 Compare({},1025,4);
136 }
137 template<class Sprite> std::array<double,2> Time(Sprite& sprite)
138 {
139 Setup(0);SpriteOptions11 options;options.sort=SpriteSort11::BackToFront;options.sortTextures=true;
140 HR(sprite.Begin(gpu.Context(),options),"benchmark begin");
141 const auto start=std::chrono::steady_clock::now();
142 Queue(sprite,6498,0,false);const auto queued=std::chrono::steady_clock::now();
143 HR(sprite.End(),"benchmark end");const auto end=std::chrono::steady_clock::now();
144 return {std::chrono::duration<double,std::milli>(queued-start).count(),std::chrono::duration<double,std::milli>(end-queued).count()};
145 }
146 void Benchmark()
147 {
148 std::vector<double> queue[2],flush[2],total[2];
149 for(unsigned frame=0;frame<144;++frame)for(unsigned order=0;order<2;++order)
150 {
151 const unsigned mode=(frame+order)%2;const auto time=mode ? Time(current) : Time(baseline);
152 if(frame<24)continue;
153 queue[mode].push_back(time[0]);flush[mode].push_back(time[1]);total[mode].push_back(time[0]+time[1]);
154 }
155 for(unsigned mode=0;mode<2;++mode)
156 {
157 double q=0,f=0;for(double value:queue[mode])q+=value;for(double value:flush[mode])f+=value;
158 std::sort(total[mode].begin(),total[mode].end());
159 std::cout<<"BENCH "<<(mode?"optimized":"baseline")<<" 6498 sprites, CPU ms: queue="<<q/120<<" flush="<<f/120
160 <<" total="<<(q+f)/120<<" p95="<<total[mode][114]<<'\n';
161 }
162 }
163 void DebugClean()
164 {
165 ComPtr<ID3D11InfoQueue> info;if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&info))))return;
166 for(UINT64 i=0;i<info->GetNumStoredMessages();++i)
167 {
168 SIZE_T size=0;info->GetMessage(i,nullptr,&size);std::vector<char> bytes(size);auto* message=reinterpret_cast<D3D11_MESSAGE*>(bytes.data());
169 HR(info->GetMessage(i,message,&size),"debug message");if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
170 }
171 }
172 };
173}
174int main(int argc,char** argv)
175{
176 try
177 {
178 bool warp=false,debug=true;for(int i=1;i<argc;++i)
179 if(!strcmp(argv[i],"--warp"))warp=true;else if(!strcmp(argv[i],"--no-debug-layer"))debug=false;else throw std::runtime_error("unknown option");
180 Fixture test(warp,debug);
181 for(unsigned mode=0;mode<5;++mode)
182 {
184 options.sortTextures=mode==4;
185 for(unsigned count:{0u,1u,1023u,1024u,1025u,3233u,6498u})test.Compare(options,count,count%4);
186 for(unsigned variant=0;variant<5;++variant)test.Compare(options,97,variant);
187 options.alphaBlend=false;test.Compare(options,97,4);
188 }
189 test.ErrorsAndLifetime();test.DebugClean();
190 std::cout<<"PASS: "<<test.comparisons<<" exact before/after pixel comparisons; ordering, equal-depth transparency, chunk boundaries, mip SRVs, flush/scissor, validation and reinitialize\n";
191 test.Benchmark();test.DebugClean();return 0;
192 }
193 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<'\n';return 1;}
194}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
ID3D11DeviceContext * Context() const
Definition Device11.h:66
ID3D11Device * Device() const
Definition Device11.h:65
const std::string & Status() const
Definition Device11.h:75
HRESULT Create(const DeviceOptions11 &options={})
Definition Device11.cpp:84
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
HRESULT Begin(ID3D11DeviceContext *context, const SpriteOptions11 &options={})
Definition Sprite11.cpp:47
void Draw(RiseMath::Color prmColor)
Definition Sprite.cpp:75
Definition DDS.h:24
constexpr float Height
HRESULT Render(RiseDialog &hud, float elapsedTime, int dialogId, Logger &logger)
info
Definition erin.py:153