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

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

1#include "../Rendering/Device11.h"
2#include "../Rendering/Font11.h"
3#include <d3dx9.h>
4#include <d3d11sdklayers.h>
5#include <cstring>
6#include <cmath>
7#include <fstream>
8#include <iostream>
9#include <stdexcept>
10#include <chrono>
11using namespace Rendering;
12using Microsoft::WRL::ComPtr;
13namespace
14{
15 constexpr UINT Width=320,Height=240;
16 void HR(HRESULT hr,const char* what){if(FAILED(hr))throw std::runtime_error(std::string(what)+": "+std::to_string(hr));}
17 void Check(bool value,const char* what){if(!value)throw std::runtime_error(what);}
18 struct Fixture
19 {
20 Device11 gpu;
21 Sprite11 sprite;
22 Font11 font;
23 ComPtr<ID3DXFont> oldFont;
24 ComPtr<IDirect3D9> api;
25 ComPtr<IDirect3DDevice9> old;
26 ComPtr<ID3DXSprite> oldSprite;
27 ComPtr<IDirect3DTexture9> oldBackground;
28 ComPtr<ID3D11ShaderResourceView> background;
29 ComPtr<IDirect3DSurface9> oldTarget,oldStaging;
30 ComPtr<ID3D11Texture2D> target,staging;
31 ComPtr<ID3D11RenderTargetView> rtv;
32 HWND window=nullptr;
33 std::filesystem::path folder;
34 std::ofstream metrics;
35 unsigned failures=0;
36 Fixture(bool warp,bool debug)
37 {
38 folder=std::string("outputs/direct3d11/font-")+(warp ? "warp" : "hardware");std::filesystem::create_directories(folder);
39 metrics.open(folder/"metrics.csv");metrics<<"case,mean_rgb,mean_alpha,fraction_over_3,max_rgb\n";
40 HR(gpu.Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,debug}),"native device");std::cout<<gpu.Status()<<std::endl;
41 HR(sprite.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"native sprite");
42 window=CreateWindowW(L"STATIC",L"Font parity",WS_POPUP,0,0,Width,Height,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);Check(window!=nullptr,"window");
43 api.Attach(Direct3DCreate9(D3D_SDK_VERSION));Check(bool(api),"reference API");D3DPRESENT_PARAMETERS pp{};
44 pp.Windowed=TRUE;pp.SwapEffect=D3DSWAPEFFECT_DISCARD;pp.BackBufferWidth=Width;pp.BackBufferHeight=Height;pp.hDeviceWindow=window;
45 HR(api->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,&pp,&old),"reference device");
46 HR(D3DXCreateSprite(old.Get(),&oldSprite),"reference sprite");
47 HR(old->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&oldTarget,nullptr),"reference target");
48 HR(old->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&oldStaging,nullptr),"reference staging");
49 D3D11_TEXTURE2D_DESC desc{};desc.Width=Width;desc.Height=Height;desc.ArraySize=desc.MipLevels=1;
50 desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;desc.SampleDesc.Count=1;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
51 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&target),"native target");HR(gpu.Device()->CreateRenderTargetView(target.Get(),nullptr,&rtv),"native RTV");
52 desc.BindFlags=0;desc.Usage=D3D11_USAGE_STAGING;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"native staging");
53 const DWORD white=0xffffffff;
54 HR(old->CreateTexture(1,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&oldBackground,nullptr),"reference readout background");
55 D3DLOCKED_RECT locked{};HR(oldBackground->LockRect(0,&locked,nullptr,0),"reference background lock");
56 memcpy(locked.pBits,&white,sizeof(white));oldBackground->UnlockRect(0);
57 desc.Width=desc.Height=1;desc.Usage=D3D11_USAGE_IMMUTABLE;desc.CPUAccessFlags=0;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
58 const D3D11_SUBRESOURCE_DATA data{&white,sizeof(white),0};ComPtr<ID3D11Texture2D> image;
59 HR(gpu.Device()->CreateTexture2D(&desc,&data,&image),"native readout background");
60 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&background),"native background view");
61 }
62 ~Fixture(){sprite.Reset();gpu.Context()->ClearState();oldSprite.Reset();old.Reset();api.Reset();if(window)DestroyWindow(window);}
63 void SelectFont(unsigned scenario)
64 {
65 LOGFONTW desc{};desc.lfHeight=16;desc.lfWeight=FW_MEDIUM;
66 desc.lfCharSet=DEFAULT_CHARSET;desc.lfOutPrecision=OUT_TT_ONLY_PRECIS;desc.lfQuality=ANTIALIASED_QUALITY;
67 wcscpy_s(desc.lfFaceName,L"Courier New");
68 if(scenario==1) {desc.lfHeight=12;desc.lfWidth=6;desc.lfWeight=FW_LIGHT;wcscpy_s(desc.lfFaceName,L"DejaVu Sans Mono");}
69 if(scenario==2) {desc.lfHeight=24;wcscpy_s(desc.lfFaceName,L"License Plate");}
70 if(scenario==3) {desc.lfHeight=-12;desc.lfWeight=FW_SEMIBOLD;wcscpy_s(desc.lfFaceName,L"Palatino Linotype");}
71 if(scenario==4) {desc.lfHeight=30;desc.lfWidth=24;desc.lfWeight=FW_LIGHT;wcscpy_s(desc.lfFaceName,L"Arial Narrow");}
72 if(scenario==5) {desc.lfHeight=9;desc.lfWidth=6;desc.lfWeight=FW_SEMIBOLD;wcscpy_s(desc.lfFaceName,L"RCAF_60SQO_ATH_GIMP");}
73 if(scenario>=6)wcscpy_s(desc.lfFaceName,L"Arial");
74 if(scenario==23){desc.lfItalic=TRUE;desc.lfHeight=28;}
75 HR(font.Initialize(gpu.Device(),desc),"native font");oldFont.Reset();
76 HR(D3DXCreateFontW(old.Get(),desc.lfHeight,desc.lfWidth,desc.lfWeight,1,desc.lfItalic,desc.lfCharSet,
77 desc.lfOutPrecision,desc.lfQuality,desc.lfPitchAndFamily,desc.lfFaceName,&oldFont),"reference font");
78 TEXTMETRICW a{},b{};Check(font.Metrics(a) && oldFont->GetTextMetricsW(&b),"font metrics");
79 Check(a.tmHeight==b.tmHeight && a.tmAscent==b.tmAscent && a.tmAveCharWidth==b.tmAveCharWidth,"font metric parity");
80 }
81 void Draw(unsigned scenario,bool native)
82 {
83 const wchar_t* text=L"Rise 0123456789\nC-2 Dasher";
84 UINT format=DT_NOCLIP;RECT rect{25,25,280,190};
85 if(scenario==6){text=L"Center line";format=DT_CENTER|DT_VCENTER|DT_SINGLELINE;}
86 if(scenario==7){text=L"Right\naligned";format=DT_RIGHT;}
87 if(scenario==8){text=L"Wrap long words over several cockpit display lines";rect.right=150;format=DT_WORDBREAK;}
88 if(scenario==9){text=L"Clipped instrument label";rect.right=120;rect.bottom=35;format=DT_LEFT;}
89 if(scenario==10){text=L"Unicode \u00c9\u00fc \u03a9 \u0416 \u2190\u2191\u2192\u2193";format=DT_NOCLIP;}
90 if(scenario==11){text=L"&Awaken && cancel";format=DT_LEFT;}
91 if(scenario==12){text=L"Bottom line";format=DT_SINGLELINE|DT_BOTTOM;rect.right=120;}
92 if(scenario==13){text=L"Flight freeze";format=DT_CENTER|DT_VCENTER;}
93 if(scenario==14){text=L"Temperature: -42\u00b0C";format=DT_NOCLIP;rect.right=rect.bottom=0;}
94 if(scenario==16){text=L"Two\ncentered lines";format=DT_CENTER|DT_VCENTER;}
95 if(scenario==17){text=L"A\tB\tC\n123\t456";format=DT_EXPANDTABS;}
96 if(scenario==18){text=L"First\r\nSecond\r\n";format=DT_LEFT;}
97 if(scenario==19){text=L"UninterruptedSuperlongCockpitInstrumentLabel";format=DT_WORDBREAK;rect.right=110;}
98 if(scenario==20){text=L"\u0633\u0644\u0627\u0645 \u05e9\u05dc\u05d5\u05dd";format=DT_RTLREADING|DT_NOCLIP;}
99 if(scenario==21){text=L"Long centered line";format=DT_CENTER|DT_VCENTER|DT_NOCLIP;rect={100,70,130,75};}
100 if(scenario==23){text=L"Italic fj AVW";format=DT_NOCLIP;}
101 if(scenario==24){text=L"AB\tCD";format=DT_SINGLELINE|DT_NOCLIP;}
102 D3DXMATRIX transform;D3DXMatrixIdentity(&transform);
103 if(scenario>=25)
104 {
105 // XML display text uses transform Z=1, while the surrounding
106 // artwork uses Draw position Z. Both share one sorted batch.
107 const RECT source{0,0,280,180};
108 const DWORD tint=scenario==25 ? 0xffffffff : 0xff000000;
109 if(native)
110 {
111 Sprite11::Matrix identity;memcpy(&identity,&transform,sizeof(identity));sprite.SetTransform(identity);
112 const Sprite11::Vector at(15,15,.2f);HR(sprite.Draw(background.Get(),&source,nullptr,&at,tint),"native instrument background");
113 }
114 else
115 {
116 oldSprite->SetTransform(&transform);const D3DXVECTOR3 at(15,15,.2f);
117 HR(oldSprite->Draw(oldBackground.Get(),&source,nullptr,&at,tint),"reference instrument background");
118 }
119 text=L"IAS 123\nALT 116.064\nSAT -42.0";format=DT_NOCLIP;transform._43=1;
120 }
121 if(scenario==15){D3DXMATRIX scale,rotation;D3DXMatrixScaling(&scale,1.35f,.85f,1);D3DXMatrixRotationZ(&rotation,.2f);transform=scale*rotation;}
122 if(scenario==22)D3DXMatrixScaling(&transform,.625f,.625f,1);
123 if(native){Sprite11::Matrix matrix;memcpy(&matrix,&transform,sizeof(matrix));sprite.SetTransform(matrix);}
124 else oldSprite->SetTransform(&transform);
125 RECT measured9=rect,measured11=rect;
126 const int height9=oldFont->DrawTextW(nullptr,text,-1,&measured9,format|DT_CALCRECT,0xffffffff);
127 const int height11=font.Draw(nullptr,text,-1,&measured11,format|DT_CALCRECT,0xffffffff);
128 if(height9!=height11 || memcmp(&measured9,&measured11,sizeof(RECT)))
129 {
130 std::cout<<"LAYOUT "<<scenario<<": old="<<height9<<" ["<<measured9.left<<','<<measured9.top<<','<<measured9.right<<','<<measured9.bottom
131 <<"] native="<<height11<<" ["<<measured11.left<<','<<measured11.top<<','<<measured11.right<<','<<measured11.bottom<<"]\n";
132 if(native)++failures;
133 }
134 const auto color=scenario==25 ? 0xff000000 : scenario==26 ? 0xffffffff : 0xc0f0d090;
135 if(native)Check(font.Draw(&sprite,text,-1,&rect,format,color)!=0,"native text");
136 else Check(oldFont->DrawTextW(oldSprite.Get(),text,-1,&rect,format,color)!=0,"reference text");
137 }
138 void Save(const std::vector<uint32_t>& pixels,const std::string& name)
139 {
140 D3DLOCKED_RECT lock{};HR(oldStaging->LockRect(&lock,nullptr,0),"save map");for(UINT y=0;y<Height;++y)memcpy(static_cast<char*>(lock.pBits)+y*lock.Pitch,pixels.data()+y*Width,Width*4);
141 oldStaging->UnlockRect();HR(D3DXSaveSurfaceToFileW((folder/name).c_str(),D3DXIFF_PNG,oldStaging.Get(),nullptr,nullptr),"save PNG");
142 }
143 void Compare(unsigned scenario)
144 {
145 SelectFont(scenario);
146 old->SetRenderTarget(0,oldTarget.Get());old->SetDepthStencilSurface(nullptr);
147 D3DVIEWPORT9 vp9{0,0,Width,Height,0,1};
148 // D3D9 Clear observes both the viewport and scissor; D3D11's RTV clear does not.
149 old->SetViewport(&vp9);old->SetRenderState(D3DRS_SCISSORTESTENABLE,FALSE);
150 old->Clear(0,nullptr,D3DCLEAR_TARGET,0xff203040,1,0);
151
152 old->SetViewport(&vp9);old->SetRenderState(D3DRS_ZENABLE,FALSE);old->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
153 old->SetRenderState(D3DRS_SCISSORTESTENABLE,FALSE);const RECT clip{25,30,160,165};old->SetScissorRect(&clip);
154 old->BeginScene();
155 DWORD flags=D3DXSPRITE_ALPHABLEND;
156 if(scenario>=25)flags|=D3DXSPRITE_SORT_DEPTH_BACKTOFRONT|D3DXSPRITE_SORT_TEXTURE;
157 HR(oldSprite->Begin(flags),"reference begin");Draw(scenario,false);HR(oldSprite->End(),"reference end");old->EndScene();
158 HR(old->GetRenderTargetData(oldTarget.Get(),oldStaging.Get()),"reference read");D3DLOCKED_RECT locked{};
159 HR(oldStaging->LockRect(&locked,nullptr,D3DLOCK_READONLY),"reference map");std::vector<uint32_t> expected(Width*Height);
160 for(UINT y=0;y<Height;++y)memcpy(expected.data()+y*Width,static_cast<char*>(locked.pBits)+y*locked.Pitch,Width*4);oldStaging->UnlockRect();
161 auto* context=gpu.Context();context->ClearState();auto* renderTarget=rtv.Get();context->OMSetRenderTargets(1,&renderTarget,nullptr);
162 D3D11_VIEWPORT viewport{float(vp9.X),float(vp9.Y),float(vp9.Width),float(vp9.Height),0,1};context->RSSetViewports(1,&viewport);
163 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;ComPtr<ID3D11DepthStencilState> depthState;HR(gpu.Device()->CreateDepthStencilState(&ds,&depthState),"native disabled depth");context->OMSetDepthStencilState(depthState.Get(),0);
164 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_FRONT;rs.DepthClipEnable=TRUE;rs.ScissorEnable=FALSE;
165 ComPtr<ID3D11RasterizerState> raster;HR(gpu.Device()->CreateRasterizerState(&rs,&raster),"native raster");context->RSSetState(raster.Get());context->RSSetScissorRects(1,&clip);
166 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
167 const float clear[]={32.f/255,48.f/255,64.f/255,1};context->ClearRenderTargetView(renderTarget,clear);
168 SpriteOptions11 options;
169 if(scenario>=25){options.sort=SpriteSort11::BackToFront;options.sortTextures=true;}
170 HR(sprite.Begin(context,options),"native begin");Draw(scenario,true);HR(sprite.End(),"native end");
171 ComPtr<ID3D11RasterizerState> restored;context->RSGetState(&restored);Check(restored==raster,"caller raster state restored");
172 D3D11_PRIMITIVE_TOPOLOGY topology{};context->IAGetPrimitiveTopology(&topology);Check(topology==D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP,"caller topology restored");
173 context->OMSetRenderTargets(0,nullptr,nullptr);context->CopyResource(staging.Get(),target.Get());D3D11_MAPPED_SUBRESOURCE mapped{};
174 HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"native map");std::vector<uint32_t> actual(Width*Height),difference(Width*Height);
175 double error=0,alpha=0;unsigned over=0,maximum=0,active=0;
176 for(UINT y=0;y<Height;++y)for(UINT x=0;x<Width;++x)
177 {
178 const auto a=expected[y*Width+x],b=reinterpret_cast<uint32_t*>(static_cast<char*>(mapped.pData)+y*mapped.RowPitch)[x];actual[y*Width+x]=b;
179 if(a!=0xff203040 || b!=0xff203040)++active;
180 unsigned worst=0;for(int shift:{0,8,16}){const auto delta=unsigned(std::abs(int((a>>shift)&255)-int((b>>shift)&255)));error+=delta;worst=(std::max)(worst,delta);}
181 alpha+=std::abs(int(a>>24)-int(b>>24));maximum=(std::max)(maximum,worst);if(worst>3)++over;difference[y*Width+x]=0xff000000|((std::min)(255u,worst*8)*0x10101);
182 }
183 context->Unmap(staging.Get(),0);Check(active>0,"nonempty text fixture");
184 error/=active*3.;alpha/=active;const double fraction=double(over)/active;
185 // WARP and the D3D9 hardware driver implement anisotropic filtering
186 // differently. Bound the rotated edge case explicitly; every error
187 // metric is normalized over text pixels, not the empty background.
188 const bool samplingPass=scenario==15 ? fraction<=.05 && maximum<=16 : fraction<=.01;
189 const bool passed=error<=1 && alpha<=1 && samplingPass;std::cout<<(passed ? "PASS: " : "FAIL: ")<<"font "<<scenario<<" mean="<<error<<" alpha="<<alpha<<" over3="<<fraction<<" max="<<maximum<<std::endl;
190 metrics<<scenario<<','<<error<<','<<alpha<<','<<fraction<<','<<maximum<<'\n';metrics.flush();
191 const auto prefix="font-"+std::to_string(scenario);Save(expected,prefix+"-d3d9.png");Save(actual,prefix+"-d3d11.png");Save(difference,prefix+"-diff8x.png");
192 if(!passed)++failures;
193 }
194 void DebugCheck()
195 {
196 ComPtr<ID3D11InfoQueue> queue;if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&queue))))return;
197 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
198 {
199 SIZE_T size=0;queue->GetMessage(i,nullptr,&size);std::vector<char> bytes(size);auto* message=reinterpret_cast<D3D11_MESSAGE*>(bytes.data());
200 HR(queue->GetMessage(i,message,&size),"debug message");if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
201 }
202 }
203 void LayoutEdges()
204 {
205 SelectFont(6);
206 for(const auto* text:{L"",L" ",L" ",L"A ",L" A",L"\n",L" \r\n ",L"A\n\n",L"\t",L"A\tB",L"\rA"})
207 for(const UINT flags:{UINT(0),UINT(DT_SINGLELINE),UINT(DT_EXPANDTABS)})
208 {
209 RECT a{10,10,200,100},b=a;
210 const int ra=oldFont->DrawTextW(nullptr,text,-1,&a,flags|DT_CALCRECT,0xffffffff);
211 const int rb=font.Draw(nullptr,text,-1,&b,flags|DT_CALCRECT,0xffffffff);
212 if(ra!=rb || memcmp(&a,&b,sizeof(RECT)))
213 {
214 std::cout<<"EDGE "<<wcslen(text)<<','<<int(*text)<<','<<flags<<": old "<<ra<<' '<<a.left<<','<<a.top<<','<<a.right<<','<<a.bottom
215 <<" native "<<rb<<' '<<b.left<<','<<b.top<<','<<b.right<<','<<b.bottom<<'\n';++failures;
216 }
217 }
218 RECT a{10,10,200,100},b=a;
219 const int ra=oldFont->DrawTextA(nullptr,"C-2 Dasher",5,&a,DT_CALCRECT,0xffffffff);
220 const int rb=font.DrawAnsi(nullptr,"C-2 Dasher",5,&b,DT_CALCRECT,0xffffffff);
221 Check(ra==rb && !memcmp(&a,&b,sizeof(RECT)),"ANSI explicit-count layout");
222 Check(font.Draw(nullptr,L"invalid",7,&b,DT_CALCRECT|DT_END_ELLIPSIS,0xffffffff)==0,"unsupported format rejected");
223 std::cout<<"PASS: 33 whitespace layouts, ANSI count and unsupported flags\n";
224 }
225 void FixedTextCheck()
226 {
227 const wchar_t* rows[]={L" LAST 123.456 km",L">WAYPT Unused",L">AB12CD 0.001 km",L" PRONLY 9876.543 km",
228 L" YSP 123.456 kkm",L">TAC1 0.123 km",L" CPOCd 0.000 km",L" ^^^ MORE ^^^",L" vvv MORE vvv",
229 L"0123456789. -+",L"!\"#$%&'()*+,-./:;<=>?",L"@ABCDEFGHIJKLMN[\\]^_",L"`abcdefghijklmno{|}~",L" Spaces "};
230 auto* context=gpu.Context();auto* view=rtv.Get();
231 const auto begin=[&](float scale,float angle) {
232 context->ClearState();context->OMSetRenderTargets(1,&view,nullptr);
233 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};context->RSSetViewports(1,&viewport);
234 const float clear[]={32.f/255,48.f/255,64.f/255,1};context->ClearRenderTargetView(view,clear);
235 SpriteOptions11 options;options.sort=SpriteSort11::BackToFront;options.sortTextures=true;
236 HR(sprite.Begin(context,options),"fixed text begin");
237 D3DXMATRIX scaling,rotation;D3DXMatrixScaling(&scaling,scale,scale,1);D3DXMatrixRotationZ(&rotation,angle);
238 const auto combined=scaling*rotation;Sprite11::Matrix transform;memcpy(&transform,&combined,sizeof(transform));
239 transform._43=1;sprite.SetTransform(transform);
240 };
241 const auto read=[&]() {
242 HR(sprite.End(),"fixed text end");context->OMSetRenderTargets(0,nullptr,nullptr);
243 context->CopyResource(staging.Get(),target.Get());D3D11_MAPPED_SUBRESOURCE mapped{};
244 HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"fixed text read");
245 std::vector<uint32_t> result(Width*Height);
246 for(UINT y=0;y<Height;++y)memcpy(result.data()+size_t(y)*Width,static_cast<char*>(mapped.pData)+y*mapped.RowPitch,Width*4);
247 context->Unmap(staging.Get(),0);return result;
248 };
249 for(unsigned face=0;face<3;++face)
250 {
251 LOGFONTW desc{};desc.lfHeight=13;desc.lfWidth=5;desc.lfWeight=FW_MEDIUM;
252 desc.lfCharSet=DEFAULT_CHARSET;desc.lfOutPrecision=OUT_TT_ONLY_PRECIS;desc.lfQuality=ANTIALIASED_QUALITY;
253 wcscpy_s(desc.lfFaceName,face==0 ? L"DejaVu Sans Mono" : face==1 ? L"Courier New" : L"Arial");
254 HR(font.Initialize(gpu.Device(),desc),"fixed font initialize");
255 for(unsigned scenario=0;scenario<4;++scenario)
256 {
257 const float scale=scenario==0 ? 1.f : scenario==1 ? .625f : 1.35f,angle=scenario==3 ? .2f : 0;
258 std::vector<uint32_t> expected;
259 for(unsigned mode=0;mode<2;++mode)
260 {
261 begin(scale,angle);
262 for(unsigned row=0;row<std::size(rows);++row)
263 {
264 RECT rect{25,10+LONG(row)*14,25,10+LONG(row)*14};const uint32_t color=row%2 ? 0xff00ffff : 0x807fdf3f;
265 const int result=mode ? font.DrawFixed(&sprite,rows[row],-1,&rect,DT_NOCLIP,color)
266 : font.Draw(&sprite,rows[row],-1,&rect,DT_NOCLIP,color);
267 Check(result>0,"contact row draw");
268 }
269 auto actual=read();
270 if(!mode){expected=std::move(actual);continue;}
271 unsigned maximum=0,over=0,active=0;double error=0;
272 for(size_t i=0;i<actual.size();++i)
273 {
274 if(actual[i]!=0xff203040 || expected[i]!=0xff203040)++active;
275 unsigned worst=0;
276 for(unsigned shift:{0,8,16,24})
277 {const unsigned delta=unsigned(std::abs(int((actual[i]>>shift)&255)-int((expected[i]>>shift)&255)));error+=delta;worst=(std::max)(worst,delta);}
278 maximum=(std::max)(maximum,worst);if(worst>3)++over;
279 }
280 const bool pass=active && actual==expected;
281 std::cout<<(pass ? "PASS: " : "FAIL: ")<<"contact atlas face="<<face<<" scale="<<scale<<" angle="<<angle
282 <<" mean="<<error/(4*active)<<" over3="<<double(over)/active<<" max="<<maximum<<std::endl;
283 if(!pass){++failures;Save(expected,"contact-expected.png");Save(actual,"contact-actual.png");}
284 }
285 }
286 Check((font.FixedAtlasBytes()>0)==(face!=2),"fixed-pitch eligibility and proportional fallback");
287 if(face==0)
288 {
289 // Exercise every decimal digit pair and repeated printable
290 // ASCII glyph, including overhang/overlap fallback cases.
291 for(unsigned scenario=0;scenario<2;++scenario)
292 {
293 std::vector<uint32_t> expected;
294 for(unsigned mode=0;mode<2;++mode)
295 {
296 begin(1,0);
297 for(unsigned item=0;item<(scenario ? 95u : 10u);++item)
298 {
299 std::wstring text;
300 if(scenario)text.assign(3,wchar_t(32+item));
301 else for(unsigned digit=0;digit<10;++digit){text+=wchar_t(L'0'+item);text+=wchar_t(L'0'+digit);text+=L' ';}
302 RECT rect{10+LONG(scenario ? item%12 : 0)*24,10+LONG(scenario ? item/12 : item)*14,0,0};
303 rect.right=rect.left;rect.bottom=rect.top;
304 Check((mode ? font.DrawFixed(&sprite,text.c_str(),-1,&rect,DT_NOCLIP,0x8000ffff)
305 : font.Draw(&sprite,text.c_str(),-1,&rect,DT_NOCLIP,0x8000ffff))>0,"glyph pair draw");
306 }
307 auto actual=read();if(!mode)expected=std::move(actual);
308 else Check(actual==expected,"all digit pairs and printable ASCII preserve pixels");
309 }
310 }
311 std::cout<<"PASS: exact pixels for all 100 digit pairs and 95 repeated ASCII characters\n";
312 const auto bytes=font.CachedBytes(),runs=font.CachedRuns();
313 begin(1,0);
314 for(unsigned i=0;i<1000;++i)
315 {
316 wchar_t text[99];swprintf_s(text,L"%cCPOC%d %.3f %s",i%2 ? L'>' : L' ',i%9,double(i)/1000,i%2 ? L"km" : L"kkm");
317 RECT rect{10,10,10,10};Check(font.DrawFixed(&sprite,text,-1,&rect,DT_NOCLIP,0xffffffff)>0,"changing contact distance");
318 if(i%16==15)HR(sprite.Flush(),"changing contact flush");
319 }
320 HR(sprite.End(),"changing contact end");
321 Check(font.CachedBytes()==bytes && font.CachedRuns()==runs,"1000 changing values reuse atlas without new runs");
322 std::cout<<"PASS: 1000 changing contacts, constant cache; atlas bytes="<<font.FixedAtlasBytes()<<std::endl;
323 RECT a{20,20,120,60},b=a;
324 Check(font.DrawFixed(nullptr,rows[0],-1,&a,DT_CALCRECT,0)==font.Draw(nullptr,rows[0],-1,&b,DT_CALCRECT,0)
325 && !memcmp(&a,&b,sizeof(a)),"CALCRECT fallback");
326 begin(1,0);
327 Check(font.DrawFixed(&sprite,L"\u03a9 contact",-1,&a,DT_NOCLIP,0xffffffff)>0,"Unicode fallback");
328 Check(font.DrawFixed(&sprite,L"Clipped text",7,&a,0,0xffffffff)>0,"clipped explicit-count fallback");
329 HR(sprite.End(),"fallback end");
330 std::vector<double> drawMs[2],submitMs[2];
331 for(unsigned frame=0;frame<256;++frame)for(unsigned order=0;order<2;++order)
332 {
333 const unsigned mode=(order+frame)%2; // Alternate order to reduce benchmark bias.
334 wchar_t distances[3][99];
335 for(unsigned station=0;station<3;++station)
336 swprintf_s(distances[station],L"%s %.3f km",station==0 ? L" YSP " : station==1 ? L">TAC " : L" CPOC ",
337 100.+station*10.+frame*.001);
338 begin(1,0);const auto start=std::chrono::steady_clock::now();
339 for(unsigned row=0;row<std::size(rows);++row)
340 {
341 RECT rect{25,10+LONG(row)*14,25,10+LONG(row)*14};
342 const auto* text=row>=4 && row<=6 ? distances[row-4] : rows[row];
343 Check((mode ? font.DrawFixed(&sprite,text,-1,&rect,DT_NOCLIP,0xff00ffff)
344 : font.Draw(&sprite,text,-1,&rect,DT_NOCLIP,0xff00ffff))>0,"benchmark contact draw");
345 }
346 const auto drawn=std::chrono::steady_clock::now();HR(sprite.End(),"benchmark contact end");
347 const auto submitted=std::chrono::steady_clock::now();
348 if(frame>=16)
349 {
350 drawMs[mode].push_back(std::chrono::duration<double,std::milli>(drawn-start).count());
351 submitMs[mode].push_back(std::chrono::duration<double,std::milli>(submitted-start).count());
352 }
353 }
354 for(unsigned mode=0;mode<2;++mode)
355 {
356 double draw=0,total=0;for(double value:drawMs[mode])draw+=value;for(double value:submitMs[mode])total+=value;
357 std::sort(submitMs[mode].begin(),submitMs[mode].end());
358 std::cout<<"BENCH: "<<(mode ? "atlas" : "whole runs")<<" 14 rows / 3 changing, 240 refreshes; draw mean ms="
359 <<draw/drawMs[mode].size()<<" including sprite submit mean ms="<<total/submitMs[mode].size()
360 <<" p95="<<submitMs[mode][228]<<std::endl;
361 }
362 }
363 font.Reset();Check(font.FixedAtlasBytes()==0 && font.CachedBytes()==0,"atlas released on font reset");
364 }
365 }
366 void CacheCheck()
367 {
368 auto* targetView=rtv.Get();auto* context=gpu.Context();
369 context->OMSetRenderTargets(1,&targetView,nullptr);
370 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};context->RSSetViewports(1,&viewport);
371 HR(sprite.Begin(context),"cache sprite begin");RECT rect{5,5,200,100};
372 Check(font.Draw(&sprite,L"Cache entry",-1,&rect,DT_NOCLIP,0xffffffff)>0,"cache first draw");
373 const auto bytes=font.CachedBytes();
374 Check(font.Draw(&sprite,L"Cache entry",-1,&rect,DT_NOCLIP,0x80332211)>0 && font.CachedBytes()==bytes,"cache hit across tint");
375 for(unsigned i=0;i<300;++i)
376 {
377 const auto label=L"Live value "+std::to_wstring(i);
378 Check(font.Draw(&sprite,label.c_str(),-1,&rect,DT_NOCLIP,0xffffffff)>0,"cache changing text");
379 if(i%16==15)HR(sprite.Flush(),"cache flush");
380 }
381 HR(sprite.End(),"cache end");Check(font.CachedBytes()<=16*1024*1024 && font.CachedRuns()==256,"cache bounds and eviction");
382 font.Reset();Check(font.CachedBytes()==0,"cache reset");
383 std::cout<<"PASS: text reuse, tint reuse, 300 updates, eviction and reset\n";
384 }
385 };
386}
387int main(int argc,char** argv)
388{
389 try
390 {
391 bool warp=false,debug=true;for(int i=1;i<argc;++i){if(!strcmp(argv[i],"--warp"))warp=true;else if(!strcmp(argv[i],"--no-debug-layer"))debug=false;else throw std::runtime_error("unknown argument");}
392 for(const auto* file:{L"Fonts/cour.ttf",L"Fonts/LicensePlate.ttf",L"Fonts/pala.ttf",L"Fonts/rcaf6-GIMP.ttf",L"Fonts/DejaVuSansMono.ttf",L"Fonts/ARIALN.TTF"})
393 Check(AddFontResourceExW(file,FR_PRIVATE,nullptr)!=0,"authored test font registered");
394 Fixture test(warp,debug);for(unsigned i=0;i<27;++i)test.Compare(i);test.LayoutEdges();test.CacheCheck();test.FixedTextCheck();test.DebugCheck();
395 std::cout<<"27 font fixtures; "<<test.failures<<" failures\n";return test.failures ? 1 : 0;
396 }
397 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<std::endl;return 1;}
398}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
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
int DrawFixed(Sprite11 *sprite, const wchar_t *text, int count, RECT *rectangle, UINT format, uint32_t color)
Definition Font11.cpp:346
int Draw(Sprite11 *sprite, const wchar_t *text, int count, RECT *rectangle, UINT format, uint32_t color)
Definition Font11.cpp:215
bool Metrics(TEXTMETRICW &result) const
Definition Font11.h:25
size_t FixedAtlasBytes() const
Definition Font11.h:29
size_t CachedRuns() const
Definition Font11.h:28
int DrawAnsi(Sprite11 *sprite, const char *text, int count, RECT *rectangle, UINT format, uint32_t color)
Definition Font11.cpp:383
HRESULT Initialize(ID3D11Device *device, const LOGFONTW &description)
Definition Font11.cpp:22
size_t CachedBytes() const
Definition Font11.h:27
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
Definition Sprite11.cpp:26
void SetTransform(const Matrix &value)
Definition Sprite11.h:21
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
constexpr float Width
constexpr float Height
HRESULT Draw(Rendering::RenderDevice *device, Rendering::RenderTexture *texture, Rendering::RenderBuffer *vertices, const RiseMath::Matrix &world, UINT segments, Rendering::RenderMaterial *volumeEffect=nullptr, float physicalScale=1)