File size: 15,073 Bytes
2edf277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// FCS Glass - dx.cpp
//
// Implements: HC4, W1, E2, E3, G1, G2, R6.  (Research notes in dx.h; every
// signature and behaviour there was measured before being written.)

#include "device/dx.h"

#include <cstdio>

namespace fcs {

// D-26 / D-24. The buffer is a D3D11_FEATURE_DATA_FORMAT_SUPPORT struct, NOT a
// bare DXGI_FORMAT - passing the latter returns E_INVALIDARG and silently
// downgrades every quality decision.
bool D3D11SupportsFormat(ID3D11Device* dev, DXGI_FORMAT fmt) {
  if (!dev) return false;
  D3D11_FEATURE_DATA_FORMAT_SUPPORT data = {};
  data.InFormat = fmt;
  HRESULT hr = dev->CheckFeatureSupport(D3D11_FEATURE_FORMAT_SUPPORT, &data, sizeof(data));
  if (FAILED(hr)) return false;
  return (data.OutFormatSupport & D3D11_FORMAT_SUPPORT_RENDER_TARGET) != 0;
}

// D-22. The DComp device is created from an IDXGIDevice, NOT by
// QueryInterface on the D3D11 device - that returns E_NOINTERFACE every time.
HRESULT CreateCompositionDeviceFor(IDXGIDevice* dxgi, IDCompositionDevice** out) {
  if (!dxgi || !out) return E_POINTER;
  *out = nullptr;
  return ::DCompositionCreateDevice(dxgi, IID_PPV_ARGS(out));
}

DxDevice::~DxDevice() { Destroy(); }

void DxDevice::ReportFailure(const char* where, HRESULT hr) {
  info_.last_failure = hr;
  // Reported through the project's single HRESULT funnel so the probe can
  // surface file/line/expr rather than a bare code.
  FCS_CHECK_HR(hr);
  (void)where;
}

// REQ HC4 - hardware, then WARP. Both paths are attempted before giving up.
bool DxDevice::Create() {
  Destroy();
  if (!CreateDeviceInternal()) return false;
  if (!CreateCompositionInternal()) {
    Destroy();
    return false;
  }
  return true;
}

// REQ E3 - rebuild for device removed/reset. Caller keeps its own state.
bool DxDevice::Recreate() { return Create(); }

// E3 injection seam - the single point through which a frame is presented, so a
// DXGI_ERROR_DEVICE_REMOVED can be synthesised. Placed BEFORE the chain check
// deliberately: when a device really is lost, the chain is usually already gone,
// and an injection that returned "no chain" would be testing the wrong branch.
HRESULT DxDevice::Present(UINT flags) {
  if (injected_removals_ > 0) {
    --injected_removals_;
    return DXGI_ERROR_DEVICE_REMOVED;
  }
  IDXGISwapChain1* chain = swap_chain_.Get();
  if (chain == nullptr) return DXGI_ERROR_DEVICE_REMOVED;
  return chain->Present(0, flags);
}

bool DxDevice::CreateDeviceInternal() {
  static const D3D_FEATURE_LEVEL kLevels[] = {
      D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0,
      D3D_FEATURE_LEVEL_9_3,  D3D_FEATURE_LEVEL_9_2,  D3D_FEATURE_LEVEL_9_1,
  };
  // BGRA_SUPPORT is required: the R7 font atlas is built with GDI and the D2D
  // interop depends on it.
  const UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

  D3D_DRIVER_TYPE order[] = {D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP};
  DriverKind kinds[] = {DriverKind::Hardware, DriverKind::Warp};

  HRESULT last = E_FAIL;
  for (int attempt = 0; attempt < 2; ++attempt) {
    device_.Reset();
    context_.Reset();
    D3D_FEATURE_LEVEL got = D3D_FEATURE_LEVEL_9_1;
    last = ::D3D11CreateDevice(nullptr, order[attempt], nullptr, flags, kLevels,
                              ARRAYSIZE(kLevels), D3D11_SDK_VERSION, device_.GetAddressOf(), &got,
                              context_.GetAddressOf());
    if (SUCCEEDED(last)) {
      info_.driver = kinds[attempt];
      info_.feature_level = got;
      info_.last_failure = S_OK;

      // D-22: the D3D device must hand us its IDXGIDevice for DComp.
      HRESULT q = device_.QueryInto<IDXGIDevice>(dxgi_device_.GetAddressOf());
      if (FAILED(q)) {
        ReportFailure("QueryInterface(IDXGIDevice)", q);
        return false;
      }

      // G2: measured, not assumed. Both were confirmed available on hardware
      // AND on WARP, so this is a capability check that can legitimately fail
      // on some future driver rather than a hard-coded tier mapping. (D-26)
      info_.supports_r10g10b10a2 =
          D3D11SupportsFormat(device_.Get(), DXGI_FORMAT_R10G10B10A2_UNORM);
      info_.supports_b8g8r8a8 =
          D3D11SupportsFormat(device_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM);
      return true;
    }
  }

  ReportFailure("D3D11CreateDevice(hardware+WARP)", last);
  return false;
}

bool DxDevice::CreateCompositionInternal() {
  HRESULT hr = CreateCompositionDeviceFor(dxgi_device_.Get(), dcomp_.GetAddressOf());
  if (FAILED(hr)) {
    ReportFailure("DCompositionCreateDevice", hr);
    return false;
  }
  // IID_PPV_ARGS expands straight to the SDK's IID_PPV_ARGS_Helper, which only
  // overloads for T**, so a ComPtr<T>* is passed via GetAddressOf() rather
  // than through IID_PPV_ARGS.
  hr = ::CreateDXGIFactory2(0, IID_PPV_ARGS(factory_.GetAddressOf()));
  if (FAILED(hr)) {
    ReportFailure("CreateDXGIFactory2", hr);
    return false;
  }
  return true;
}
// REQ G2 / J5 - the PRESENTED swap chain is always B8G8R8A8_UNORM.
//
// X28: this previously returned R10G10B10A2_UNORM for QualityTier::Full, and
// CreateSwapChain assigned it to the swap chain while also setting
// DXGI_ALPHA_MODE_PREMULTIPLIED. R10G10B10A2 has a 2-BIT alpha channel, so a
// premultiplied alpha of 0.045, 0.30 or 0.72 would quantise to 0, 0.33, 0.67
// or 1 - every translucent tint would have been wrong from M3 onward. G2 and
// G1 cannot both hold on a swap chain (C-8), and the later rule (J5) wins.
//
// R10G10B10A2 remains correct, and is still used, for INTERNAL OPAQUE targets
// (backdrop, blur pyramid) whose alpha is unused - which is what G2 actually
// asked for. That is a separate accessor so the two cannot be confused again.
DXGI_FORMAT DxDevice::RenderTargetFormat(QualityTier tier) const {
  (void)tier;   // J5: the presented format does not vary by tier
  return DXGI_FORMAT_B8G8R8A8_UNORM;
}

// REQ G2 - format for an internal opaque render target, where the 2-bit alpha
// of R10G10B10A2 is harmless and its wider colour depth is wanted. Returns
// B8G8R8A8 when the format is genuinely unsupported (D-26 made this a
// measurement rather than an assumption).
DXGI_FORMAT DxDevice::InternalOpaqueFormat() const {
  if (info_.supports_r10g10b10a2) return DXGI_FORMAT_R10G10B10A2_UNORM;
  return DXGI_FORMAT_B8G8R8A8_UNORM;
}

// REQ W1 / G1 - the composition swap chain.
bool DxDevice::CreateSwapChain(HWND hwnd, UINT width, UINT height, QualityTier tier) {
  if (!hwnd || !device_ || !dcomp_ || !factory_) {
    info_.last_failure = E_INVALIDARG;
    return false;
  }
  if (width == 0 || height == 0) {
    // E2: a zero-size swap chain is invalid, and ResizeBuffers(0,0) is
    // E_INVALIDARG (D-25), so refuse rather than hand DXGI a bad call.
    info_.last_failure = E_INVALIDARG;
    return false;
  }

  DXGI_SWAP_CHAIN_DESC1 desc = {};
  desc.Width = width;
  desc.Height = height;
  desc.Format = RenderTargetFormat(tier);
  desc.SampleDesc.Count = 1;
  desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  desc.BufferCount = 2;
  desc.Scaling = DXGI_SCALING_STRETCH;
  // MANDATORY for a composition swap chain: DISCARD returns
  // DXGI_ERROR_INVALID_CALL (D-25).
  desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
  // G1: premultiplied end to end, which is what prevents a dark fringe on
  // antialiased edges. Note the API does NOT enforce this - D-17's lesson
  // applies - so setting it is entirely our responsibility.
  desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;

  swap_chain_.Reset();
  rtv_.Reset();
  HRESULT hr = factory_->CreateSwapChainForComposition(device_.Get(), &desc, nullptr,
                                                       swap_chain_.GetAddressOf());
  if (FAILED(hr)) {
    ReportFailure("CreateSwapChainForComposition", hr);
    return false;
  }

  // D-23: the method is CreateVisual; there is no CreateRootVisual.
  //
  // OWNERSHIP: this function OWNS the composition tree for the window - the
  // target, the root visual, and the SetContent link. The caller in main.cpp
  // previously built a SECOND target/visual over the SAME swap chain, which
  // meant two DComp targets for one HWND fighting over one root. `topmost`
  // also differed (TRUE here, FALSE there), so which tree won was undefined.
  //
  // The fix is that the tree is built HERE and ONLY here. AttachContent() below
  // re-establishes the link after a ResizeBuffers without rebuilding the tree.
  ComPtr<IDCompositionTarget> target;
  hr = dcomp_->CreateTargetForHwnd(hwnd, /*topmost=*/TRUE, target.GetAddressOf());
  if (FAILED(hr)) {
    ReportFailure("CreateTargetForHwnd", hr);
    return false;
  }
  ComPtr<IDCompositionVisual> root;
  hr = dcomp_->CreateVisual(root.GetAddressOf());
  if (FAILED(hr)) {
    ReportFailure("CreateVisual", hr);
    return false;
  }
  hr = root->SetContent(swap_chain_.Get());
  if (FAILED(hr)) {
    ReportFailure("IDCompositionVisual::SetContent", hr);
    return false;
  }
  hr = target->SetRoot(root.Get());
  if (FAILED(hr)) {
    ReportFailure("IDCompositionTarget::SetRoot", hr);
    return false;
  }
  hr = dcomp_->Commit();
  if (FAILED(hr)) {
    ReportFailure("IDCompositionDevice::Commit", hr);
    return false;
  }
  // The tree outlives this call, so both objects are retained. Without these the
  // ComPtrs release here and DComp is left holding a tree it can no longer
  // reason about on the next Commit. Swap, not assignment: ComPtr is move-only
  // and has a deleted copy-assignment (C2280).
  target_.Swap(target);
  root_.Swap(root);

  width_ = width;
  height_ = height;
  has_swap_chain_ = true;
  return true;
}

// REQ W1 / E2 - re-attach the back buffer after ResizeBuffers.
//
// ResizeBuffers detaches the buffers, so the root visual's content reference
// has to be re-established or the window goes black. The target and visual
// themselves are reused: rebuilding them on every resize is what produced a
// second target per HWND in the first place.
bool DxDevice::AttachContent() {
  if (!has_swap_chain_ || !dcomp_ || !root_) return false;
  HRESULT hr = root_->SetContent(swap_chain_.Get());
  if (FAILED(hr)) {
    ReportFailure("IDCompositionVisual::SetContent (reattach)", hr);
    return false;
  }
  hr = dcomp_->Commit();
  if (FAILED(hr)) {
    ReportFailure("IDCompositionDevice::Commit (reattach)", hr);
    return false;
  }
  return true;
}

void DxDevice::DestroySwapChain() {
  rtv_.Reset();
  // Order matters. The chain is a child of root_ in the composition graph, so
  // it must be released BEFORE the target that commits it - otherwise the
  // target holds a frame reference and Commit/destroy can stall or fault.
  swap_chain_.Reset();
  // Release the composition tree too. Leaving target_/root_ alive here is what
  // let a destroyed chain keep a target bound to the HWND, so the next
  // CreateSwapChain built a SECOND target for the same window. Resetting here
  // keeps "DxDevice owns exactly one tree per swap chain" (W1) true across a
  // rebuild, not just across a resize.
  root_.Reset();
  target_.Reset();
  has_swap_chain_ = false;
  width_ = 0;
  height_ = 0;
}

ID3D11RenderTargetView* DxDevice::AcquireRtv(HRESULT* hr_out) {
  if (hr_out) *hr_out = S_OK;
  if (!has_swap_chain_ || !device_) {
    if (hr_out) *hr_out = E_UNEXPECTED;
    return nullptr;
  }
  if (rtv_) return rtv_.Get();

  ComPtr<ID3D11Texture2D> back;
  HRESULT hr = swap_chain_->GetBuffer(0, IID_PPV_ARGS(back.GetAddressOf()));
  if (FAILED(hr)) {
    ReportFailure("IDXGISwapChain1::GetBuffer", hr);
    if (hr_out) *hr_out = hr;
    return nullptr;
  }
  hr = device_->CreateRenderTargetView(back.Get(), nullptr, rtv_.GetAddressOf());
  if (FAILED(hr)) {
    ReportFailure("CreateRenderTargetView", hr);
    if (hr_out) *hr_out = hr;
    return nullptr;
  }
  return rtv_.Get();
}

// REQ E2 - ResizeBuffers only when the size is genuinely non-zero. Measured:
// ResizeBuffers(0, 0, ...) is E_INVALIDARG, so the guard is required.
bool DxDevice::ResizeSwapChain(UINT width, UINT height) {
  if (!has_swap_chain_) {
    info_.last_failure = E_UNEXPECTED;
    return false;
  }
  if (width == 0 || height == 0) return true;  // nothing to do, not an error

  // BUG-29: release every reference to the back buffer BEFORE ResizeBuffers.
  // Dropping the RTV object is not enough: the device context still holds a
  // reference while the RTV is bound to the output-merger stage, and
  // PresentFrame binds it every frame and never unbinds. DXGI documents that
  // ResizeBuffers fails (DXGI_ERROR_INVALID_CALL) while the back buffer is still
  // referenced. Latent rather than observed - every resize on this host had
  // happened to succeed - but now load-bearing: the whole BUG-26 drag fix is
  // built on ResizeBuffers being reliable.
  // ComPtr has an explicit operator bool and operator! but NO operator==, so
  // `context_ != nullptr` is C2678 (main.cpp research note 5a).
  if (context_) context_->OMSetRenderTargets(0, nullptr, nullptr);
  rtv_.Reset();
  // P3-12: D3D11 releases objects lazily; flush so the runtime drops its back-buffer
  // reference before ResizeBuffers (the usual resize pattern in the DirectX samples).
  if (context_) context_->Flush();
  HRESULT hr = swap_chain_->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, 0);
  if (FAILED(hr)) {
    ReportFailure("IDXGISwapChain1::ResizeBuffers", hr);
    return false;
  }
  width_ = width;
  height_ = height;
  return true;
}

// REQ E2 - the size DXGI actually granted, not the size we asked for.
//
// Cached width_/height_ record intent. This reads DXGI_SWAP_CHAIN_DESC back out
// of the chain, so it is the only value that can prove the back buffer really
// covers the client area. The M0 capture showed a 443 px uncovered strip, and
// nothing in the cached fields would have revealed it: we had asked for a size
// and believed we got it.
bool DxDevice::SwapChainBufferSize(UINT* out_w, UINT* out_h) const {
  if (out_w) *out_w = 0;
  if (out_h) *out_h = 0;
  if (!swap_chain_) return false;
  DXGI_SWAP_CHAIN_DESC desc = {};
  HRESULT hr = swap_chain_->GetDesc(&desc);
  if (FAILED(hr)) return false;
  if (out_w) *out_w = desc.BufferDesc.Width;
  if (out_h) *out_h = desc.BufferDesc.Height;
  return true;
}

// REQ R6 - 60 fps Full, 30 fps Basic.
int DxDevice::TargetFrameMs(QualityTier tier) const {
  switch (tier) {
    case QualityTier::Full:     return 16;  // ~60 Hz
    case QualityTier::Balanced: return 16;
    case QualityTier::Basic:    return 33;  // ~30 Hz
    default:                    return 16;
  }
}

void DxDevice::Destroy() {
  DestroySwapChain();
  factory_.Reset();
  dcomp_.Reset();
  dxgi_device_.Reset();
  context_.Reset();
  device_.Reset();
  info_ = DeviceInfo();
}

}  // namespace fcs