载入中...
搜索中...
未找到
GraphicsTextureMips.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <array>
5#include <chrono>
6#include <cstring>
7#include <limits>
8#if defined(__EMSCRIPTEN__)
9#include <emscripten/emscripten.h>
10#endif
11
12namespace eve::graphics::webgpu {
13namespace {
14struct UploadError {
15 wgpu::PopErrorScopeStatus status = wgpu::PopErrorScopeStatus::Error;
16 wgpu::ErrorType type = wgpu::ErrorType::NoError;
17 std::array<char, 512> message{};
18 bool done = false;
19};
20
21// Scopes belong to this graphics-thread operation. Callback state outlives a
22// failed or timed-out observation on both native Dawn and Emscripten.
23class UploadScopes {
24public:
25 explicit UploadScopes(const wgpu::Device& device) : device_(device) {
26 for (auto& result : results_) result = std::make_shared<UploadError>();
27 for (auto filter :
28 {wgpu::ErrorFilter::Validation, wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal}) {
29 device_.PushErrorScope(filter);
30 ++pending_;
31 }
32 }
33 ~UploadScopes() {
34 // Unwind any scopes left by a CPU allocation exception before publication.
35 while (pending_) {
36 WGPUPopErrorScopeCallbackInfo callback{};
37 callback.mode = WGPUCallbackMode_AllowSpontaneous;
38 callback.callback = [](WGPUPopErrorScopeStatus, WGPUErrorType, WGPUStringView, void*, void*) {};
39 (void)wgpuDevicePopErrorScope(device_.Get(), callback);
40 --pending_;
41 }
42 }
43 [[nodiscard]] Result<void> finish(const wgpu::Instance& instance) {
44 std::array<wgpu::Future, 3> futures{};
45 for (size_t i = 0; i < futures.size(); ++i) {
46 futures[i] = device_.PopErrorScope(
47#if defined(__EMSCRIPTEN__)
48 wgpu::CallbackMode::AllowProcessEvents,
49#else
50 wgpu::CallbackMode::WaitAnyOnly,
51#endif
52 [result = results_[i]](wgpu::PopErrorScopeStatus status, wgpu::ErrorType type,
53 wgpu::StringView message) noexcept {
54 result->status = status;
55 result->type = type;
56 if (message.data) {
57 const auto length = message.length == WGPU_STRLEN ? std::strlen(message.data) : message.length;
58 std::memcpy(result->message.data(), message.data, std::min(length, result->message.size() - 1));
59 }
60 result->done = true;
61 });
62 --pending_;
63 }
64 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
65 for (size_t i = 0; i < futures.size(); ++i) {
66#if defined(__EMSCRIPTEN__)
67 while (!results_[i]->done && std::chrono::steady_clock::now() < deadline) {
68 emscripten_sleep(0);
69 wgpuInstanceProcessEvents(instance.Get());
70 }
71 if (!results_[i]->done)
73 "WebGPU mip upload error scope could not be observed",
74 {}, {}, "graphics.texture.mips"));
75#else
76 const auto remaining = deadline - std::chrono::steady_clock::now();
77 const auto timeout =
78 std::max<int64_t>(0, std::chrono::duration_cast<std::chrono::nanoseconds>(remaining).count());
79 if (instance.WaitAny(futures[i], uint64_t(timeout)) != wgpu::WaitStatus::Success)
81 "WebGPU mip upload error scope could not be observed",
82 {}, {}, "graphics.texture.mips"));
83#endif
84 }
85 for (const auto& result : results_)
86 if (result->status != wgpu::PopErrorScopeStatus::Success || result->type != wgpu::ErrorType::NoError)
87 return Result<void>::failure(Diagnostic::error(
88 DiagnosticCode::Failed, std::string("WebGPU mip upload rejected: ") + result->message.data(), {},
89 {}, "graphics.texture.mips"));
90 return Result<void>::success();
91 }
92
93private:
94 wgpu::Device device_;
95 unsigned pending_ = 0;
96 std::array<std::shared_ptr<UploadError>, 3> results_;
97};
98} // namespace
99
100Result<Texture*> Graphics::newTextureMipChain(uint32_t width, uint32_t height, uint32_t levels,
101 std::span<const uint8_t> rgba) {
102 auto fail = [](DiagnosticCode code, std::string message) {
103 return Result<Texture*>::failure(Diagnostic::error(code, message, {}, {}, "graphics.texture.mips"));
104 };
105 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
106 const auto maximum = caps.maxTextureDimension2D();
107 if (!width || !height || width > maximum || height > maximum)
108 return fail(DiagnosticCode::InvalidArgument, "mip dimensions exceed device limits");
109 uint64_t expected = 0;
110 uint32_t count = 0, w = width, h = height;
111 for (;;) {
112 expected += uint64_t(w) * h * 4;
113 ++count;
114 if (w == 1 && h == 1) break;
115 w = std::max(w / 2, 1u);
116 h = std::max(h / 2, 1u);
117 }
118 if (levels != count || expected != rgba.size() || expected > UINT32_MAX)
119 return fail(DiagnosticCode::InvalidArgument, "mip count, packed bytes or staging offset budget invalid");
120 try {
121 ownedTextures.reserve(ownedTextures.size() + 1);
122 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1);
123 auto tex = std::make_unique<Texture>();
124 auto gpu = std::make_unique<GpuTexture>();
125 gpu->width = int(width);
126 gpu->height = int(height);
127 gpu->mipLevels = levels;
128 gpu->samplerState = TextureSampler::linearMipmap();
129 UploadScopes scopes(device);
130 wgpu::TextureDescriptor descriptor{};
131 descriptor.dimension = wgpu::TextureDimension::e2D;
132 descriptor.size = {width, height, 1};
133 descriptor.format = wgpu::TextureFormat::RGBA8Unorm;
134 descriptor.mipLevelCount = levels;
135 descriptor.sampleCount = 1;
136 descriptor.usage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopyDst;
137 gpu->texture = device.CreateTexture(&descriptor);
138 if (!gpu->texture) {
139 auto checked = scopes.finish(instance);
140 if (!checked) return fail(DiagnosticCode::Failed, checked.error()->message());
141 return fail(DiagnosticCode::Failed, "WebGPU mip texture allocation returned no object");
142 }
143 w = width;
144 h = height;
145 size_t offset = 0;
146 for (uint32_t level = 0; level < levels; ++level) {
147 wgpu::TexelCopyTextureInfo destination{};
148 destination.texture = gpu->texture;
149 destination.mipLevel = level;
150 wgpu::TexelCopyBufferLayout layout{};
151 layout.bytesPerRow = w * 4;
152 layout.rowsPerImage = h;
153 wgpu::Extent3D extent{w, h, 1};
154 const size_t bytes = size_t(w) * h * 4;
155 queue.WriteTexture(&destination, rgba.data() + offset, bytes, &layout, &extent);
156 offset += bytes;
157 w = std::max(w / 2, 1u);
158 h = std::max(h / 2, 1u);
159 }
160 gpu->view = gpu->texture.CreateView();
161 gpu->sampler = makeSampler(gpu->samplerState, levels);
162 auto checked = scopes.finish(instance);
163 if (!checked) return fail(DiagnosticCode::Failed, checked.error()->message());
164 if (!gpu->view || !gpu->sampler)
165 return fail(DiagnosticCode::Failed, "WebGPU mip view or sampler allocation returned no object");
166 tex->width = tex->pixelWidth = int(width);
167 tex->height = tex->pixelHeight = int(height);
168 tex->mipmapCount = int(levels);
169 tex->sampler = gpu->samplerState;
170 tex->gpuHandle = gpu.get();
171 auto* result = tex.get();
172 ownedTextures.push_back(std::move(tex));
173 ownedGpuTextures.push_back(std::move(gpu));
175 } catch (const std::exception& error) {
176 return fail(DiagnosticCode::Failed, error.what());
177 }
178}
179
181 std::span<const uint16_t> rgbaHalf) {
182 auto fail = [](DiagnosticCode code, std::string message) {
184 Diagnostic::error(code, message, {}, {}, "graphics.texture.array"));
185 };
186 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
187 wgpu::Limits limits{};
188 const uint64_t texels = uint64_t(width) * height * layers;
189 if (device.GetLimits(&limits) != wgpu::Status::Success || !width || !height || !layers ||
190 width > limits.maxTextureDimension2D || height > limits.maxTextureDimension2D ||
191 layers > limits.maxTextureArrayLayers || texels > SIZE_MAX / 4u || rgbaHalf.size() != texels * 4u)
192 return fail(DiagnosticCode::InvalidArgument, "array dimensions or packed RGBA16F size are invalid");
193 try {
194 ownedTextures.reserve(ownedTextures.size() + 1u);
195 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1u);
196 auto tex = std::make_unique<Texture>();
197 auto gpu = std::make_unique<GpuTexture>();
198 gpu->width = int(width);
199 gpu->height = int(height);
200 gpu->isArray = true;
201 gpu->samplerState = TextureSampler::linear();
202 UploadScopes scopes(device);
203 wgpu::TextureDescriptor descriptor{};
204 descriptor.dimension = wgpu::TextureDimension::e2D;
205 descriptor.size = {width, height, layers};
206 descriptor.format = wgpu::TextureFormat::RGBA16Float;
207 descriptor.mipLevelCount = 1;
208 descriptor.sampleCount = 1;
209 descriptor.usage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopyDst;
210 gpu->texture = device.CreateTexture(&descriptor);
211 wgpu::TexelCopyTextureInfo destination{};
212 destination.texture = gpu->texture;
213 wgpu::TexelCopyBufferLayout layout{};
214 layout.bytesPerRow = width * 8u;
215 layout.rowsPerImage = height;
216 const wgpu::Extent3D extent{width, height, layers};
217 queue.WriteTexture(&destination, rgbaHalf.data(), rgbaHalf.size_bytes(), &layout, &extent);
218 wgpu::TextureViewDescriptor view{};
219 view.format = wgpu::TextureFormat::RGBA16Float;
220 view.dimension = wgpu::TextureViewDimension::e2DArray;
221 view.mipLevelCount = 1;
222 view.arrayLayerCount = layers;
223 gpu->view = gpu->texture.CreateView(&view);
224 gpu->sampler = makeSampler(gpu->samplerState, 1);
225 auto checked = scopes.finish(instance);
226 if (!checked) return fail(DiagnosticCode::Failed, checked.error()->message());
227 if (!gpu->texture || !gpu->view || !gpu->sampler)
228 return fail(DiagnosticCode::Failed, "WebGPU array texture allocation returned no object");
229 tex->width = tex->pixelWidth = int(width);
230 tex->height = tex->pixelHeight = int(height);
231 tex->layers = int(layers);
232 tex->sampler = gpu->samplerState;
233 tex->gpuHandle = gpu.get();
234 auto* result = tex.get();
235 ownedTextures.push_back(std::move(tex));
236 ownedGpuTextures.push_back(std::move(gpu));
238 } catch (const std::exception& error) {
239 return fail(DiagnosticCode::Failed, error.what());
240 }
241}
242
244 std::span<const uint8_t> rgba) {
245 auto fail = [](DiagnosticCode code, std::string message) {
247 Diagnostic::error(code, message, {}, {}, "graphics.texture.volume"));
248 };
249 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
250 wgpu::Limits limits{};
251 const uint64_t texels = uint64_t(width) * height * depth;
252 if (device.GetLimits(&limits) != wgpu::Status::Success || !width || !height || !depth ||
253 width > limits.maxTextureDimension3D || height > limits.maxTextureDimension3D ||
254 depth > limits.maxTextureDimension3D || texels > SIZE_MAX / 4u || rgba.size() != texels * 4u)
255 return fail(DiagnosticCode::InvalidArgument, "volume dimensions or packed RGBA8 size are invalid");
256 try {
257 ownedTextures.reserve(ownedTextures.size() + 1u);
258 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1u);
259 auto tex = std::make_unique<Texture>();
260 auto gpu = std::make_unique<GpuTexture>();
261 gpu->width = int(width);
262 gpu->height = int(height);
263 gpu->isVolume = true;
264 gpu->samplerState = TextureSampler::linear();
265 gpu->samplerState.repeatU = gpu->samplerState.repeatV = gpu->samplerState.repeatW = true;
266 UploadScopes scopes(device);
267 wgpu::TextureDescriptor descriptor{};
268 descriptor.dimension = wgpu::TextureDimension::e3D;
269 descriptor.size = {width, height, depth};
270 descriptor.format = wgpu::TextureFormat::RGBA8Unorm;
271 descriptor.mipLevelCount = 1;
272 descriptor.sampleCount = 1;
273 descriptor.usage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopyDst;
274 gpu->texture = device.CreateTexture(&descriptor);
275 wgpu::TexelCopyTextureInfo destination{};
276 destination.texture = gpu->texture;
277 wgpu::TexelCopyBufferLayout layout{};
278 layout.bytesPerRow = width * 4u;
279 layout.rowsPerImage = height;
280 const wgpu::Extent3D extent{width, height, depth};
281 queue.WriteTexture(&destination, rgba.data(), rgba.size(), &layout, &extent);
282 wgpu::TextureViewDescriptor view{};
283 view.format = wgpu::TextureFormat::RGBA8Unorm;
284 view.dimension = wgpu::TextureViewDimension::e3D;
285 view.mipLevelCount = 1;
286 view.arrayLayerCount = 1;
287 gpu->view = gpu->texture.CreateView(&view);
288 gpu->sampler = makeSampler(gpu->samplerState, 1);
289 auto checked = scopes.finish(instance);
290 if (!checked) return fail(DiagnosticCode::Failed, checked.error()->message());
291 if (!gpu->texture || !gpu->view || !gpu->sampler)
292 return fail(DiagnosticCode::Failed, "WebGPU volume texture allocation returned no object");
293 tex->width = tex->pixelWidth = int(width);
294 tex->height = tex->pixelHeight = int(height);
295 tex->depth = int(depth);
296 tex->sampler = gpu->samplerState;
297 tex->gpuHandle = gpu.get();
298 auto* result = tex.get();
299 ownedTextures.push_back(std::move(tex));
300 ownedGpuTextures.push_back(std::move(gpu));
302 } catch (const std::exception& error) {
303 return fail(DiagnosticCode::Failed, error.what());
304 }
305}
306} // namespace eve::graphics::webgpu
float w
Definition AnimClip.cpp:738
std::string descriptor
std::string layout
std::string message
DiagnosticCode code
float maximum[3]
vkb::Device & device
wgpu::PopErrorScopeStatus status
int h
std::uint32_t height
std::uint32_t width
size_t offset
std::chrono::steady_clock::time_point deadline
Poco::JSON::Object::Ptr result
bool done
std::uint64_t bytes
int level
std::shared_ptr< OceanGpuSpectrum > gpu
OceanSprayView view
std::string error
Definition Package.cpp:174
std::string filter
std::string string
int count
std::uint32_t depth
const AssetImportLimits & limits
ViewPreparation callback
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
uint32_t maxTextureDimension2D() const
Maximum 2D texture dimension the device guarantees.
Result< Texture * > newTextureArrayRgba16f(uint32_t width, uint32_t height, uint32_t layers, std::span< const uint16_t > rgbaHalf) override
Upload a sampled 2D array of tightly packed linear RGBA16F texels.
Result< Texture * > newTexture3DRgba8(uint32_t width, uint32_t height, uint32_t depth, std::span< const uint8_t > rgba) override
Upload one tightly packed linear RGBA8 3D sampled texture.
Result< Texture * > newTextureMipChain(uint32_t width, uint32_t height, uint32_t levels, std::span< const uint8_t > rgba) override
Upload complete explicit linear RGBA8 mips without regenerating pixels.
eve::Diagnostic Diagnostic
eve::Result< T > Result
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
static TextureSampler linear()
Linear.
static TextureSampler linearMipmap()
Trilinear (linear + linear mips). Caller should create the texture with generateMipmaps.