Add GID encode/decode with range validation

Bit layout [atlas:8][tile_id:20][rot:2][res:2] matches
lib-core.maps init.lua so JS-produced GIDs are byte-identical to
engine-produced ones. >>> 0 forces unsigned u32 output.
This commit is contained in:
Axel Meyer
2026-05-23 13:40:25 +02:00
parent 86aea8e2de
commit 2949a96e11
2 changed files with 113 additions and 0 deletions

30
src/gid.js Normal file
View File

@@ -0,0 +1,30 @@
'use strict';
const MAX_ATLAS = 255;
const MAX_TILE = 1048575;
const MAX_ROT = 3;
const MAX_U32 = 0xFFFFFFFF;
function checkInt(name, value, min, max) {
if (!Number.isInteger(value) || value < min || value > max) {
throw new RangeError(`${name} ${value} out of range [${min},${max}]`);
}
}
function encodeGid(atlas, tile, rotation = 0) {
checkInt('atlas', atlas, 0, MAX_ATLAS);
checkInt('tile', tile, 0, MAX_TILE);
checkInt('rotation', rotation, 0, MAX_ROT);
return ((atlas << 24) | (tile << 4) | (rotation << 2)) >>> 0;
}
function decodeGid(gid) {
checkInt('gid', gid, 0, MAX_U32);
return {
atlas: (gid >>> 24) & 0xFF,
tile: (gid >>> 4) & 0xFFFFF,
rotation: (gid >>> 2) & 0x3,
};
}
module.exports = { encodeGid, decodeGid, MAX_ATLAS, MAX_TILE, MAX_ROT };