1#include "../Rendering/Window11.h"
2#include "../Rendering/DeviceDiagnostics11.h"
3#include "../Viewscreen/GeometryBounds.h"
4#include "../Viewscreen/BuildingDrawBatches.h"
5#include "../Viewscreen/ShipDrawBatch.h"
6#include <dbt.h>
7#include <d3d11sdklayers.h>
8#include <iostream>
9#include <limits>
10#include <stdexcept>
11#include <random>
12
15using Microsoft::WRL::ComPtr;
16namespace
17{
18 unsigned checks=0;
19 void Check(bool ok,const char* message) {++checks;if(!ok)throw std::runtime_error(message);}
20 void HR(
HRESULT hr,
const char* message)
21 {
22 if(FAILED(hr))std::cerr<<message<<" HRESULT=0x"<<std::hex<<hr<<std::dec<<'\n';
23 Check(SUCCEEDED(hr),message);
24 }
26 {
27 ComPtr<ID3D11InfoQueue> queue;
if(FAILED(gpu.
Device()->QueryInterface(IID_PPV_ARGS(&queue))))
return;
28 unsigned errors=0;
29 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
30 {
31 SIZE_T size=0;queue->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);
32 auto* message=reinterpret_cast<D3D11_MESSAGE*>(data.data());HR(queue->GetMessage(i,message,&size),"read debug message");
33 if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING){++errors;std::cerr<<message->pDescription<<'\n';}
34 }
35 Check(!errors,"D3D11 debug layer is clean");queue->ClearStoredMessages();
36 }
38 {
39 D3D11_TEXTURE2D_DESC desc{};gpu.
SceneColor()->GetDesc(&desc);
40 ComPtr<ID3D11Texture2D> resolved;
42 if(desc.SampleDesc.Count!=1)
43 {
44 desc.SampleDesc={1,0};desc.BindFlags=0;
45 HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&resolved),
"create MSAA comparison resolve");
46 gpu.
Context()->ResolveSubresource(resolved.Get(),0,source,0,desc.Format);source=resolved.Get();
47 }
48 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;desc.MiscFlags=0;
49 ComPtr<ID3D11Texture2D> staging;HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&staging),
"create readback");
50 gpu.
Context()->CopyResource(staging.Get(),source);
51 D3D11_MAPPED_SUBRESOURCE map{};HR(gpu.
Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&map),
"map readback");
52 std::vector<uint32_t> result(size_t(desc.Width)*desc.Height);
53 for(UINT y=0;y<desc.Height;++y)memcpy(result.data()+size_t(y)*desc.Width,static_cast<uint8_t*>(map.pData)+size_t(y)*map.RowPitch,desc.Width*4);
54 gpu.
Context()->Unmap(staging.Get(),0);
55 Check(desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM,"native scene color format");
56 for(auto& pixel:result)pixel=(pixel&0xff00ff00)|((pixel&255)<<16)|((pixel>>16)&255);
57 return result;
58 }
60 {
64 }
65 template<
class T,
size_t N>
void Fill(
Geometry11& geometry,
const T(&data)[N])
66 {
67 void*
output=
nullptr;HR(geometry.
Lock(0,
sizeof(data),&output),
"lock geometry");
68 memcpy(output,data,
sizeof(data));HR(geometry.
Unlock(),
"unlock geometry");
69 }
70 struct ScreenVertex {float x,y,z,w;uint32_t color;};
71 constexpr ScreenVertex quad[]={{8,8,.5f,1,0xffd02f63},{56,8,.5f,1,0xffd02f63},{56,40,.5f,1,0xffd02f63},{8,40,.5f,1,0xffd02f63}};
74 void GeometryAndState(
Window11& host)
75 {
76 auto& draw=host.
Draws();
auto& gpu=host.
Device();
const auto layout=ScreenLayout();
77 draw.Pipeline().raster.CullMode=D3D11_CULL_NONE;draw.Pipeline().depth.DepthEnable=FALSE;
78 draw.Fixed().lighting=false;
83 const auto reference=
Pixels(gpu);Check(reference[20*64+20]==0xffd02f63,
"authored packed ARGB survives conversion");
84 Check(reference[0]==0xff000000,"fan stays inside geometry");
85 const uint16_t order[]={0,1,2,0,2,3};
Geometry11 indices;
86 HR(indices.
Create(gpu.
Device(),
sizeof(order),
false,
true),
"create authored 16-bit indices");
Fill(indices,order);
88 Check(reference==
Pixels(gpu),
"fan and indexed triangles match every pixel");
89
90
91 gpu.
Context()->RSSetState(
nullptr);gpu.
Context()->OMSetDepthStencilState(
nullptr,0);
92 gpu.
Context()->OMSetBlendState(
nullptr,
nullptr,UINT_MAX);
94 Check(reference==
Pixels(gpu),
"cached pipeline survives external context changes");
95 const uint32_t fanOrder[]={1,2,3,4};
Geometry11 wide;
96 HR(wide.
Create(gpu.
Device(),
sizeof(fanOrder),
true,
true,
true),
"create 32-bit fan indices");
Fill(wide,fanOrder);
98 Check(reference==
Pixels(gpu),
"indexed fan applies base vertex once");
99 Check(FAILED(draw.Draw(vertices,layout,
Primitive11::Triangles,0,3,&indices)),
"out-of-range indices rejected");
103 HR(vertices.
Lock(0,0,&output,
true),
"read authored geometry for physics");
104 Check(!memcmp(output,quad,
sizeof(quad)),
"CPU geometry remains authored layout");HR(vertices.
Unlock(),
"unlock physics read");
105 Check(revision==vertices.
Revision(),
"read-only access retains GPU cache");
106 HR(vertices.
Lock(offsetof(ScreenVertex,color),4,&output),
"edit authored color");*
static_cast<uint32_t*
>(
output)=0xff10e050;
108 HR(vertices.
Unlock(),
"finish authored edit");
Clear(host);
110 Check(reference!=
Pixels(gpu),
"CPU edit invalidates canonical GPU cache");
Fill(vertices,quad);
111 auto saved=draw.Capture();draw.Pipeline().raster.ScissorEnable=TRUE;draw.Scissor({0,0,32,48});
113 auto clipped=
Pixels(gpu);Check(clipped[20*64+20]==0xffd02f63 && clipped[20*64+44]==0xff000000,
"native scissor clips authored draw");
114 HR(draw.Restore(saved),
"restore scene state");
Clear(host);
116 Check(reference==
Pixels(gpu),
"restored state and immediate draw match authored geometry");
117 Check(FAILED(draw.DrawImmediate(quad,
sizeof(ScreenVertex)*2,layout,
Primitive11::TriangleFan,2)),
"old immediate capacity cannot hide a short new draw");
118 auto bad=draw.Viewport();bad.MinDepth=std::numeric_limits<float>::quiet_NaN();
120
121 struct MeshVertex {float x,y,z,nx,ny,nz,u,v;};
122 const MeshVertex mesh[]={{-1,1,.5f,0,0,1,0,0},{1,1,.5f,0,0,1,1,0},{-1,-1,.5f,0,0,1,0,1}};
125 XMFLOAT4X4 identity;XMStoreFloat4x4(&identity,XMMatrixIdentity());
126 auto& values=draw.Materials().Values();values.Set("matWorldViewProj",identity);values.Set("matWorld",identity);
127 values.Set("ambient",XMFLOAT4(1,1,1,1));values.Set("Sunlight",XMFLOAT4(0,0,1,1));values.Set("Radiosity",XMFLOAT4(0,0,1,1));
128 values.Set("Features",XMFLOAT4(1,0,0,0));
130 const auto material=
Pixels(gpu);Check((material[10*64+10]&0xffffff)!=0,
"native material writes scene color");
131
132 saved={};HR(host.
Resize(80,60),
"resize native host");
133 Check(draw.Material()==13,"resize preserves active material");
135 Check(
Pixels(gpu)[10*80+10]==material[10*64+10],
"resize preserves material uniforms and color");
136 HR(host.
Resize(0,0),
"minimize host");Check(host.
Suspended(),
"minimized host suspends rendering");
137 Check(host.
Frame()==S_FALSE,
"minimized frame skipped");HR(host.
Resize(64,48),
"restore host");
138 Check(!host.
Suspended(),
"restored host resumes rendering");DebugClean(gpu);
139 }
140 void CullingPreservesPixels(bool warp,bool debug)
141 {
142
143
144
147 Window11 host;HR(host.
Create(options,{}),
"create culling oracle");
149 D3D11_TEXTURE2D_DESC td{};td.Width=td.Height=td.MipLevels=td.ArraySize=1;
150 td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.SampleDesc.Count=1;td.BindFlags=D3D11_BIND_SHADER_RESOURCE;
151 const uint32_t white=0xffffffff;D3D11_SUBRESOURCE_DATA data{&white,4,4};
152 ComPtr<ID3D11Texture2D> texture;ComPtr<ID3D11ShaderResourceView> image;
153 HR(gpu.
Device()->CreateTexture2D(&td,&data,&texture),
"create culling oracle texture");
154 HR(gpu.
Device()->CreateShaderResourceView(texture.Get(),
nullptr,&image),
"create oracle texture view");
155 D3D11_TEXTURE3D_DESC vd{};vd.Width=vd.Height=vd.Depth=2;vd.MipLevels=1;
156 vd.Format=td.Format;vd.BindFlags=D3D11_BIND_SHADER_RESOURCE;
157 const uint32_t colors[]={0xff302010,0xff806050,0xff507060,0xff204070,0xff607040,0xff305080,0xff807020,0xff608090};
158 D3D11_SUBRESOURCE_DATA volumeData{colors,8,16};ComPtr<ID3D11Texture3D> volume;
159 ComPtr<ID3D11ShaderResourceView> volumeView;
160 HR(gpu.
Device()->CreateTexture3D(&vd,&volumeData,&volume),
"create translucent batch oracle texture");
161 HR(gpu.
Device()->CreateShaderResourceView(volume.Get(),
nullptr,&volumeView),
"create batch volume view");
162 auto& values=draw.Materials().Values();values.Texture("ColorMap",image.Get());values.Texture("ColorMap2",image.Get());
163 values.Texture("ColorMap3",volumeView.Get());
164 values.Set("ambient",XMFLOAT4(1,1,1,100));values.Set("Features",XMFLOAT4(0,0,0,0));
165 values.Set("clouduv",XMFLOAT4(0,0,0,0));
166 draw.Pipeline().raster.CullMode=D3D11_CULL_NONE;
167 draw.Pipeline().depth.DepthEnable=TRUE;draw.Pipeline().depth.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;
168 struct Vertex {float x,y,z,nx,ny,nz,u,v,u2=0,v2=0;};
170 unsigned rejected=0,visible=0,retained=0;
171 for(UINT samples:{1u,2u,4u,8u})
172 {
174 HR(host.
SetSamples(samples),
"set oracle MSAA");
175 values.Set("Features",XMFLOAT4(0,0,0,0));
176 values.Set("clouduv",XMFLOAT4(0,0,0,0));
177 draw.Pipeline().blend.RenderTarget[0].BlendEnable=FALSE;
178 draw.Pipeline().depth.DepthEnable=TRUE;
179 for(int pass:{2,3}) for(int projection=0;projection<2;++projection)
180 {
181 std::mt19937 random(7821);std::uniform_real_distribution<float> unit(-1,1);
182 for(unsigned scene=0;scene<96;++scene)
183 {
184
185
186 float x=unit(random)*2,y=unit(random)*2,z=unit(random)*2;
187 float size=scene%4==0 ? .0008f : .4f;
188 if(scene<4){x=(scene&1 ? 1.0f : -1.0f)+(scene&1 ? .007f : -.007f);y=0;z=.5f;size=.004f;}
189 if(scene==4){x=0;y=0;z=.5f;size=4;}
190 if(scene==5){x=0;y=0;z=.02f;size=.5f;}
191 if(scene==6){x=0;y=0;z=100;size=.5f;}
192 const float offset=scene%7==0 ? 3000.0f : 0.0f;
193 Vertex triangle[]={{offset-size,0,0,0,0,1,0,0},{offset+size,0,0,0,0,1,1,0},{offset,size*2,size*.1f,0,0,1,.5f,1}};
195 auto world=XMMatrixTranslation(-offset,0,0)*XMMatrixRotationZ(float(scene)*.173f)*XMMatrixTranslation(x,y,z);
196 auto transform=projection ? world*XMMatrixPerspectiveFovLH(1.2f,64.0f/48,.01f,100) : world;
197 XMFLOAT4X4 matrix,model;XMStoreFloat4x4(&matrix,transform);XMStoreFloat4x4(&model,world);
198 values.Set("matWorldViewProj",matrix);values.Set("matWorld",model);draw.Material(pass);
200 const auto reference=
Pixels(gpu);
201 const bool hasPixels=std::any_of(reference.begin(),reference.end(),[](uint32_t p){return p!=0xff000000;});
202 visible+=hasPixels;
204 if(keep)++retained;else ++rejected;
205 Check(!hasPixels || keep,"CPU cull rejected GPU-visible samples");
207 if(keep)HR(draw.DrawImmediate(triangle,
sizeof(triangle),layout,
Primitive11::Triangles,1),
"culled oracle draw");
208 Check(
Pixels(gpu)==reference,
"component culling changed rendered pixels");
209 }
210 }
211
212
213 Vertex triangles[36]{};std::vector<BuildingDrawBatch> batches;
214 for(unsigned i=0;i<12;++i)
215 {
216 const float x=float(i%3)*.23f-.8f,y=float(i%4)*.12f-.7f,z=.2f+float(i%3)*.15f;
217 const float uv=float(i)/13;
218 triangles[i*3]={x,y,z,0,0,1,uv,.1f};
219 triangles[i*3+1]={x+1.1f,y,z,0,0,1,uv,.4f};
220 triangles[i*3+2]={x+.3f,y+1.2f,z,0,0,1,uv,.8f};
222 for(
unsigned j=0;j<3;++j)bounds.
Include(triangles[i*3+j]);
223 }
224 Check(batches.size()==1 && batches[0].primitives==12,"identical adjacent components merge");
225 Geometry11 geometry;HR(geometry.
Create(gpu.
Device(),
sizeof(triangles),
false),
"create batch geometry");
Fill(geometry,triangles);
226 XMFLOAT4X4 identity;XMStoreFloat4x4(&identity,XMMatrixIdentity());
227 values.Set("matWorldViewProj",identity);values.Set("matWorld",identity);values.Set("Features",XMFLOAT4(141,.3f,0,0));
228 auto& blend=draw.Pipeline().blend.RenderTarget[0];blend.BlendEnable=TRUE;
229 blend.SrcBlend=D3D11_BLEND_SRC_ALPHA;blend.DestBlend=D3D11_BLEND_INV_SRC_ALPHA;blend.BlendOp=D3D11_BLEND_OP_ADD;
230 blend.SrcBlendAlpha=D3D11_BLEND_ONE;blend.DestBlendAlpha=D3D11_BLEND_ZERO;blend.BlendOpAlpha=D3D11_BLEND_OP_ADD;
231 for(int pass:{2,3,4,5}) for(bool depth:{false,true})
232 {
233 if(pass<4)values.Set("Features",XMFLOAT4(141,.3f,0,0));
234 else
235 {
236 values.Set("Features",XMFLOAT4(.45f,0,1,0));
237 values.Set("clouduv",XMFLOAT4(0,0,.7f,57));
238 }
239 draw.Material(pass);draw.Pipeline().depth.DepthEnable=depth;
241 for(
unsigned i=0;i<12;++i)HR(draw.Draw(geometry,layout,
Primitive11::Triangles,i*3,1),
"individual component draw");
242 const auto reference=
Pixels(gpu);
243 Check(std::any_of(reference.begin(),reference.end(),[](uint32_t p){return p!=0xff000000;}),"batch fixture paints pixels");
245 HR(draw.Draw(geometry,layout,
Primitive11::Triangles,batches[0].first,batches[0].primitives),
"merged component draw");
246 Check(
Pixels(gpu)==reference,
"batching changed overlapping component pixels");
247 }
248 DebugClean(gpu);
249 }
250 Check(rejected>100 && visible>100 && retained>100,"culling oracle exercises visible and invisible geometry");
251 std::cout<<"Culling oracle: "<<rejected<<" rejected, "<<visible<<" visible, "<<retained<<" retained\n";
252 }
253 void BatchBoundaries()
254 {
255 std::vector<BuildingDrawBatch> batches;
258 Check(batches.size()==1 && batches[0].first==0 && batches[0].primitives==5 &&
259 batches[0].component==0 && batches[0].bounds.low[0]==-3 && batches[0].bounds.high[2]==6,"merged range and bounds preserve all vertices");
260 const auto separate=[&](
unsigned first,
unsigned count,
short texture,
unsigned char type){
262 Check(batches.size()==size+1,"incompatible components stay separate");};
263 separate(15,1,2,0);separate(18,1,2,57);separate(30,1,2,57);
264 separate(33,1,2,78);separate(36,1,2,78);
265 separate(39,1,2,8);separate(42,1,2,8);
266 separate(45,0,2,0);separate(45,1,2,0);
269 {
270 bool visible=true,useLightMap=true;
271 unsigned startvertex=0,primitives=1;
272 short texture=2;
273 unsigned char type=0;
274 float speedRetract=.3f;
275 XMFLOAT4X4 matWorld;
276 };
278 for(unsigned i=0;i<5;++i){components[i].startvertex=i*3;XMStoreFloat4x4(&components[i].matWorld,XMMatrixIdentity());}
280 Check(batch.last==4 && batch.primitives==5,"identical ship transforms/materials merge");
281 const auto split=[&](auto edit){
282 const auto saved=components[2];edit(components[2]);
284 Check(stopped.last==1 && stopped.primitives==2,"ship material/animation boundary stops merge");
285 components[2]=saved;
286 };
287 split([](auto& c){c.visible=false;});split([](auto& c){c.type=43;});
288 split([](auto& c){c.texture=3;});split([](auto& c){c.useLightMap=false;});
289 split([](auto& c){c.speedRetract=.5f;});split([](auto& c){c.startvertex+=3;});
290 split([](auto& c){c.primitives=0;});split([](auto& c){c.matWorld._41=.001f;});
291 split([](auto& c){XMStoreFloat4x4(&c.matWorld,XMMatrixRotationX(.001f));});
292 Check(
FindShipDrawBatch(components,5,3).last==4,
"ship batch starting partway through range");
293 Check(
FindShipDrawBatch(components,5,4).last==4,
"last ship component stays within array");
294 components[0].visible=false;
295 Check(
FindShipDrawBatch(components,5,0).last==0,
"invisible first component does not merge");
296 }
297 void LoginClockReset(bool warp,bool debug)
298 {
302 unsigned resetPhase=0;
304 callbacks.
move=[&](double,float){
if(resetPhase==1){host.
ResetClock();resetPhase=0;}};
305 callbacks.
draw=[&](double,float){
Clear(host);
if(resetPhase==2){host.
ResetClock();resetPhase=0;}
return S_OK;};
306 HR(host.
Create(options,callbacks),
"create login clock regression host");
307 for(unsigned phase:{1u,2u})
308 {
309
310
311 Sleep(1100);resetPhase=phase;
312 HR(host.
Frame(),
"frame that resets game clock");
313 Check(resetPhase==0,"game callback reset the clock");
314 Check(host.
FPS()==0,
"reset frame cannot publish FPS from the old clock epoch");
315 Sleep(550);HR(host.
Frame(),
"frame in the new FPS window");
316 Check(host.
FPS()>0,
"FPS resumes within one sampling window after login");
317 }
318 DebugClean(host.
Device());
319 }
320 void Lifecycle(bool warp,bool debug)
321 {
324 Window11 host;
unsigned creates=0,resizes=0,releases=0,destroys=0,moves=0,draws=0,keys=0;
float lastElapsed=0;
325 HDEVNOTIFY notification=nullptr;unsigned registrations=0,unregistrations=0;
326 const auto deviceNotificationMessage=[&](HWND handle,UINT message)
327 {
328 if(message==WM_CREATE)
329 {
330 Check(!notification,"one notification registration per native window");
331 DEV_BROADCAST_DEVICEINTERFACE_W filter{};filter.dbcc_size=sizeof(filter);
332 filter.dbcc_devicetype=DBT_DEVTYP_DEVICEINTERFACE;
333 filter.dbcc_classguid={0x4d1e55b2,0xf16f,0x11cf,{0x88,0xcb,0,0x11,0x11,0,0,0x30}};
334 notification=RegisterDeviceNotificationW(handle,&filter,DEVICE_NOTIFY_WINDOW_HANDLE);
335 Check(notification!=nullptr,"WM_CREATE can register real device notifications");++registrations;
336 }
337 if(message==WM_DESTROY)
338 {
339 Check(notification && UnregisterDeviceNotification(notification),"WM_DESTROY releases device notifications");
340 notification=nullptr;++unregistrations;
341 }
342 };
343 std::vector<UINT> mouseMessages;
344 struct KeyEvent {UINT key;bool down,alt;};
345 std::vector<KeyEvent> keyEvents;
346 unsigned menuRequests=0;
348 callbacks.
create=[&] {Check(notification!=
nullptr,
"window registration precedes GPU callbacks");++creates;
return S_OK;};
349 callbacks.
resize=[&](UINT,UINT){++resizes;
return S_OK;};
351 callbacks.
move=[&](double,
float elapsed){++moves;lastElapsed=elapsed;};callbacks.
draw=[&](double,float){++draws;
Clear(host);
return S_OK;};
352 callbacks.
keyboard=[&](UINT key,
bool down,
bool alt){keyEvents.push_back({key,down,alt});++keys;};
353 callbacks.
message=[&](HWND handle,UINT message,WPARAM wParam,LPARAM,
bool& handled)->LRESULT
354 {
355 deviceNotificationMessage(handle,message);
356 if(message==WM_LBUTTONDOWN || message==WM_LBUTTONUP || message==WM_LBUTTONDBLCLK)
357 {mouseMessages.push_back(message);handled=true;}
358
359
360 if(message==WM_SYSCOMMAND && (wParam&0xfff0)==SC_KEYMENU){++menuRequests;handled=true;}
361 return 0;
362 };
363 HR(host.
Create(options,callbacks),
"create native window host");std::cout<<host.
Status()<<
'\n';
364 Check((GetClassLongPtrW(host.
Handle(),GCL_STYLE)&CS_DBLCLKS)!=0,
"native window requests Windows double-click recognition");
366 std::cout<<
"debugLayer="<<(host.
Device().DebugLayerEnabled() ?
"enabled" :
"disabled")<<
'\n';
367 Check(creates==1 && resizes==1,"initial resource callback order");
368 const LONG_PTR style=GetWindowLongPtrW(host.
Handle(),GWL_STYLE);
369 Check((style&WS_POPUP) && !(style&(WS_CAPTION|WS_THICKFRAME)),"startup window has no caption or resize frame");
370 RECT outer{},client{};Check(GetWindowRect(host.
Handle(),&outer) && GetClientRect(host.
Handle(),&client),
"read startup window bounds");
371 Check(outer.right-outer.left==64 && outer.bottom-outer.top==48 && client.right==64 && client.bottom==48,
372 "borderless startup preserves requested client dimensions");
373 MONITORINFO monitor{sizeof(monitor)};
374 Check(GetMonitorInfoW(MonitorFromWindow(host.
Handle(),MONITOR_DEFAULTTOPRIMARY),&monitor)!=FALSE,
"read startup monitor");
375 Check(std::abs(outer.left+outer.right-monitor.rcWork.left-monitor.rcWork.right)<=1 &&
376 std::abs(outer.top+outer.bottom-monitor.rcWork.top-monitor.rcWork.bottom)<=1,"startup centered in monitor work area");
377
378 SetWindowLongPtrW(host.
Handle(),GWL_STYLE,WS_OVERLAPPEDWINDOW);
379 Check(SetWindowPos(host.
Handle(),
nullptr,0,0,640,480,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_FRAMECHANGED)!=FALSE,
380 "transition from splash to framed window");
381 Check((GetWindowLongPtrW(host.
Handle(),GWL_STYLE)&WS_CAPTION)==WS_CAPTION,
"game frame restored");
383 host.
Device().
Depth().
Description().Height==UINT(client.bottom),
"frame transition resizes native render targets");
384
385
386 HR(host.
Resize(64,48),
"size readback fixture");
387 GeometryAndState(host);HR(host.
Frame(),
"native frame and presentation");
388 Check(moves==1 && draws==1,"frame callbacks execute once");
389 Sleep(350);HR(host.
Frame(),
"frame after a stall");Check(lastElapsed>=.3f,
"game receives full elapsed time after a stall");
390 SendMessageW(host.
Handle(),WM_KEYDOWN,
'A',0);Check(keys==1,
"keyboard callback reached game");
391 Check(keyEvents.back().key=='A' && keyEvents.back().down && !keyEvents.back().alt,"native keyboard dispatch");
392 const auto f10=[&](bool system,bool alt) {
393 keyEvents.clear();
394 const LPARAM down=1|(LPARAM(MapVirtualKeyW(VK_F10,MAPVK_VK_TO_VSC))<<16)|(alt ? LPARAM(1)<<29 : 0);
395 SendMessageW(host.
Handle(),system ? WM_SYSKEYDOWN : WM_KEYDOWN,VK_F10,down);
396 SendMessageW(host.
Handle(),system ? WM_SYSKEYDOWN : WM_KEYDOWN,VK_F10,down|(LPARAM(1)<<30));
397 SendMessageW(host.
Handle(),system ? WM_SYSKEYUP : WM_KEYUP,VK_F10,down|LPARAM(0xc0000000u));
398 Check(keyEvents.size()==3,"F10 press, repeat and release reach game");
399 for(size_t i=0;i<keyEvents.size();++i)
400 Check(keyEvents[i].key==VK_F10 && keyEvents[i].down==(i<2) && keyEvents[i].alt==alt,"F10 callback preserves key state");
401 };
402 for(bool system:{false,true})
403 {
404 f10(system,false);
405 Check(menuRequests==0,"F10 does not activate an absent Windows menu");
406 const auto before=moves;HR(host.
Frame(),
"render after F10 without another input");
407 Check(moves==before+1,"F10 leaves game frames running");
408 }
409 f10(true,true);Check(menuRequests==0,"Alt-F10 remains available to game bindings");
410
411 const HMENU menu=CreateMenu(),popup=CreatePopupMenu();Check(menu && popup,"create native menu fixture");
412 Check(AppendMenuW(popup,MF_STRING,1,L"Test") && AppendMenuW(menu,MF_POPUP,reinterpret_cast<UINT_PTR>(popup),L"File") &&
413 SetMenu(host.
Handle(),menu),
"attach native menu fixture");
414 f10(true,false);Check(menuRequests>0,"F10 still activates an attached native menu");
415 Check(SetMenu(host.
Handle(),
nullptr) && DestroyMenu(menu),
"remove native menu fixture");
416
417
418 HR(host.
Resize(64,48),
"prepare quality change fixture");
419 for(UINT samples:{2u,4u,8u,1u})
420 {
421 const unsigned released=releases,resized=resizes;
424 {
425 Check(FAILED(host.
SetSamples(samples)),
"unsupported MSAA rejected");
426 Check(releases==released && resizes==resized,"unsupported MSAA leaves resources intact");
427 continue;
428 }
429 HR(host.
SetSamples(samples),
"change MSAA without resizing the window");
432 Check(color.SampleDesc.Count==samples && depth.SampleDesc.Count==samples,"color/depth sample counts agree");
433 Check(depth.Width==64 && depth.Height==48,"MSAA preserves resolution");
434 Check(releases==released+(oldSamples!=samples) && resizes==resized+(oldSamples!=samples),"MSAA releases and rebuilds game targets once");
435 HR(host.
SetSamples(samples),
"repeat selected MSAA setting");
436 Check(releases==released+(oldSamples!=samples),"unchanged MSAA does not rebuild resources");
437 HR(host.
Frame(),
"present changed MSAA scene");DebugClean(host.
Device());
438 }
439 const unsigned released=releases;
440 Check(FAILED(host.
SetSamples(3)) && FAILED(host.
SetSamples(0)),
"invalid sample counts rejected");
441 Check(releases==released && host.
Device().
Depth().
Description().SampleDesc.Count==1,
"invalid samples preserve current targets");
442 host.
SetVSync(
false);Check(!host.
VSync(),
"disable vertical sync");HR(host.
Frame(),
"present without vertical sync");
443 host.
SetVSync(
true);Check(host.
VSync(),
"enable vertical sync");HR(host.
Frame(),
"present with vertical sync");
444
445
446 for(const auto& sequence:{std::vector<UINT>{WM_LBUTTONDOWN,WM_LBUTTONUP,WM_LBUTTONDOWN,WM_LBUTTONUP},
447 std::vector<UINT>{WM_LBUTTONDOWN,WM_LBUTTONUP,WM_LBUTTONDBLCLK,WM_LBUTTONUP}})
448 {
449 mouseMessages.clear();
450 for(UINT message:sequence)SendMessageW(host.
Handle(),message,message==WM_LBUTTONUP ? 0 : MK_LBUTTON,MAKELPARAM(12,12));
451 Check(mouseMessages==sequence,"single and double clicks reach game callbacks unchanged");
452 }
454 HR(host.
SetSamples(retainedSamples),
"set quality before device recreation");host.
SetVSync(
false);
455 const unsigned priorRelease=releases,priorResize=resizes;
456 HR(host.
RecreateDevice(),
"recreate native device and game resources");
457 Check(creates==2 && destroys==1 && releases==priorRelease+1 && resizes==priorResize+1,"device recreation owns complete callback sequence");
458 Check(registrations==1 && unregistrations==0,"GPU recreation preserves window notification registration");
459 Check(host.
Device().
Depth().
Description().SampleDesc.Count==retainedSamples && !host.
VSync(),
"device recreation retains MSAA and VSync choices");
460 HR(host.
Frame(),
"frame after device recreation");DebugClean(host.
Device());
462 Check(!IsWindow(handle) && !host.
Handle(),
"host destruction completes native window teardown");
463 Check(destroys==2,
"game resources destroyed once per device");host.
Destroy();Check(destroys==2,
"repeated cleanup is harmless");
464 Check(registrations==1 && unregistrations==1 && !notification,"window cleanup releases notifications exactly once");
466 Window11 failed;
unsigned partialCreates=0,partialDestroys=0;
467 callbacks={};callbacks.
create=[&]{++partialCreates;
return E_FAIL;};callbacks.
destroy=[&]{++partialDestroys;};
468 callbacks.
message=[&](HWND handle,UINT message,WPARAM,LPARAM,
bool&)->LRESULT {deviceNotificationMessage(handle,message);
return 0;};
469 Check(FAILED(failed.
Create(options,callbacks)),
"partial game initialization failure propagated");
470 Check(partialCreates==1 && partialDestroys==1 && !failed.
Handle(),
"partial initialization cleans resources and window");
471 Check(registrations==2 && unregistrations==2 && !notification,"failed GPU initialization releases window registration");
472 callbacks={};callbacks.
move=[&](double,float){failed.
Close();};
unsigned afterClose=0;
473 callbacks.
message=[&](HWND handle,UINT message,WPARAM,LPARAM,
bool&)->LRESULT {deviceNotificationMessage(handle,message);
return 0;};
474 callbacks.
draw=[&](double,float){++afterClose;
return S_OK;};
475 HR(failed.
Create(options,callbacks),
"reuse host after failed initialization");
476 Check(failed.
Frame()==S_FALSE && !afterClose,
"frame move can close before rendering");failed.
Destroy();
477 Check(registrations==3 && unregistrations==3 && !notification,"early frame shutdown releases window registration");
478 }
479}
480namespace {
481
482
483struct DeviceLifetime final : IUnknown {
484 ULONG refs=1;
485 unsigned& deaths;
486 explicit DeviceLifetime(unsigned& value):deaths(value){}
487 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID
id,
void** out)
override {
488 if(!out)return E_POINTER;*out=nullptr;
489 if(id!=__uuidof(IUnknown))return E_NOINTERFACE;*out=this;AddRef();return S_OK;
490 }
491 ULONG STDMETHODCALLTYPE AddRef() override{return ++refs;}
492 ULONG STDMETHODCALLTYPE Release() override {const auto left=--refs;if(!left){++deaths;delete this;}return left;}
493};
494const GUID lifetimeKey={0x3294c324,0x2528,0x42fa,{0xa4,0x91,0x33,0x92,0x88,0x37,0x91,0x11}};
495void MemoryAndRecovery(bool warp,bool debug) {
496 Device11 device;HR(device.
Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,debug}),
"memory fixture device");
498 Check(geometry.
Bytes().capacity()>=8*1024*1024,
"CPU geometry storage allocated");
499 geometry.
Reset();Check(geometry.
Bytes().capacity()==0,
"reset returns CPU backing memory to the allocator");
500 HR(geometry.
Create(device.
Device(),1024,
false),
"reuse reset geometry");
501 Check(geometry.
Create(
nullptr,1024,
false)==E_INVALIDARG && geometry.
Bytes().capacity()==0,
502 "failed recreation releases the previous CPU allocation");
504 Check(memory.find("processQuery=ok")!=std::string::npos && memory.find("largestFreeBlock=")!=std::string::npos,
505 "memory diagnostics include process and address-space data");
507 "missing GPU budget is explicitly unavailable");
509 for(
HRESULT failure:{DXGI_ERROR_DEVICE_REMOVED,DXGI_ERROR_DEVICE_RESET,DXGI_ERROR_DEVICE_HUNG,DXGI_ERROR_DRIVER_INTERNAL_ERROR}) {
510 unsigned deaths=0,creates=0,destroys=0,frames=0,presented=0;
511 std::vector<uint32_t> before;
516 Check(host.
Recovering()==(creates!=0),
"recovery state is explicit during create");
517 Check(deaths==creates,"old device destroyed before replacement application resources");
518 auto* observer=new DeviceLifetime(deaths);
519 HR(host.
Device().
Device()->SetPrivateDataInterface(lifetimeKey,observer),
"attach device lifetime observer");observer->Release();++creates;
520 if(creates==1)
521 {
522 HR(resource.
Create(host.
Device().
Device(),
sizeof(quad),
false),
"create selected model geometry");
Fill(resource,quad);
523 }
525 return S_OK;
526 };
528 callbacks.
draw=[&](double,float){
529 auto& draw=host.
Draws();draw.
Pipeline().
raster.CullMode=D3D11_CULL_NONE;draw.Pipeline().depth.DepthEnable=FALSE;
530 draw.Fixed().lighting=
false;draw.Fixed().stages[0].color=draw.Fixed().stages[0].alpha=
TextureOp11::Select1;
534 if(frames==0){before=pixels;Check(before[20*64+20]==0xffd02f63,"selected model visible before failure");}
535 else Check(pixels==before,"every model pixel survives device replacement");
536 return frames++==0 ? failure : S_OK;
537 };
538 callbacks.
presented=[&]{Check(frames==2 && !host.
Recovering(),
"window promotion waits for recovered frame presentation");++presented;
return S_OK;};
539 HR(host.
Create(options,callbacks),
"create recovery fixture");
540 HR(host.
Frame(),
"render failure recreates the device");
541 Check(creates==2 && destroys==1 && deaths==1 && !presented && !host.
Recovering(),
"one complete recovery without presenting a failed frame");
542 HR(host.
Frame(),
"rendering resumes after recovery");
543 Check(presented==1,"only successful frame triggers window presentation");
544 host.
Destroy();Check(deaths==2 && destroys==2 && resource.
Bytes().capacity()==0,
"all recovered device and CPU resources released");
545 }
546
547
551 callbacks.
create=[&]{++creates;HR(resource.
Create(host.
Device().
Device(),4096,
false),
"partial recovery resource");
return creates==1 ? S_OK : E_OUTOFMEMORY;};
553 callbacks.
draw=[](double,float){
return DXGI_ERROR_DEVICE_REMOVED;};
554 HR(host.
Create(options,callbacks),
"create failed-recovery fixture");
555 Check(host.
Frame()==E_OUTOFMEMORY && !host.
Recovering(),
"recovery allocation failure propagates and clears recovery state");
557 Check(creates==2 && destroys==2 && resource.
Bytes().capacity()==0,
"partial recovery cleanup is complete and idempotent");
558}
559}
560int main(
int argc,
char** argv)
561{
562 try
563 {
564 bool warp=false,debug=true;
565 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");
566 MemoryAndRecovery(warp,debug);BatchBoundaries();Lifecycle(warp,debug);LoginClockReset(warp,debug);CullingPreservesPixels(warp,debug);std::cout<<"PASS: "<<checks<<" native draw/host checks\n";return 0;
567 }
568 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<'\n';return 1;}
569}
GeometryBounds & AppendBuildingDrawBatch(std::vector< BuildingDrawBatch > &batches, unsigned component, unsigned first, unsigned primitives, short texture, unsigned char type)
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
ShipDrawBatch FindShipDrawBatch(const Component *components, unsigned count, unsigned first)
UINT SelectSamples(UINT requested) const
ID3D11Texture2D * SceneColor() const
bool SupportsSamples(UINT count) const
ID3D11DeviceContext * Context() const
ID3D11RenderTargetView * SceneTarget() const
ID3D11Device * Device() const
bool DebugLayerEnabled() const
HRESULT Create(const DeviceOptions11 &options={})
const SceneDepth11 & Depth() const
HRESULT Create(ID3D11Device *device, UINT bytes, bool dynamic, bool index=false, bool indices32=false)
HRESULT RestoreDevice(ID3D11Device *device)
HRESULT Lock(UINT offset, UINT size, void **destination, bool readOnly=false, bool discard=false)
uint64_t Revision() const
const std::vector< uint8_t > & Bytes() const
const D3D11_TEXTURE2D_DESC & Description() const
ID3D11DepthStencilView * WriteView() const
HRESULT Create(const WindowOptions11 &options, Callbacks callbacks)
HRESULT SetSamples(UINT samples)
void SetVSync(bool value)
HRESULT Resize(UINT width, UINT height)
const std::string & Status() const
constexpr uint8_t Pixels[262144]
std::string MemoryDiagnostics11(ID3D11Device *device)
void Include(const Vector &p)
bool IntersectsFrustum(const Matrix &m, float guardX=0, float guardY=0) const
D3D11_RASTERIZER_DESC raster
std::function< HRESULT(UINT, UINT)> resize
std::function< void()> destroy
std::function< void(double, float)> move
std::function< LRESULT(HWND, UINT, WPARAM, LPARAM, bool &)> message
std::function< HRESULT()> presented
std::function< HRESULT()> create
std::function< void(UINT, bool, bool)> keyboard
std::function< void()> releaseSizeDependent
std::function< HRESULT(double, float)> draw