Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TilemapBindings.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#ifdef ES_ENABLE_TILEMAP
4
5#include "TilemapBindings.hpp"
6
7#include "ActiveContext.hpp"
8#include "BoundarySpan.hpp"
18
19#include <cstring>
20#include <string>
21#include <utility>
22#include <vector>
23
24namespace esengine {
25
26static EstellaContext& ctx() { return activeCtx(); }
27
28static tilemap::TilemapSystem& getTilemapSystem() {
30}
31
32void tilemap_initLayer(u32 entity, u32 width, u32 height,
33 f32 tileWidth, f32 tileHeight) {
34 auto e = Entity::fromRaw(entity);
35 if (e == INVALID_ENTITY) return;
36 getTilemapSystem().initLayer(e, width, height, tileWidth, tileHeight);
37}
38
39void tilemap_initInfinite(u32 entity, f32 tileWidth, f32 tileHeight) {
40 auto e = Entity::fromRaw(entity);
41 if (e == INVALID_ENTITY) return;
42 // Idempotent for the chunk store, but always reconcile the tile size: the scene
43 // loader's importChunks auto-creates the layer with a placeholder size before the
44 // sync knows the component's cellSize, and the renderer derives UVs from tile_width.
45 if (auto* layer = getTilemapSystem().getLayerDataMut(e)) {
46 layer->tile_width = tileWidth;
47 layer->tile_height = tileHeight;
48 layer->infinite = true;
49 return;
50 }
51 getTilemapSystem().initInfiniteLayer(e, tileWidth, tileHeight);
52}
53
54void tilemap_destroyLayer(u32 entity) {
55 auto e = Entity::fromRaw(entity);
56 if (e == INVALID_ENTITY) return;
57 getTilemapSystem().destroyLayer(e);
58}
59
60void tilemap_setTile(u32 entity, i32 x, i32 y, u32 tileId) {
61 auto e = Entity::fromRaw(entity);
62 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
63 getTilemapSystem().setTile(e, x, y, static_cast<u16>(tileId));
64}
65
66u32 tilemap_getTile(u32 entity, i32 x, i32 y) {
67 auto e = Entity::fromRaw(entity);
68 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return 0;
69 return getTilemapSystem().getTile(e, x, y);
70}
71
72void tilemap_fillRect(u32 entity, i32 x, i32 y,
73 u32 w, u32 h, u32 tileId) {
74 auto e = Entity::fromRaw(entity);
75 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
76 getTilemapSystem().fillRect(e, x, y, w, h, static_cast<u16>(tileId));
77}
78
79void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count) {
80 auto e = Entity::fromRaw(entity);
81 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
82 const auto* tiles = boundarySpan<u16>(tilesPtr, count, "tilemap_setTiles");
83 if (!tiles) return;
84 getTilemapSystem().setTiles(e, tiles, count);
85}
86
87// Multi-tileset table: `count` slots, each SLOT_STRIDE packed u32
88// [first_id, textureHandle, columns, margin, spacing, extrude].
89// Empty table reverts the layer to its single tileset.
90void tilemap_setTilesets(u32 entity, uintptr_t dataPtr, u32 count) {
91 // The SDK's TILESET_SLOT_STRIDE. No generator spans this boundary, so the
92 // field list above is the contract and this number is the other half of it.
93 constexpr u32 SLOT_STRIDE = 6;
94 auto e = Entity::fromRaw(entity);
95 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
96 const auto* d = count
97 ? boundarySpan<u32>(dataPtr, static_cast<u64>(count) * SLOT_STRIDE, "tilemap_setTilesets")
98 : nullptr;
99 if (count && !d) return;
100 std::vector<tilemap::TilesetSlot> slots;
101 slots.reserve(count);
102 for (u32 i = 0; i < count; ++i) {
104 slot.first_id = static_cast<u16>(d[i * SLOT_STRIDE + 0]);
105 slot.texture_handle = d[i * SLOT_STRIDE + 1];
106 slot.columns = d[i * SLOT_STRIDE + 2];
107 slot.margin = d[i * SLOT_STRIDE + 3];
108 slot.spacing = d[i * SLOT_STRIDE + 4];
109 slot.extrude = d[i * SLOT_STRIDE + 5];
110 slots.push_back(slot);
111 }
112 getTilemapSystem().setTilesets(e, std::move(slots));
113}
114
115bool tilemap_hasLayer(u32 entity) {
116 return getTilemapSystem().hasLayer(Entity::fromRaw(entity));
117}
118
119u32 tilemap_getEditRevision(u32 entity) {
120 const auto* layer = getTilemapSystem().getLayerData(Entity::fromRaw(entity));
121 return layer ? layer->edit_revision : 0;
122}
123
124u32 tilemap_getGeneration(u32 entity) {
125 const auto* layer = getTilemapSystem().getLayerData(Entity::fromRaw(entity));
126 return layer ? layer->generation : 0;
127}
128
129u32 tilemap_readChunkIndex(u32 entity, uintptr_t rowsPtr, u32 capacity) {
130 const auto* layer = getTilemapSystem().getLayerData(Entity::fromRaw(entity));
131 const u32 count = layer ? static_cast<u32>(layer->chunks.size()) : 0;
132 if (count == 0 || capacity < count) return count;
133 auto* out = boundarySpanMut<u8>(rowsPtr, static_cast<u64>(count) * 3 * sizeof(u32), "tilemap_readChunkIndex");
134 if (!out) return 0;
135 for (const auto& [coord, chunk] : layer->chunks) {
136 std::memcpy(out, &coord.x, sizeof(i32));
137 std::memcpy(out + sizeof(u32), &coord.y, sizeof(i32));
138 std::memcpy(out + 2 * sizeof(u32), &chunk.revision, sizeof(u32));
139 out += 3 * sizeof(u32);
140 }
141 return count;
142}
143
144bool tilemap_readChunkTiles(u32 entity, i32 chunkX, i32 chunkY, uintptr_t tilesPtr, u32 capacity) {
145 constexpr u32 cells = tilemap::CHUNK_SIZE * tilemap::CHUNK_SIZE;
146 if (capacity < cells) return false;
147 const auto* layer = getTilemapSystem().getLayerData(Entity::fromRaw(entity));
148 if (!layer) return false;
149 const auto found = layer->chunks.find({chunkX, chunkY});
150 if (found == layer->chunks.end()) return false;
151 auto* out = boundarySpanMut<u8>(tilesPtr, cells * sizeof(u16), "tilemap_readChunkTiles");
152 if (!out) return false;
153 std::memcpy(out, found->second.tiles, cells * sizeof(u16));
154 return true;
155}
156
157void tilemap_setRenderProps(u32 entity, u32 textureHandle, u32 tilesetColumns,
158 f32 uvTileW, f32 uvTileH,
159 i32 sortLayer, f32 depth,
160 f32 parallaxX, f32 parallaxY) {
161 getTilemapSystem().setRenderProps(Entity::fromRaw(entity),
162 textureHandle, tilesetColumns, uvTileW, uvTileH,
163 sortLayer, depth, parallaxX, parallaxY);
164}
165
166void tilemap_setTint(u32 entity, f32 r, f32 g, f32 b, f32 a, f32 opacity) {
167 getTilemapSystem().setTint(Entity::fromRaw(entity), r, g, b, a, opacity);
168}
169
170void tilemap_setVisible(u32 entity, bool visible) {
171 getTilemapSystem().setVisible(Entity::fromRaw(entity), visible);
172}
173
174void tilemap_setOriginEntity(u32 layerKey, u32 originEntity) {
175 getTilemapSystem().setOriginEntity(Entity::fromRaw(layerKey),
176 Entity::fromRaw(originEntity));
177}
178
179// --- Chunk serialization ---
180
181namespace {
182
183// Base64 encoding uses the URL-safe alphabet (`-` / `_` instead of `+` / `/`)
184// so the output embeds cleanly in JSON scene files without escaping and can
185// also survive a ?query= parameter if anyone ever serves scenes over HTTP.
186constexpr const char* kB64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
187
188void base64Encode(const u8* data, usize len, std::string& out) {
189 out.reserve(out.size() + ((len + 2) / 3) * 4);
190 usize i = 0;
191 while (i + 3 <= len) {
192 const u32 v = (u32(data[i]) << 16) | (u32(data[i + 1]) << 8) | u32(data[i + 2]);
193 out.push_back(kB64[(v >> 18) & 0x3F]);
194 out.push_back(kB64[(v >> 12) & 0x3F]);
195 out.push_back(kB64[(v >> 6) & 0x3F]);
196 out.push_back(kB64[v & 0x3F]);
197 i += 3;
198 }
199 if (i < len) {
200 const u32 v = (u32(data[i]) << 16) | (i + 1 < len ? (u32(data[i + 1]) << 8) : 0);
201 out.push_back(kB64[(v >> 18) & 0x3F]);
202 out.push_back(kB64[(v >> 12) & 0x3F]);
203 if (i + 1 < len) {
204 out.push_back(kB64[(v >> 6) & 0x3F]);
205 } else {
206 out.push_back('=');
207 }
208 out.push_back('=');
209 }
210}
211
212i32 b64Value(char c) {
213 if (c >= 'A' && c <= 'Z') return c - 'A';
214 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
215 if (c >= '0' && c <= '9') return c - '0' + 52;
216 if (c == '-' || c == '+') return 62;
217 if (c == '_' || c == '/') return 63;
218 return -1;
219}
220
221bool base64Decode(const std::string& in, std::vector<u8>& out) {
222 out.clear();
223 out.reserve(in.size() * 3 / 4);
224 i32 buf = 0;
225 i32 bits = 0;
226 for (char c : in) {
227 if (c == '=' || c == '\n' || c == '\r' || c == ' ') continue;
228 const i32 v = b64Value(c);
229 if (v < 0) return false;
230 buf = (buf << 6) | v;
231 bits += 6;
232 if (bits >= 8) {
233 bits -= 8;
234 out.push_back(static_cast<u8>((buf >> bits) & 0xFF));
235 }
236 }
237 return true;
238}
239
240} // namespace
241
242// Exports every non-empty chunk of `entity` as a single base64-encoded
243// blob. Layout (all little-endian):
244// u32 magic = 'TMAP'
245// u16 chunkSize, idMask, flipH, flipV, flipD, reserved(0)
246// u32 chunkCount
247// repeated for each chunk:
248// i32 chunkX, i32 chunkY
249// u16 tiles[chunkSize * chunkSize]
250// Empty chunks are skipped to keep the payload compact for sparse maps.
251std::string tilemap_exportChunks(u32 entity) {
252 auto e = Entity::fromRaw(entity);
253 const auto* layer = getTilemapSystem().getLayerData(e);
254 if (!layer) return {};
255
256 std::vector<std::pair<tilemap::ChunkCoord, const tilemap::ChunkData*>> nonEmpty;
257 nonEmpty.reserve(layer->chunks.size());
258 for (const auto& [coord, chunk] : layer->chunks) {
259 bool anyTile = false;
260 for (u32 i = 0; i < tilemap::CHUNK_SIZE * tilemap::CHUNK_SIZE; ++i) {
261 if (chunk.tiles[i] != tilemap::EMPTY_TILE) { anyTile = true; break; }
262 }
263 if (anyTile) nonEmpty.emplace_back(coord, &chunk);
264 }
265
266 const u32 count = static_cast<u32>(nonEmpty.size());
267 const usize perChunk = sizeof(i32) * 2
269 std::vector<u8> raw;
270 raw.reserve(tilemap::BLOB_HEADER_V2_BYTES + count * perChunk);
271
272 auto append = [&](const void* p, usize n) {
273 const u8* b = static_cast<const u8*>(p);
274 raw.insert(raw.end(), b, b + n);
275 };
276 tilemap::appendBlobHeader(raw, count);
277 for (const auto& [coord, chunk] : nonEmpty) {
278 append(&coord.x, sizeof(coord.x));
279 append(&coord.y, sizeof(coord.y));
280 append(chunk->tiles, sizeof(chunk->tiles));
281 }
282
283 std::string out;
284 base64Encode(raw.data(), raw.size(), out);
285 return out;
286}
287
288bool tilemap_importChunks(u32 entity, const std::string& encoded) {
289 auto e = Entity::fromRaw(entity);
290 // Auto-init as infinite if the caller didn't pre-create a layer — the
291 // scene loader path inserts the TilemapLayer component first and then
292 // expects the chunks to land, so we can't require a separate init call.
293 if (!getTilemapSystem().hasLayer(e)) {
294 getTilemapSystem().initInfiniteLayer(e, 32.0f, 32.0f);
295 }
296 auto* layer = getTilemapSystem().getLayerDataMut(e);
297 if (!layer) return false;
298
299 std::vector<u8> raw;
300 if (!base64Decode(encoded, raw)) return false;
301
302 tilemap::BlobHeader header{};
303 if (!tilemap::parseBlobHeader(raw.data(), raw.size(), header)) return false;
304
305 // One path, migrating or not: a map written under this engine's own
306 // encoding takes the same walk as one written under an older one, so the
307 // case that runs every day is the case the migration is tested on.
309 const i32 side = static_cast<i32>(tilemap::CHUNK_SIZE);
310 tilemap::ChunkData* into = nullptr;
311 tilemap::ChunkCoord at{ 0, 0 };
312 bool first = true;
313 bool lost = false;
314
315 if (!layer->chunks.empty()) ++layer->edit_revision;
316 layer->chunks.clear();
317 const bool walked = tilemap::walkBlobCells(raw.data(), raw.size(), header,
318 [&](i32 x, i32 y, u16 word) {
319 u16 cell = 0;
320 // A narrowed id mask cannot carry the tile, and putting SOME other
321 // tile there is the failure this whole header exists to stop.
322 if (!tilemap::recodeCell(word, header.wrote, running, cell)) { lost = true; return; }
323 const tilemap::ChunkCoord coord{ tilemap::floorDiv(x, side), tilemap::floorDiv(y, side) };
324 // Cells arrive along a row, so the chunk they land in changes rarely.
325 if (first || coord.x != at.x || coord.y != at.y) {
326 auto& chunk = layer->chunks[coord];
327 chunk.revision = ++layer->edit_revision;
328 into = &chunk;
329 at = coord;
330 first = false;
331 }
332 into->tiles[static_cast<usize>(tilemap::floorMod(y, side)) * tilemap::CHUNK_SIZE
333 + static_cast<usize>(tilemap::floorMod(x, side))] = cell;
334 });
335 if (!walked || lost) {
336 layer->chunks.clear();
337 return false;
338 }
339 return true;
340}
341
342void tilemap_initInfiniteLayer(u32 entity, f32 tileWidth, f32 tileHeight) {
343 auto e = Entity::fromRaw(entity);
344 if (e == INVALID_ENTITY) return;
345 getTilemapSystem().initInfiniteLayer(e, tileWidth, tileHeight);
346}
347
348void tilemap_setChunkTiles(u32 entity, i32 chunkX, i32 chunkY,
349 uintptr_t tilesPtr, u32 width, u32 height) {
350 auto e = Entity::fromRaw(entity);
351 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
352 const auto* tiles = boundarySpan<u16>(tilesPtr, static_cast<u64>(width) * height, "tilemap_setChunkTiles");
353 if (!tiles) return;
354 getTilemapSystem().setChunkTiles(e, chunkX, chunkY, tiles, width, height);
355}
356
357void tilemap_removeChunk(u32 entity, i32 chunkX, i32 chunkY) {
358 auto e = Entity::fromRaw(entity);
359 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
360 getTilemapSystem().removeChunk(e, chunkX, chunkY);
361}
362
363void tilemap_setTileAnimation(u32 entity, u32 tileId,
364 uintptr_t framesPtr, u32 frameCount) {
365 auto e = Entity::fromRaw(entity);
366 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
367 const auto* data = boundarySpan<u32>(framesPtr, static_cast<u64>(frameCount) * 2, "tilemap_setTileAnimation");
368 if (!data) return;
369 std::vector<tilemap::AnimFrame> frames(frameCount);
370 for (u32 i = 0; i < frameCount; i++) {
371 frames[i].tile_id = static_cast<u16>(data[i * 2]);
372 frames[i].duration_ms = static_cast<u16>(data[i * 2 + 1]);
373 }
374 getTilemapSystem().setTileAnimation(e, static_cast<u16>(tileId),
375 frames.data(), frameCount);
376}
377
378void tilemap_clearTileAnimations(u32 entity) {
379 auto e = Entity::fromRaw(entity);
380 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
381 getTilemapSystem().clearTileAnimations(e);
382}
383
384void tilemap_advanceAnimations(u32 entity, f32 dtMs) {
385 auto e = Entity::fromRaw(entity);
386 if (e == INVALID_ENTITY) return;
387 getTilemapSystem().advanceAnimations(e, dtMs);
388}
389
390void tilemap_setTileProperty(u32 entity, u32 tileId,
391 const std::string& key, const std::string& value) {
392 auto e = Entity::fromRaw(entity);
393 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
394 getTilemapSystem().setTileProperty(e, static_cast<u16>(tileId), key, value);
395}
396
397std::string tilemap_getTileProperty(u32 entity, i32 x, i32 y,
398 const std::string& key) {
399 auto e = Entity::fromRaw(entity);
400 if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return "";
401 u16 raw = getTilemapSystem().getTile(e, x, y);
402 u16 tileId = raw & tilemap::TILE_ID_MASK;
403 if (tileId == tilemap::EMPTY_TILE) return "";
404 return getTilemapSystem().getTileProperty(e, tileId, key);
405}
406
407void tilemap_flipTile(u32 entity, i32 x, i32 y,
408 bool flipH, bool flipV, bool flipD) {
409 auto e = Entity::fromRaw(entity);
410 if (e == INVALID_ENTITY) return;
411 getTilemapSystem().flipTile(e, x, y, flipH, flipV, flipD);
412}
413
414void tilemap_rotateTile(u32 entity, i32 x, i32 y, i32 degrees) {
415 auto e = Entity::fromRaw(entity);
416 if (e == INVALID_ENTITY) return;
417 getTilemapSystem().rotateTile(e, x, y, degrees);
418}
419
420void tilemap_setGridType(u32 entity, u32 type) {
421 auto e = Entity::fromRaw(entity);
422 if (e == INVALID_ENTITY) return;
423 getTilemapSystem().setGridType(e, static_cast<tilemap::GridType>(type));
424}
425
426void tilemap_setHexParams(u32 entity, f32 sideLength, u32 staggerAxisX, u32 staggerIndexEven) {
427 auto e = Entity::fromRaw(entity);
428 if (e == INVALID_ENTITY) return;
429 getTilemapSystem().setHexParams(e, sideLength, staggerAxisX != 0, staggerIndexEven != 0);
430}
431
432static f32 s_coordBuffer[2] = {};
433
434uintptr_t tilemap_tileToWorld(u32 entity, i32 tx, i32 ty,
435 f32 originX, f32 originY) {
436 auto e = Entity::fromRaw(entity);
437 getTilemapSystem().tileToWorld(e, tx, ty, originX, originY,
438 s_coordBuffer[0], s_coordBuffer[1]);
439 return reinterpret_cast<uintptr_t>(s_coordBuffer);
440}
441
442uintptr_t tilemap_worldToTile(u32 entity, f32 wx, f32 wy,
443 f32 originX, f32 originY) {
444 auto e = Entity::fromRaw(entity);
445 i32 tx, ty;
446 getTilemapSystem().worldToTile(e, wx, wy, originX, originY, tx, ty);
447 s_coordBuffer[0] = static_cast<f32>(tx);
448 s_coordBuffer[1] = static_cast<f32>(ty);
449 return reinterpret_cast<uintptr_t>(s_coordBuffer);
450}
451
452} // namespace esengine
453
454#endif // ES_ENABLE_TILEMAP
Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.
Custom geometry for user-defined mesh rendering.
Immediate mode 2D drawing API.
Post-processing effects pipeline.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Central resource management system.
The tilemap entry points the SDK drives layers through.
System for computing hierarchical world transforms.
i32 floorMod(i32 a, i32 b)
bool parseBlobHeader(const u8 *raw, usize size, BlobHeader &out)
static constexpr u32 CHUNK_SIZE
void appendBlobHeader(std::vector< u8 > &out, u32 chunkCount)
Definition ChunkBlob.hpp:86
constexpr usize BLOB_HEADER_V2_BYTES
Definition ChunkBlob.hpp:77
static constexpr u16 EMPTY_TILE
CellEncoding runningEncoding()
Definition ChunkBlob.hpp:66
bool walkBlobCells(const u8 *raw, usize size, const BlobHeader &header, Fn &&emit)
const T * boundarySpan(uintptr_t ptr, u64 count, const char *what)
Validates a JS-supplied pointer to count elements of T and returns it typed.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
T * boundarySpanMut(uintptr_t ptr, u64 count, const char *what)
Mutable variant of boundarySpan, for entry points that WRITE into a JS buffer.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
static EstellaContext & ctx()
EstellaContext & activeCtx()
The engine context every binding routes through — single source of truth.
float f32
32-bit floating point
Definition Types.hpp:59
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162