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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(material): a material names its texture by handle, not by id
esengine24b75cbb20eb
diff --git a/src/esengine/bindings/MaterialBindings.cpp b/src/esengine/bindings/MaterialBindings.cppindex cf2a57b9e..7cdafeb55 100644--- a/src/esengine/bindings/MaterialBindings.cpp+++ b/src/esengine/bindings/MaterialBindings.cpp@@ -52,7 +52,7 @@ static MaterialUniformLayout buildMaterialLayout(const resource::ParsedShader& p// Resolve the param's `default(<name>)` to a built-in default texture, bound when// a material leaves the param unset.layout.textures.push_back({ p.name, static_cast<u32>(p.textureUnit),- rc.defaultTextureByName(p.defaultValue) });+ materialDefaultByName(p.defaultValue) });}} else if (p.std140Offset >= 0) {MaterialParamSlot slot{ p.name, static_cast<u32>(p.std140Offset), materialParamArity(p.type) };@@ -143,15 +143,10 @@ void material_setUniform(u32 materialId, const std::string& name, u32 arity,void material_setTexture(u32 materialId, const std::string& name, u32 textureHandle) {auto* rc = g_renderContext;if (!rc) return;- u32 gpuTexture = 0;- if (textureHandle != 0) {- if (auto* rm = g_resourceManager) {- if (Texture* t = rm->getTexture(resource::TextureHandle(textureHandle))) {- gpuTexture = t->getId();- }- }- }- rc->materials().setTexture(materialId, name, gpuTexture);+ // The handle is stored as-is. Resolving it here would freeze the material to+ // the GPU object the texture happened to have at this moment, which is the+ // one thing a re-upload behind that handle must not need to undo.+ rc->materials().setTexture(materialId, name, resource::TextureHandle(textureHandle));}void material_undefine(u32 materialId) {diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex adc862b07..18845066f 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -134,6 +134,9 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {auto renderContext = makeUnique<RenderContext>(*gfxDevicePtr);renderContext->init();+ // Materials name their textures by resource handle and resolve them per draw,+ // so the store needs the manager that owns the pool.+ renderContext->materials().setResourceManager(services_.getService<resource::ResourceManager>());services_.registerOwned<RenderContext>(std::move(renderContext));// GPU state is owned by the device: pipelines (setPipeline) carry program/blend/depth/diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cppindex e58341895..d9126e20f 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp@@ -456,11 +456,11 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, TextureHandle inputT// Texture params (LUTs, masks) bind at their reflected material units;// an unset param gets its declared default (white/black/flatnormal).for (const auto& slot : layout->textures) {- u32 glTexture = slot.defaultGlTexture;+ TextureHandle gpu = context_.materials().builtinDefault(slot.defaultTexture);for (const auto& [name, glId] : pass.textureUniforms) {- if (name == slot.name && glId != 0) { glTexture = glId; break; }+ if (name == slot.name && glId != 0) { gpu = TextureHandle{glId}; break; }}- if (glTexture != 0) device->bindTexture(slot.unit, TextureHandle{glTexture});+ if (gpu != TextureHandle::Invalid) device->bindTexture(slot.unit, gpu);}} else if (glsl) {// Legacy loose-uniform path for raw-GLSL passes (addPass with adiff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cppindex 78e24648c..b1eb3cde2 100644--- a/src/esengine/renderer/frame/RenderContext.cpp+++ b/src/esengine/renderer/frame/RenderContext.cpp@@ -43,6 +43,7 @@ void RenderContext::init() {initDefaultTextures();initFrameUbo();materials_.setDevice(&device_);+ materials_.setBuiltinDefaults(whiteTexture_, blackTexture_, flatNormalTexture_);lights_.setDevice(&device_);initialized_ = true;@@ -96,12 +97,6 @@ void RenderContext::initDefaultTextures() {static_cast<u32>(flatNormalTexture_));}-u32 RenderContext::defaultTextureByName(const std::string& name) const {- if (name == "black") return static_cast<u32>(blackTexture_);- if (name == "flatnormal" || name == "normal") return static_cast<u32>(flatNormalTexture_);- return static_cast<u32>(whiteTexture_); // "white" / empty / unknown-}-void RenderContext::initFrameUbo() {FrameConstants initial{};frameUbo_ = device_.createBuffer(diff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hppindex 5a7633f48..fc43113ba 100644--- a/src/esengine/renderer/frame/RenderContext.hpp+++ b/src/esengine/renderer/frame/RenderContext.hpp@@ -142,13 +142,6 @@ public:*/u32 getWhiteTextureId() const { return static_cast<u32>(whiteTexture_); }- /**- * @brief Texture handle value for a named built-in default texture, used to resolve a- * material texture param's `#pragma param ... texture default(<name>)`.- * @details "black" → opaque black, "flatnormal"/"normal" → a flat tangent-space normal- * (RGB 128,128,255 → (0,0,1)); anything else (incl. "white" / empty) → white.- */- u32 defaultTextureByName(const std::string& name) const;/*** @brief Uploads the per-frame view-projection into the shared FrameConstants UBO.diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 1b56bf29f..2a4f5226b 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -6,8 +6,10 @@*/#include "./MaterialStore.hpp"+#include "../../resource/ResourceManager.hpp"#include "../rhi/GfxDevice.hpp"#include "../rhi/GfxEnums.hpp"+#include "../rhi/Texture.hpp"#include "./MaterialConstants.hpp"namespace esengine {@@ -73,13 +75,31 @@ void MaterialStore::bindForDraw(u32 materialId) {// whatever stale texture is at the unit.if (lit != layouts_.end()) {for (const auto& slot : lit->second.textures) {- u32 glTexture = slot.defaultGlTexture;+ TextureHandle gpu = builtinDefault(slot.defaultTexture);for (const auto& b : rec.textures) {- if (b.unit == slot.unit) { glTexture = b.glTexture; break; }+ if (b.unit != slot.unit) continue;+ // Resolved HERE rather than cached at set time. A pool lookup is+ // an array index next to the GL call it precedes, and it is what+ // lets a texture re-uploaded behind its handle reach the material.+ if (resources_) {+ if (Texture* texture = resources_->getTexture(b.texture)) {+ gpu = texture->handle();+ }+ }+ break;}- if (glTexture != 0) device_->bindTexture(slot.unit, TextureHandle{glTexture});+ if (gpu != TextureHandle::Invalid) device_->bindTexture(slot.unit, gpu);}}}+TextureHandle MaterialStore::builtinDefault(MaterialDefaultTexture which) const {+ switch (which) {+ case MaterialDefaultTexture::Black: return defaultBlack_;+ case MaterialDefaultTexture::FlatNormal: return defaultFlatNormal_;+ case MaterialDefaultTexture::White: break;+ }+ return defaultWhite_;+}+} // namespace esenginediff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 96736f7e1..67e5bd5c1 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -23,6 +23,7 @@#pragma once#include "../../core/Types.hpp"+#include "../../resource/Handle.hpp"#include "../draw/BlendMode.hpp"#include "../rhi/GfxEnums.hpp"@@ -34,6 +35,9 @@namespace esengine {+namespace resource { class ResourceManager; }++class GfxDevice;/** @brief Triangle culling mode baked into a material's pipeline. */@@ -51,19 +55,33 @@ struct MaterialParamSlot {f32 defaults[4] = {0, 0, 0, 0}; ///< Shader-declared default(...); the block's initial value.};+/** @brief Which built-in texture a param falls back to when a material leaves it unset. */+enum class MaterialDefaultTexture : u8 { White, Black, FlatNormal };++/** @brief Maps a shader's declared `default(<name>)` to the built-in it names. */+inline MaterialDefaultTexture materialDefaultByName(const std::string& name) {+ if (name == "black") return MaterialDefaultTexture::Black;+ if (name == "flatnormal" || name == "normal") return MaterialDefaultTexture::FlatNormal;+ return MaterialDefaultTexture::White; // "white" / empty / unknown+}+/** @brief A texture param's sampler unit (>= MATERIAL_TEXTURE_UNIT_BASE, above the batch's 0..7). */struct MaterialTextureSlot {std::string name;u32 unit = 0;- /// GL texture bound when a material leaves this param unset — the shader's declared- /// `default(white|black|flatnormal)`. Resolved once when the layout is registered.- u32 defaultGlTexture = 0;+ /// The shader's declared `default(white|black|flatnormal)`, kept as the CHOICE+ /// rather than the resolved id: the built-ins are re-created when the device+ /// is, and an id resolved at registration would outlive the texture it names.+ MaterialDefaultTexture defaultTexture = MaterialDefaultTexture::White;};/** @brief A material's bound texture: the GL texture id at a sampler unit. */struct MaterialTextureBinding {u32 unit = 0;- u32 glTexture = 0;+ /// The resource handle, NOT a resolved GPU id. Resolving at bind time is what+ /// lets the texture behind it be re-uploaded — by a hot update, or by a device+ /// loss — without every material that references it having to be re-bound.+ resource::TextureHandle texture;};/** @brief A shader's layout: std140 block (scalar/vector params) + texture sampler slots. */@@ -115,6 +133,21 @@ public:/// The render path uses this device to create/upload/delete per-material UBOs.void setDevice(GfxDevice* device) { device_ = device; }+ /// Resolves texture handles at bind time; without one, texture params bind nothing.+ void setResourceManager(resource::ResourceManager* resources) { resources_ = resources; }++ /// The context's current built-in fallbacks. Pushed rather than cached from a+ /// resolved id, so re-creating them after a device loss reaches the materials too.+ void setBuiltinDefaults(TextureHandle white, TextureHandle black, TextureHandle flatNormal) {+ defaultWhite_ = white;+ defaultBlack_ = black;+ defaultFlatNormal_ = flatNormal;+ }++ /// The context's current fallback for a declared `default(...)`. One authority,+ /// so the post-process pipeline's params fall back to the same textures.+ TextureHandle builtinDefault(MaterialDefaultTexture which) const;+/// Drops every material UBO after a device loss, keeping the records so the/// scene's materialIds stay meaningful. See the definition.void recreateGpuResources();@@ -168,9 +201,9 @@ public:rec.uboDirty = true;}- /// Binds a GL texture id to a named texture param's sampler unit. No-op if the material,- /// its layout, or the texture param is unknown. Render path binds it in bindForDraw.- void setTexture(u32 materialId, const std::string& name, u32 glTexture) {+ /// Binds a texture to a named texture param's sampler unit. No-op if the material,+ /// its layout, or the texture param is unknown. Render path resolves it in bindForDraw.+ void setTexture(u32 materialId, const std::string& name, resource::TextureHandle texture) {auto it = materials_.find(materialId);if (it == materials_.end()) return;auto lit = layouts_.find(it->second.shader);@@ -178,9 +211,9 @@ public:const MaterialTextureSlot* slot = lit->second.findTexture(name);if (!slot) return;for (auto& b : it->second.textures) {- if (b.unit == slot->unit) { b.glTexture = glTexture; return; }+ if (b.unit == slot->unit) { b.texture = texture; return; }}- it->second.textures.push_back({ slot->unit, glTexture });+ it->second.textures.push_back({ slot->unit, texture });}void undefine(u32 materialId);@@ -223,6 +256,10 @@ private:std::unordered_map<u32, MaterialRecord> materials_;std::unordered_map<u32, MaterialUniformLayout> layouts_;GfxDevice* device_ = nullptr;+ resource::ResourceManager* resources_ = nullptr;+ TextureHandle defaultWhite_ = TextureHandle::Invalid;+ TextureHandle defaultBlack_ = TextureHandle::Invalid;+ TextureHandle defaultFlatNormal_ = TextureHandle::Invalid;};} // namespace esengine