载入中...
搜索中...
未找到
VirtualTextureBlend.cpp
浏览该文件的文档.
2
3#include <utility>
4
5#include "image/ImageData.h"
6
7#include <algorithm>
8#include <cmath>
9#include <functional>
10#include <unordered_set>
11
12namespace eve::graphics {
13namespace {
14
16
17eve::Diagnostic invalid(std::string message) {
19}
20
21float wrap01(float value) {
22 value -= std::floor(value);
23 return value < 0.f ? value + 1.f : value;
24}
25
26Color sampleRepeat(const image::ImageData& image, float u, float v) {
27 const int width = image.getWidth();
28 const int height = image.getHeight();
29 const float x = wrap01(u) * float(width) - 0.5f;
30 const float y = wrap01(v) * float(height) - 0.5f;
31 const int x0 = int(std::floor(x));
32 const int y0 = int(std::floor(y));
33 const float tx = x - float(x0);
34 const float ty = y - float(y0);
35 auto pixel = [&](int px, int py) {
36 px = (px % width + width) % width;
37 py = (py % height + height) % height;
38 return image.getPixel(px, py);
39 };
40 const Color a = pixel(x0, y0);
41 const Color b = pixel(x0 + 1, y0);
42 const Color c = pixel(x0, y0 + 1);
43 const Color d = pixel(x0 + 1, y0 + 1);
44 const auto mix = [tx, ty](float av, float bv, float cv, float dv) {
45 return (av + (bv - av) * tx) + ((cv + (dv - cv) * tx) - (av + (bv - av) * tx)) * ty;
46 };
47 Color out{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)};
48 return out;
49}
50
51std::shared_ptr<const image::ImageData> copyImage(const image::ImageData& source) {
52 return std::make_shared<image::ImageData>(source);
53}
54
55} // namespace
56
58 if (config.width <= 0 || config.height <= 0)
60 invalid("virtual texture dimensions must be positive"));
61 if (config.tileSize < 4 || config.tileSize > 1024)
63 invalid("virtual texture tile size must be in [4, 1024]"));
66 invalid("virtual texture border must be non-negative and smaller than half a tile"));
69 invalid("virtual texture resident page capacity must be positive"));
71 std::unique_ptr<VirtualTextureBlend>(new VirtualTextureBlend(config)));
72}
73
75 if (!layer.albedo) return eve::Result<std::uint32_t>::failure(invalid("virtual texture layer requires albedo"));
76 if (layer.albedo->getWidth() <= 0 || layer.albedo->getHeight() <= 0 || layer.albedo->getFormat() != "RGBA8")
77 return eve::Result<std::uint32_t>::failure(invalid("layer albedo must be non-empty RGBA8"));
78 if (layer.normal && layer.normal->getFormat() != "RGBA8")
79 return eve::Result<std::uint32_t>::failure(invalid("layer normal must be RGBA8"));
80 if (layer.weight && layer.weight->getFormat() != "RGBA8")
81 return eve::Result<std::uint32_t>::failure(invalid("layer weight must be RGBA8"));
82 if (!std::isfinite(layer.uvScale) || layer.uvScale <= 0.f || !std::isfinite(layer.constantWeight) ||
83 layer.constantWeight < 0.f || !std::isfinite(layer.heightContrast) || layer.heightContrast < 0.f)
84 return eve::Result<std::uint32_t>::failure(invalid("layer blend parameters are invalid"));
85 if (layers_.size() >= 16)
86 return eve::Result<std::uint32_t>::failure(invalid("virtual texture supports at most 16 layers"));
87
89 owned.albedo = copyImage(*layer.albedo);
90 if (layer.normal) owned.normal = copyImage(*layer.normal);
91 if (layer.weight) owned.weight = copyImage(*layer.weight);
92 layers_.push_back(std::move(owned));
93 invalidate();
94 return eve::Result<std::uint32_t>::success(std::uint32_t(layers_.size() - 1));
95}
96
97std::size_t VirtualTextureBlend::PageKeyHash::operator()(const PageKey& key) const noexcept {
98 std::size_t seed = std::hash<int>{}(key.x);
99 seed ^= std::hash<int>{}(key.y) + 0x9e3779b9u + (seed << 6u) + (seed >> 2u);
100 seed ^= std::hash<int>{}(key.mip) + 0x9e3779b9u + (seed << 6u) + (seed >> 2u);
101 seed ^= std::hash<int>{}(int(key.attribute)) + 0x9e3779b9u + (seed << 6u) + (seed >> 2u);
102 return seed;
103}
104
105int VirtualTextureBlend::pageCountX(int mipLevel) const {
106 if (mipLevel < 0 || mipLevel > 30) return 0;
107 const int width = std::max(1, config_.width >> mipLevel);
108 return (width + config_.tileSize - 1) / config_.tileSize;
109}
110
111int VirtualTextureBlend::pageCountY(int mipLevel) const {
112 if (mipLevel < 0 || mipLevel > 30) return 0;
113 const int height = std::max(1, config_.height >> mipLevel);
114 return (height + config_.tileSize - 1) / config_.tileSize;
115}
116
118 int mipLevel) {
119 return requestPage({pageX, pageY, mipLevel, Attribute::Albedo});
120}
121
123 int mipLevel) {
124 return requestPage({pageX, pageY, mipLevel, Attribute::Normal});
125}
126
127eve::Result<std::shared_ptr<const image::ImageData>> VirtualTextureBlend::requestPage(PageKey key) {
128 if (layers_.empty())
130 invalid("virtual texture has no material layers"));
131 if (key.mip < 0 || key.mip > 30 || key.x < 0 || key.y < 0 || key.x >= pageCountX(key.mip) ||
132 key.y >= pageCountY(key.mip))
134 invalid("virtual texture page coordinate is outside the mip"));
135 auto found = cache_.find(key);
136 if (found != cache_.end()) {
137 ++hits_;
138 lru_.splice(lru_.begin(), lru_, found->second.lru);
139 return eve::Result<std::shared_ptr<const image::ImageData>>::success(found->second.image);
140 }
141
142 ++misses_;
143 auto page = composePage(key);
144 if (cache_.size() == config_.residentPageCapacity) {
145 cache_.erase(lru_.back());
146 lru_.pop_back();
147 ++evictions_;
148 }
149 lru_.push_front(key);
150 cache_.emplace(key, CacheEntry{page, lru_.begin()});
151 return eve::Result<std::shared_ptr<const image::ImageData>>::success(std::move(page));
152}
153
154std::shared_ptr<const image::ImageData> VirtualTextureBlend::composePage(const PageKey& key) const {
155 const int extent = config_.tileSize + config_.borderSize * 2;
156 auto page = std::make_shared<image::ImageData>(extent, extent, "RGBA8");
157 const int mipWidth = std::max(1, config_.width >> key.mip);
158 const int mipHeight = std::max(1, config_.height >> key.mip);
159 std::vector<float> influences(layers_.size());
160 std::vector<Color> samples(layers_.size());
161 for (int py = 0; py < extent; ++py) {
162 for (int px = 0; px < extent; ++px) {
163 const int virtualX = key.x * config_.tileSize + px - config_.borderSize;
164 const int virtualY = key.y * config_.tileSize + py - config_.borderSize;
165 const float u = (float(virtualX) + 0.5f) / float(mipWidth);
166 const float v = (float(virtualY) + 0.5f) / float(mipHeight);
167 float maximum = 0.f;
168 for (std::size_t i = 0; i < layers_.size(); ++i) {
169 const auto& layer = layers_[i];
170 const Color albedo = sampleRepeat(*layer.albedo, u * layer.uvScale, v * layer.uvScale);
171 const float mask = layer.weight ? sampleRepeat(*layer.weight, u, v).r : 1.f;
172 influences[i] = layer.constantWeight * mask + albedo.a * layer.heightContrast;
173 maximum = std::max(maximum, influences[i]);
174 if (key.attribute == Attribute::Normal && layer.normal)
175 samples[i] = sampleRepeat(*layer.normal, u * layer.uvScale, v * layer.uvScale);
176 else if (key.attribute == Attribute::Normal)
177 samples[i] = Color{0.5f, 0.5f, 1.f, 1.f};
178 else
179 samples[i] = albedo;
180 }
181 float total = 0.f;
182 constexpr float transition = 0.15f;
183 for (float& influence : influences) {
184 influence = std::max(0.f, influence - maximum + transition);
185 total += influence;
186 }
187 if (total <= 1e-6f) {
188 influences.front() = 1.f;
189 total = 1.f;
190 }
191 Color output{0.f, 0.f, 0.f, 0.f};
192 for (std::size_t i = 0; i < samples.size(); ++i) {
193 const float weight = influences[i] / total;
194 if (key.attribute == Attribute::Normal) {
195 output.r += (samples[i].r * 2.f - 1.f) * weight;
196 output.g += (samples[i].g * 2.f - 1.f) * weight;
197 output.b += (samples[i].b * 2.f - 1.f) * weight;
198 } else {
199 output.r += samples[i].r * weight;
200 output.g += samples[i].g * weight;
201 output.b += samples[i].b * weight;
202 output.a += samples[i].a * weight;
203 }
204 }
205 if (key.attribute == Attribute::Normal) {
206 const float length = std::sqrt(output.r * output.r + output.g * output.g + output.b * output.b);
207 const float inverse = length > 1e-6f ? 1.f / length : 1.f;
208 output = Color{output.r * inverse * 0.5f + 0.5f, output.g * inverse * 0.5f + 0.5f,
209 output.b * inverse * 0.5f + 0.5f, 1.f};
210 }
211 page->setPixel(px, py, output);
212 }
213 }
214 return page;
215}
216
218 return bakeAttribute(Attribute::Albedo);
219}
220
222 return bakeAttribute(Attribute::Normal);
223}
224
225eve::Result<std::unique_ptr<image::ImageData>> VirtualTextureBlend::bakeAttribute(Attribute attribute) {
226 if (layers_.empty())
228 invalid("virtual texture has no material layers"));
229 auto output = std::make_unique<image::ImageData>(config_.width, config_.height, "RGBA8");
230 for (int pageY = 0; pageY < pageCountY(); ++pageY) {
231 for (int pageX = 0; pageX < pageCountX(); ++pageX) {
232 auto pageResult = requestPage({pageX, pageY, 0, attribute});
233 if (!pageResult.ok()) return eve::Result<std::unique_ptr<image::ImageData>>::failure(pageResult.status());
234 const auto& page = *pageResult.value();
235 const int copyWidth = std::min(config_.tileSize, config_.width - pageX * config_.tileSize);
236 const int copyHeight = std::min(config_.tileSize, config_.height - pageY * config_.tileSize);
237 output->paste(const_cast<image::ImageData*>(&page), pageX * config_.tileSize, pageY * config_.tileSize,
238 config_.borderSize, config_.borderSize, copyWidth, copyHeight);
239 }
240 }
241 return eve::Result<std::unique_ptr<image::ImageData>>::success(std::move(output));
242}
243
245 const std::vector<VirtualTexturePageId>& residentPages) {
246 if (layers_.empty())
247 return eve::Result<VirtualTextureResidentSet>::failure(invalid("virtual texture has no material layers"));
248 if (residentPages.size() > config_.residentPageCapacity)
250 invalid("resident page selection exceeds physical cache capacity"));
251
252 std::unordered_set<std::uint64_t> unique;
253 for (const auto& page : residentPages) {
254 if (page.x < 0 || page.y < 0 || page.x >= pageCountX() || page.y >= pageCountY())
256 invalid("resident page coordinate is outside mip zero"));
257 const auto key = (std::uint64_t(std::uint32_t(page.y)) << 32u) | std::uint32_t(page.x);
258 if (!unique.insert(key).second)
260 invalid("resident page selection contains duplicates"));
261 }
262
263 const int extent = config_.tileSize + config_.borderSize * 2;
264 const std::size_t slotCount = config_.residentPageCapacity + 1;
265 const int slotsX = int(std::ceil(std::sqrt(double(slotCount))));
266 const int slotsY = int((slotCount + std::size_t(slotsX) - 1) / std::size_t(slotsX));
268 output.albedoAtlas = std::make_unique<image::ImageData>(slotsX * extent, slotsY * extent, "RGBA8");
269 output.normalAtlas = std::make_unique<image::ImageData>(slotsX * extent, slotsY * extent, "RGBA8");
270 output.pageTable = std::make_unique<image::ImageData>(pageCountX(), pageCountY(), "RGBA8");
271 output.atlasSlotsX = slotsX;
272 output.atlasSlotsY = slotsY;
273 output.pageExtent = extent;
274 output.borderFraction = float(config_.borderSize) / float(extent);
275 output.residentPages = residentPages.size();
276
277 auto albedoFallback = bakeAlbedo();
278 if (!albedoFallback.ok()) return eve::Result<VirtualTextureResidentSet>::failure(albedoFallback.status());
279 auto normalFallback = bakeNormal();
280 if (!normalFallback.ok()) return eve::Result<VirtualTextureResidentSet>::failure(normalFallback.status());
281
282 auto writeFallback = [&](image::ImageData& atlas, const image::ImageData& source) {
283 for (int y = 0; y < extent; ++y) {
284 for (int x = 0; x < extent; ++x) {
285 const float u = (float(x - config_.borderSize) + 0.5f) / float(config_.tileSize);
286 const float v = (float(y - config_.borderSize) + 0.5f) / float(config_.tileSize);
287 atlas.setPixel(x, y, sampleRepeat(source, u, v));
288 }
289 }
290 };
291 writeFallback(*output.albedoAtlas, *albedoFallback.value());
292 writeFallback(*output.normalAtlas, *normalFallback.value());
293
294 const Color fallbackEntry{0.5f / float(slotsX), 0.5f / float(slotsY), 0.f, 1.f};
295 for (int y = 0; y < pageCountY(); ++y)
296 for (int x = 0; x < pageCountX(); ++x) output.pageTable->setPixel(x, y, fallbackEntry);
297
298 for (std::size_t index = 0; index < residentPages.size(); ++index) {
299 const int slot = int(index) + 1;
300 const int slotX = slot % slotsX;
301 const int slotY = slot / slotsX;
302 auto albedo = requestAlbedoPage(residentPages[index].x, residentPages[index].y, 0);
304 auto normal = requestNormalPage(residentPages[index].x, residentPages[index].y, 0);
306 output.albedoAtlas->paste(const_cast<image::ImageData*>(albedo.value().get()), slotX * extent, slotY * extent,
307 0, 0, extent, extent);
308 output.normalAtlas->paste(const_cast<image::ImageData*>(normal.value().get()), slotX * extent, slotY * extent,
309 0, 0, extent, extent);
310 const Color entry{(float(slotX) + 0.5f) / float(slotsX), (float(slotY) + 0.5f) / float(slotsY), 1.f, 1.f};
311 output.pageTable->setPixel(residentPages[index].x, residentPages[index].y, entry);
312 }
314}
315
317 cache_.clear();
318 lru_.clear();
319}
320
321VirtualTextureBlendStats VirtualTextureBlend::stats() const { return {cache_.size(), hits_, misses_, evictions_}; }
322
323} // namespace eve::graphics
double y
double x
std::string output
ActiveSource owned
int mask
graphics::Texture * albedo
SQObjectPtr key
Definition ECS.cpp:155
std::string message
float maximum[3]
vk::UniqueImage image
float u
Definition Grass.cpp:233
float v
std::int32_t c
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
float length
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
TileLayer * layer
Object::Ptr value
float d
std::string slot
std::string attribute
bool found
ScriptStructure out
std::string_view source
uint32_t seed
Definition TreeMesh.cpp:276
double weight
uint32_t index
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
CPU reference implementation of a tiled, height-aware material virtual texture.
eve::Result< std::unique_ptr< image::ImageData > > bakeNormal()
Bake the complete mip-zero tangent-space normal substitute for nonresident pages.
eve::Result< std::uint32_t > addLayer(const VirtualTextureBlendLayer &layer)
Copy and append one material layer, invalidating generated pages atomically.
static eve::Result< std::unique_ptr< VirtualTextureBlend > > create(const VirtualTextureBlendConfig &config)
Validate configuration and create an empty virtual texture.
eve::Result< std::shared_ptr< const image::ImageData > > requestAlbedoPage(int pageX, int pageY, int mipLevel)
Resolve one page at the requested mip level.
int pageCountX(int mipLevel=0) const
Page count x.
eve::Result< std::unique_ptr< image::ImageData > > bakeAlbedo()
Bake the complete mip-zero albedo substitute used for nonresident pages.
eve::Result< std::shared_ptr< const image::ImageData > > requestNormalPage(int pageX, int pageY, int mipLevel)
Resolve a tangent-space normal page using vector blending and renormalization.
eve::Result< VirtualTextureResidentSet > buildResidentSet(const std::vector< VirtualTexturePageId > &residentPages)
Build an atlas, page table, and whole-surface substitute for selected mip-zero pages.
void invalidate()
Clear generated pages while preserving immutable source layers.
const VirtualTextureBlendConfig & config() const
Config.
int pageCountY(int mipLevel=0) const
Page count y.
VirtualTextureBlendStats stats() const
Snapshot current cache counters.
Represents raw pixel data.
Definition ImageData.h:38
void setPixel(int x, int y, const Colorf &p)
Sets the pixel at location (x,y).
medialoader::Colorf Colorf
Definition ImageData.h:41
Status invalid(const char *message)
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
Backend-neutral configuration for a paged material-attribute texture.
One immutable source layer copied into a VirtualTextureBlend.
std::shared_ptr< const image::ImageData > albedo
Observable residency counters for virtual-texture diagnostics.
CPU images and sampling metadata for one atomically publishable physical cache.
std::unique_ptr< image::ImageData > albedoAtlas