载入中...
搜索中...
未找到
VirtualTextureStreaming.cpp
浏览该文件的文档.
2
3#include <utility>
4
5#include "graphics/Graphics.h"
6#include "graphics/Material.h"
7#include "graphics/Texture.h"
9
10#include <algorithm>
11#include <cmath>
12#include <cstring>
13#include <unordered_set>
14
15namespace eve::graphics {
16namespace {
17
18eve::Diagnostic invalid(std::string message) {
20}
21
22eve::Diagnostic failed(std::string message) {
24}
25
26float wrap01(float value) {
27 value -= std::floor(value);
28 return value < 0.f ? value + 1.f : value;
29}
30
31using Pixel = image::ImageData::Colorf;
32
33Pixel sampleRepeat(const image::ImageData& image, float u, float v) {
34 const int width = image.getWidth();
35 const int height = image.getHeight();
36 const float x = wrap01(u) * float(width) - 0.5f;
37 const float y = wrap01(v) * float(height) - 0.5f;
38 const int x0 = int(std::floor(x));
39 const int y0 = int(std::floor(y));
40 const float tx = x - float(x0);
41 const float ty = y - float(y0);
42 auto pixel = [&](int px, int py) {
43 px = (px % width + width) % width;
44 py = (py % height + height) % height;
45 return image.getPixel(px, py);
46 };
47 const Pixel a = pixel(x0, y0);
48 const Pixel b = pixel(x0 + 1, y0);
49 const Pixel c = pixel(x0, y0 + 1);
50 const Pixel d = pixel(x0 + 1, y0 + 1);
51 auto mix = [tx, ty](float av, float bv, float cv, float dv) {
52 return (av + (bv - av) * tx) + ((cv + (dv - cv) * tx) - (av + (bv - av) * tx)) * ty;
53 };
54 return Pixel{mix(a.r, b.r, c.r, d.r), mix(a.g, b.g, c.g, d.g), mix(a.b, b.b, c.b, d.b), mix(a.a, b.a, c.a, d.a)};
55}
56
57} // namespace
58
59std::size_t VirtualTextureStreaming::PageKeyHash::operator()(const PageKey& key) const noexcept {
60 std::size_t seed = std::hash<int>{}(key.x);
61 seed ^= std::hash<int>{}(key.y) + 0x9e3779b9u + (seed << 6u) + (seed >> 2u);
62 return seed;
63}
64
66 const VirtualTextureStreamingConfig& config) {
67 if (config.maxDecodesPerUpdate == 0)
69 invalid("virtual texture streaming maxDecodesPerUpdate must be positive"));
70 if (config.feedbackCapacity == 0)
72 invalid("virtual texture streaming feedbackCapacity must be positive"));
76 std::unique_ptr<VirtualTextureStreaming>(new VirtualTextureStreaming(config, std::move(producer).value())));
77}
78
79VirtualTextureStreaming::VirtualTextureStreaming(VirtualTextureStreamingConfig config,
80 std::unique_ptr<VirtualTextureBlend> producer)
81 : config_(std::move(config)), producer_(std::move(producer)) {}
82
84 auto result = producer_->addLayer(layer);
85 if (!result.ok()) return result;
86 if (initialized_) {
87 // Layer edits invalidate every produced page; force re-decode of resident mappings.
88 for (auto& slot : working_.slots) {
89 if (slot.occupied) slot.dirty = true;
90 }
91 for (auto& slot : published_.slots) {
92 if (slot.occupied) slot.dirty = true;
93 }
94 ++lifetime_.pagesInvalidated;
95 }
96 return result;
97}
98
100 if (producer_->pageCountX() <= 0 || producer_->pageCountY() <= 0)
101 return eve::Result<void>::failure(invalid("virtual texture producer has no pages"));
102 auto bootstrap = producer_->buildResidentSet({});
103 if (!bootstrap.ok()) return eve::Result<void>::failure(bootstrap.status());
104
105 const auto& set = bootstrap.value();
106 pageExtent_ = set.pageExtent;
107 borderFraction_ = set.borderFraction;
108 atlasSlotsX_ = set.atlasSlotsX;
109 atlasSlotsY_ = set.atlasSlotsY;
110 const int slotCount = atlasSlotsX_ * atlasSlotsY_;
111
112 auto makeState = [&](PhysicalState& state) {
113 state.albedo = std::make_unique<image::ImageData>(*set.albedoAtlas);
114 state.normal = std::make_unique<image::ImageData>(*set.normalAtlas);
115 state.pageTable = std::make_unique<image::ImageData>(*set.pageTable);
116 state.slots.assign(std::size_t(slotCount), SlotRecord{});
117 state.lru.clear();
118 state.pageToSlot.clear();
119 // Slot 0 is reserved for the whole-surface substitute and is never LRU-managed.
120 state.slots[0].occupied = true;
121 state.slots[0].pageX = -1;
122 state.slots[0].pageY = -1;
123 };
124 makeState(published_);
125 makeState(working_);
126 pending_.reset();
127 gpuAlbedo_ = gpuNormal_ = gpuPageTable_ = nullptr;
128 generation_ = 0;
129 initialized_ = true;
130 lifetime_ = {};
131 lifetime_.generation = 0;
132 lifetime_.residentPages = 0;
134}
135
136std::uint32_t VirtualTextureStreaming::packFeedback(int pageX, int pageY, int mipLevel) noexcept {
137 return (std::uint32_t(pageX) & 0xFFFu) | ((std::uint32_t(pageY) & 0xFFFu) << 12u) |
138 ((std::uint32_t(mipLevel) & 0xFFu) << 24u);
139}
140
143 sample.pageX = int(packed & 0xFFFu);
144 sample.pageY = int((packed >> 12u) & 0xFFFu);
145 sample.mipLevel = int((packed >> 24u) & 0xFFu);
146 if (sample.pageX < 0 || sample.pageY < 0 || sample.mipLevel < 0)
148 invalid("packed virtual texture feedback fields are out of range"));
150}
151
152eve::Result<void> VirtualTextureStreaming::ensureInitialized() const {
153 if (!initialized_) return eve::Result<void>::failure(invalid("virtual texture streaming is not initialized"));
155}
156
157eve::Result<void> VirtualTextureStreaming::validatePage(int pageX, int pageY, int mipLevel) const {
158 if (mipLevel != 0)
159 return eve::Result<void>::failure(invalid("virtual texture streaming currently residencies mip zero only"));
160 if (pageX < 0 || pageY < 0 || pageX >= pageCountX() || pageY >= pageCountY())
161 return eve::Result<void>::failure(invalid("virtual texture page coordinate is outside mip zero"));
163}
164
166 auto ready = ensureInitialized();
167 if (!ready.ok()) return ready;
168 auto valid = validatePage(pageX, pageY, mipLevel);
169 if (!valid.ok()) return valid;
170 if (feedback_.size() >= config_.feedbackCapacity) feedback_.erase(feedback_.begin());
171 feedback_.push_back(VirtualTextureFeedbackSample{pageX, pageY, mipLevel});
172 ++lifetime_.feedbackSamples;
174}
175
177 auto ready = ensureInitialized();
178 if (!ready.ok()) return ready;
179 if (!std::isfinite(u) || !std::isfinite(v))
180 return eve::Result<void>::failure(invalid("virtual texture feedback UV must be finite"));
181 const int pageX = int(std::floor(wrap01(u) * float(pageCountX())));
182 const int pageY = int(std::floor(wrap01(v) * float(pageCountY())));
183 return recordFeedback(std::min(pageX, pageCountX() - 1), std::min(pageY, pageCountY() - 1), mipLevel);
184}
185
187 auto ready = ensureInitialized();
188 if (!ready.ok()) return ready;
189 for (std::uint32_t word : packed) {
190 auto decoded = unpackFeedback(word);
191 if (!decoded.ok()) continue;
192 auto sample = decoded.value();
193 // Higher mips collapse onto their mip-zero parents for the current physical pool.
194 if (sample.mipLevel != 0) {
195 sample.pageX >>= sample.mipLevel;
196 sample.pageY >>= sample.mipLevel;
197 sample.mipLevel = 0;
198 }
199 auto recorded = recordFeedback(sample.pageX, sample.pageY, sample.mipLevel);
200 if (!recorded.ok()) return recorded;
201 }
203}
204
206 if (gridW <= 0 || gridH <= 0)
207 return eve::Result<void>::failure(invalid("feedback grid dimensions must be positive"));
208 for (int y = 0; y < gridH; ++y) {
209 for (int x = 0; x < gridW; ++x) {
210 const float u = (float(x) + 0.5f) / float(gridW);
211 const float v = (float(y) + 0.5f) / float(gridH);
212 auto recorded = recordFeedbackUv(u, v, mipLevel);
213 if (!recorded.ok()) return recorded;
214 }
215 }
217}
218
220 auto ready = ensureInitialized();
221 if (!ready.ok()) return ready;
222 auto valid = validatePage(pageX, pageY, mipLevel);
223 if (!valid.ok()) return valid;
224 auto found = working_.pageToSlot.find(PageKey{pageX, pageY});
225 if (found == working_.pageToSlot.end()) return eve::Result<void>::success();
226 working_.slots[std::size_t(found->second)].dirty = true;
227 ++lifetime_.pagesInvalidated;
229}
230
231eve::Result<void> VirtualTextureStreaming::invalidateRect(float u0, float v0, float u1, float v1, int mipLevel) {
232 auto ready = ensureInitialized();
233 if (!ready.ok()) return ready;
234 if (!std::isfinite(u0) || !std::isfinite(v0) || !std::isfinite(u1) || !std::isfinite(v1))
235 return eve::Result<void>::failure(invalid("invalidate rect coordinates must be finite"));
236 if (u1 < u0) std::swap(u0, u1);
237 if (v1 < v0) std::swap(v0, v1);
238 const int minX = std::clamp(int(std::floor(wrap01(u0) * float(pageCountX()))), 0, pageCountX() - 1);
239 const int maxX = std::clamp(int(std::floor(wrap01(u1) * float(pageCountX()))), 0, pageCountX() - 1);
240 const int minY = std::clamp(int(std::floor(wrap01(v0) * float(pageCountY()))), 0, pageCountY() - 1);
241 const int maxY = std::clamp(int(std::floor(wrap01(v1) * float(pageCountY()))), 0, pageCountY() - 1);
242 for (int y = minY; y <= maxY; ++y)
243 for (int x = minX; x <= maxX; ++x) {
244 auto invalidated = invalidatePage(x, y, mipLevel);
245 if (!invalidated.ok()) return invalidated;
246 }
248}
249
250void VirtualTextureStreaming::touchSlot(PhysicalState& state, int slot) {
251 auto& record = state.slots[std::size_t(slot)];
252 if (!record.occupied || slot == 0) return;
253 state.lru.splice(state.lru.begin(), state.lru, record.lru);
254}
255
256void VirtualTextureStreaming::clearPageMapping(PhysicalState& state, int pageX, int pageY) {
257 const Pixel fallback{(0.5f) / float(atlasSlotsX_), (0.5f) / float(atlasSlotsY_), 0.f, 1.f};
258 state.pageTable->setPixel(pageX, pageY, fallback);
259}
260
261VirtualTextureRegionPixels VirtualTextureStreaming::copyRegion(const image::ImageData& image, int x, int y, int w,
262 int h) {
263 VirtualTextureRegionPixels region;
264 region.x = x;
265 region.y = y;
266 region.width = w;
267 region.height = h;
268 region.rgba.resize(std::size_t(w) * std::size_t(h) * 4u);
269 const auto* src = static_cast<const std::uint8_t*>(image.getData());
270 const int srcStride = image.getWidth() * 4;
271 for (int row = 0; row < h; ++row) {
272 std::memcpy(region.rgba.data() + std::size_t(row) * std::size_t(w) * 4u, src + (y + row) * srcStride + x * 4,
273 std::size_t(w) * 4u);
274 }
275 return region;
276}
277
278VirtualTextureRegionPixels VirtualTextureStreaming::copyPageTableTexel(const image::ImageData& table, int pageX,
279 int pageY) {
280 return copyRegion(table, pageX, pageY, 1, 1);
281}
282
283eve::Result<int> VirtualTextureStreaming::allocateSlot(PhysicalState& state,
284 std::vector<VirtualTextureRegionPixels>& pageTableClears) {
285 for (int slot = 1; slot < int(state.slots.size()); ++slot) {
286 if (!state.slots[std::size_t(slot)].occupied) {
287 state.slots[std::size_t(slot)].occupied = true;
288 state.lru.push_front(slot);
289 state.slots[std::size_t(slot)].lru = state.lru.begin();
291 }
292 }
293 if (state.lru.empty())
294 return eve::Result<int>::failure(failed("virtual texture physical cache has no evictable slots"));
295 const int victim = state.lru.back();
296 state.lru.pop_back();
297 auto& record = state.slots[std::size_t(victim)];
298 if (record.occupied && record.pageX >= 0 && record.pageY >= 0) {
299 clearPageMapping(state, record.pageX, record.pageY);
300 pageTableClears.push_back(copyPageTableTexel(*state.pageTable, record.pageX, record.pageY));
301 state.pageToSlot.erase(PageKey{record.pageX, record.pageY});
302 ++lifetime_.pagesEvicted;
303 }
304 record.occupied = true;
305 record.dirty = false;
306 record.pageX = -1;
307 record.pageY = -1;
308 state.lru.push_front(victim);
309 record.lru = state.lru.begin();
310 return eve::Result<int>::success(victim);
311}
312
313eve::Result<void> VirtualTextureStreaming::decodeIntoSlot(PhysicalState& state, int slot, int pageX, int pageY,
314 std::vector<VirtualTextureRegionPixels>& albedoRegions,
315 std::vector<VirtualTextureRegionPixels>& normalRegions,
316 std::vector<VirtualTextureRegionPixels>& pageTableSets) {
317 auto albedo = producer_->requestAlbedoPage(pageX, pageY, 0);
318 if (!albedo.ok()) return eve::Result<void>::failure(albedo.status());
319 auto normal = producer_->requestNormalPage(pageX, pageY, 0);
320 if (!normal.ok()) return eve::Result<void>::failure(normal.status());
321
322 const int slotX = slot % atlasSlotsX_;
323 const int slotY = slot / atlasSlotsX_;
324 const int dstX = slotX * pageExtent_;
325 const int dstY = slotY * pageExtent_;
326 state.albedo->paste(const_cast<image::ImageData*>(albedo.value().get()), dstX, dstY, 0, 0, pageExtent_,
327 pageExtent_);
328 state.normal->paste(const_cast<image::ImageData*>(normal.value().get()), dstX, dstY, 0, 0, pageExtent_,
329 pageExtent_);
330 albedoRegions.push_back(copyRegion(*state.albedo, dstX, dstY, pageExtent_, pageExtent_));
331 normalRegions.push_back(copyRegion(*state.normal, dstX, dstY, pageExtent_, pageExtent_));
332
333 auto& record = state.slots[std::size_t(slot)];
334 record.pageX = pageX;
335 record.pageY = pageY;
336 record.dirty = false;
337 record.occupied = true;
338 state.pageToSlot[PageKey{pageX, pageY}] = slot;
339 touchSlot(state, slot);
340
341 const Pixel entry{(float(slotX) + 0.5f) / float(atlasSlotsX_), (float(slotY) + 0.5f) / float(atlasSlotsY_), 1.f,
342 1.f};
343 state.pageTable->setPixel(pageX, pageY, entry);
344 pageTableSets.push_back(copyPageTableTexel(*state.pageTable, pageX, pageY));
345 ++lifetime_.pagesDecoded;
347}
348
350 auto ready = ensureInitialized();
351 if (!ready.ok()) return eve::Result<VirtualTextureStreamingStats>::failure(ready.status());
352 if (pending_.has_value())
354 failed("commit or abandon the pending virtual texture upload before update"));
355
356 // Compact + dedupe feedback (UE feedback analyze).
357 std::unordered_map<PageKey, int, PageKeyHash> unique;
358 unique.reserve(feedback_.size());
359 for (const auto& sample : feedback_) {
360 if (sample.mipLevel != 0) continue;
361 ++unique[PageKey{sample.pageX, sample.pageY}];
362 }
363 feedback_.clear();
364 lifetime_.uniqueFeedback += unique.size();
365 lifetime_.pendingFeedback = 0;
366
367 std::vector<std::pair<PageKey, int>> ordered(unique.begin(), unique.end());
368 std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
369 if (a.second != b.second) return a.second > b.second;
370 if (a.first.y != b.first.y) return a.first.y < b.first.y;
371 return a.first.x < b.first.x;
372 });
373
375 batch.expectedGeneration = generation_;
376 std::size_t decoded = 0;
377
378 for (const auto& [page, weight] : ordered) {
379 (void)weight;
380 auto found = working_.pageToSlot.find(page);
381 if (found != working_.pageToSlot.end()) {
382 touchSlot(working_, found->second);
383 if (!working_.slots[std::size_t(found->second)].dirty) continue;
384 if (decoded >= config_.maxDecodesPerUpdate) break;
385 auto decodedOk = decodeIntoSlot(working_, found->second, page.x, page.y, batch.albedoRegions,
386 batch.normalRegions, batch.pageTableSets);
387 if (!decodedOk.ok()) return eve::Result<VirtualTextureStreamingStats>::failure(decodedOk.status());
388 ++decoded;
389 continue;
390 }
391 if (decoded >= config_.maxDecodesPerUpdate) break;
392 auto slot = allocateSlot(working_, batch.pageTableClears);
394 auto decodedOk = decodeIntoSlot(working_, slot.value(), page.x, page.y, batch.albedoRegions,
395 batch.normalRegions, batch.pageTableSets);
396 if (!decodedOk.ok()) return eve::Result<VirtualTextureStreamingStats>::failure(decodedOk.status());
397 ++decoded;
398 }
399
400 // Also process dirty residents that were not in this frame's feedback.
401 if (decoded < config_.maxDecodesPerUpdate) {
402 for (int slot = 1; slot < int(working_.slots.size()) && decoded < config_.maxDecodesPerUpdate; ++slot) {
403 auto& record = working_.slots[std::size_t(slot)];
404 if (!record.occupied || !record.dirty || record.pageX < 0) continue;
405 auto decodedOk = decodeIntoSlot(working_, slot, record.pageX, record.pageY, batch.albedoRegions,
406 batch.normalRegions, batch.pageTableSets);
407 if (!decodedOk.ok()) return eve::Result<VirtualTextureStreamingStats>::failure(decodedOk.status());
408 ++decoded;
409 }
410 }
411
412 const bool hasWork = !batch.pageTableClears.empty() || !batch.albedoRegions.empty() ||
413 !batch.normalRegions.empty() || !batch.pageTableSets.empty();
414 if (hasWork) {
415 pending_ = std::move(batch);
416 lifetime_.pendingUploads = pending_->pageTableClears.size() + pending_->albedoRegions.size() +
417 pending_->normalRegions.size() + pending_->pageTableSets.size();
418 } else {
419 lifetime_.pendingUploads = 0;
420 }
421 lifetime_.generation = generation_;
422 lifetime_.residentPages = working_.pageToSlot.size();
424}
425
427 if (!pending_.has_value())
428 return eve::Result<VirtualTextureUploadBatch>::failure(failed("no pending virtual texture upload batch"));
429 VirtualTextureUploadBatch batch = std::move(*pending_);
430 // Keep the optional engaged with an empty marker? We need commit/abandon to know a batch was taken.
431 // Store a sentinel empty batch with the same expectedGeneration.
432 pending_ = VirtualTextureUploadBatch{};
433 pending_->expectedGeneration = batch.expectedGeneration;
434 lifetime_.pendingUploads = 0;
436}
437
439 if (!pending_.has_value())
440 return eve::Result<void>::failure(failed("no pending virtual texture publish to commit"));
441 if (pending_->expectedGeneration != expectedGeneration)
442 return eve::Result<void>::failure(failed("virtual texture publish generation mismatch"));
443 published_ = cloneState(working_);
444 pending_.reset();
445 ++generation_;
446 ++lifetime_.publishes;
447 lifetime_.generation = generation_;
448 lifetime_.residentPages = published_.pageToSlot.size();
449 lifetime_.pendingUploads = 0;
451}
452
454 if (!pending_.has_value())
455 return eve::Result<void>::failure(failed("no pending virtual texture publish to abandon"));
456 working_ = cloneState(published_);
457 pending_.reset();
458 ++lifetime_.abandonedPublishes;
459 lifetime_.pendingUploads = 0;
460 lifetime_.residentPages = published_.pageToSlot.size();
462}
463
464VirtualTextureStreaming::PhysicalState VirtualTextureStreaming::cloneState(const PhysicalState& source) const {
465 PhysicalState copy;
466 copy.albedo = std::make_unique<image::ImageData>(*source.albedo);
467 copy.normal = std::make_unique<image::ImageData>(*source.normal);
468 copy.pageTable = std::make_unique<image::ImageData>(*source.pageTable);
469 copy.slots = source.slots;
470 copy.pageToSlot = source.pageToSlot;
471 copy.lru.clear();
472 // Rebuild LRU iterators against the new list.
473 for (int slot : source.lru) {
474 copy.lru.push_back(slot);
475 copy.slots[std::size_t(slot)].lru = std::prev(copy.lru.end());
476 }
477 // Slot 0 has no LRU entry.
478 if (!copy.slots.empty()) copy.slots[0].lru = copy.lru.end();
479 return copy;
480}
481
484 out.generation = generation_;
485 out.residentPages = initialized_ ? published_.pageToSlot.size() : 0;
486 out.pendingFeedback = feedback_.size();
487 out.pendingUploads = pending_.has_value() ? (pending_->pageTableClears.size() + pending_->albedoRegions.size() +
488 pending_->normalRegions.size() + pending_->pageTableSets.size())
489 : 0;
490 return out;
491}
492
493const image::ImageData& VirtualTextureStreaming::albedoAtlas() const { return *published_.albedo; }
494const image::ImageData& VirtualTextureStreaming::normalAtlas() const { return *published_.normal; }
495const image::ImageData& VirtualTextureStreaming::pageTable() const { return *published_.pageTable; }
496
497int VirtualTextureStreaming::pageCountX() const { return producer_->pageCountX(); }
498int VirtualTextureStreaming::pageCountY() const { return producer_->pageCountY(); }
499
500namespace {
501eve::Result<void> uploadRegions(Graphics& gfx, Texture* texture,
502 const std::vector<VirtualTextureRegionPixels>& regions) {
503 if (!texture) return eve::Result<void>::failure(invalid("virtual texture GPU texture is null"));
504 for (const auto& region : regions) {
505 TextureRegionUpload upload;
506 upload.x = region.x;
507 upload.y = region.y;
508 upload.width = region.width;
509 upload.height = region.height;
510 upload.rgba = std::span<const std::uint8_t>(region.rgba.data(), region.rgba.size());
511 upload.bytesPerRow = std::size_t(region.width) * 4u;
512 auto status = gfx.updateTextureRegions(texture, std::span<const TextureRegionUpload>(&upload, 1));
513 if (!status.ok()) return status;
514 }
516}
517} // namespace
518
520 auto ready = ensureInitialized();
521 if (!ready.ok()) return ready;
522
523 if (!gpuAlbedo_ || !gpuNormal_ || !gpuPageTable_) {
525 info.generateMipmaps = false;
526 gpuAlbedo_ = gfx.newTexture(const_cast<image::ImageData*>(published_.albedo.get()), info);
527 gpuNormal_ = gfx.newTexture(const_cast<image::ImageData*>(published_.normal.get()), info);
528 gpuPageTable_ = gfx.newTexture(const_cast<image::ImageData*>(published_.pageTable.get()), info);
529 if (!gpuAlbedo_ || !gpuNormal_ || !gpuPageTable_)
530 return eve::Result<void>::failure(failed("failed to create virtual texture GPU atlases"));
531 auto bound = material.setVirtualTexture(gpuAlbedo_, gpuNormal_, gpuPageTable_, pageCountX(), pageCountY(),
532 atlasSlotsX_, atlasSlotsY_, borderFraction_);
533 if (!bound.ok()) return bound;
534 }
535
536 if (!pending_.has_value()) return eve::Result<void>::success();
537
538 auto batchResult = takePendingUploads();
539 if (!batchResult.ok()) return eve::Result<void>::failure(batchResult.status());
540 auto batch = std::move(batchResult).value();
541
542 auto restoreGpuFromPublished = [&]() -> eve::Result<void> {
543 TextureRegionUpload albedoUpload;
544 albedoUpload.width = published_.albedo->getWidth();
545 albedoUpload.height = published_.albedo->getHeight();
546 albedoUpload.rgba = std::span<const std::uint8_t>(
547 static_cast<const std::uint8_t*>(published_.albedo->getData()), published_.albedo->getSize());
548 albedoUpload.bytesPerRow = std::size_t(albedoUpload.width) * 4u;
549 auto albedoStatus =
550 gfx.updateTextureRegions(gpuAlbedo_, std::span<const TextureRegionUpload>(&albedoUpload, 1));
551 if (!albedoStatus.ok()) return albedoStatus;
552 TextureRegionUpload normalUpload = albedoUpload;
553 normalUpload.rgba = std::span<const std::uint8_t>(
554 static_cast<const std::uint8_t*>(published_.normal->getData()), published_.normal->getSize());
555 auto normalStatus =
556 gfx.updateTextureRegions(gpuNormal_, std::span<const TextureRegionUpload>(&normalUpload, 1));
557 if (!normalStatus.ok()) return normalStatus;
558 TextureRegionUpload tableUpload = albedoUpload;
559 tableUpload.width = published_.pageTable->getWidth();
560 tableUpload.height = published_.pageTable->getHeight();
561 tableUpload.rgba = std::span<const std::uint8_t>(
562 static_cast<const std::uint8_t*>(published_.pageTable->getData()), published_.pageTable->getSize());
563 tableUpload.bytesPerRow = std::size_t(tableUpload.width) * 4u;
564 return gfx.updateTextureRegions(gpuPageTable_, std::span<const TextureRegionUpload>(&tableUpload, 1));
565 };
566
567 auto clears = uploadRegions(gfx, gpuPageTable_, batch.pageTableClears);
568 if (!clears.ok()) {
569 (void)abandonPublish();
570 (void)restoreGpuFromPublished();
571 return clears;
572 }
573 auto albedo = uploadRegions(gfx, gpuAlbedo_, batch.albedoRegions);
574 if (!albedo.ok()) {
575 (void)abandonPublish();
576 (void)restoreGpuFromPublished();
577 return albedo;
578 }
579 auto normal = uploadRegions(gfx, gpuNormal_, batch.normalRegions);
580 if (!normal.ok()) {
581 (void)abandonPublish();
582 (void)restoreGpuFromPublished();
583 return normal;
584 }
585 auto sets = uploadRegions(gfx, gpuPageTable_, batch.pageTableSets);
586 if (!sets.ok()) {
587 (void)abandonPublish();
588 (void)restoreGpuFromPublished();
589 return sets;
590 }
591 return commitPublish(batch.expectedGeneration);
592}
593
594} // namespace eve::graphics
double y
double x
float w
Definition AnimClip.cpp:738
graphics::Texture * albedo
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
ScriptFieldRegion region
std::string message
vk::UniqueImage image
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
float v
std::int32_t c
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
bool ordered
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
std::array< uint32_t, 16 > material
Texture * texture
TileLayer * layer
Object::Ptr value
float d
std::string slot
bool found
ScriptStructure out
std::string_view source
uint32_t seed
Definition TreeMesh.cpp:276
double weight
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
virtual eve::Result< void > updateTextureRegions(Texture *texture, std::span< const TextureRegionUpload > regions)=0
Validate then upload multiple independent mip-zero RGBA8 regions as one batch.
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
static eve::Result< std::unique_ptr< VirtualTextureBlend > > create(const VirtualTextureBlendConfig &config)
Validate configuration and create an empty virtual texture.
Internal UE5-style runtime virtual texture session: feedback → decode → atomic publish.
eve::Result< std::uint32_t > addLayer(const VirtualTextureBlendLayer &layer)
Copy and append one material layer through the owned producer.
eve::Result< VirtualTextureUploadBatch > takePendingUploads()
Take the staged upload batch for GPU application.
eve::Result< void > ingestPackedFeedback(std::span< const std::uint32_t > packed)
Ingest a packed feedback buffer (UE-style page IDs). @cost Cheap relative to update(); copies and ret...
eve::Result< void > invalidatePage(int pageX, int pageY, int mipLevel=0)
Mark one page dirty for writer-style attribute edits.
eve::Result< void > initializePhysicalCache()
Allocate CPU atlases and a page table with only the substitute slot resident.
int pageCountY() const
Mip-zero page count y.
VirtualTextureStreamingStats stats() const
Snapshot counters.
eve::Result< void > commitPublish(std::uint64_t expectedGeneration)
Publish working state after successful GPU uploads (bumps generation).
eve::Result< void > abandonPublish()
Discard staged working changes and restore the last published mapping.
VirtualTextureBlend & producer()
Borrowed producer.
static eve::Result< std::unique_ptr< VirtualTextureStreaming > > create(const VirtualTextureStreamingConfig &config)
Validate config and create an empty streaming session.
static eve::Result< VirtualTextureFeedbackSample > unpackFeedback(std::uint32_t packed)
Unpack a feedback sample into page coordinates.
static std::uint32_t packFeedback(int pageX, int pageY, int mipLevel) noexcept
Pack a feedback sample into the 32-bit GPU/CPU wire format.
const image::ImageData & pageTable() const
Published page table.
eve::Result< VirtualTextureStreamingStats > update()
Compact feedback, decode up to budget, and stage an incremental upload batch. @cost Expensive relativ...
eve::Result< void > recordFeedbackUv(float u, float v, int mipLevel=0)
Record the page covering normalized UV (fract).
eve::Result< void > syncToMaterial(Graphics &gfx, Material &material)
Create or refresh GPU textures and bind them to a material. @cost Expensive on first call (full atlas...
const image::ImageData & normalAtlas() const
Published normal atlas.
int pageCountX() const
Mip-zero page count x.
eve::Result< void > recordFeedbackGrid(int gridW, int gridH, int mipLevel=0)
Record every cell centre of a low-resolution UV grid (CPU feedback stand-in). @cost Linear in gridW*g...
const image::ImageData & albedoAtlas() const
Published albedo atlas (valid after initializePhysicalCache).
eve::Result< void > invalidateRect(float u0, float v0, float u1, float v1, int mipLevel=0)
Mark resident pages covering a UV rectangle dirty so the next update re-decodes them.
eve::Result< void > recordFeedback(int pageX, int pageY, int mipLevel=0)
Record one page request (cheap; retained until the next update compact).
Represents raw pixel data.
Definition ImageData.h:38
medialoader::Colorf Colorf
Definition ImageData.h:41
std::string word
Result< T > failed(Status status, eve::DiagnosticCode code, RuleId rule, std::string message)
Construct a failed editing result with explicit status and diagnostic categories.
Status invalid(const char *message)
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
Options for Graphics::newTexture / newCubemap. When generateMipmaps is true and sampler....
One borrowed RGBA8 source rectangle for a batched texture update. @ownership rgba remains owned by th...
Definition Graphics.h:76
std::span< const std::uint8_t > rgba
Definition Graphics.h:81
One immutable source layer copied into a VirtualTextureBlend.
One GPU/CPU feedback sample requesting residency for a virtual page.
Runtime streaming budgets over a VirtualTextureBlend producer.
std::size_t feedbackCapacity
Soft cap on retained raw feedback samples before compact.
std::size_t maxDecodesPerUpdate
Maximum page decodes applied by one update() call.
Observable counters for one streaming session.
Ordered GPU upload transaction for atlas pages and page-table texels.
std::vector< VirtualTextureRegionPixels > normalRegions
std::vector< VirtualTextureRegionPixels > pageTableClears
std::vector< VirtualTextureRegionPixels > albedoRegions
std::vector< VirtualTextureRegionPixels > pageTableSets
glm::uvec4 info