载入中...
搜索中...
未找到
GraphicsResourceUpdates.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <memory>
3#include "common/Exception.h"
4#include "common/Resource.h"
6#include "graphics/Mesh.h"
7#include "graphics/Texture.h"
10#include "image/Image.h"
11#include "image/ImageData.h"
12namespace eve::graphics::webgpu {
13namespace {
14std::string normalizeTexPath(std::string path) {
15 std::replace(path.begin(), path.end(), '\\', '/');
16 while (path.starts_with("./")) path.erase(0, 2);
17 while (path.size() > 1 && path.back() == '/') path.pop_back();
18 return path;
19}
20} // namespace
21ResultRef<Texture> Graphics::requestFileTexture(const std::string& filename) {
22 if (filename.empty())
24 DiagnosticCode::InvalidArgument, "file texture path is empty", {}, {}, "graphics.texture.request"));
25 try {
26 const std::string key = normalizeTexPath(filename);
27 auto it = texturesByPath.find(key);
28 if (it != texturesByPath.end() && it->second) return ResultRef<Texture>::success(std::ref(*it->second));
31 "file texture source is absent: " + filename, {}, {},
32 "graphics.texture.request"));
33#if defined(__EMSCRIPTEN__)
34 // Browser frames run on the main thread. Decode packaged file pixels
35 // before returning so present() never waits on a pthread there.
37 if (!decoded.ok()) return ResultRef<Texture>::failure(decoded.status());
38#else
40#endif
41 auto texture = std::make_unique<Texture>();
42 texture->markDeferredFilePixels(this);
43 Texture* raw = texture.get();
44 DeferredFileTexture pending{key, raw};
45 if (ownedTextures.size() == ownedTextures.capacity())
46 ownedTextures.reserve(std::max(size_t(1), ownedTextures.capacity() * 2));
47 if (deferredFileTextures_.size() == deferredFileTextures_.capacity())
48 deferredFileTextures_.reserve(std::max(size_t(1), deferredFileTextures_.capacity() * 2));
49 texturesByPath.insert_or_assign(key, raw);
50 ownedTextures.push_back(std::move(texture));
51 deferredFileTextures_.push_back(std::move(pending));
52 return ResultRef<Texture>::success(std::ref(*raw));
53 } catch (const std::exception& error) {
55 Diagnostic::error(DiagnosticCode::Failed, error.what(), {}, {}, "graphics.texture.request"));
56 }
57}
58
60 if (!texture || !data) return false;
61 if (texture->gpuHandle)
62 return updateTexture(texture, data->getWidth(), data->getHeight(),
63 static_cast<const uint8_t*>(data->getData()));
65 info.sampler = texture->sampler;
66 Texture* fresh = newTexture(data, info);
67 if (!fresh || !fresh->gpuHandle) return false;
68 texture->gpuHandle = fresh->gpuHandle;
69 texture->width = fresh->width;
70 texture->height = fresh->height;
71 texture->pixelWidth = fresh->pixelWidth;
72 texture->pixelHeight = fresh->pixelHeight;
73 texture->mipmapCount = fresh->mipmapCount;
74 texture->sampler = fresh->sampler;
75 fresh->gpuHandle = nullptr;
76 auto texIt = std::find_if(ownedTextures.begin(), ownedTextures.end(),
77 [&](const std::unique_ptr<Texture>& t) { return t.get() == fresh; });
78 if (texIt == ownedTextures.end()) return false;
79 (void)texIt->release();
80 ownedTextures.erase(texIt);
81 delete fresh;
82 return true;
83}
84
85bool Graphics::reloadTextureFromFile(const std::string& filename) {
86 const std::string key = normalizeTexPath(filename);
87 auto it = texturesByPath.find(key);
88 if (it == texturesByPath.end()) return false;
89
91 applyPendingResourceChanges();
92
93 // The provider hands back a cache-owned ImageData; the pin keeps it alive until
94 // the pixels have been copied out of it.
95 image::ImageData* data = nullptr;
96 eve::ResourcePin keepAlive;
97 try {
98 auto* imgMod = image::Image::create();
99 data = imgMod->newImageDataFromFile(filename);
100 if (data != nullptr) {
102 if (!pinned.ok()) return false;
103 keepAlive = std::move(pinned).takeValue();
104 // The pin is the authority from here on; the borrowed pointer may have gone
105 // stale before the pin was taken.
106 data = static_cast<image::ImageData*>(keepAlive.get());
107 }
108 } catch (...) {
109 return false;
110 }
111 if (!data) return false;
112
113 Texture* tex = it->second;
114 return updateTexture(tex, data->getWidth(), data->getHeight(), static_cast<const uint8_t*>(data->getData()));
115}
116
117bool Graphics::updateMeshVertices(Mesh* mesh, const float* posXYZ, const float* nrmXYZ, const float* uvST,
118 int vertexCount, const uint32_t* indices, int indexCount) {
119 if (!mesh || !mesh->gpuHandle || !posXYZ || vertexCount <= 0 || indexCount < 0) return false;
120 if (indexCount > 0 && (!indices || indexCount % 3 != 0)) return false;
121 for (int i = 0; i < indexCount; ++i) {
122 if (indices[i] >= uint32_t(vertexCount)) return false;
123 }
124 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
125 const auto owned =
126 std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
127 [gpu](const std::unique_ptr<GpuMesh>& candidate) { return candidate.get() == gpu; });
128 if (owned == ownedGpuMeshes.end()) return false;
129
130 auto& verts = gpu->updateVertices;
131 verts.clear();
132 verts.reserve(size_t(vertexCount) * 8u);
133 for (int i = 0; i < vertexCount; ++i) {
134 verts.insert(verts.end(), posXYZ + size_t(i) * 3u, posXYZ + size_t(i) * 3u + 3u);
135 if (nrmXYZ)
136 verts.insert(verts.end(), nrmXYZ + size_t(i) * 3u, nrmXYZ + size_t(i) * 3u + 3u);
137 else
138 verts.insert(verts.end(), {0.f, 0.f, 1.f});
139 if (uvST)
140 verts.insert(verts.end(), uvST + size_t(i) * 2u, uvST + size_t(i) * 2u + 2u);
141 else
142 verts.insert(verts.end(), {0.f, 0.f});
143 }
144
145 const uint64_t vertexBytes = verts.size() * sizeof(float);
146 if (vertexBytes > gpu->vertexCapacity) {
147 WGPUBufferDescriptor desc{};
148 desc.label = sv("eve_mesh_dynamic_vb");
149 desc.size = vertexBytes;
150 desc.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex | WGPUBufferUsage_Storage;
151 gpu->vertexBuffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&desc));
152 gpu->vertexCapacity = vertexBytes;
153 }
154 queue.WriteBuffer(gpu->vertexBuffer, 0, verts.data(), vertexBytes);
155 gpu->vertexCount = uint32_t(vertexCount);
156
157 if (indexCount > 0) {
158 const wgpu::IndexFormat format = vertexCount <= 65535 ? wgpu::IndexFormat::Uint16 : wgpu::IndexFormat::Uint32;
159 auto& idx16 = gpu->updateIndices16;
160 idx16.clear();
161 const void* indexData = indices;
162 uint64_t indexBytes = uint64_t(indexCount) * sizeof(uint32_t);
163 if (format == wgpu::IndexFormat::Uint16) {
164 idx16.reserve(size_t(indexCount) + 1u);
165 for (int i = 0; i < indexCount; ++i) idx16.push_back(uint16_t(indices[i]));
166 if (idx16.size() % 2 != 0) idx16.push_back(0);
167 indexData = idx16.data();
168 indexBytes = idx16.size() * sizeof(uint16_t);
169 }
170 if (format != gpu->indexFormat || indexBytes > gpu->indexCapacity) {
171 WGPUBufferDescriptor desc{};
172 desc.label = sv("eve_mesh_dynamic_ib");
173 desc.size = indexBytes;
174 desc.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index | WGPUBufferUsage_Storage;
175 gpu->indexBuffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&desc));
176 gpu->indexCapacity = indexBytes;
177 }
178 queue.WriteBuffer(gpu->indexBuffer, 0, indexData, indexBytes);
179 gpu->indexFormat = format;
180 gpu->indexCount = uint32_t(indexCount);
181 }
182
183 mesh->computeBounds(posXYZ, vertexCount);
184 mesh->gpuVertexCount = int(gpu->vertexCount);
185 mesh->indexCount = int(gpu->indexCount);
186 return true;
187}
188} // namespace eve::graphics::webgpu
ActiveSource owned
std::vector< QuestEvent > pending
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
SQObjectPtr key
Definition ECS.cpp:155
double raw
scene::NodeDesc desc
std::uint32_t vertexCount
std::uint32_t indexCount
std::vector< std::uint32_t > indices
eve::ResourcePin pinned
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
std::string error
Definition Package.cpp:174
Texture * texture
std::string path
Definition PlayHost.cpp:111
float t
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
eve::Result< ResourcePin > pin(Resource *resource)
Keeps one cached resource alive across unload()/clear()/reload.
Definition Resource.cpp:311
ResultRef< Resource > waitFor(std::string key)
Block until key is cached, failed, or unclaimed.
Definition Resource.cpp:226
static ResourceManager & getInstance()
Returns the instance.
Definition Resource.cpp:15
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
std::vector< DeferredFileTexture > deferredFileTextures_
Definition Graphics.h:2313
bool fileTextureSourceExists(const std::string &filename) const
File texture source exists.
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
void requestFileImageDecode(const std::string &key)
Request file image decode.
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
TextureSampler sampler
Definition Texture.h:65
bool uploadDeferredFileTexture(Texture *texture, image::ImageData *data) override
Uploads deferred file texture.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount) override
Updates mesh vertices.
bool reloadTextureFromFile(const std::string &filename) override
Creates a texture from file. @ownership Caller deletes unless documented otherwise.
bool updateTexture(Texture *texture, int width, int height, const uint8_t *rgba) override
Updates texture.
Represents raw pixel data.
Definition ImageData.h:38
RAII keep-alive for one RuntimeObjectRegistry entry.
T * get() const noexcept
Borrows the pinned object; valid until the pin is released.
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
Options for Graphics::newTexture / newCubemap. When generateMipmaps is true and sampler....
Vertex/index buffers for one mesh.
Definition Graphics.h:159
glm::uvec4 info