# swapchain presentation paths

Choosing a DXGI swapchain presentation path that resizes smoothly.

- Page: https://oh4.co/site/swapchain-presentation-paths.html
- Under: [graphics](graphics.md)
- Last change: 7EAB1A (2026-11-26)

When setting up your renderer (DX11, DX12, Vulkan) on Windows you have a couple of options for DXGI swapchain presentation. But not all of these options are equal if you want to allow for smoothly resizing a windowed view. Choosing the naive route will produce very laggy and bizarre resizing behavior. Everything here assumes a single-threaded renderer.

<p>Windows composites every desktop window through the <strong>Desktop Window
Manager (DWM)</strong>. The difference between the three paths is <strong>how
your backbuffer gets into DWM</strong>.</p>

<h4>Naive route (laggy)</h4>

<p>Use <code>DXGI_SWAP_EFFECT_FLIP_DISCARD</code>. Instead of copying into the
window's legacy DWM redirection bitmap, DXGI hands your backbuffer directly to
DWM via an <strong>independent flip queue</strong> (enabling MPO / Independent
Flip, HDR, and VRR).</p>

<p><strong>The catch</strong>: That flip queue is <em>asynchronous</em>
from <code>SetWindowPos</code>. Every <code>ResizeBuffers</code> tears down and
re-handshakes the flip queue with DWM (<code>2–4+ ms</code> spikes), while the
OS window border moves ahead of the swapchain and exposes pitch-black gutters
(<code>DXGI_SCALING_NONE</code>).</p>

```C
DXGI_SWAP_CHAIN_DESC1 desc = {
    .BufferCount = 2,
    .Scaling     = DXGI_SCALING_NONE,
    .SwapEffect  = DXGI_SWAP_EFFECT_FLIP_DISCARD, // independent DWM flip queue
    ...
};
factory->CreateSwapChainForHwnd(device, hwnd, &desc, 0, 0, &swapchain);

// On every WM_PAINT resize:
swapchain->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0);
...
swapchain->Present(1, 0);
```

<h4>Deprecated, yet smooth (DX11-only)</h4>

<p>The legacy D3D11 path (used by <code>raddebugger</code>).
On <code>Present</code>, DXGI <strong>blits (copies)</strong> your backbuffer
directly into the window's DWM redirection surface in lockstep
with <code>SetWindowPos</code> and <code>WM_PAINT</code>.</p>

<ul>
  <li><strong>Why it's faster on resize</strong>: No flip-queue/MPO teardown on <code>ResizeBuffers</code> (<code>4.5×</code> faster <code>p95</code>), and the client pixels stay glued to the OS border.</li>
  <li><strong>Trade-off</strong>: Extra copy in steady state, no <code>ALLOW_TEARING</code> / HDR / Independent Flip, D3D11 debug-layer advisory warning, and <strong>banned in DX12</strong>.</li>
</ul>

```C
DXGI_SWAP_CHAIN_DESC1 desc = {
    .BufferCount = 2,
    .Scaling     = DXGI_SCALING_STRETCH,
    .SwapEffect  = DXGI_SWAP_EFFECT_DISCARD,
    ...
};
factory->CreateSwapChainForHwnd(device, hwnd, &desc, 0, 0, &swapchain);

swapchain->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0);
...
swapchain->Present(1, 0);
```

<h4>Official Microsoft "right way" (DirectComposition)</h4>

<p>Shipped Flip-model desktop apps (<strong>Windows
Terminal</strong>, <strong>Zed</strong>, <strong>Chromium</strong>) decouple
the swapchain from the <code>HWND</code> by creating the window
with <code>WS_EX_NOREDIRECTIONBITMAP</code> and binding
a <strong><code>CreateSwapChainForComposition</code></strong> swapchain to
a <strong>DirectComposition</strong> visual tree.</p>

<p><strong>Important catch — DComp alone still hitches</strong>: Switching
from <code>CreateSwapChainForHwnd</code>
to <code>CreateSwapChainForComposition</code> fixes redirection-bitmap gutter
artifacts, <strong>not</strong> flip-model resize stalls. If you still
call <code>ResizeBuffers(0, w, h, ...)</code> + <code>Present(1, 0)</code>
synchronously inside <code>WM_PAINT</code>, <code>ResizeBuffers</code> still
takes <code>1.6–1.8 ms</code> avg (spikes <code>10–19 ms</code>)
and <code>Present(1, 0)</code> blocks the Win32 modal drag loop waiting on DWM
vblank.</p>

<p><strong>How shipped DX12 / DComp apps actually avoid the hitch</strong>:</p>

<ol>
  <li><strong>Defer until <code>WM_EXITSIZEMOVE</code></strong> (DX12 game templates, Godot D3D12): zero drag hitching, no live reflow.</li>
  <li><strong>Dedicated render thread / GPU process</strong> (Chromium, Edge, Windows Terminal): Win32 <code>WndProc</code> never blocks on <code>ResizeBuffers</code> or <code>Present</code>; rendering feeds DirectComposition asynchronously.</li>
  <li><strong>Single-threaded live reflow — bucketed over-allocation + <code>SetClip</code> + <code>Present(0, 0)</code></strong>: You need <strong>both</strong> halves together:
    <ul>
      <li><strong>Over-allocate in buckets (e.g. 512 px) + <code>SetClip</code></strong>: Unlike an HWND swapchain, a composition swapchain bound to an <code>IDCompositionVisual</code> with an identity transform renders at <strong>1:1 physical pixels</strong> anchored at <code>(0, 0)</code> — it does not stretch to the window. Set your GPU viewport/scissor and UI coordinates to <code>(clientW, clientH)</code> (zero stretching, zero ImGui/pointer breakage) and clip the visual with <code>visual->SetClip(&#123;0, 0, clientW, clientH&#125;)</code>. <code>ResizeBuffers</code> drops to <strong>0 calls</strong> while dragging inside a bucket (firing only when crossing a bucket boundary, and optionally shrinking once on <code>WM_EXITSIZEMOVE</code>).</li>
      <li><strong><code>Present(0, 0)</code> on resize frames (and no per-frame <code>Commit()</code>)</strong>: Under DWM flip-model, <code>Present(0, 0)</code> (flags <code>0</code>) is still tear-free — DWM composites on vblank and <code>FLIP_DISCARD</code> drops superseded frames instead of stalling <code>WM_PAINT</code>. <code>dcomp->Commit()</code> is only needed when the visual tree or clip rect changes, not on every <code>Present()</code>.</li>
    </ul>
  </li>
</ol>

<p><strong>The tax</strong>: Works in both <strong>D3D11 and DX12</strong> and
avoids Blt's steady-state copy, but <code>WS_EX_NOREDIRECTIONBITMAP</code>
pushes you toward owning <strong>custom chrome</strong>
(<code>WM_NCCALCSIZE</code> + <code>WM_NCHITTEST</code> + titlebar/buttons) and
a <strong>backdrop</strong> (a DComp solid-color visual
or <code>DWMWA_SYSTEMBACKDROP_TYPE</code> behind the swapchain). You also pay
extra VRAM for bucketed triple buffers, ~150+ LOC of COM glue
(<code>dcomp.h</code> is C++-only), and still
no <code>ALLOW_TEARING</code>.</p>

```C
// Window created with WS_EX_NOREDIRECTIONBITMAP (app owns chrome + backdrop)
DXGI_SWAP_CHAIN_DESC1 desc = {
    .Width       = round_up_512(w),
    .Height      = round_up_512(h),
    .BufferCount = 3,
    .Scaling     = DXGI_SCALING_STRETCH,          // required for composition
    .SwapEffect  = DXGI_SWAP_EFFECT_FLIP_DISCARD,
    .AlphaMode   = DXGI_ALPHA_MODE_IGNORE,        // UNSPECIFIED fails
    ...
};
factory->CreateSwapChainForComposition(device, &desc, 0, &swapchain);

// Bind swapchain into a DirectComposition visual tree once (1:1 pixels, clipped to client rect):
DCompositionCreateDevice(dxgi_device, &IID_IDCompositionDevice, &dcomp);
dcomp->CreateTargetForHwnd(hwnd, TRUE, &target);
dcomp->CreateVisual(&visual);
visual->SetContent(swapchain);
visual->SetClip((D2D_RECT_F){ 0, 0, (float)w, (float)h });
target->SetRoot(visual);
dcomp->Commit();

// On resize (WM_PAINT): only ResizeBuffers when exceeding the current 512px bucket
if (w > alloc_w || h > alloc_h) {
    alloc_w = round_up_512(max(w, alloc_w));
    alloc_h = round_up_512(max(h, alloc_h));
    swapchain->ResizeBuffers(0, alloc_w, alloc_h, DXGI_FORMAT_UNKNOWN, 0);
}
// Render with viewport/scissor/UI size = (w, h), then present non-blocking + update clip:
...
swapchain->Present(resized_this_frame ? 0 : 1, 0);
if (resized_this_frame) {
    visual->SetClip((D2D_RECT_F){ 0, 0, (float)w, (float)h });
    dcomp->Commit();
}
```

<h4>Measured comparison (100-step modal resize, Win11 165 Hz)</h4>

<p>Ablation on the same <code>WM_PAINT</code> live-resize loop
(<code>950..1350 × 620..880</code>, D3D11, <code>Release-Profile</code>):</p>

<table>
  <tr>
    <th>Path</th>
    <th><code>ResizeBuffers</code> (100 steps)</th>
    <th><code>Present</code> in <code>WM_PAINT</code></th>
    <th><code>WND_WM_PAINT</code> avg/fr</th>
    <th><code>WND_DispatchMsg</code> p50 / p95 / p99 / max</th>
  </tr>

<tr>
    <td>Naive HWND <code>FLIP_DISCARD</code> + <code>Present(1,0)</code></td>
    <td><code>1.20 ms</code>/fr</td>
    <td>—</td>
    <td><code>4.89 ms</code></td>
    <td>— (<code>WM_PAINT</code> p95 <code>8.45 ms</code>, p99 <code>10.17 ms</code>)</td>
  </tr>

<tr>
    <td>Naive DComp (per-px <code>ResizeBuffers</code> + <code>Present(1,0)</code>)</td>
    <td><code>1.63 ms</code>/fr</td>
    <td><code>1.78 ms</code>/fr</td>
    <td><code>4.29 ms</code></td>
    <td>— (<code>Present</code> spikes up to <code>36.7 ms</code>)</td>
  </tr>

<tr>
    <td>DComp (<code>Present(0,0)</code> only, still per-px <code>ResizeBuffers</code>)</td>
    <td><code>1.69 ms</code>/fr</td>
    <td><code>0.44 ms</code>/fr</td>
    <td><code>3.06 ms</code></td>
    <td>— (<code>ResizeBuffers</code> max <code>10.1 ms</code>)</td>
  </tr>

<tr>
    <td>DComp (512px bucket only, still <code>Present(1,0)</code>)</td>
    <td><strong><code>0.00 ms</code></strong></td>
    <td><code>4.16 ms</code>/fr</td>
    <td><code>4.97 ms</code></td>
    <td>— (<code>Present(1,0)</code> absorbs the savings)</td>
  </tr>

<tr>
    <td>Blt <code>DISCARD</code> (DX11-only)</td>
    <td><code>0.41 ms</code>/fr</td>
    <td><code>0.92 ms</code>/fr</td>
    <td><code>2.17 ms</code></td>
    <td><code>2.50</code> / <code>5.21</code> / <strong><code>6.23</code></strong> / <strong><code>6.65</code></strong> <code>ms</code></td>
  </tr>

<tr>
    <td>DComp Smooth (512px bucket + <code>SetClip</code> + <code>Present(0,0)</code>)</td>
    <td><strong><code>0.00 ms</code></strong></td>
    <td><strong><code>0.70 ms</code></strong>/fr</td>
    <td><strong><code>1.51 ms</code></strong></td>
    <td><strong><code>1.97</code></strong> / <strong><code>3.66</code></strong> / <code>11.04</code> / <code>15.10</code> <code>ms</code></td>
  </tr>
</table>

<p><strong>Takeaway</strong>: Neither bucketed over-allocation
nor <code>Present(0, 0)</code> fixes DComp resize on its own — combining both
beats Blt <code>DISCARD</code> on avg/p95 resize time (<code>1.51 ms</code>
vs <code>2.17 ms</code>) and works on DX12, while Blt <code>DISCARD</code>
still has the tightest worst-case tail (<code>6.65 ms</code> max
vs <code>15.10 ms</code>) with zero extra VRAM or COM/chrome machinery.</p>

<h4>Minimal example</h4>

<p>A complete D3D11 + DirectComposition program in pure C that uses the bucketed
over-allocation, <code>SetClip</code> and <code>Present(0, 0)</code> approach
above.</p>

```C
/*
	Minimal DirectComposition + D3D11 setup in pure C that supports window
	resizing without constant hitching, unlike more naive setups. Comparable or
	better performance than using DXGI_SWAP_EFFECT_DISCARD.

	Soli Deo gloria

	To compile, run:

		cl /TC /std:c11 /W4 /WX d3d11_dcomp_smooth_resize.c
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d11_1.h>
#include <dxgi1_2.h>
#include <d3dcompiler.h>
#include <stdint.h>

#pragma comment(lib, "user32")
#pragma comment(lib, "d3d11")
#pragma comment(lib, "dxgi")
#pragma comment(lib, "dcomp")
#pragma comment(lib, "d3dcompiler")
#pragma comment(lib, "dxguid")
#pragma comment(linker, "/SUBSYSTEM:WINDOWS")

#define kResizeBucketPx	512u
#define com_release(x)	do { if ( (x) != 0 ) { (x)->lpVtbl->Release(x); (x) = 0; } } while (0)

typedef struct DComp_RectF DComp_RectF;
struct DComp_RectF {
	float	Left;
	float	Top;
	float	Right;
	float	Bottom;
};

typedef struct DComp_Device DComp_Device;
typedef struct DComp_Target DComp_Target;
typedef struct DComp_Visual DComp_Visual;

typedef struct DComp_Device_Vtbl DComp_Device_Vtbl;
struct DComp_Device_Vtbl {
	HRESULT(STDMETHODCALLTYPE *QueryInterface)(DComp_Device*, REFIID, void**);
	ULONG(STDMETHODCALLTYPE *AddRef)(DComp_Device*);
	ULONG(STDMETHODCALLTYPE *Release)(DComp_Device*);
	HRESULT(STDMETHODCALLTYPE *Commit)(DComp_Device*);
	HRESULT(STDMETHODCALLTYPE *WaitForCommitCompletion)(DComp_Device*);
	HRESULT(STDMETHODCALLTYPE *GetFrameStatistics)(DComp_Device*, void*);
	HRESULT(STDMETHODCALLTYPE *CreateTargetForHwnd)(DComp_Device*, HWND, BOOL, DComp_Target**);
	HRESULT(STDMETHODCALLTYPE *CreateVisual)(DComp_Device*, DComp_Visual**);
};
struct DComp_Device {
	const DComp_Device_Vtbl*	lpVtbl;
};

typedef struct DComp_Target_Vtbl DComp_Target_Vtbl;
struct DComp_Target_Vtbl {
	HRESULT(STDMETHODCALLTYPE *QueryInterface)(DComp_Target*, REFIID, void**);
	ULONG(STDMETHODCALLTYPE *AddRef)(DComp_Target*);
	ULONG(STDMETHODCALLTYPE *Release)(DComp_Target*);
	HRESULT(STDMETHODCALLTYPE *SetRoot)(DComp_Target*, DComp_Visual*);
};
struct DComp_Target {
	const DComp_Target_Vtbl*	lpVtbl;
};

typedef struct DComp_Visual_Vtbl DComp_Visual_Vtbl;
struct DComp_Visual_Vtbl {
	HRESULT(STDMETHODCALLTYPE *QueryInterface)(DComp_Visual*, REFIID, void**);
	ULONG(STDMETHODCALLTYPE *AddRef)(DComp_Visual*);
	ULONG(STDMETHODCALLTYPE *Release)(DComp_Visual*);
	HRESULT(STDMETHODCALLTYPE *SetOffsetXAnim)(DComp_Visual*, void*);
	HRESULT(STDMETHODCALLTYPE *SetOffsetX)(DComp_Visual*, float);
	HRESULT(STDMETHODCALLTYPE *SetOffsetYAnim)(DComp_Visual*, void*);
	HRESULT(STDMETHODCALLTYPE *SetOffsetY)(DComp_Visual*, float);
	HRESULT(STDMETHODCALLTYPE *SetTransformObj)(DComp_Visual*, void*);
	HRESULT(STDMETHODCALLTYPE *SetTransformMat)(DComp_Visual*, const void*);
	HRESULT(STDMETHODCALLTYPE *SetTransformParent)(DComp_Visual*, DComp_Visual*);
	HRESULT(STDMETHODCALLTYPE *SetEffect)(DComp_Visual*, void*);
	HRESULT(STDMETHODCALLTYPE *SetBitmapInterpolationMode)(DComp_Visual*, UINT);
	HRESULT(STDMETHODCALLTYPE *SetBorderMode)(DComp_Visual*, UINT);
	HRESULT(STDMETHODCALLTYPE *SetClipObj)(DComp_Visual*, void*);
	HRESULT(STDMETHODCALLTYPE *SetClipRect)(DComp_Visual*, const DComp_RectF*);
	HRESULT(STDMETHODCALLTYPE *SetContent)(DComp_Visual*, IUnknown*);
};
struct DComp_Visual {
	const DComp_Visual_Vtbl*	lpVtbl;
};

extern HRESULT WINAPI DCompositionCreateDevice(IDXGIDevice* dxgi_device, REFIID iid, void** dcomp_device);

static const GUID kIIDDCompDevice = {
	0xC37EA93Au, 0xE7AAu, 0x450Du,
	{ 0xB1u, 0x6Fu, 0x97u, 0x46u, 0xCBu, 0x04u, 0x07u, 0xF3u }
};

static const char g_shader_src[] =
	"cbuffer Params : register(b0) { float2 Size; float2 Pad; };\n"
	"struct VSOut { float4 pos : SV_POSITION; float3 col : COLOR; };\n"
	"VSOut VSMain(uint id : SV_VertexID) {\n"
	"	float2 pts[3] = { float2(0.0, 220.0), float2(190.5, -110.0), float2(-190.5, -110.0) };\n"
	"	float3 col[3] = { float3(0.95, 0.35, 0.30), float3(0.25, 0.85, 0.55), float3(0.30, 0.55, 0.95) };\n"
	"	VSOut o;\n"
	"	o.pos = float4(pts[id] / (Size * 0.5), 0.0, 1.0);\n"
	"	o.col = col[id];\n"
	"	return o;\n"
	"}\n"
	"float4 PSMain(VSOut i) : SV_TARGET {\n"
	"	return float4(i.col, 1.0);\n"
	"}\n";

typedef struct App_State App_State;
struct App_State {
	ID3D11Device*			Device;
	ID3D11DeviceContext*	Context;
	IDXGISwapChain1*		SwapChain;
	ID3D11RenderTargetView*	RTV;
	ID3D11VertexShader*		VertexShader;
	ID3D11PixelShader*		PixelShader;
	ID3D11Buffer*			ParamsCB;
	DComp_Device*			DComp;
	DComp_Target*			Target;
	DComp_Visual*			Visual;
	uint32_t				ClientW;
	uint32_t				ClientH;
	uint32_t				RenderedW;
	uint32_t				RenderedH;
	uint32_t				AllocW;
	uint32_t				AllocH;
	BOOL					InLiveResize;
	BOOL					InRepaint;
	BOOL					Ready;
};

static App_State g_app;

static uint32_t round_bucket(uint32_t v) {
	uint32_t rounded = ( ( v + kResizeBucketPx - 1u ) / kResizeBucketPx ) * kResizeBucketPx;
	return( ( rounded > 0u ) ? rounded : kResizeBucketPx );
}

static void bind_backbuffer(void) {
	com_release(g_app.RTV);
	ID3D11Texture2D* backbuffer = 0;
	if ( FAILED(g_app.SwapChain->lpVtbl->GetBuffer(g_app.SwapChain, 0, &IID_ID3D11Texture2D, (void**)&backbuffer)) ) {
		return;
	}
	D3D11_TEXTURE2D_DESC desc = {0};
	backbuffer->lpVtbl->GetDesc(backbuffer, &desc);
	g_app.AllocW = desc.Width;
	g_app.AllocH = desc.Height;
	g_app.Device->lpVtbl->CreateRenderTargetView(g_app.Device, (ID3D11Resource*)backbuffer, 0, &g_app.RTV);
	com_release(backbuffer);
}

static void resize_swapchain(uint32_t w, uint32_t h) {
	g_app.Context->lpVtbl->OMSetRenderTargets(g_app.Context, 0, 0, 0);
	com_release(g_app.RTV);
	g_app.Context->lpVtbl->Flush(g_app.Context);
	if ( SUCCEEDED(g_app.SwapChain->lpVtbl->ResizeBuffers(g_app.SwapChain, 0, w, h, DXGI_FORMAT_UNKNOWN, 0u)) ) {
		bind_backbuffer();
	}
}

static void render_frame(void) {
	if ( !g_app.Ready || ( g_app.ClientW == 0 ) || ( g_app.ClientH == 0 ) ) {
		return;
	}

	BOOL size_changed = ( g_app.ClientW != g_app.RenderedW ) || ( g_app.ClientH != g_app.RenderedH );
	BOOL resized = FALSE;

	if ( g_app.InLiveResize ) {
		if ( ( g_app.ClientW > g_app.AllocW ) || ( g_app.ClientH > g_app.AllocH ) ) {
			uint32_t bw = round_bucket(( g_app.ClientW > g_app.AllocW ) ? g_app.ClientW : g_app.AllocW);
			uint32_t bh = round_bucket(( g_app.ClientH > g_app.AllocH ) ? g_app.ClientH : g_app.AllocH);
			resize_swapchain(bw, bh);
			resized = TRUE;
		}
	}
	else if ( ( g_app.ClientW != g_app.AllocW ) || ( g_app.ClientH != g_app.AllocH ) ) {
		resize_swapchain(g_app.ClientW, g_app.ClientH);
		resized = TRUE;
	}

	if ( g_app.RTV == 0 ) {
		return;
	}

	g_app.RenderedW = g_app.ClientW;
	g_app.RenderedH = g_app.ClientH;

	const float clear[4] = { 0.08f, 0.09f, 0.11f, 1.0f };
	const float params[4] = { (float)g_app.ClientW, (float)g_app.ClientH, 0.0f, 0.0f };
	D3D11_VIEWPORT vp = { 0.0f, 0.0f, (float)g_app.ClientW, (float)g_app.ClientH, 0.0f, 1.0f };

	g_app.Context->lpVtbl->UpdateSubresource(g_app.Context, (ID3D11Resource*)g_app.ParamsCB, 0, 0, params, 0, 0);
	g_app.Context->lpVtbl->OMSetRenderTargets(g_app.Context, 1, &g_app.RTV, 0);
	g_app.Context->lpVtbl->RSSetViewports(g_app.Context, 1, &vp);
	g_app.Context->lpVtbl->ClearRenderTargetView(g_app.Context, g_app.RTV, clear);
	g_app.Context->lpVtbl->IASetPrimitiveTopology(g_app.Context, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	g_app.Context->lpVtbl->VSSetConstantBuffers(g_app.Context, 0, 1, &g_app.ParamsCB);
	g_app.Context->lpVtbl->VSSetShader(g_app.Context, g_app.VertexShader, 0, 0);
	g_app.Context->lpVtbl->PSSetShader(g_app.Context, g_app.PixelShader, 0, 0);
	g_app.Context->lpVtbl->Draw(g_app.Context, 3, 0);

	UINT sync_interval = ( g_app.InLiveResize && ( size_changed || resized ) ) ? 0u : 1u;
	g_app.SwapChain->lpVtbl->Present(g_app.SwapChain, sync_interval, 0u);

	if ( size_changed || resized ) {
		DComp_RectF clip = { 0.0f, 0.0f, (float)g_app.ClientW, (float)g_app.ClientH };
		g_app.Visual->lpVtbl->SetClipRect(g_app.Visual, &clip);
		g_app.DComp->lpVtbl->Commit(g_app.DComp);
	}
}

static LRESULT CALLBACK wnd_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
	switch ( msg ) {
		case WM_ERASEBKGND: {
				return( 1 );
			}
		case WM_ENTERSIZEMOVE: {
				g_app.InLiveResize = TRUE;
			}
			break;
		case WM_EXITSIZEMOVE: {
				g_app.InLiveResize = FALSE;
			}
			break;
		case WM_SIZE: {
				g_app.ClientW = (uint32_t)LOWORD(lp);
				g_app.ClientH = (uint32_t)HIWORD(lp);
				return( 0 );
			}
		case WM_PAINT: {
				ValidateRect(hwnd, 0);
				if ( g_app.InLiveResize && !g_app.InRepaint ) {
					g_app.InRepaint = TRUE;
					render_frame();
					g_app.InRepaint = FALSE;
				}
				return( 0 );
			}
		case WM_DESTROY: {
				PostQuitMessage(0);
				return( 0 );
			}
		default: break;
	}
	return( DefWindowProcW(hwnd, msg, wp, lp) );
}

static BOOL init_graphics(HWND hwnd) {
	D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 };
	UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED;
	if ( FAILED(D3D11CreateDevice(0, D3D_DRIVER_TYPE_HARDWARE, 0, flags, levels, 2, D3D11_SDK_VERSION, &g_app.Device, 0, &g_app.Context)) ) {
		return( FALSE );
	}

	IDXGIDevice* dxgi_device = 0;
	IDXGIAdapter* adapter = 0;
	IDXGIFactory2* factory = 0;
	HRESULT hr = g_app.Device->lpVtbl->QueryInterface(g_app.Device, &IID_IDXGIDevice, (void**)&dxgi_device);
	if ( SUCCEEDED(hr) ) {
		hr = dxgi_device->lpVtbl->GetAdapter(dxgi_device, &adapter);
	}
	if ( SUCCEEDED(hr) ) {
		hr = adapter->lpVtbl->GetParent(adapter, &IID_IDXGIFactory2, (void**)&factory);
	}
	if ( SUCCEEDED(hr) ) {
		hr = DCompositionCreateDevice(dxgi_device, &kIIDDCompDevice, (void**)&g_app.DComp);
	}

	DXGI_SWAP_CHAIN_DESC1 sc_desc = {0};
	sc_desc.Width				= ( g_app.ClientW > 0 ) ? g_app.ClientW : 1u;
	sc_desc.Height				= ( g_app.ClientH > 0 ) ? g_app.ClientH : 1u;
	sc_desc.Format				= DXGI_FORMAT_B8G8R8A8_UNORM;
	sc_desc.SampleDesc.Count	= 1;
	sc_desc.BufferUsage			= DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sc_desc.BufferCount			= 3;
	sc_desc.Scaling				= DXGI_SCALING_STRETCH;
	sc_desc.SwapEffect			= DXGI_SWAP_EFFECT_FLIP_DISCARD;
	sc_desc.AlphaMode			= DXGI_ALPHA_MODE_IGNORE;

	if ( SUCCEEDED(hr) ) {
		hr = factory->lpVtbl->CreateSwapChainForComposition(factory, (IUnknown*)g_app.Device, &sc_desc, 0, &g_app.SwapChain);
	}
	if ( SUCCEEDED(hr) ) {
		hr = g_app.DComp->lpVtbl->CreateTargetForHwnd(g_app.DComp, hwnd, TRUE, &g_app.Target);
	}
	if ( SUCCEEDED(hr) ) {
		hr = g_app.DComp->lpVtbl->CreateVisual(g_app.DComp, &g_app.Visual);
	}
	if ( SUCCEEDED(hr) ) {
		DComp_RectF clip = { 0.0f, 0.0f, (float)sc_desc.Width, (float)sc_desc.Height };
		hr = g_app.Visual->lpVtbl->SetContent(g_app.Visual, (IUnknown*)g_app.SwapChain);
		if ( SUCCEEDED(hr) ) {
			hr = g_app.Visual->lpVtbl->SetClipRect(g_app.Visual, &clip);
		}
		if ( SUCCEEDED(hr) ) {
			hr = g_app.Target->lpVtbl->SetRoot(g_app.Target, g_app.Visual);
		}
		if ( SUCCEEDED(hr) ) {
			hr = g_app.DComp->lpVtbl->Commit(g_app.DComp);
		}
	}

	com_release(factory);
	com_release(adapter);
	com_release(dxgi_device);
	if ( FAILED(hr) ) {
		return( FALSE );
	}

	ID3DBlob* vs_blob = 0;
	ID3DBlob* ps_blob = 0;
	hr = D3DCompile(g_shader_src, sizeof(g_shader_src) - 1, 0, 0, 0, "VSMain", "vs_5_0", 0, 0, &vs_blob, 0);
	if ( SUCCEEDED(hr) ) {
		hr = D3DCompile(g_shader_src, sizeof(g_shader_src) - 1, 0, 0, 0, "PSMain", "ps_5_0", 0, 0, &ps_blob, 0);
	}
	if ( SUCCEEDED(hr) ) {
		hr = g_app.Device->lpVtbl->CreateVertexShader(g_app.Device, vs_blob->lpVtbl->GetBufferPointer(vs_blob), vs_blob->lpVtbl->GetBufferSize(vs_blob), 0, &g_app.VertexShader);
	}
	if ( SUCCEEDED(hr) ) {
		hr = g_app.Device->lpVtbl->CreatePixelShader(g_app.Device, ps_blob->lpVtbl->GetBufferPointer(ps_blob), ps_blob->lpVtbl->GetBufferSize(ps_blob), 0, &g_app.PixelShader);
	}
	com_release(vs_blob);
	com_release(ps_blob);
	if ( FAILED(hr) ) {
		return( FALSE );
	}

	D3D11_BUFFER_DESC cb_desc = {0};
	cb_desc.ByteWidth	= 16;
	cb_desc.Usage		= D3D11_USAGE_DEFAULT;
	cb_desc.BindFlags	= D3D11_BIND_CONSTANT_BUFFER;
	if ( FAILED(g_app.Device->lpVtbl->CreateBuffer(g_app.Device, &cb_desc, 0, &g_app.ParamsCB)) ) {
		return( FALSE );
	}

	bind_backbuffer();
	g_app.RenderedW = g_app.ClientW;
	g_app.RenderedH = g_app.ClientH;
	g_app.Ready = TRUE;
	return( g_app.RTV != 0 );
}

int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmd, int show) {
	(void)prev;
	(void)cmd;
	SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);

	WNDCLASSEXW wc = { sizeof(wc) };
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc		= wnd_proc;
	wc.hInstance		= inst;
	wc.hCursor			= LoadCursorW(0, (LPCWSTR)IDC_ARROW);
	wc.lpszClassName	= L"D3D11DCompTriangle";
	RegisterClassExW(&wc);

	RECT rc = { 0, 0, 960, 600 };
	DWORD style = WS_OVERLAPPEDWINDOW;
	DWORD ex_style = WS_EX_APPWINDOW | WS_EX_NOREDIRECTIONBITMAP;
	AdjustWindowRectEx(&rc, style, FALSE, ex_style);

	HWND hwnd = CreateWindowExW(
		ex_style, wc.lpszClassName, L"D3D11 + DirectComposition",
		style, CW_USEDEFAULT, CW_USEDEFAULT,
		rc.right - rc.left, rc.bottom - rc.top,
		0, 0, inst, 0);

	RECT client = {0};
	GetClientRect(hwnd, &client);
	g_app.ClientW = (uint32_t)( client.right - client.left );
	g_app.ClientH = (uint32_t)( client.bottom - client.top );

	if ( !init_graphics(hwnd) ) {
		return( 1 );
	}

	ShowWindow(hwnd, show);

	MSG msg = {0};
	BOOL running = TRUE;
	while ( running ) {
		while ( PeekMessageW(&msg, 0, 0, 0, PM_REMOVE) ) {
			if ( msg.message == WM_QUIT ) {
				running = FALSE;
				break;
			}
			TranslateMessage(&msg);
			DispatchMessageW(&msg);
		}
		if ( running ) {
			render_frame();
		}
	}

	if ( g_app.Target != 0 ) {
		g_app.Target->lpVtbl->SetRoot(g_app.Target, 0);
		if ( g_app.DComp != 0 ) {
			g_app.DComp->lpVtbl->Commit(g_app.DComp);
		}
	}
	com_release(g_app.Visual);
	com_release(g_app.Target);
	com_release(g_app.DComp);
	com_release(g_app.ParamsCB);
	com_release(g_app.PixelShader);
	com_release(g_app.VertexShader);
	com_release(g_app.RTV);
	com_release(g_app.SwapChain);
	com_release(g_app.Context);
	com_release(g_app.Device);
	return( (int)msg.wParam );
}
```

## Links

- [dxgi flip model](https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/dxgi-flip-model)
- [idxgifactory2::createswapchainforcomposition](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgifactory2-createswapchainforcomposition)
- [directcomposition](https://learn.microsoft.com/en-us/windows/win32/directcomp/directcomposition-portal)
