Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(resource): a texture survives its GPU object

esengineaae86a1a03ba
diff --git a/src/esengine/renderer/rhi/Texture.cpp b/src/esengine/renderer/rhi/Texture.cpp
index c6b9c39c0..3c0038cb3 100644
--- a/src/esengine/renderer/rhi/Texture.cpp
+++ b/src/esengine/renderer/rhi/Texture.cpp
@@ -145,6 +145,11 @@ Unique<Texture> Texture::createCompressed(GfxDevice& device, u32 width, u32 heig
return texture;
}
+void Texture::retarget(TextureHandle gpuHandle, bool owns) {
+ handle_ = gpuHandle;
+ owns_ = owns;
+}
+
Unique<Texture> Texture::createFromExternalId(GfxDevice& device, u32 glTextureId, u32 width, u32 height,
TextureFormat format) {
TextureDesc desc;
diff --git a/src/esengine/renderer/rhi/Texture.hpp b/src/esengine/renderer/rhi/Texture.hpp
index 824120d0d..5fde4ea0d 100644
--- a/src/esengine/renderer/rhi/Texture.hpp
+++ b/src/esengine/renderer/rhi/Texture.hpp
@@ -157,6 +157,20 @@ public:
TextureFormat format = TextureFormat::RGBA8,
bool flipY = false);
+ // =========================================================================
+ // Device Loss
+ // =========================================================================
+
+ /**
+ * @brief Points this texture at a different GPU object, keeping its identity.
+ * @details How a device loss stays invisible above: the resource::Handle
+ * naming this Texture never changes, so no component, material or
+ * font has to learn that the pixels were re-uploaded. The old GPU
+ * object is NOT deleted — it died with the device.
+ * @param owns Whether this Texture should free @p gpuHandle at destruction.
+ */
+ void retarget(TextureHandle gpuHandle, bool owns);
+
// =========================================================================
// Operations
// =========================================================================
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 79a764c62..49b776a13 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -266,6 +266,45 @@ TextureHandle ResourceManager::registerExternalTexture(u32 glTextureId, u32 widt
return textures_.add(std::move(texture), "", bytes);
}
+void ResourceManager::invalidateGpuTextures(::esengine::TextureHandle placeholder) {
+ awaitingReupload_.clear();
+ textures_.forEachAlive([&](TextureHandle handle, Texture& texture) {
+ // Retargeted, never deleted: the GPU object is already gone, and asking
+ // a dead device to free its id is at best a no-op. owns=false so the
+ // shared placeholder is not freed when one of them is released.
+ texture.retarget(placeholder, /*owns=*/false);
+ awaitingReupload_.push_back(handle);
+ });
+ ES_LOG_INFO("Device loss: {} texture(s) now on the placeholder, awaiting re-upload",
+ awaitingReupload_.size());
+}
+
+bool ResourceManager::retargetExternalTexture(TextureHandle handle, u32 glTextureId,
+ u32 width, u32 height) {
+ if (!device_) return false;
+ Texture* texture = textures_.get(handle);
+ if (!texture) return false;
+
+ TextureDesc desc;
+ desc.width = width;
+ desc.height = height;
+ desc.format = GfxPixelFormat::RGBA8;
+ texture->retarget(device_->importExternalTexture(glTextureId, desc), /*owns=*/false);
+
+ for (usize i = 0; i < awaitingReupload_.size(); ++i) {
+ if (awaitingReupload_[i] == handle) {
+ awaitingReupload_[i] = awaitingReupload_.back();
+ awaitingReupload_.pop_back();
+ break;
+ }
+ }
+ return true;
+}
+
+std::vector<TextureHandle> ResourceManager::texturesAwaitingReupload() const {
+ return awaitingReupload_;
+}
+
void ResourceManager::registerTextureWithPath(TextureHandle handle, const std::string& path) {
if (handle.isValid() && !path.empty()) {
textures_.setPath(handle, path);
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 606658d1c..e7fe84fb0 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -285,6 +285,28 @@ public:
*/
void registerTextureWithPath(TextureHandle handle, const std::string& path);
+ // =========================================================================
+ // Device Loss
+ // =========================================================================
+
+ /**
+ * @brief Points every texture at @p placeholder, keeping all handles valid.
+ * @details The GPU objects died with the device; the handles did not. They
+ * are pool indices, and components, materials and fonts all name
+ * textures by them, so re-uploading behind one is invisible.
+ * Sampling the placeholder meanwhile renders pale, not garbage.
+ */
+ void invalidateGpuTextures(::esengine::TextureHandle placeholder);
+
+ /**
+ * @brief Re-points an existing handle at a freshly uploaded GPU texture.
+ * @return False if the handle names no live texture.
+ */
+ bool retargetExternalTexture(TextureHandle handle, u32 glTextureId, u32 width, u32 height);
+
+ /** @brief Texture handles that were invalidated and not yet re-uploaded. */
+ std::vector<TextureHandle> texturesAwaitingReupload() const;
+
/**
* @brief Gets the cached path for a texture
* @param handle The texture handle
@@ -532,6 +554,9 @@ private:
ResourcePool<VertexBuffer> vertexBuffers_;
ResourcePool<IndexBuffer> indexBuffers_;
ResourcePool<text::BitmapFont> fonts_;
+ /// Handles whose GPU texture died with the device, still showing the
+ /// placeholder. Empty means the content is whole again.
+ std::vector<TextureHandle> awaitingReupload_;
std::unordered_map<std::string, TextureHandle> guidToTexture_;
std::unordered_map<TextureHandle::IdType, TextureMetadata> textureMetadata_;
LoaderRegistry loaderRegistry_;
diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hpp
index 7d014db62..a672b2ee0 100644
--- a/src/esengine/resource/ResourcePool.hpp
+++ b/src/esengine/resource/ResourcePool.hpp
@@ -138,6 +138,21 @@ public:
return handle;
}
+ /**
+ * @brief Visits every live resource, with the handle naming it.
+ * @details For sweeps that must reach resources by identity rather than by
+ * path — a device loss invalidates all of them, including the ones
+ * created from pixels and never given a path.
+ */
+ template<typename Fn>
+ void forEachAlive(Fn&& fn) {
+ for (usize i = 1; i < entries_.size(); ++i) {
+ Entry& entry = entries_[i];
+ if (!entry.resource) continue;
+ fn(Handle<T>::fromParts(static_cast<u32>(i), entry.generation), *entry.resource);
+ }
+ }
+
/**
* @brief Gets a resource by handle
* @param handle The resource handle
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 6684e0b52..f5b491dab 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -122,6 +122,7 @@ add_test(NAME test_buffer_device COMMAND test_buffer_device)
# Header-only, so nothing but Log.cpp is needed to link.
add_executable(test_device_loss
renderer/test_device_loss.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/rhi/Texture.cpp
${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
)
target_include_directories(test_device_loss PRIVATE ${CMAKE_SOURCE_DIR}/src)
diff --git a/tests/renderer/test_device_loss.cpp b/tests/renderer/test_device_loss.cpp
index 92271a042..eabeab917 100644
--- a/tests/renderer/test_device_loss.cpp
+++ b/tests/renderer/test_device_loss.cpp
@@ -5,6 +5,8 @@
#include "MockGfxDevice.hpp"
#include "esengine/renderer/rhi/GfxEnums.hpp"
+#include "esengine/renderer/rhi/Texture.hpp"
+#include "esengine/resource/ResourcePool.hpp"
#include <cstdio>
#include <string>
@@ -149,6 +151,42 @@ int main() {
CHECK(dead.deviceStatus() == GfxDeviceStatus::Dead, "it stays Dead");
}
+ // --- The identity that survives the loss ---
+ //
+ // The recovery design rests on this: a pool handle names the Texture, not the
+ // GPU object, so re-uploading behind it is invisible to every holder.
+ {
+ MockGfxDevice d;
+ resource::ResourcePool<Texture> pool;
+
+ auto first = Texture::createFromExternalId(d, 41, 64, 64, TextureFormat::RGBA8);
+ auto second = Texture::createFromExternalId(d, 42, 32, 32, TextureFormat::RGBA8);
+ const resource::Handle<Texture> hA = pool.add(std::move(first));
+ const resource::Handle<Texture> hB = pool.add(std::move(second));
+ CHECK(pool.get(hA)->handle() == static_cast<TextureHandle>(41u),
+ "a texture starts on the GPU object it was registered with");
+
+ // A loss: every live texture is swept onto a placeholder.
+ const auto placeholder = static_cast<TextureHandle>(999u);
+ int swept = 0;
+ pool.forEachAlive([&](resource::Handle<Texture>, Texture& texture) {
+ texture.retarget(placeholder, /*owns=*/false);
+ ++swept;
+ });
+ CHECK(swept == 2, "forEachAlive reaches every live texture, path or no path");
+ CHECK(pool.get(hA)->handle() == placeholder, "sampling falls back to the placeholder");
+ CHECK(pool.get(hB)->handle() == placeholder, "for all of them");
+
+ // The re-upload: a NEW GPU object behind the SAME handle.
+ pool.get(hA)->retarget(static_cast<TextureHandle>(77u), /*owns=*/false);
+ CHECK(pool.get(hA)->handle() == static_cast<TextureHandle>(77u),
+ "a re-uploaded texture points at its new GPU object");
+ CHECK(pool.get(hA) != nullptr && pool.get(hB) != nullptr,
+ "and both handles still resolve — nothing above had to be told");
+ CHECK(pool.get(hB)->handle() == placeholder,
+ "a texture not yet re-uploaded keeps showing the placeholder");
+ }
+
std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);
return g_failures ? 1 : 0;
}