🧱 What is a Fence? (Simple Analogy)
Imagine a fence as a progress counter that tells you how far the GPU has completed its work. It's like numbering tasks in a to-do list:
- CPU assigns tasks to GPU with a number (fence value)
- GPU works through tasks and updates the number as it completes them
- CPU checks the number to see if GPU has reached a certain point
🎯 Why We Need Fences
DirectX 12 runs the CPU and GPU asynchronously (they work independently). Without fences:
- CPU might overwrite resources GPU is still using
- GPU might read data CPU hasn't finished preparing
- 💥 Result: Visual glitches or crashes!
Fences solve this by letting CPU and GPU coordinate their work.
🔑 Key Components
-
Fence Object (ID3D12Fence):
- Tracks GPU progress via a UINT64 value
- Created once per application (usually)
-
Fence Event (HANDLE):
- A simple OS event object
- Lets CPU "sleep" until GPU reaches a certain point
- Created once per application
-
Fence Values:
- Unique numbers tracking specific GPU milestones
- Need one per frame in flight (e.g., 3 for triple buffering)
🛠️ How to Create Them
// 1. Create fence object (just one needed)
ComPtr<ID3D12Fence> fence;
UINT64 initialFenceValue = 0;
device->CreateFence(
initialFenceValue,
D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&fence)
);
// 2. Create fence event (just one needed)
HANDLE fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
🔄 Triple Buffering Setup
For triple buffering (3 frames in flight), we need:
- 1 fence object (shared by all frames)
- 1 fence event (shared by all frames)
- 3 fence values (one per frame)
// Fence values for 3 frames
UINT64 frameFenceValues[3] = {0, 0, 0};
UINT64 currentFenceValue = 1; // Next value to use
🚦 How to Use Fences in Rendering Loop
At Start of Frame:
// Wait until GPU finishes THIS frame's previous work
if(fence->GetCompletedValue() < frameFenceValues[frameIndex])
{
fence->SetEventOnCompletion(frameFenceValues[frameIndex], fenceEvent);
WaitForSingleObject(fenceEvent, INFINITE);
}
// Now safe to reset resources for this frame
commandAllocators[frameIndex]->Reset();
After Submitting Commands:
// Signal fence with new value AFTER commands execute
commandQueue->Signal(fence.Get(), currentFenceValue);
// Store value for this frame
frameFenceValues[frameIndex] = currentFenceValue;
currentFenceValue++; // Prepare next unique value
📊 Why This Setup Works
Frame 0 Frame 1 Frame 2
----------- ----------- -----------
CPU: Start CPU: Start CPU: Start
│ │ │
GPU: Work ──────► GPU: Work ──────► GPU: Work
│ │ │
FenceValue=1 FenceValue=2 FenceValue=3
- Each frame gets its own fence value (1,2,3,...)
- CPU waits for frame-specific value before reusing resources
- GPU updates fence values as it completes work
- Single fence event efficiently wakes CPU when needed
💡 Why Only One Fence Event?
- The event is just a "wake-up call" for the CPU
- It's reusable because:
- CPU waits for specific value (e.g., value 2)
- GPU signals event when value is reached
- CPU wakes up and resets the event automatically
- Same event can wait for next value (e.g., value 3)
🚫 Common Mistake to Avoid
Don't do this:
// WRONG: Creates unnecessary fence objects
for(int i=0; i<3; i++) {
device->CreateFence(...); // ❌ One fence per frame
}
Do this instead:
// RIGHT: One fence + multiple values
device->CreateFence(...); // ✅ Single fence
UINT64 frameValues[3]; // ✅ Three tracking values
📋 Full Triple Buffering Example
// Initialization
ComPtr<ID3D12Fence> fence;
HANDLE fenceEvent = CreateEvent(...);
UINT64 frameFenceValues[3] = {};
UINT64 globalFenceValue = 1;
// Per-frame logic
void RenderFrame(UINT frameIndex) {
// 1. Wait for previous frame's GPU work
if(fence->GetCompletedValue() < frameFenceValues[frameIndex]) {
fence->SetEventOnCompletion(frameFenceValues[frameIndex], fenceEvent);
WaitForSingleObject(fenceEvent, INFINITE);
}
// 2. Reset allocator/command list
commandAllocators[frameIndex]->Reset();
commandList->Reset(...);
// 3. Record commands (draw scene)
// ...
// 4. Execute commands
ID3D12CommandList* lists[] = { commandList.Get() };
commandQueue->ExecuteCommandLists(1, lists);
// 5. Update fence
commandQueue->Signal(fence.Get(), globalFenceValue);
frameFenceValues[frameIndex] = globalFenceValue;
globalFenceValue++;
// 6. Present
swapChain->Present(1, 0);
}
🎯 Summary
- Fence: GPU progress tracker (one for app)
- Fence Event: CPU wake-up call (one for app)
- Fence Values: Per-frame progress markers (3 for triple buffering)
- Purpose: Coordinate CPU/GPU work to prevent resource conflicts
- Key Benefit: Enables smooth multi-frame rendering without glitches
This pattern gives you safe, efficient triple buffering in DirectX 12! 😊