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
feat(tilemap): per-tileset-slot render batching + tileset table (multi-tileset, part 1)
yhhe0e44bdfe0e4
diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cppindex 02d00cf62..139952956 100644--- a/src/esengine/bindings/TilemapBindings.cpp+++ b/src/esengine/bindings/TilemapBindings.cpp@@ -77,6 +77,24 @@ void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count) {getTilemapSystem().setTiles(e, tiles, count);}+// Multi-tileset table: `count` slots, each 3 packed u32 [first_id, textureHandle,+// columns]. Empty table reverts the layer to its single tileset.+void tilemap_setTilesets(u32 entity, uintptr_t dataPtr, u32 count) {+ auto e = Entity::fromRaw(entity);+ if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;+ const auto* d = reinterpret_cast<const u32*>(dataPtr);+ std::vector<tilemap::TilesetSlot> slots;+ slots.reserve(count);+ for (u32 i = 0; i < count; ++i) {+ tilemap::TilesetSlot slot;+ slot.first_id = static_cast<u16>(d[i * 3 + 0]);+ slot.texture_handle = d[i * 3 + 1];+ slot.columns = d[i * 3 + 2];+ slots.push_back(slot);+ }+ getTilemapSystem().setTilesets(e, std::move(slots));+}+bool tilemap_hasLayer(u32 entity) {return getTilemapSystem().hasLayer(Entity::fromRaw(entity));}@@ -674,6 +692,7 @@ EMSCRIPTEN_BINDINGS(esengine_tilemap) {emscripten::function("tilemap_getTile", &esengine::tilemap_getTile);emscripten::function("tilemap_fillRect", &esengine::tilemap_fillRect);emscripten::function("tilemap_setTiles", &esengine::tilemap_setTiles);+ emscripten::function("tilemap_setTilesets", &esengine::tilemap_setTilesets);emscripten::function("tilemap_hasLayer", &esengine::tilemap_hasLayer);emscripten::function("tilemap_setRenderProps", &esengine::tilemap_setRenderProps);emscripten::function("tilemap_setTint", &esengine::tilemap_setTint);diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cppindex 0acb619c8..b8a0dd376 100644--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp@@ -21,11 +21,12 @@ void TilemapRenderPlugin::rebuildChunk(const tilemap::TilemapSystem::LayerData& layer,const tilemap::ChunkData& chunk, tilemap::ChunkCoord coord,f32 originX, f32 originY, u32 packedColor,- u32 tilesetColumns, f32 uvTileW, f32 uvTileH,+ const std::vector<tilemap::TilesetSlot>& slots,+ const std::vector<ResolvedSlot>& resolved,Entity entity, ChunkCache& cache) {- cache.vertices.clear();- cache.indices.clear();+ cache.slots.resize(slots.size());+ for (auto& mesh : cache.slots) { mesh.vertices.clear(); mesh.indices.clear(); }cache.has_animated_tiles = false;i32 baseX = coord.x * static_cast<i32>(tilemap::CHUNK_SIZE);@@ -53,11 +54,21 @@ void TilemapRenderPlugin::rebuildChunk(tileId = tilemap_system_->resolveAnimatedTile(entity, tileId);}+ // Resolve which tileset (slot) this tile belongs to, then its local+ // index within that tileset. A tile whose tileset texture is missing+ // is skipped.+ int slotIndex = tilemap::resolveTilesetSlot(slots, tileId);+ if (slotIndex < 0 || !resolved[slotIndex].valid) continue;+ u32 tilesetColumns = slots[slotIndex].columns;+ if (tilesetColumns == 0) continue;+ f32 uvTileW = resolved[slotIndex].uvW;+ f32 uvTileH = resolved[slotIndex].uvH;+bool flipH = (rawTile & tilemap::TILE_FLIP_H) != 0;bool flipV = (rawTile & tilemap::TILE_FLIP_V) != 0;bool flipD = (rawTile & tilemap::TILE_FLIP_D) != 0;- u32 tileIndex = tileId - 1;+ u32 tileIndex = tileId - slots[slotIndex].first_id;u32 tileCol = tileIndex % tilesetColumns;u32 tileRow = tileIndex / tilesetColumns;@@ -94,14 +105,15 @@ void TilemapRenderPlugin::rebuildChunk(glm::vec2 tr = cornerUV(1.0f, 1.0f);glm::vec2 tl = cornerUV(0.0f, 1.0f);- u32 baseVertex = static_cast<u32>(cache.vertices.size());- cache.vertices.push_back({ {worldX - hw, worldY - hh}, packedColor, {bl.x, bl.y} });- cache.vertices.push_back({ {worldX + hw, worldY - hh}, packedColor, {br.x, br.y} });- cache.vertices.push_back({ {worldX + hw, worldY + hh}, packedColor, {tr.x, tr.y} });- cache.vertices.push_back({ {worldX - hw, worldY + hh}, packedColor, {tl.x, tl.y} });+ SlotMesh& mesh = cache.slots[slotIndex];+ u32 baseVertex = static_cast<u32>(mesh.vertices.size());+ mesh.vertices.push_back({ {worldX - hw, worldY - hh}, packedColor, {bl.x, bl.y} });+ mesh.vertices.push_back({ {worldX + hw, worldY - hh}, packedColor, {br.x, br.y} });+ mesh.vertices.push_back({ {worldX + hw, worldY + hh}, packedColor, {tr.x, tr.y} });+ mesh.vertices.push_back({ {worldX - hw, worldY + hh}, packedColor, {tl.x, tl.y} });for (u32 i = 0; i < 6; ++i) {- cache.indices.push_back(baseVertex + BATCH_QUAD_INDICES[i]);+ mesh.indices.push_back(baseVertex + BATCH_QUAD_INDICES[i]);}}}@@ -134,46 +146,62 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {const ecs::TilemapLayer* comp = registry.tryGet<ecs::TilemapLayer>(entity);bool visible;- resource::TextureHandle tilesetHandle;- u32 tilesetColumns;i32 sortLayer;f32 depth;glm::vec4 tint;f32 opacity;glm::vec2 parallax;+ resource::TextureHandle singleTileset; // single-tileset fallback source+ u32 singleColumns;if (comp) {visible = comp->visible;- tilesetHandle = comp->tileset;- tilesetColumns = static_cast<u32>(comp->tilesetColumns);sortLayer = comp->renderLayer;depth = 0.0f;tint = comp->tintColor;opacity = comp->opacity;parallax = comp->parallaxFactor;+ singleTileset = comp->tileset;+ singleColumns = static_cast<u32>(comp->tilesetColumns);} else {visible = layer.visible;- tilesetHandle = resource::TextureHandle(layer.texture_handle);- tilesetColumns = layer.tileset_columns;sortLayer = layer.sort_layer;depth = layer.depth;tint = layer.tint;opacity = layer.opacity;parallax = layer.parallax_factor;+ singleTileset = resource::TextureHandle(layer.texture_handle);+ singleColumns = layer.tileset_columns;}- if (!visible || !tilesetHandle.isValid() || tilesetColumns == 0) continue;+ if (!visible) continue;- auto* texRes = ctx.resources.getTexture(tilesetHandle);- if (!texRes) continue;- u32 glTextureId = texRes->getId();+ // The layer's tileset slot list: the multi-tileset table when present+ // (Tiled imports), else a single slot from the painted/synthetic tileset.+ std::vector<tilemap::TilesetSlot> slots;+ if (!layer.tilesets.empty()) {+ slots = layer.tilesets;+ } else {+ if (!singleTileset.isValid() || singleColumns == 0) continue;+ slots.push_back(tilemap::TilesetSlot{ 1, singleTileset.id(), singleColumns });+ }- // UVs derive from tile size / texture size — the single source is the- // tile dimensions + the texture, so there is no synced uv copy to drift.- f32 texW = static_cast<f32>(texRes->getWidth());- f32 texH = static_cast<f32>(texRes->getHeight());- if (texW <= 0.0f || texH <= 0.0f) continue;- f32 uvTileW = layer.tile_width / texW;- f32 uvTileH = layer.tile_height / texH;+ // Resolve each slot's texture + UV scale (tile size / texture size). Kept+ // parallel to `slots`; a slot whose texture is missing renders nothing.+ std::vector<ResolvedSlot> resolved(slots.size());+ bool anySlotValid = false;+ for (usize i = 0; i < slots.size(); ++i) {+ auto* tex = ctx.resources.getTexture(resource::TextureHandle(slots[i].texture_handle));+ if (!tex) continue;+ f32 tw = static_cast<f32>(tex->getWidth());+ f32 th = static_cast<f32>(tex->getHeight());+ if (tw <= 0.0f || th <= 0.0f) continue;+ resolved[i].valid = true;+ resolved[i].glTexId = tex->getId();+ resolved[i].uvW = layer.tile_width / tw;+ resolved[i].uvH = layer.tile_height / th;+ anySlotValid = true;+ }+ if (!anySlotValid) continue;f32 originX = 0, originY = 0;Entity transformEntity = (layer.origin_entity != INVALID_ENTITY)@@ -215,8 +243,9 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {auto& chunkCaches = layer_caches_[entity];- vertices_.clear();- indices_.clear();+ // Per-slot merged geometry for this layer (one draw call per slot/texture).+ std::vector<std::vector<BatchVertex>> slotVertices(slots.size());+ std::vector<std::vector<u32>> slotIndices(slots.size());for (i32 cy = minCY; cy < maxCY; ++cy) {for (i32 cx = minCX; cx < maxCX; ++cx) {@@ -227,41 +256,46 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {const auto& chunkData = chunkIt->second;auto& cache = chunkCaches[coord];- if (chunkData.revision != cache.built_revision || cache.has_animated_tiles) {+ if (chunkData.revision != cache.built_revision+ || cache.has_animated_tiles+ || cache.slots.size() != slots.size()) {rebuildChunk(layer, chunkData, coord,adjOriginX, adjOriginY, packedColor,- tilesetColumns, uvTileW, uvTileH,- entity, cache);+ slots, resolved, entity, cache);cache.built_revision = chunkData.revision;}- if (cache.indices.empty()) continue;-- u32 baseVertex = static_cast<u32>(vertices_.size());- vertices_.insert(vertices_.end(), cache.vertices.begin(), cache.vertices.end());- for (u32 idx : cache.indices) {- indices_.push_back(baseVertex + idx);+ for (usize si = 0; si < slots.size() && si < cache.slots.size(); ++si) {+ const SlotMesh& mesh = cache.slots[si];+ if (mesh.indices.empty()) continue;+ u32 baseVertex = static_cast<u32>(slotVertices[si].size());+ slotVertices[si].insert(slotVertices[si].end(),+ mesh.vertices.begin(), mesh.vertices.end());+ for (u32 idx : mesh.indices) {+ slotIndices[si].push_back(baseVertex + idx);+ }}}}- if (indices_.empty()) continue;-- // indices_ are 0-based within the merged vertices_; appendIndexedBatch rebases them- // onto the pool's baseVertex and assembles the command.- appendIndexedBatch(buffers, draw_list, clips,- vertices_.data(), static_cast<u32>(vertices_.size()),- indices_.data(), static_cast<u32>(indices_.size()),- BatchDrawKey{- .stage = ctx.current_stage,- .layer = sortLayer,- .shaderId = batch_shader_id_,- .blend = BlendMode::Normal,- .textureId = glTextureId,- .depth = depth,- .entity = entity,- .type = RenderType::Sprite,- });+ // Emit one batch per tileset slot that produced geometry. Indices are+ // 0-based within each slot's merged vertices; appendIndexedBatch rebases them.+ for (usize si = 0; si < slots.size(); ++si) {+ if (!resolved[si].valid || slotIndices[si].empty()) continue;+ appendIndexedBatch(buffers, draw_list, clips,+ slotVertices[si].data(), static_cast<u32>(slotVertices[si].size()),+ slotIndices[si].data(), static_cast<u32>(slotIndices[si].size()),+ BatchDrawKey{+ .stage = ctx.current_stage,+ .layer = sortLayer,+ .shaderId = batch_shader_id_,+ .blend = BlendMode::Normal,+ .textureId = resolved[si].glTexId,+ .depth = depth,+ .entity = entity,+ .type = RenderType::Sprite,+ });+ }}for (auto it = layer_caches_.begin(); it != layer_caches_.end(); ) {diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.hppindex 2255533f6..ec6ad0d1a 100644--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp@@ -24,9 +24,14 @@ public:void collect(RenderCollectContext& ctx) override;private:- struct ChunkCache {+ // Per-tileset-slot geometry for one chunk. A multi-tileset layer splits a+ // chunk's tiles across slots (one texture each) so each becomes its own batch.+ struct SlotMesh {std::vector<BatchVertex> vertices;std::vector<u32> indices;+ };+ struct ChunkCache {+ std::vector<SlotMesh> slots; // indexed by the layer's render-slot orderbool has_animated_tiles = false;// Revision of the content chunk this cache was last built from. Compared// against ChunkData::revision so we rebuild only on real edits — the@@ -34,21 +39,27 @@ private:u32 built_revision = 0;};+ // A layer slot with its texture resolved for the current frame.+ struct ResolvedSlot {+ u32 glTexId = 0;+ f32 uvW = 0.0f;+ f32 uvH = 0.0f;+ bool valid = false;+ };+using ChunkMap = std::unordered_map<tilemap::ChunkCoord, ChunkCache, tilemap::ChunkCoordHash>;using LayerChunkMap = std::unordered_map<Entity, ChunkMap>;void rebuildChunk(const tilemap::TilemapSystem::LayerData& layer,const tilemap::ChunkData& chunk, tilemap::ChunkCoord coord,f32 originX, f32 originY, u32 packedColor,- u32 tilesetColumns, f32 uvTileW, f32 uvTileH,+ const std::vector<tilemap::TilesetSlot>& slots,+ const std::vector<ResolvedSlot>& resolved,Entity entity, ChunkCache& cache);tilemap::TilemapSystem* tilemap_system_ = nullptr;u32 batch_shader_id_ = 0;LayerChunkMap layer_caches_;-- std::vector<BatchVertex> vertices_;- std::vector<u32> indices_;};} // namespace esenginediff --git a/src/esengine/tilemap/TilemapSystem.cpp b/src/esengine/tilemap/TilemapSystem.cppindex d1bfe6869..9e9c3afe7 100644--- a/src/esengine/tilemap/TilemapSystem.cpp+++ b/src/esengine/tilemap/TilemapSystem.cpp@@ -211,6 +211,14 @@ void TilemapSystem::setRenderProps(Entity entity, u32 textureHandle, u32 tilesetlayer->parallax_factor = {parallaxX, parallaxY};}+void TilemapSystem::setTilesets(Entity entity, std::vector<TilesetSlot> slots) {+ auto* layer = getLayerDataMut(entity);+ if (!layer) return;+ std::sort(slots.begin(), slots.end(),+ [](const TilesetSlot& a, const TilesetSlot& b) { return a.first_id < b.first_id; });+ layer->tilesets = std::move(slots);+}+void TilemapSystem::setTint(Entity entity, f32 r, f32 g, f32 b, f32 a, f32 opacity) {auto* layer = getLayerDataMut(entity);if (!layer) return;diff --git a/src/esengine/tilemap/TilemapSystem.hpp b/src/esengine/tilemap/TilemapSystem.hppindex a323f5b9c..6ed4ebe9b 100644--- a/src/esengine/tilemap/TilemapSystem.hpp+++ b/src/esengine/tilemap/TilemapSystem.hpp@@ -3,6 +3,7 @@#pragma once#include "../core/Types.hpp"+#include "TilesetTable.hpp"#include <glm/glm.hpp>#include <string>@@ -106,10 +107,17 @@ public:f32 tile_width = 0;f32 tile_height = 0;+ // Single-tileset fields (kept for painted layers / the single-tileset+ // fallback). Multi-tileset layers (e.g. Tiled imports) instead populate+ // `tilesets` below; when it is non-empty the renderer uses it and these+ // are ignored.u32 texture_handle = 0;u32 tileset_columns = 1;f32 uv_tile_width = 0;f32 uv_tile_height = 0;++ // Multi-tileset table (sorted by first_id). Empty = single-tileset layer.+ std::vector<TilesetSlot> tilesets;i32 sort_layer = 0;f32 depth = 0;glm::vec4 tint{1.0f, 1.0f, 1.0f, 1.0f};@@ -140,6 +148,10 @@ public:f32 uvTileW, f32 uvTileH,i32 sortLayer, f32 depth,f32 parallaxX, f32 parallaxY);++ // Replace the layer's multi-tileset table (sorted ascending by first_id).+ // Passing an empty table reverts the layer to the single-tileset fields.+ void setTilesets(Entity entity, std::vector<TilesetSlot> slots);void setTint(Entity entity, f32 r, f32 g, f32 b, f32 a, f32 opacity);void setVisible(Entity entity, bool visible);void setOriginEntity(Entity layerKey, Entity originEntity);diff --git a/src/esengine/tilemap/TilesetTable.hpp b/src/esengine/tilemap/TilesetTable.hppnew file mode 100644index 000000000..8bf17a0d7--- /dev/null+++ b/src/esengine/tilemap/TilesetTable.hpp@@ -0,0 +1,44 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file TilesetTable.hpp+ * @brief Per-layer tileset table + GID→tileset resolution (dependency-free).+ *+ * A layer can reference several tilesets (as Tiled maps do). Tile ids are global+ * and contiguous across tilesets (matching Tiled GIDs): each tileset starts at a+ * `first_id`, so an id resolves to (tileset, local index) via the largest+ * `first_id <= id`. A single-tileset layer is just one slot with first_id == 1.+ */+#pragma once++#include <cstdint>+#include <vector>++namespace esengine {+namespace tilemap {++struct TilesetSlot {+ uint16_t first_id = 1; // global tile-id at which this tileset begins (Tiled firstgid)+ uint32_t texture_handle = 0; // resource::TextureHandle id+ uint32_t columns = 1; // tiles per row in the tileset texture+};++/**+ * Index of the slot owning @p id — the one with the largest first_id <= id.+ * Returns -1 if none (id below the first slot, or empty table). @p slots must be+ * sorted ascending by first_id (TilemapSystem::setTilesets guarantees this).+ */+inline int resolveTilesetSlot(const std::vector<TilesetSlot>& slots, uint16_t id) {+ int found = -1;+ for (std::size_t i = 0; i < slots.size(); ++i) {+ if (id >= slots[i].first_id) {+ found = static_cast<int>(i);+ } else {+ break;+ }+ }+ return found;+}++} // namespace tilemap+} // namespace esenginediff --git a/tests/tilemap/test_tilemap.cpp b/tests/tilemap/test_tilemap.cppindex e41238a4c..8721f7154 100644--- a/tests/tilemap/test_tilemap.cpp+++ b/tests/tilemap/test_tilemap.cpp@@ -244,3 +244,31 @@ TEST_CASE("tilemap_tile_flip_uv") {CHECK(uv(1,1, true,true,false) == P{0,0});}}++TEST_CASE("tilemap_resolve_tileset_slot") {+ // A tile id resolves to the slot with the largest first_id <= id. Slots are+ // sorted ascending; -1 means no owning tileset.+ SUBCASE("empty table") {+ std::vector<TilesetSlot> slots;+ CHECK_EQ(resolveTilesetSlot(slots, 1), -1);+ }+ SUBCASE("single tileset starting at 1") {+ std::vector<TilesetSlot> slots{ {1, 100, 4} };+ CHECK_EQ(resolveTilesetSlot(slots, 1), 0);+ CHECK_EQ(resolveTilesetSlot(slots, 4), 0);+ CHECK_EQ(resolveTilesetSlot(slots, 9999), 0);+ }+ SUBCASE("two tilesets — pick by first_id range") {+ std::vector<TilesetSlot> slots{ {1, 100, 4}, {5, 200, 8} };+ CHECK_EQ(resolveTilesetSlot(slots, 1), 0);+ CHECK_EQ(resolveTilesetSlot(slots, 4), 0);+ CHECK_EQ(resolveTilesetSlot(slots, 5), 1); // firstgid boundary of tileset 2+ CHECK_EQ(resolveTilesetSlot(slots, 12), 1);+ }+ SUBCASE("three tilesets") {+ std::vector<TilesetSlot> slots{ {1, 1, 4}, {5, 2, 4}, {9, 3, 4} };+ CHECK_EQ(resolveTilesetSlot(slots, 7), 1);+ CHECK_EQ(resolveTilesetSlot(slots, 9), 2);+ CHECK_EQ(resolveTilesetSlot(slots, 20), 2);+ }+}