Repository navigation
Expand file tree
/
Copy pathplaced_surface.cpp
More file actions
591 lines (579 loc) · 34.1 KB
/
Copy pathplaced_surface.cpp
File metadata and controls
591 lines (579 loc) · 34.1 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#include "placed_surface.h"
#include "depth16.h"
#include "depth_tiles.h"
#include "gdk_xg.h"
#include "placed_texture.h"
#include "title_device_abi.h"
#include "title_memory.h"
#include "title_texture_upload.h"
#include <algorithm>
#include <bit>
#include <cstdint>
#include <cstdio>
#include <map>
namespace title_d3d {
namespace {
bool depth_layout(D3D12_BARRIER_LAYOUT layout) {
return layout == D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE || layout == D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ;
}
}
HRESULT SurfacePlacement::DepthImage::get(ID3D12Device10& device, ID3D12Resource*& result) {
std::lock_guard guard(lock);
if (!native) {
const D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN, 1, 1};
const HRESULT hr = device.CreateCommittedResource3(&properties, D3D12_HEAP_FLAG_NONE, &desc, initial,
clear ? &*clear : nullptr, nullptr, 0, nullptr, IID_PPV_ARGS(&native));
if (FAILED(hr)) return hr;
}
result = native.Get();
return S_OK;
}
HRESULT depth_uav_barrier(ID3D12GraphicsCommandList7& list, ID3D12Device10& device, SurfacePlacement& placement,
const D3D12_TEXTURE_BARRIER& guest) {
const bool from_depth = depth_layout(guest.LayoutBefore), to_depth = depth_layout(guest.LayoutAfter);
const bool before_undefined = guest.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED;
const bool after_undefined = guest.LayoutAfter == D3D12_BARRIER_LAYOUT_UNDEFINED;
// DIRECT_QUEUE_GENERIC_READ can require simultaneous DSV and SRV reads of the same subresource.
if (guest.LayoutBefore == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ ||
guest.LayoutAfter == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ || (before_undefined && after_undefined))
return DXGI_ERROR_UNSUPPORTED;
const bool split = (UINT(guest.SyncBefore) | UINT(guest.SyncAfter)) & UINT(D3D12_BARRIER_SYNC_SPLIT);
if (split && (from_depth != to_depth || before_undefined || after_undefined)) return DXGI_ERROR_UNSUPPORTED;
if (placement.tile_view && (!from_depth || !to_depth)) {
if (split) return DXGI_ERROR_UNSUPPORTED;
const auto& span = guest.Subresources;
const bool all = !span.NumMipLevels && span.IndexOrFirstMipLevel == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
const UINT first = all ? 0 : span.NumMipLevels ? span.FirstArraySlice : span.IndexOrFirstMipLevel;
const UINT count = all ? placement.tile_view->layers : span.NumMipLevels ? span.NumArraySlices : 1;
if (span.NumMipLevels && (span.IndexOrFirstMipLevel || span.NumMipLevels != 1 || span.FirstPlane || span.NumPlanes != 1))
return E_INVALIDARG;
const auto hr = orient_depth_tiles(list, placement, first, count);
if (FAILED(hr)) return hr;
}
ID3D12Resource* depth{};
if (from_depth || to_depth || before_undefined) {
const HRESULT hr = placement.depth->get(device, depth);
if (FAILED(hr)) return hr;
}
auto emit = [&](D3D12_TEXTURE_BARRIER* barriers, UINT count) {
// Simultaneous-access tiles have an immutable layout. The access and sync scopes still order writes.
if (!placement.tile_heaps.empty()) {
for (UINT i = 0; i < count; ++i) {
if (barriers[i].pResource != guest.pResource) continue;
barriers[i].LayoutBefore = barriers[i].LayoutAfter = D3D12_BARRIER_LAYOUT_UNDEFINED;
barriers[i].Flags = D3D12_TEXTURE_BARRIER_FLAG_NONE;
}
}
D3D12_BARRIER_GROUP group{};
group.Type = D3D12_BARRIER_TYPE_TEXTURE;
group.NumBarriers = count;
group.pTextureBarriers = barriers;
list.Barrier(1, &group);
};
if (before_undefined) {
// The caller discarded the old contents without naming their layout. Park the unused image in COMMON.
D3D12_TEXTURE_BARRIER barriers[]{guest, guest};
barriers[0].pResource = to_depth ? depth : guest.pResource;
barriers[1].pResource = to_depth ? guest.pResource : depth;
barriers[1].LayoutAfter = D3D12_BARRIER_LAYOUT_COMMON;
barriers[1].AccessAfter = D3D12_BARRIER_ACCESS_COMMON;
barriers[1].SyncAfter = D3D12_BARRIER_SYNC_ALL;
barriers[1].Flags = D3D12_TEXTURE_BARRIER_FLAG_NONE;
emit(barriers, 2);
return S_OK;
}
if (from_depth == to_depth || after_undefined) {
auto barrier = guest;
barrier.pResource = from_depth ? depth : guest.pResource;
emit(&barrier, 1);
return S_OK;
}
const auto desc = guest.pResource->GetDesc();
const UINT mips = desc.MipLevels, slices = desc.DepthOrArraySize;
auto range = guest.Subresources;
if (!range.NumMipLevels) {
const UINT index = range.IndexOrFirstMipLevel;
if (index == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) range = {0, mips, 0, slices, 0, 1};
else if (index < mips * slices) range = {index % mips, 1, index / mips, 1, 0, 1};
else return E_INVALIDARG;
}
if (range.FirstPlane || range.NumPlanes != 1 || range.IndexOrFirstMipLevel >= mips ||
range.NumMipLevels > mips - range.IndexOrFirstMipLevel || !range.NumArraySlices ||
range.FirstArraySlice >= slices || range.NumArraySlices > slices - range.FirstArraySlice) return E_INVALIDARG;
auto* source = from_depth ? depth : guest.pResource;
auto* target = to_depth ? depth : guest.pResource;
D3D12_TEXTURE_BARRIER before[]{
{guest.SyncBefore, D3D12_BARRIER_SYNC_COPY, guest.AccessBefore, D3D12_BARRIER_ACCESS_COPY_SOURCE,
guest.LayoutBefore, D3D12_BARRIER_LAYOUT_COPY_SOURCE, source, range},
{D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_ACCESS_COPY_DEST,
D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_LAYOUT_COPY_DEST, target, range}
};
emit(before, 2);
for (UINT slice = range.FirstArraySlice; slice < range.FirstArraySlice + range.NumArraySlices; ++slice) {
for (UINT mip = range.IndexOrFirstMipLevel; mip < range.IndexOrFirstMipLevel + range.NumMipLevels; ++mip) {
const UINT index = slice * mips + mip;
D3D12_TEXTURE_COPY_LOCATION from{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
D3D12_TEXTURE_COPY_LOCATION to{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
from.SubresourceIndex = to.SubresourceIndex = index;
list.CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
}
}
D3D12_TEXTURE_BARRIER after[]{
{D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_ACCESS_COMMON,
D3D12_BARRIER_LAYOUT_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COMMON, source, range},
{D3D12_BARRIER_SYNC_COPY, guest.SyncAfter, D3D12_BARRIER_ACCESS_COPY_DEST, guest.AccessAfter,
D3D12_BARRIER_LAYOUT_COPY_DEST, guest.LayoutAfter, target, range}
};
emit(after, 2);
return S_OK;
}
HRESULT SurfaceHeaps::acquire(ID3D12Device& device, UINT64 address, UINT64 end, D3D12_RESOURCE_ALLOCATION_INFO native, UINT64 granularity, bool dcc,
std::shared_ptr<SurfacePlacement>& result, bool& alias) {
std::erase_if(placements_, [](const auto& weak) { return weak.expired(); });
const UINT64 bytes = end - address;
const bool rebase = dcc || bytes < native.SizeInBytes || address % native.Alignment;
std::shared_ptr<SurfaceHeap> overlap, available;
for (const auto& weak : placements_) {
const auto live = weak.lock();
if (!live) continue;
if (!live->tile_heaps.empty()) {
if (live->begin < end && address < live->end) {
if (GetEnvironmentVariableW(L"RDNA4RAGE_TRACE_FRAMES", nullptr, 0)) {
char line[192]{};
std::snprintf(line, sizeof(line), "rdna4rage: ordinary surface 0x%llx+%llu overlaps reserved tiles 0x%llx+%llu\n",
address, bytes, live->begin, live->end - live->begin);
OutputDebugStringA(line);
}
return DXGI_ERROR_UNSUPPORTED;
}
continue;
}
const auto& heap = live->heap;
const bool fits = native.Alignment <= heap->alignment && (heap->exact_guest_bytes
? address == heap->base && bytes == heap->exact_guest_bytes && native.SizeInBytes <= heap->size
: !rebase && address >= heap->base && end - heap->base <= heap->size && (address - heap->base) % native.Alignment == 0);
// Only the guest's live byte ranges alias. A Windows heap may have several MiB of padding.
if (live->begin < end && address < live->end) {
if (live->depth || (live->transfer && live->transfer->mapped) || !fits || (overlap && overlap != heap)) {
if (GetEnvironmentVariableW(L"RDNA4RAGE_TRACE_FRAMES", nullptr, 0)) {
char line[320]{};
std::snprintf(line, sizeof(line), "rdna4rage: placement overlap guest=0x%llx+%llu previous=0x%llx+%llu "
"Windows heap=0x%llx+%llu requested=%llu fits=%d previousDepthUav=%d\n",
address, bytes, live->begin, live->end - live->begin, heap->base, heap->size, native.SizeInBytes,
int(fits), int(bool(live->depth)));
OutputDebugStringA(line);
}
return DXGI_ERROR_UNSUPPORTED;
}
overlap = heap;
}
if (fits) available = heap;
}
auto heap = overlap ? overlap : available;
if (!heap) {
const UINT64 base = rebase ? address : address & ~(granularity - 1);
// The Scarlett DCC plane is part of the guest interval. Windows owns its own compression metadata.
const UINT64 extent = dcc ? native.SizeInBytes : std::max(end - base, native.SizeInBytes);
if (extent > UINT64_MAX - (granularity - 1)) return E_INVALIDARG;
heap = std::make_shared<SurfaceHeap>();
heap->base = base;
heap->alignment = granularity;
heap->size = (extent + granularity - 1) & ~(granularity - 1);
// Native padding belongs only to this image. An adjacent Scarlett tile can start inside those bytes.
heap->exact_guest_bytes = rebase ? bytes : 0;
D3D12_HEAP_DESC desc{};
desc.SizeInBytes = heap->size;
desc.Alignment = granularity;
desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
desc.Properties.CreationNodeMask = desc.Properties.VisibleNodeMask = 1;
// The RX 9070 XT supports tier 2 heaps. Render-target and UAV-only aliases can share them.
desc.Flags = D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES;
const HRESULT hr = device.CreateHeap(&desc, IID_PPV_ARGS(&heap->native));
if (FAILED(hr)) return hr;
}
auto placement = std::make_shared<SurfacePlacement>(SurfacePlacement{address, end, std::move(heap)});
placements_.emplace_back(placement);
result = std::move(placement);
alias = bool(overlap);
return S_OK;
}
SurfaceHeaps::~SurfaceHeaps() { finish_upload(); }
HRESULT SurfaceHeaps::finish_upload() {
if (!upload_texture_) return S_OK;
// Re-signal the same fence value on retry. No subsequent upload can reuse the allocator before this one finishes.
HRESULT hr = upload_queue_->Signal(upload_fence_.Get(), uploaded_);
if (SUCCEEDED(hr)) hr = upload_fence_->SetEventOnCompletion(uploaded_, nullptr);
if (SUCCEEDED(hr) || upload_fence_->GetCompletedValue() == UINT64_MAX) {
upload_staging_.Reset();
upload_texture_.Reset();
upload_placement_.reset();
}
return hr;
}
HRESULT SurfaceHeaps::open_upload_queue(ID3D12Device10& device) {
HRESULT hr = S_OK;
if (!upload_queue_) {
const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
hr = device.CreateCommandQueue(&desc, IID_PPV_ARGS(&upload_queue_));
}
if (SUCCEEDED(hr) && !upload_fence_) hr = device.CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&upload_fence_));
return hr;
}
HRESULT SurfaceHeaps::map_depth_tiles(ID3D12Device10& device, UINT64 address, UINT64 bytes, const D3D12_RESOURCE_DESC& source,
std::shared_ptr<SurfacePlacement>& placement, Microsoft::WRL::ComPtr<ID3D12Resource>& image) {
constexpr UINT64 tile = D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES;
if (address % tile || bytes % tile || source.MipLevels != 1) return S_FALSE;
auto reserved = source;
reserved.Alignment = 0;
reserved.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
reserved.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS |
(source.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
Microsoft::WRL::ComPtr<ID3D12Resource> texture;
HRESULT hr = device.CreateReservedResource2(&reserved, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 0, nullptr, IID_PPV_ARGS(&texture));
if (hr == E_INVALIDARG || hr == DXGI_ERROR_UNSUPPORTED) return S_FALSE;
if (FAILED(hr)) return hr;
UINT total{}, layers = source.DepthOrArraySize;
D3D12_TILE_SHAPE shape{};
D3D12_PACKED_MIP_INFO packed{};
std::vector<D3D12_SUBRESOURCE_TILING> slices(layers);
device.GetResourceTiling(texture.Get(), &total, &packed, &shape, &layers, 0, slices.data());
if (UINT64(total) * tile != bytes || packed.NumPackedMips || layers != source.DepthOrArraySize || !layers) return S_FALSE;
if (shape.WidthInTexels != 256 || shape.HeightInTexels != 128) return S_FALSE;
Microsoft::WRL::ComPtr<XGTextureAddressComputer> xg;
hr = gdk_xg::create_title_layout(std::bit_cast<XG_RESOURCE_DESC>(source), &xg);
if (FAILED(hr)) return hr;
UINT guest_tiles{}, guest_slices = layers;
XG_PACKED_MIP_DESC guest_packed{};
XG_TILE_SHAPE guest_shape{};
std::vector<XG_SUBRESOURCE_TILING> guest(layers);
hr = xg->GetResourceTiling(&guest_tiles, &guest_packed, &guest_shape, &guest_slices, 0, guest.data());
if (FAILED(hr) || guest_tiles != total || guest_slices != layers || guest_packed.NumPackedMips ||
guest_shape.WidthInTexels != shape.WidthInTexels || guest_shape.HeightInTexels != shape.HeightInTexels ||
guest_shape.DepthInTexels != 1 || shape.DepthInTexels != 1) return S_FALSE;
const UINT row = slices[0].WidthInTiles, per_slice = total / layers;
if (!row || !per_slice || UINT64(per_slice) * layers != total) return S_FALSE;
for (UINT i = 0; i < layers; ++i) {
if (slices[i].StartTileIndexInOverallResource != i * per_slice || guest[i].StartTileIndexInOverallResource != i * per_slice ||
slices[i].DepthInTiles != 1 || guest[i].DepthInTiles != 1 || slices[i].WidthInTiles != row || guest[i].WidthInTiles != row ||
UINT64(row) * slices[i].HeightInTiles != per_slice || guest[i].HeightInTiles != slices[i].HeightInTiles) return S_FALSE;
}
const UINT64 end = address + bytes;
std::map<UINT64, std::shared_ptr<SurfaceHeap>> existing;
std::erase_if(placements_, [](const auto& weak) { return weak.expired(); });
for (const auto& weak : placements_) {
const auto live = weak.lock();
if (!live) continue;
if (live->tile_heaps.empty() && live->begin < end && address < live->end) {
if (GetEnvironmentVariableW(L"RDNA4RAGE_TRACE_FRAMES", nullptr, 0)) {
char line[192]{};
std::snprintf(line, sizeof(line), "rdna4rage: reserved tiles 0x%llx+%llu overlap ordinary surface 0x%llx+%llu\n",
address, bytes, live->begin, live->end - live->begin);
OutputDebugStringA(line);
}
return DXGI_ERROR_UNSUPPORTED;
}
for (const auto& run : live->tile_heaps)
if (run->base < end && address < run->base + run->size) existing.emplace(run->base, run);
}
auto acquired = std::make_shared<SurfacePlacement>();
acquired->begin = address;
acquired->end = end;
hr = open_depth_tile_view(device, *texture.Get(), *xg.Get(), row, per_slice, layers, tile_pipeline_, acquired->tile_view);
if (hr != S_OK) return hr;
std::vector<std::shared_ptr<SurfaceHeap>> fresh;
for (UINT64 cursor = address; cursor < end;) {
const auto next = existing.upper_bound(cursor);
std::shared_ptr<SurfaceHeap> run;
if (next != existing.begin()) {
const auto& preceding = std::prev(next)->second;
if (cursor < preceding->base + preceding->size) run = preceding;
}
if (!run) {
const UINT64 gap_end = next == existing.end() ? end : std::min(end, next->first);
run = std::make_shared<SurfaceHeap>();
run->base = cursor;
run->size = gap_end - cursor;
run->alignment = tile;
D3D12_HEAP_DESC heap{};
heap.SizeInBytes = run->size;
heap.Alignment = tile;
heap.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
heap.Properties.CreationNodeMask = heap.Properties.VisibleNodeMask = 1;
heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
hr = device.CreateHeap(&heap, IID_PPV_ARGS(&run->native));
if (SUCCEEDED(hr)) hr = create_depth_masks(device, D3D12_HEAP_TYPE_DEFAULT, UINT(run->size / tile), run->tile_masks);
if (FAILED(hr)) return hr;
fresh.push_back(run);
}
cursor = std::min(end, run->base + run->size);
acquired->tile_heaps.push_back(std::move(run));
}
hr = open_upload_queue(device);
if (FAILED(hr)) return hr;
placements_.emplace_back(acquired);
if (!fresh.empty()) {
hr = open_upload_list(device);
if (FAILED(hr)) return hr;
for (const auto& run : fresh) {
upload_list_->CopyBufferRegion(run->tile_masks.Get(), 0, acquired->tile_view->desired_masks.Get(),
(run->base - address) / tile * sizeof(UINT), run->size / tile * sizeof(UINT));
D3D12_RESOURCE_BARRIER ready{};
ready.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
ready.Transition = {run->tile_masks.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS};
upload_list_->ResourceBarrier(1, &ready);
}
hr = upload_list_->Close();
if (FAILED(hr)) { upload_list_.Reset(); return hr; }
ID3D12CommandList* batch[]{upload_list_.Get()};
upload_queue_->ExecuteCommandLists(1, batch);
}
upload_placement_ = acquired;
upload_texture_ = texture;
++uploaded_;
for (const auto& run : acquired->tile_heaps) {
UINT64 cursor = std::max(address, run->base);
const UINT64 limit = std::min(end, run->base + run->size);
while (cursor < limit) {
const UINT index = UINT((cursor - address) / tile), local = index % per_slice;
const UINT count = std::min(UINT((limit - cursor) / tile), per_slice - local);
const D3D12_TILED_RESOURCE_COORDINATE start{local % row, local / row, 0, index / per_slice};
const D3D12_TILE_REGION_SIZE region{count, FALSE};
const UINT offset = UINT((cursor - run->base) / tile);
upload_queue_->UpdateTileMappings(texture.Get(), 1, &start, ®ion, run->native.Get(), 1, nullptr, &offset, &count,
D3D12_TILE_MAPPING_FLAG_NONE);
if (acquired->tile_view->padded)
upload_queue_->UpdateTileMappings(acquired->tile_view->padded.Get(), 1, &start, ®ion, run->native.Get(), 1,
nullptr, &offset, &count, D3D12_TILE_MAPPING_FLAG_NONE);
cursor += UINT64(count) * tile;
}
}
hr = finish_upload();
if (SUCCEEDED(hr)) hr = device.GetDeviceRemovedReason();
if (SUCCEEDED(hr)) { placement = std::move(acquired); image = std::move(texture); }
return hr;
}
HRESULT SurfaceHeaps::open_upload_list(ID3D12Device10& device) {
HRESULT hr = open_upload_queue(device);
if (SUCCEEDED(hr) && !upload_allocator_)
hr = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&upload_allocator_));
if (SUCCEEDED(hr) && !upload_list_)
hr = device.CreateCommandList1(0, D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_FLAG_NONE, IID_PPV_ARGS(&upload_list_));
if (SUCCEEDED(hr)) hr = upload_allocator_->Reset();
if (SUCCEEDED(hr)) hr = upload_list_->Reset(upload_allocator_.Get(), nullptr);
return hr;
}
HRESULT SurfaceHeaps::import_pixels(ID3D12Device10& device, ID3D12Resource& image, const std::shared_ptr<SurfacePlacement>& placement,
const D3D12_RESOURCE_DESC& source, D3D12_BARRIER_LAYOUT initial) {
HRESULT hr = open_upload_list(device);
if (FAILED(hr)) return hr;
const auto guest = std::bit_cast<XG_RESOURCE_DESC>(source);
Microsoft::WRL::ComPtr<ID3D12Resource> staging;
auto* sampled = placement->transfer.get();
hr = RdnaRecordChangedTextureUpload(upload_list_.Get(), &image, &guest, placement->begin, nullptr,
sampled ? &sampled->uploaded.emplace() : nullptr, &staging);
if (SUCCEEDED(hr) && initial != D3D12_BARRIER_LAYOUT_COPY_DEST) {
D3D12_TEXTURE_BARRIER barrier{};
barrier.SyncBefore = D3D12_BARRIER_SYNC_COPY;
barrier.AccessBefore = D3D12_BARRIER_ACCESS_COPY_DEST;
barrier.SyncAfter = D3D12_BARRIER_SYNC_NONE;
barrier.AccessAfter = D3D12_BARRIER_ACCESS_NO_ACCESS;
barrier.LayoutBefore = D3D12_BARRIER_LAYOUT_COPY_DEST;
barrier.LayoutAfter = initial;
barrier.pResource = ℑ
barrier.Subresources.IndexOrFirstMipLevel = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
D3D12_BARRIER_GROUP group{};
group.Type = D3D12_BARRIER_TYPE_TEXTURE;
group.NumBarriers = 1;
group.pTextureBarriers = &barrier;
upload_list_->Barrier(1, &group);
}
const HRESULT closed = upload_list_->Close();
if (FAILED(closed)) { upload_list_.Reset(); return closed; }
if (FAILED(hr)) return hr;
upload_placement_ = placement;
upload_texture_ = ℑ
upload_staging_ = std::move(staging);
++uploaded_;
ID3D12CommandList* batch[]{upload_list_.Get()};
upload_queue_->ExecuteCommandLists(1, batch);
hr = finish_upload();
return FAILED(hr) ? hr : device.GetDeviceRemovedReason();
}
HRESULT SurfaceHeaps::place(ID3D12Device10& device, UINT64 address, const D3D12_RESOURCE_DESC& source,
D3D12_RESOURCE_ALLOCATION_INFO guest, D3D12_BARRIER_LAYOUT initial, const D3D12_CLEAR_VALUE* clear, std::shared_ptr<SurfacePlacement>& placement,
Microsoft::WRL::ComPtr<ID3D12Resource>& result) {
const auto usage = UINT(source.Flags) & ~console_texture_layout_flags;
const bool dcc = (UINT(source.Flags) & allow_dcc) != 0;
constexpr UINT targets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
constexpr UINT desktop = targets | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE |
D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
constexpr UINT mixed_flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
const bool mixed = (usage & mixed_flags) == mixed_flags;
const bool depth_stencil = mixed_depth_stencil(source);
if (depth_stencil && unordered_layout(initial)) return DXGI_ERROR_UNSUPPORTED;
const auto depth_clear_format = source.Format == scarlett_d16s8 ? scarlett_d16s8 :
depth_stencil ? DXGI_FORMAT_D32_FLOAT_S8X24_UINT : DXGI_FORMAT_D16_UNORM;
if (source.Format == scarlett_d16s8 && (source.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || dcc)) return DXGI_ERROR_UNSUPPORTED;
if (mixed && ((!depth_stencil && source.Format != DXGI_FORMAT_R16_TYPELESS) || source.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D ||
source.SampleDesc.Count != 1 || source.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || dcc ||
(usage & ~(mixed_flags | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) ||
(clear && clear->Format != depth_clear_format) ||
initial == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ))
return DXGI_ERROR_UNSUPPORTED;
const bool tiled = UINT(source.Layout) >= UINT(XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR) &&
UINT(source.Layout) <= UINT(XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R_X);
const bool linear = UINT(source.Layout) == UINT(XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR);
bool cpu_sampled = !usage && !dcc && !clear && source.DepthOrArraySize == 1 && source.SampleDesc.Count == 1 &&
(source.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN || linear) &&
(initial == D3D12_BARRIER_LAYOUT_SHADER_RESOURCE || (linear && initial == D3D12_BARRIER_LAYOUT_COMMON));
if (cpu_sampled && source.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN) {
D3D12_FEATURE_DATA_FORMAT_INFO format{source.Format, 0};
cpu_sampled = SUCCEEDED(device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &format, sizeof(format))) && format.PlaneCount == 1;
}
const bool line_or_volume = (source.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D || source.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) &&
source.SampleDesc.Count == 1 && !(usage & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
if ((source.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && !line_or_volume) || !source.SampleDesc.Count || source.SampleDesc.Quality ||
(source.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN && !tiled) || (usage & targets) == targets ||
(!(usage & (targets | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) && !cpu_sampled) || (usage & ~desktop))
return DXGI_ERROR_UNSUPPORTED;
if (!guest.Alignment || guest.SizeInBytes == UINT64_MAX || !guest.SizeInBytes || address % guest.Alignment ||
guest.SizeInBytes > UINT64_MAX - address) return E_INVALIDARG;
XMEM_BASIC_INFORMATION region{};
std::shared_ptr<PlacedTexture> transfer;
if (!rage::memory::private_graphics_range(address, guest.SizeInBytes, region)) {
const auto mapped = RdnaGpuMappedSpan(address);
const bool shared_pages = region.Type == MEM_MAPPED && (region.State & MEM_COMMIT) &&
(region.XMemFlags & XMEM_GRAPHICS) == XMEM_GRAPHICS;
const bool mapped_color = !(usage & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && source.SampleDesc.Count == 1 &&
((usage & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || ((usage & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !clear));
const bool mapped_depth = (usage & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && (!mixed || depth_stencil) &&
source.SampleDesc.Count == 1 && source.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN;
const bool supported_compression = !dcc || (mapped_color && (usage & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET));
if ((shared_pages || mapped >= guest.SizeInBytes) && (mapped_color || mapped_depth) && supported_compression) {
transfer = std::make_shared<PlacedTexture>();
const HRESULT opened = transfer->mapped.emplace().open(device, address, source, guest.SizeInBytes);
if (FAILED(opened)) return opened;
} else if (!cpu_sampled || (!shared_pages && mapped < guest.SizeInBytes)) {
if (GetEnvironmentVariableW(L"RDNA4RAGE_TRACE_FRAMES", nullptr, 0)) {
char line[384]{};
std::snprintf(line, sizeof(line), "rdna4rage: texture backing unavailable address=0x%llx bytes=%llu "
"region=%p+%zu allocation=%p state=0x%lx type=0x%lx protect=0x%lx xmem=0x%llx GPU-mapped=%llu\n",
address, guest.SizeInBytes, region.BaseAddress, region.RegionSize, region.AllocationBase,
region.State, region.Type, region.Protect, region.XMemFlags, mapped);
OutputDebugStringA(line);
}
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
}
const bool msaa = source.SampleDesc.Count > 1;
D3D12_RESOURCE_DESC1 native{source.Dimension, msaa ? UINT64(D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) : 0, source.Width,
source.Height, source.DepthOrArraySize, source.MipLevels, color_storage_format(source), source.SampleDesc, D3D12_TEXTURE_LAYOUT_UNKNOWN,
static_cast<D3D12_RESOURCE_FLAGS>(usage), {}};
if (mixed) native.Flags &= ~(depth_stencil ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
D3D12_CLEAR_VALUE converted{};
HRESULT hr = prepare_depth16(native, clear, converted);
if (FAILED(hr)) return hr;
if (transfer && !transfer->mapped->tracks_layout()) native.Flags |= D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
auto size = device.GetResourceAllocationInfo2(1, 1, &native, nullptr);
if (native.Alignment && (size.SizeInBytes == UINT64_MAX || size.Alignment != native.Alignment)) {
native.Alignment = 0;
size = device.GetResourceAllocationInfo2(1, 1, &native, nullptr);
}
// GTA writes packed HDR bits through an integer UAV and reads them back through a shared-exponent SRV.
constexpr DXGI_FORMAT formats[]{DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R9G9B9E5_SHAREDEXP};
const DXGI_FORMAT* castable = nullptr;
UINT cast_count{};
if (native.Format == formats[0] && (usage & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) &&
!(usage & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !msaa) {
D3D12_FEATURE_DATA_D3D12_OPTIONS12 options{};
Microsoft::WRL::ComPtr<ID3D12Device12> api;
if (SUCCEEDED(device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options, sizeof(options))) &&
options.RelaxedFormatCastingSupported && SUCCEEDED(device.QueryInterface(IID_PPV_ARGS(&api)))) {
castable = formats;
cast_count = UINT(std::size(formats));
size = api->GetResourceAllocationInfo3(1, 1, &native, &cast_count, &castable, nullptr);
}
}
if (!size.Alignment || !size.SizeInBytes || size.SizeInBytes == UINT64_MAX) return DXGI_ERROR_UNSUPPORTED;
// All live overlapping views must land at the same relative offsets in a single local heap.
std::shared_ptr<SurfacePlacement> acquired;
const UINT64 granularity = msaa ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
std::lock_guard lock(lock_);
hr = finish_upload();
if (FAILED(hr)) return hr;
bool alias{};
Microsoft::WRL::ComPtr<ID3D12Resource> image;
if (transfer) {
for (const auto& weak : placements_) {
const auto live = weak.lock();
if (!live || live->begin != address || live->end - address != guest.SizeInBytes ||
!live->transfer || !live->transfer->mapped) continue;
const auto& previous = live->transfer->source;
const bool color_alias = native.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS &&
live->transfer->native->GetDesc().Format == native.Format &&
(previous.Format == XG_FORMAT_R8G8B8A8_UNORM || previous.Format == XG_FORMAT_R8G8B8A8_UNORM_SRGB) &&
(source.Format == DXGI_FORMAT_R8G8B8A8_UNORM || source.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
if (previous.Dimension == XG_RESOURCE_DIMENSION(source.Dimension) && previous.Width == source.Width &&
previous.Height == source.Height && previous.DepthOrArraySize == source.DepthOrArraySize &&
previous.MipLevels == source.MipLevels && (previous.Format == XG_FORMAT(source.Format) || color_alias) &&
UINT(previous.Layout) == UINT(source.Layout) && UINT(previous.MiscFlags) == UINT(source.Flags)) {
placement = live;
result = live->transfer->native;
return S_OK;
}
}
if (source.Format == scarlett_d16s8) {
hr = Depth16Pipeline::open(device, depth16_pipeline_);
if (FAILED(hr)) return hr;
transfer->mapped->depth16_pipeline = depth16_pipeline_;
}
}
if (mixed && !depth_stencil) {
hr = map_depth_tiles(device, address, guest.SizeInBytes, source, acquired, image);
if (FAILED(hr)) return hr;
}
if (!image) {
hr = acquire(device, address, address + guest.SizeInBytes, size, granularity, dcc, acquired, alias);
if (FAILED(hr)) return hr;
// An existing overlapping GPU image can already contain newer pixels than the CPU span.
if ((cpu_sampled || transfer || mixed) && alias) return DXGI_ERROR_UNSUPPORTED;
}
const bool load = (tiled || dcc) && !transfer && !msaa && !alias && initial != D3D12_BARRIER_LAYOUT_UNDEFINED;
D3D12_BARRIER_LAYOUT image_layout = load ? D3D12_BARRIER_LAYOUT_COPY_DEST : initial;
if (transfer && !transfer->mapped->tracks_layout()) image_layout = D3D12_BARRIER_LAYOUT_COMMON;
if (mixed && !depth_stencil) {
acquired->depth = std::make_unique<SurfacePlacement::DepthImage>();
auto& depth = *acquired->depth;
depth.desc = native;
depth.desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(usage & ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
if (clear) depth.clear = *clear;
if (depth_layout(initial)) {
image_layout = D3D12_BARRIER_LAYOUT_COMMON;
depth.initial = initial;
}
}
if (!image) {
const auto& heap = acquired->heap;
hr = device.CreatePlacedResource2(heap->native.Get(), address - heap->base, &native, image_layout,
mixed && !depth_stencil ? nullptr : clear, cast_count, castable, IID_PPV_ARGS(&image));
}
if (SUCCEEDED(hr) && (cpu_sampled || transfer)) {
if (!transfer) transfer = std::make_shared<PlacedTexture>();
transfer->source = std::bit_cast<XG_RESOURCE_DESC>(source);
transfer->native = image;
transfer->address = address;
const UINT count = transfer->mapped ? transfer->mapped->subresource_count() : image->GetDesc().MipLevels;
transfer->layouts.assign(count, initial);
acquired->transfer = std::move(transfer);
}
if (SUCCEEDED(hr) && load) hr = import_pixels(device, *image.Get(), acquired, source, initial);
if (SUCCEEDED(hr)) {
if (cast_count) acquired->alternate_srv = formats[1];
placement = std::move(acquired);
result = std::move(image);
}
return hr;
}
}