From 1f74419ccf7ac6a44734799561ea5dfa55222817 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:49:26 -0600 Subject: [PATCH] vector/ldtk: LDtk projects read + write as a TileMap (levels as groups, worlds, IntGrid / auto / tile / entity layers, fields, external levels through resolve) --- README.md | 3 +- docs/FORMATS.md | 1 + docs/guide/tilemap.md | 51 ++- src/Rosetta/Registry.luau | 12 + src/Rosetta/vector/ldtk/Read.luau | 334 +++++++++++++++ src/Rosetta/vector/ldtk/Write.luau | 646 +++++++++++++++++++++++++++++ src/Rosetta/vector/ldtk/init.luau | 90 ++++ tests/vector/ldtk.luau | 278 +++++++++++++ tools/fixtures/_ldtk_encode.luau | 30 ++ tools/fixtures/docs_engines.py | 7 +- tools/fixtures/ldtk.py | 111 +++++ 11 files changed, 1557 insertions(+), 6 deletions(-) create mode 100644 src/Rosetta/vector/ldtk/Read.luau create mode 100644 src/Rosetta/vector/ldtk/Write.luau create mode 100644 src/Rosetta/vector/ldtk/init.luau create mode 100644 tests/vector/ldtk.luau create mode 100644 tools/fixtures/_ldtk_encode.luau create mode 100644 tools/fixtures/ldtk.py diff --git a/README.md b/README.md index dc23830..8809bb7 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +177 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -194,6 +194,7 @@ adds each format's capabilities. | Data | toml | .toml | yes | yes | | Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | | Data | yaml | .yaml .yml | yes | yes | +| Vector graphics and tile maps | ldtk | .ldtk | yes | yes | | Vector graphics and tile maps | svg | .svg | yes | yes | | Vector graphics and tile maps | tiled | .tmx .tmj .tsx .tsj | yes | yes | | Layered images | aseprite | .aseprite .ase | yes | yes | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2b96ec4..4259416 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -150,6 +150,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | +| vector | ldtk | .ldtk | yes | yes | levels: true, worlds: true, intGrid: true, entities: true | `tests/vector/ldtk.luau` | | vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` | | vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` | | layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` | diff --git a/docs/guide/tilemap.md b/docs/guide/tilemap.md index bb86cd0..8b04fcc 100644 --- a/docs/guide/tilemap.md +++ b/docs/guide/tilemap.md @@ -1,4 +1,4 @@ -# Tile maps (Tiled TMX / TMJ) +# Tile maps (Tiled, LDtk, Ogmo) [Tiled](https://www.mapeditor.org) maps load as a `TileMap`: the map grid, its tilesets, and a list of layers (tile layers, object layers, image layers and groups) with Tiled's custom properties. The XML flavour (TMX) and the @@ -194,14 +194,61 @@ local back = assert(F.load(tmx)) assert(back.layers[1].data[6] == 0x80000009) ``` +## LDtk + +[LDtk](https://ldtk.io) projects (`.ldtk`) load as a `TileMap` whose top layers are the **levels**: one `"group"` +layer per level (`level = true`, `offsetX` / `offsetY` = its world position in pixels, `pxWidth` / `pxHeight`, the +level fields as `properties`), holding the level's layers bottom first. Multi-world projects add one group per +world (`world = true`) around its levels. External levels (`.ldtkl`) load through `opts.resolve(relPath)`; without +it the level group has `unresolved = true` and no layers. + +| LDtk layer | `TileLayer` | +|---|---| +| Tiles, AutoLayer | `type = "tiles"`, `tiles` (every tile: `x`, `y` pixels, `tile` id, `flip` bits, `srcX` / `srcY`, `alpha`), `data` (a gid grid of the top tile per cell), `tileset` | +| IntGrid | the same plus `intGrid` (one value per cell, 0 = empty) and `intGridValues` (`{ value, identifier, color }`) | +| Entities | `type = "objects"`: `class` = the entity identifier, `x` / `y` top-left (pixel position minus `pivot` x size), `width`, `height`, `pivot`, `tags`, `tile`, the fields as `properties` / `propertyTypes` (LDtk type names) | + +Every layer also has `ldtkType` and `gridSize` (LDtk layers have their own cell size), and the raw LDtk tables +(definitions, iids, uids, rules) ride along in `.ldtk` fields so a save keeps them. Gids are the tileset's +`firstGid` plus the LDtk tile id, with LDtk's X / Y flips as Tiled's flip bits. + +```luau +local map = assert(F.load(ldtkText)) +assert(map.meta.source.format == "ldtk") +local level = map.layers[1] +assert(level.level and level.name == "Stamps" and level.pxWidth == 272) +local walls = level.layers[1] +assert(walls.ldtkType == "IntGrid" and walls.intGridValues[1].identifier == "walls") +assert(#walls.tiles == 118 and map.tilesets[1].imageSource == "atlas/Inca_front_by_Kronbits-extended.png") +local cx, cy = walls.tiles[1].x // walls.gridSize, walls.tiles[1].y // walls.gridSize +assert(walls.data[1 + cx + cy * walls.width] ~= 0) +``` + +Saving writes an LDtk project: maps read from LDtk keep their definitions and raw fields (changed `properties` get +new `realEditorValues`, so the editor sees them); other maps (a Tiled map, a new `TileMap`) get layer, tileset and +entity definitions made from their content, their loose layers forming one level. A tile layer writes its `tiles` +list when it has one, else its `data` grid; set `tiles = nil` after editing `data`. Levels are always embedded. + +```luau +local map = F.Types.TileMap.new(2, 1, 16, 16) +table.insert(map.tilesets, { name = "t", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 2, count = 4, + imageSource = "t.png", imageWidth = 32, imageHeight = 32 }) +table.insert(map.layers, { type = "tiles", name = "Floor", width = 2, height = 1, visible = true, opacity = 1, + properties = {}, data = { 1, 4 } }) +local ldtk = assert(F.save(map, nil, { format = "ldtk" })) +local back = assert(F.load(ldtk)) +assert(back.layers[1].layers[1].tiles[2].tile == 3) +``` + ## Formats | Format | Read | Write | Notes | |---|---|---|---| | TMX / TSX | yes | yes | CSV, base64 (raw, zlib, gzip) and `` data; zstd data returns `UNSUPPORTED` | | TMJ / TSJ | yes | yes | | +| LDtk (`.ldtk`) | yes | yes | levels as groups, worlds, IntGrid / auto / tile / entity layers, fields; `.ldtkl` through `resolve`; writes embedded levels | -Both are the `tiled` format in [FORMATS.md](../FORMATS.md). Wang sets and terrains are dropped. +TMX and TMJ are both the `tiled` format in [FORMATS.md](../FORMATS.md) (Wang sets and terrains are dropped). ## Gotchas diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 10fd987..5805e93 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -1754,6 +1754,18 @@ local list: { Entry } = { return require("@rosetta/data/yaml") end, }, + { + name = "ldtk", + category = "vector", + path = "vector/ldtk", + extensions = { "ldtk" }, + mime = { "application/x-ldtk+json" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" }, + caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true }, + load = function() + return require("@rosetta/vector/ldtk") + end, + }, { name = "svg", category = "vector", diff --git a/src/Rosetta/vector/ldtk/Read.luau b/src/Rosetta/vector/ldtk/Read.luau new file mode 100644 index 0000000..f985ef3 --- /dev/null +++ b/src/Rosetta/vector/ldtk/Read.luau @@ -0,0 +1,334 @@ +--!strict +-- vector/ldtk/Read: an LDtk project (JSON, ldtk.io/json 1.5) into a Types.TileMap: one group layer per level (inside +-- one group per world for multi-world projects), the level's layers bottom first. Tile gids are firstGid + the +-- LDtk tile id with the f bits as Tiled's flip flags (bit 0 X -> 0x80000000, bit 1 Y -> 0x40000000). +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") + +local Read = {} + +local FLIP_X, FLIP_Y = 0x80000000, 0x40000000 + +local function n(v: any, default: number): number + return if type(v) == "number" then v else default +end +local function s(v: any): string? + return if type(v) == "string" then v else nil +end +local NULL = Json.null +local function tab(v: any): boolean + return type(v) == "table" and v ~= NULL +end +local function list(v: any): { any } + return if tab(v) then v else {} +end + +-- every key but the ones listed (the raw part kept for the writer) +local function rest(t: any, skip: { [string]: boolean }): { [string]: any } + local keys = Json.keys(t) + local out: { [string]: any } = {} + local order = {} + for _, k in keys do + if not skip[k] then + out[k] = t[k] + table.insert(order, k) + end + end + return Json.object(out, order) +end + +function Read.fields(v: any): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + for _, f in list(v) do + if type(f) == "table" and type(f.__identifier) == "string" then + props[f.__identifier] = f.__value + if type(f.__type) == "string" then + types = types or {} + ;(types :: any)[f.__identifier] = f.__type + end + end + end + return props, types +end + +type Ctx = { tilesets: { [number]: Types.Tileset }, maxCells: number, layerDefs: { [number]: any } } + +local function tiles(ctx: Ctx, raw: { any }, ts: Types.Tileset?, grid: number, cw: number, ch: number): ({ any }, { number }?) + local out = table.create(#raw) + local data: { number }? = nil + if cw > 0 and ch > 0 then + data = table.create(cw * ch, 0) + end + for i, t in raw do + if type(t) == "table" then + local px, src = list(t.px), list(t.src) + local tile = { + x = n(px[1], 0), + y = n(px[2], 0), + tile = n(t.t, 0), + flip = n(t.f, 0), + srcX = n(src[1], 0), + srcY = n(src[2], 0), + alpha = n(t.a, 1), + d = t.d, + } + out[i] = tile + if data and ts then + local cx, cy = tile.x // grid, tile.y // grid + if cx >= 0 and cy >= 0 and cx < cw and cy < ch then + local gid = ts.firstGid + tile.tile + if bit32.btest(tile.flip, 1) then + gid += FLIP_X + end + if bit32.btest(tile.flip, 2) then + gid += FLIP_Y + end + -- later tiles are drawn over earlier ones + data[1 + cx + cy * cw] = gid + end + end + end + end + return out, data +end + +local LAYER_SKIP = { __identifier = true, __type = true, __cWid = true, __cHei = true, __gridSize = true, __opacity = true, __pxTotalOffsetX = true, __pxTotalOffsetY = true, __tilesetDefUid = true, __tilesetRelPath = true, visible = true, intGridCsv = true, autoLayerTiles = true, gridTiles = true, entityInstances = true } +local ENTITY_SKIP = { __identifier = true, __grid = true, __pivot = true, __tags = true, __tile = true, __smartColor = true, __worldX = true, __worldY = true, width = true, height = true, px = true, fieldInstances = true } + +local function layer(ctx: Ctx, li: any): (Types.TileLayer?, string?) + local kind = s(li.__type) or "Tiles" + local cw, ch = n(li.__cWid, 0), n(li.__cHei, 0) + if cw < 0 or ch < 0 or cw * ch > ctx.maxCells then + return nil, "limit: layer of " .. cw .. " x " .. ch .. " cells" + end + local grid = math.max(1, n(li.__gridSize, 16)) + local out: Types.TileLayer = { + name = s(li.__identifier) or "", + type = if kind == "Entities" then "objects" else "tiles", + visible = li.visible ~= false, + opacity = n(li.__opacity, 1), + properties = {}, + offsetX = n(li.__pxTotalOffsetX, 0), + offsetY = n(li.__pxTotalOffsetY, 0), + ldtkType = kind, + gridSize = grid, + ldtk = rest(li, LAYER_SKIP), + } + if kind == "Entities" then + local objs = {} + for _, e in list(li.entityInstances) do + if type(e) == "table" then + local w, h = n(e.width, 0), n(e.height, 0) + local pv, px = list(e.__pivot), list(e.px) + local pX, pY = n(pv[1], 0), n(pv[2], 0) + local props, types = Read.fields(e.fieldInstances) + local o: { [string]: any } = { + id = s(e.iid), + name = s(e.__identifier) or "", + class = s(e.__identifier) or "", + x = n(px[1], 0) - pX * w, + y = n(px[2], 0) - pY * h, + width = w, + height = h, + rotation = 0, + visible = true, + shape = "rectangle", + pivot = { pX, pY }, + tags = e.__tags, + tile = if tab(e.__tile) then e.__tile else nil, + color = s(e.__smartColor), + properties = props, + propertyTypes = types, + ldtk = rest(e, ENTITY_SKIP), + fieldInstances = e.fieldInstances, + } + table.insert(objs, o) + end + end + out.objects = objs + return out, nil + end + out.width, out.height = cw, ch + local tsUid = li.__tilesetDefUid + local ts = if type(tsUid) == "number" then ctx.tilesets[tsUid] else nil + if ts then + out.tileset = ts.name + end + out.tilesetPath = s(li.__tilesetRelPath) + local raw = if kind == "Tiles" then list(li.gridTiles) else list(li.autoLayerTiles) + local tl, data = tiles(ctx, raw, ts, grid, cw, ch) + out.tiles = tl + out.data = data or {} + if kind == "IntGrid" then + local csv = list(li.intGridCsv) + local grid2 = table.create(cw * ch, 0) + for i = 1, math.min(#csv, cw * ch) do + grid2[i] = n(csv[i], 0) + end + out.intGrid = grid2 + local def = if type(li.layerDefUid) == "number" then ctx.layerDefs[li.layerDefUid] else nil + if def then + local values = {} + for _, v in list(def.intGridValues) do + if type(v) == "table" then + table.insert(values, { value = n(v.value, 0), identifier = s(v.identifier), color = s(v.color) }) + end + end + out.intGridValues = values + end + end + return out, nil +end + +local LEVEL_SKIP = { identifier = true, worldX = true, worldY = true, pxWid = true, pxHei = true, __bgColor = true, fieldInstances = true, layerInstances = true } + +local function level(ctx: Ctx, lv: any, resolve: ((string) -> buffer?)?): (Types.TileLayer?, string?) + local layers = lv.layerInstances + local external = s(lv.externalRelPath) + local unresolved = false + if not tab(layers) and external then + local data: any = nil + if resolve then + local ok, b = pcall(resolve, external) + data = if ok and type(b) == "buffer" then b else nil + end + if data then + local v, err = Json.decode(data, { ordered = true }) + if not tab(v) then + return nil, "external level " .. external .. ": " .. tostring(err) + end + lv = v + layers = v.layerInstances + else + unresolved = true + end + end + local props, types = Read.fields(lv.fieldInstances) + local g: Types.TileLayer = { + name = s(lv.identifier) or "", + type = "group", + visible = true, + opacity = 1, + properties = props, + propertyTypes = types, + offsetX = n(lv.worldX, 0), + offsetY = n(lv.worldY, 0), + layers = {}, + level = true, + pxWidth = n(lv.pxWid, 0), + pxHeight = n(lv.pxHei, 0), + backgroundColor = s(lv.__bgColor), + external = external, + unresolved = if unresolved then true else nil, + ldtk = rest(lv, LEVEL_SKIP), + } + local ls = list(layers) + for i = #ls, 1, -1 do + local l, err = layer(ctx, ls[i]) + if not l then + return nil, err + end + table.insert(g.layers :: { any }, l) + end + return g, nil +end + +local PROJECT_SKIP = { levels = true, worlds = true } + +function Read.project(v: any, opts: any): (Types.TileMap?, string?) + if not tab(v) or not tab(v.defs) then + return nil, "no defs: not an LDtk project" + end + local grid = math.max(1, n(v.defaultGridSize, 16)) + local map = Types.TileMap.new(0, 0, grid, grid) + local ctx: Ctx = { tilesets = {}, maxCells = opts.maxCells or 2 ^ 26, layerDefs = {} } + local gid = 1 + for _, t in list(v.defs.tilesets) do + if type(t) == "table" then + local cw, ch = n(t.__cWid, 0), n(t.__cHei, 0) + local size = n(t.tileGridSize, grid) + local ts: Types.Tileset = { + name = s(t.identifier) or ("tileset" .. #map.tilesets), + firstGid = gid, + tileWidth = size, + tileHeight = size, + columns = cw, + count = cw * ch, + imageSource = s(t.relPath), + imageWidth = n(t.pxWid, 0), + imageHeight = n(t.pxHei, 0), + spacing = n(t.spacing, 0), + margin = n(t.padding, 0), + uid = t.uid, + embedAtlas = s(t.embedAtlas), + properties = {}, + } + gid += math.max(1, cw * ch) + table.insert(map.tilesets, ts) + if type(t.uid) == "number" then + ctx.tilesets[t.uid] = ts + end + end + end + for _, d in list(v.defs.layers) do + if type(d) == "table" and type(d.uid) == "number" then + ctx.layerDefs[d.uid] = d + end + end + local resolve = opts.resolve + local worlds = list(v.worlds) + local minX, minY, maxX, maxY = math.huge, math.huge, -math.huge, -math.huge + local function addLevels(into: { any }, levels: any): string? + for _, lv in list(levels) do + if type(lv) == "table" then + local g, err = level(ctx, lv, resolve) + if not g then + return err + end + local x, y = g.offsetX :: number, g.offsetY :: number + minX, minY = math.min(minX, x), math.min(minY, y) + maxX, maxY = math.max(maxX, x + (g.pxWidth :: number)), math.max(maxY, y + (g.pxHeight :: number)) + table.insert(into, g) + end + end + return nil + end + if #worlds > 0 then + for _, w in worlds do + if type(w) == "table" then + local wg: Types.TileLayer = { + name = s(w.identifier) or "", + type = "group", + visible = true, + opacity = 1, + properties = {}, + layers = {}, + world = true, + ldtk = rest(w, { levels = true, identifier = true }), + } + local err = addLevels(wg.layers :: { any }, w.levels) + if err then + return nil, err + end + table.insert(map.layers, wg) + end + end + else + local err = addLevels(map.layers, v.levels) + if err then + return nil, err + end + end + if minX <= maxX then + map.width = math.ceil((maxX - math.min(minX, 0)) / grid) + map.height = math.ceil((maxY - math.min(minY, 0)) / grid) + end + map.backgroundColor = s(v.bgColor) + map.worldLayout = s(v.worldLayout) + map.ldtk = rest(v, PROJECT_SKIP) + map.meta.source = { format = "ldtk", version = s(v.jsonVersion), externalLevels = v.externalLevels == true, multiWorld = #worlds > 0 } + return map, nil +end + +return Read diff --git a/src/Rosetta/vector/ldtk/Write.luau b/src/Rosetta/vector/ldtk/Write.luau new file mode 100644 index 0000000..472773a --- /dev/null +++ b/src/Rosetta/vector/ldtk/Write.luau @@ -0,0 +1,646 @@ +--!strict +-- vector/ldtk/Write: a Types.TileMap as an LDtk project (JSON 1.5). Maps read from LDtk keep their raw defs, project, +-- level, layer and entity fields (the .ldtk tables); other maps get definitions made from their layers, tilesets and +-- object classes. A tile layer writes its `tiles` list when present, else its gid `data`. Levels are always embedded. +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") + +local Write = {} + +local NULL = Json.null +local FLAGS = 0xF0000000 + +local function tab(v: any): boolean + return type(v) == "table" and v ~= NULL +end +local function list(v: any): { any } + return if tab(v) then v else {} +end +local function n(v: any, default: number): number + return if type(v) == "number" and v == v then v else default +end + +type Ctx = { + uid: number, + iid: number, + defs: any, + tilesetByName: { [string]: any }, + tilesetByUid: { [number]: any }, + layerDefs: { [string]: any }, + entityDefs: { [string]: any }, + levelFields: { [string]: any }, + map: Types.TileMap, +} + +local function clone(t: any): any + if not tab(t) then + return Json.object({}) + end + local keys = Json.keys(t) + local out = {} + for _, k in keys do + out[k] = t[k] + end + return Json.object(out, keys) +end + +local function obj(pairs_: { any }): any + local out, keys = {}, {} + for i = 1, #pairs_, 2 do + local k, v = pairs_[i], pairs_[i + 1] + table.insert(keys, k) + out[k] = v + end + return Json.object(out, keys) +end + +local function set(t: any, k: string, v: any) + Json.set(t, k, if v == nil then NULL else v) +end + +local function nextUid(ctx: Ctx): number + ctx.uid += 1 + return ctx.uid +end + +local function newIid(ctx: Ctx): string + ctx.iid += 1 + return string.format("%08x-0000-4000-8000-%012x", 0x5ce7a000 + ctx.iid // 0x1000000, ctx.iid) +end + +-- ------------------------------------------------------------------------------------------------ fields +local function hexColor(v: any): number? + if type(v) ~= "string" then + return nil + end + local h = string.match(v, "^#(%x%x%x%x%x%x)$") or string.match(v, "^#%x%x(%x%x%x%x%x%x)$") + return if h then tonumber(h, 16) else nil +end + +local function wrap(typ: string, v: any): any + if v == nil or v == NULL then + return NULL + end + if typ == "Int" then + return obj({ "id", "V_Int", "params", { v } }) + elseif typ == "Float" then + return obj({ "id", "V_Float", "params", { v } }) + elseif typ == "Bool" then + return obj({ "id", "V_Bool", "params", { v == true } }) + elseif typ == "Color" then + local c = hexColor(v) + return if c then obj({ "id", "V_Int", "params", { c } }) else NULL + elseif typ == "Point" and tab(v) then + return obj({ "id", "V_String", "params", { tostring(v.cx) .. "," .. tostring(v.cy) } }) + elseif type(v) == "string" then + return obj({ "id", "V_String", "params", { v } }) + end + return nil +end + +local function editorValues(typ: string, v: any): any + local inner = string.match(typ, "^Array<(.+)>$") + if inner then + local out = {} + for i, x in list(v) do + local w = wrap(inner, x) + if w == nil then + return nil + end + out[i] = w + end + return out + end + local w = wrap(typ, v) + return if w == nil then nil else { w } +end + +local function same(a: any, b: any): boolean + if a == b then + return true + end + if tab(a) and tab(b) then + for k, x in a do + if not same(x, b[k]) then + return false + end + end + for k in b do + if a[k] == nil then + return false + end + end + return true + end + return false +end + +local LDTK_TYPE: { [string]: string } = { int = "Int", float = "Float", bool = "Bool", string = "String", color = "Color", file = "FilePath" } + +local function valueType(v: any): string + if type(v) == "number" then + return if v % 1 == 0 then "Int" else "Float" + elseif type(v) == "boolean" then + return "Bool" + end + return "String" +end + +local function fieldDef(ctx: Ctx, name: string, typ: string): any + local isArray = string.match(typ, "^Array<") ~= nil + local base = string.match(typ, "^Array<(.+)>$") or typ + return obj({ + "identifier", name, "doc", NULL, "__type", typ, "uid", nextUid(ctx), "type", "F_" .. base, "isArray", isArray, + "canBeNull", true, "arrayMinLength", NULL, "arrayMaxLength", NULL, "editorDisplayMode", "Hidden", + "editorDisplayScale", 1, "editorDisplayPos", "Above", "editorLinkStyle", "StraightArrow", "editorDisplayColor", NULL, + "editorAlwaysShow", false, "editorShowInWorld", true, "editorCutLongValues", true, "editorTextSuffix", NULL, + "editorTextPrefix", NULL, "useForSmartColor", false, "exportToToc", false, "searchable", false, "min", NULL, + "max", NULL, "regex", NULL, "acceptFileTypes", NULL, "defaultOverride", NULL, "textLanguageMode", NULL, + "symmetricalRef", false, "autoChainRef", true, "allowOutOfLevelRef", true, "allowedRefs", "OnlySame", + "allowedRefsEntityUid", NULL, "allowedRefTags", {}, "tilesetUid", NULL, + }) +end + +-- raw field instances updated from the properties; properties without an instance get one when a definition exists +-- (or is made: makeDefs) +local function fieldInstances(ctx: Ctx, raw: any, props: any, types: any, defs: { [string]: any }?, makeDefs: { any }?): { any } + local out = {} + local seen: { [string]: boolean } = {} + props = if tab(props) then props else {} + types = if tab(types) then types else {} + for _, fi in list(raw) do + if tab(fi) and type(fi.__identifier) == "string" then + local id = fi.__identifier + seen[id] = true + local f = clone(fi) + local v = props[id] + if v ~= nil and not same(v, fi.__value) then + set(f, "__value", v) + local ev = editorValues(if type(fi.__type) == "string" then fi.__type else valueType(v), v) + if ev then + set(f, "realEditorValues", ev) + end + end + table.insert(out, f) + end + end + local names = {} + for k in props do + if type(k) == "string" and not seen[k] then + table.insert(names, k) + end + end + table.sort(names) + for _, k in names do + local v = props[k] + local def = defs and defs[k] + if not def and makeDefs and defs then + local typ = if type(types[k]) == "string" then (LDTK_TYPE[types[k]] or types[k]) else valueType(v) + def = fieldDef(ctx, k, typ) + defs[k] = def + table.insert(makeDefs, def) + end + if def then + local typ = if type(def.__type) == "string" then def.__type else valueType(v) + table.insert(out, obj({ "__identifier", k, "__type", typ, "__value", v, "__tile", NULL, "defUid", def.uid, "realEditorValues", editorValues(typ, v) or {} })) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ defs +local function tilesetOf(ctx: Ctx, gid: number): any + local best: any = nil + for _, ts in ctx.map.tilesets do + if ts.firstGid <= gid and (best == nil or ts.firstGid > best.firstGid) then + best = ts + end + end + return best +end + +local function defsFor(ctx: Ctx, raw: any) + local defs = if tab(raw) then clone(raw) else obj({ "layers", {}, "entities", {}, "tilesets", {}, "enums", {}, "externalEnums", {}, "levelFields", {} }) + for _, k in { "layers", "entities", "tilesets", "enums", "externalEnums", "levelFields" } do + if not tab(defs[k]) then + set(defs, k, {}) + end + end + ctx.defs = defs + for _, d in list(defs.tilesets) do + if tab(d) and type(d.uid) == "number" then + ctx.uid = math.max(ctx.uid, d.uid) + ctx.tilesetByUid[d.uid] = d + if type(d.identifier) == "string" then + ctx.tilesetByName[d.identifier] = d + end + end + end + for _, d in list(defs.layers) do + if tab(d) and type(d.identifier) == "string" then + ctx.uid = math.max(ctx.uid, n(d.uid, 0)) + ctx.layerDefs[d.identifier] = d + end + end + for _, d in list(defs.entities) do + if tab(d) and type(d.identifier) == "string" then + ctx.uid = math.max(ctx.uid, n(d.uid, 0)) + ctx.entityDefs[d.identifier] = d + for _, f in list(d.fieldDefs) do + ctx.uid = math.max(ctx.uid, n(tab(f) and f.uid, 0)) + end + end + end + for _, f in list(defs.levelFields) do + if tab(f) and type(f.identifier) == "string" then + ctx.uid = math.max(ctx.uid, n(f.uid, 0)) + ctx.levelFields[f.identifier] = f + end + end + for _, d in list(defs.enums) do + ctx.uid = math.max(ctx.uid, n(tab(d) and d.uid, 0)) + end + -- tilesets of the map the defs lack + for _, ts in ctx.map.tilesets do + if type(ts.name) == "string" and not ctx.tilesetByName[ts.name] then + local size = n(ts.tileWidth, 16) + local cols = math.max(1, n(ts.columns, 1)) + local d = obj({ + "__cWid", cols, "__cHei", math.ceil(n(ts.count, cols) / cols), "identifier", ts.name, "uid", nextUid(ctx), + "relPath", ts.imageSource or NULL, "embedAtlas", NULL, "pxWid", n(ts.imageWidth, cols * size), + "pxHei", n(ts.imageHeight, math.ceil(n(ts.count, cols) / cols) * size), "tileGridSize", size, + "spacing", n(ts.spacing, 0), "padding", n(ts.margin, 0), "tags", {}, "tagsSourceEnumUid", NULL, + "enumTags", {}, "customData", {}, "savedSelections", {}, "cachedPixelData", NULL, + }) + table.insert(defs.tilesets, d) + ctx.tilesetByName[ts.name] = d + ctx.tilesetByUid[d.uid] = d + end + end +end + +local function layerDef(ctx: Ctx, l: any, kind: string, grid: number, tsUid: number?): any + local d = ctx.layerDefs[l.name] + if d then + return d + end + local values = {} + for _, v in list(l.intGridValues) do + table.insert(values, obj({ "value", n(v.value, 1), "identifier", v.identifier or NULL, "color", v.color or "#FFFFFF", "tile", NULL, "groupUid", 0 })) + end + if kind == "IntGrid" and #values == 0 then + local maxV = 0 + for _, v in list(l.intGrid) do + maxV = math.max(maxV, n(v, 0)) + end + for v = 1, maxV do + table.insert(values, obj({ "value", v, "identifier", NULL, "color", "#FFFFFF", "tile", NULL, "groupUid", 0 })) + end + end + d = obj({ + "__type", kind, "identifier", l.name, "type", kind, "uid", nextUid(ctx), "doc", NULL, "uiColor", NULL, + "gridSize", grid, "guideGridWid", 0, "guideGridHei", 0, "displayOpacity", n(l.opacity, 1), "inactiveOpacity", 1, + "hideInList", false, "hideFieldsWhenInactive", true, "canSelectWhenInactive", true, "renderInWorldView", true, + "pxOffsetX", 0, "pxOffsetY", 0, "parallaxFactorX", 0, "parallaxFactorY", 0, "parallaxScaling", true, + "requiredTags", {}, "excludedTags", {}, "autoTilesKilledByOtherLayerUid", NULL, "uiFilterTags", {}, + "useAsyncRender", false, "intGridValues", values, "intGridValuesGroups", {}, "autoRuleGroups", {}, + "autoSourceLayerDefUid", NULL, "tilesetDefUid", tsUid or NULL, "tilePivotX", 0, "tilePivotY", 0, "biomeFieldUid", NULL, + }) + table.insert(ctx.defs.layers, d) + ctx.layerDefs[l.name] = d + return d +end + +local function entityDef(ctx: Ctx, o: any): any + local name = if type(o.class) == "string" and o.class ~= "" then o.class elseif type(o.name) == "string" and o.name ~= "" then o.name else "Entity" + local d = ctx.entityDefs[name] + if d then + return d + end + local pv = if tab(o.pivot) then o.pivot else { 0, 0 } + d = obj({ + "identifier", name, "uid", nextUid(ctx), "tags", {}, "exportToToc", false, "allowOutOfBounds", false, "doc", NULL, + "width", math.max(1, n(o.width, 16)), "height", math.max(1, n(o.height, 16)), "resizableX", false, + "resizableY", false, "minWidth", NULL, "maxWidth", NULL, "minHeight", NULL, "maxHeight", NULL, + "keepAspectRatio", false, "tileOpacity", 1, "fillOpacity", 0.08, "lineOpacity", 0, "hollow", false, + "color", if type(o.color) == "string" then o.color else "#94D9B3", "renderMode", "Rectangle", "showName", true, + "tilesetId", NULL, "tileRenderMode", "FitInside", "tileRect", NULL, "uiTileRect", NULL, "nineSliceBorders", {}, + "maxCount", 0, "limitScope", "PerLevel", "limitBehavior", "MoveLastOne", "pivotX", n(pv[1], 0), "pivotY", n(pv[2], 0), + "fieldDefs", {}, + }) + table.insert(ctx.defs.entities, d) + ctx.entityDefs[name] = d + return d +end + +-- ------------------------------------------------------------------------------------------------ layers +local function gridTiles(ctx: Ctx, l: any, grid: number, ts: any): { any } + local out = {} + if tab(l.tiles) then + for _, t in l.tiles do + local o = obj({ "px", { n(t.x, 0), n(t.y, 0) }, "src", { n(t.srcX, 0), n(t.srcY, 0) }, "f", n(t.flip, 0), "t", n(t.tile, 0) }) + if tab(t.d) then + set(o, "d", t.d) + end + set(o, "a", n(t.alpha, 1)) + table.insert(out, o) + end + return out + end + local w = n(l.width, 0) + for i, raw in list(l.data) do + local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) + if gid ~= 0 then + local tset = tilesetOf(ctx, gid) + if tset and (ts == nil or ctx.tilesetByName[tset.name] == ts) then + local id = gid - tset.firstGid + local cols = math.max(1, n(tset.columns, 1)) + local tw, th = n(tset.tileWidth, grid), n(tset.tileHeight, grid) + local sp, mg = n(tset.spacing, 0), n(tset.margin, 0) + local f = (if bit32.btest(raw, 0x80000000) then 1 else 0) + (if bit32.btest(raw, 0x40000000) then 2 else 0) + local cx, cy = (i - 1) % math.max(w, 1), (i - 1) // math.max(w, 1) + table.insert(out, obj({ + "px", { cx * grid, cy * grid }, "src", { mg + (id % cols) * (tw + sp), mg + (id // cols) * (th + sp) }, + "f", f, "t", id, "d", { cx + cy * w }, "a", 1, + })) + end + end + end + return out +end + +local function layerTileset(ctx: Ctx, l: any): any + if type(l.tileset) == "string" and ctx.tilesetByName[l.tileset] then + return ctx.tilesetByName[l.tileset] + end + if tab(l.ldtk) and type(l.ldtk.overrideTilesetUid) == "number" and ctx.tilesetByUid[l.ldtk.overrideTilesetUid] then + return ctx.tilesetByUid[l.ldtk.overrideTilesetUid] + end + for _, raw in list(l.data) do + local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) + if gid ~= 0 then + local tset = tilesetOf(ctx, gid) + return if tset then ctx.tilesetByName[tset.name] else nil + end + end + return nil +end + +local function entities(ctx: Ctx, l: any, levelIid: string, lx: number, ly: number, grid: number): { any } + local out = {} + for _, o in list(l.objects) do + if tab(o) then + local d = entityDef(ctx, o) + local w, h = n(o.width, n(d.width, 16)), n(o.height, n(d.height, 16)) + local pv = if tab(o.pivot) then o.pivot else { n(d.pivotX, 0), n(d.pivotY, 0) } + local px, py = n(o.x, 0) + n(pv[1], 0) * w, n(o.y, 0) + n(pv[2], 0) * h + local e = clone(o.ldtk) + set(e, "__identifier", d.identifier) + set(e, "__grid", { px // grid, py // grid }) + set(e, "__pivot", { n(pv[1], 0), n(pv[2], 0) }) + set(e, "__tags", if tab(o.tags) then o.tags else {}) + set(e, "__tile", if tab(o.tile) then o.tile else NULL) + set(e, "__smartColor", if type(o.color) == "string" then o.color else d.color) + if type(e.iid) ~= "string" then + set(e, "iid", if type(o.id) == "string" then o.id else newIid(ctx)) + end + set(e, "width", w) + set(e, "height", h) + set(e, "defUid", d.uid) + set(e, "px", { px, py }) + local fdefs: { [string]: any } = {} + for _, f in list(d.fieldDefs) do + if tab(f) and type(f.identifier) == "string" then + fdefs[f.identifier] = f + end + end + set(e, "fieldInstances", fieldInstances(ctx, o.fieldInstances, o.properties, o.propertyTypes, fdefs, d.fieldDefs)) + set(e, "__worldX", lx + px) + set(e, "__worldY", ly + py) + table.insert(out, e) + end + end + return out +end + +local function layerInstance(ctx: Ctx, l: any, levelUid: number, levelIid: string, lx: number, ly: number, pxW: number, pxH: number): any + local kind = if type(l.ldtkType) == "string" then l.ldtkType + elseif l.type == "objects" then "Entities" + elseif tab(l.intGrid) then "IntGrid" + else "Tiles" + local grid = math.max(1, n(l.gridSize, ctx.map.tileWidth)) + local ts = if kind ~= "Entities" then layerTileset(ctx, l) else nil + local d = layerDef(ctx, l, kind, grid, if ts then ts.uid else nil) + local cw = n(l.width, math.ceil(pxW / grid)) + local ch = n(l.height, math.ceil(pxH / grid)) + local li = clone(l.ldtk) + set(li, "__identifier", l.name) + set(li, "__type", kind) + set(li, "__cWid", cw) + set(li, "__cHei", ch) + set(li, "__gridSize", grid) + set(li, "__opacity", n(l.opacity, 1)) + set(li, "__pxTotalOffsetX", n(l.offsetX, 0)) + set(li, "__pxTotalOffsetY", n(l.offsetY, 0)) + set(li, "__tilesetDefUid", if ts then ts.uid else NULL) + set(li, "__tilesetRelPath", if ts and type(ts.relPath) == "string" then ts.relPath else NULL) + if type(li.iid) ~= "string" then + set(li, "iid", newIid(ctx)) + end + set(li, "levelId", levelUid) + set(li, "layerDefUid", d.uid) + if li.pxOffsetX == nil then + set(li, "pxOffsetX", n(l.offsetX, 0) - n(d.pxOffsetX, 0)) + set(li, "pxOffsetY", n(l.offsetY, 0) - n(d.pxOffsetY, 0)) + end + set(li, "visible", l.visible ~= false) + if li.optionalRules == nil then + set(li, "optionalRules", {}) + end + local csv = {} + if kind == "IntGrid" then + local g = list(l.intGrid) + for i = 1, cw * ch do + csv[i] = n(g[i], 0) + end + end + set(li, "intGridCsv", csv) + local tl = if kind ~= "Entities" then gridTiles(ctx, l, grid, ts) else {} + set(li, "autoLayerTiles", if kind == "IntGrid" or kind == "AutoLayer" then tl else {}) + if li.seed == nil then + set(li, "seed", 0) + end + if li.overrideTilesetUid == nil then + set(li, "overrideTilesetUid", NULL) + end + set(li, "gridTiles", if kind == "Tiles" then tl else {}) + set(li, "entityInstances", if kind == "Entities" then entities(ctx, l, levelIid, lx, ly, grid) else {}) + return li +end + +-- ------------------------------------------------------------------------------------------------ levels +local function flat(layers: { any }, into: { any }) + for _, l in layers do + if l.type == "group" and not l.level and not l.world then + flat(list(l.layers), into) + elseif l.type ~= "group" and l.type ~= "image" then + table.insert(into, l) + end + end +end + +local function levelValue(ctx: Ctx, g: any, layers: { any }, index: number): any + local lv = clone(g.ldtk) + local grid = ctx.map.tileWidth + local pxW = n(g.pxWidth, 0) + local pxH = n(g.pxHeight, 0) + if pxW <= 0 or pxH <= 0 then + for _, l in layers do + local gs = n(l.gridSize, grid) + pxW = math.max(pxW, n(l.width, 0) * gs) + pxH = math.max(pxH, n(l.height, 0) * gs) + end + pxW = if pxW > 0 then pxW else ctx.map.width * grid + pxH = if pxH > 0 then pxH else ctx.map.height * grid + end + local uid = if type(lv.uid) == "number" then lv.uid else nextUid(ctx) + local iid = if type(lv.iid) == "string" then lv.iid else newIid(ctx) + local lx, ly = n(g.offsetX, 0), n(g.offsetY, 0) + set(lv, "identifier", if type(g.name) == "string" and g.name ~= "" then g.name else "Level_" .. index) + set(lv, "iid", iid) + set(lv, "uid", uid) + set(lv, "worldX", lx) + set(lv, "worldY", ly) + if lv.worldDepth == nil then + set(lv, "worldDepth", 0) + end + set(lv, "pxWid", pxW) + set(lv, "pxHei", pxH) + set(lv, "__bgColor", if type(g.backgroundColor) == "string" then g.backgroundColor elseif type(ctx.map.backgroundColor) == "string" then ctx.map.backgroundColor else "#696A79") + for _, k in { "bgColor", "bgRelPath", "bgPos", "__smartColor", "__bgPos" } do + if lv[k] == nil then + set(lv, k, if k == "__smartColor" then "#ADADB5ff" else NULL) + end + end + if lv.useAutoIdentifier == nil then + set(lv, "useAutoIdentifier", false) + end + if lv.bgPivotX == nil then + set(lv, "bgPivotX", 0.5) + set(lv, "bgPivotY", 0.5) + end + set(lv, "externalRelPath", NULL) + set(lv, "fieldInstances", fieldInstances(ctx, lv.fieldInstances, g.properties, g.propertyTypes, ctx.levelFields, ctx.defs.levelFields)) + local out = {} + for i = #layers, 1, -1 do + table.insert(out, layerInstance(ctx, layers[i], uid, iid, lx, ly, pxW, pxH)) + end + set(lv, "layerInstances", out) + if lv.__neighbours == nil then + set(lv, "__neighbours", {}) + end + return lv +end + +local function levels(ctx: Ctx, layers: { any }): { any } + local out = {} + local loose = {} + for _, l in layers do + if l.type == "group" and not l.world then + local ls = {} + flat(list(l.layers), ls) + table.insert(out, levelValue(ctx, l, ls, #out)) + elseif l.type ~= "group" and l.type ~= "image" then + table.insert(loose, l) + end + end + if #loose > 0 then + table.insert(out, 1, levelValue(ctx, { name = "Level_0", properties = {}, offsetX = 0, offsetY = 0 }, loose, 0)) + end + return out +end + +local PROJECT: { any } = { + "__header__", NULL, "iid", NULL, "jsonVersion", "1.5.3", "appBuildId", 473703, "nextUid", 0, "identifierStyle", "Capitalize", + "toc", {}, "worldLayout", "Free", "worldGridWidth", 256, "worldGridHeight", 256, "defaultLevelWidth", 256, + "defaultLevelHeight", 256, "defaultPivotX", 0, "defaultPivotY", 0, "defaultGridSize", 16, "defaultEntityWidth", 16, + "defaultEntityHeight", 16, "bgColor", "#40465B", "defaultLevelBgColor", "#696A79", "minifyJson", false, + "externalLevels", false, "exportTiled", false, "simplifiedExport", false, "imageExportMode", "None", + "exportLevelBg", true, "pngFilePattern", NULL, "backupOnSave", false, "backupLimit", 10, "backupRelPath", NULL, + "levelNamePattern", "Level_%idx", "tutorialDesc", NULL, "customCommands", {}, "flags", {}, "defs", NULL, + "levels", NULL, "worlds", NULL, "dummyWorldIid", NULL, +} + +function Write.project(map: Types.TileMap, opts: any): (any, string?) + local ctx: Ctx = { + uid = 0, + iid = 0, + defs = nil, + tilesetByName = {}, + tilesetByUid = {}, + layerDefs = {}, + entityDefs = {}, + levelFields = {}, + map = map, + } + local raw = if tab(map.ldtk) then map.ldtk else nil + local p = if raw then clone(raw) else Json.object({}) + if not raw then + for i = 1, #PROJECT, 2 do + set(p, PROJECT[i], PROJECT[i + 1]) + end + set(p, "__header__", obj({ "fileType", "LDtk Project JSON", "app", "LDtk", "doc", "https://ldtk.io/json", "schema", "https://ldtk.io/files/JSON_SCHEMA.json", "appAuthor", "Sebastien 'deepnight' Benard", "appVersion", "1.5.3", "url", "https://ldtk.io" })) + set(p, "iid", newIid(ctx)) + set(p, "defaultGridSize", map.tileWidth) + end + ctx.uid = math.max(ctx.uid, n(p.nextUid, 1) - 1) + defsFor(ctx, p.defs) + local worlds = {} + local hasWorlds = false + for _, l in map.layers do + if l.type == "group" and l.world then + hasWorlds = true + end + end + local lvls: { any } = {} + if hasWorlds then + for _, l in map.layers do + if l.type == "group" and l.world then + local w = clone(l.ldtk) + set(w, "identifier", l.name) + if type(w.iid) ~= "string" then + set(w, "iid", newIid(ctx)) + end + for _, k in { "worldGridWidth", "worldGridHeight" } do + if w[k] == nil then + set(w, k, 256) + end + end + if w.worldLayout == nil then + set(w, "worldLayout", "Free") + end + set(w, "levels", levels(ctx, list(l.layers))) + table.insert(worlds, w) + end + end + else + lvls = levels(ctx, map.layers) + end + if type(map.backgroundColor) == "string" then + set(p, "bgColor", map.backgroundColor) + end + if type(map.worldLayout) == "string" and not hasWorlds then + set(p, "worldLayout", map.worldLayout) + end + set(p, "externalLevels", false) + set(p, "defs", ctx.defs) + set(p, "levels", lvls) + set(p, "worlds", worlds) + if type(p.dummyWorldIid) ~= "string" then + set(p, "dummyWorldIid", newIid(ctx)) + end + set(p, "nextUid", ctx.uid + 1) + return p, nil +end + +return Write diff --git a/src/Rosetta/vector/ldtk/init.luau b/src/Rosetta/vector/ldtk/init.luau new file mode 100644 index 0000000..cdc139e --- /dev/null +++ b/src/Rosetta/vector/ldtk/init.luau @@ -0,0 +1,90 @@ +--!strict +-- vector/ldtk: LDtk projects (.ldtk JSON, ldtk.io/json, 1.x) as a TileMap, read + write. Supports: IntGrid, +-- AutoLayer, Tiles and Entities layers, tilesets as image paths, typed fields (properties), multi-world projects, +-- external levels (.ldtkl through opts.resolve). Not supported: auto-layer rules are kept, never run; writing +-- external level files (levels are embedded); standalone .ldtkl files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Sniff = require("@rosetta/core/Sniff") +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") +local Read = require("@rosetta/vector/ldtk/Read") +local Write = require("@rosetta/vector/ldtk/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ldtk = { + name = "ldtk", + category = "vector", + extensions = { "ldtk" }, + mime = { "application/x-ldtk+json" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" }, + caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- default 2^28 + maxCells: number?, -- per layer, default 2^26 + resolve: ((string) -> buffer?)?, -- external .ldtkl level files by their relative path +} +export type EncodeOptions = { + indent: number?, -- default 2; 0 = compact +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ldtk.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 1024) + if not string.match(h, "^%s*{") then + return 0 + end + if string.find(h, "\"fileType\"%s*:%s*\"LDtk Project JSON\"") then + return 1 + end + if string.find(h, "\"jsonVersion\"", 1, true) and string.find(h, "\"worldLayout\"", 1, true) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ldtk.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) + local o: any = opts or {} + if r.limit - r.base > (o.maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true }) + if v == nil then + return nil, jerr + end + local ok, map, msg = pcall(Read.project, v, o) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad project: " .. tostring(map)) + end + if not map then + return nil, Err.from(msg) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ldtk.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then + return nil, Err.new(Err.ARG, "needs a TileMap value") + end + local ok, v, msg = pcall(Write.project, map, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad map: " .. tostring(v)) + end + if v == nil then + return nil, Err.new(Err.ARG, msg or "bad map") + end + local indent = if opts and opts.indent == 0 then nil else (opts and opts.indent or 2) + local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s), nil +end + +return Ldtk diff --git a/tests/vector/ldtk.luau b/tests/vector/ldtk.luau new file mode 100644 index 0000000..2971c61 --- /dev/null +++ b/tests/vector/ldtk.luau @@ -0,0 +1,278 @@ +-- vector/ldtk tests: LDtk's sample projects (and a multi-world one) against the editor's own JSON (levels, layers, +-- tile lists, IntGrid values, entities), external levels through resolve; our writer's output summarised by Python; +-- round trips; a TileMap from Tiled written as LDtk; errors; fuzz. Fixtures: tools/fixtures/ldtk.py. +local T = require("@tests/T") +local F = require("@rosetta") +local Ldtk = require("@rosetta/vector/ldtk") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/ldtk") +local Ours = require("@tests/gen/ldtk_ours") + +local t = T.suite("ldtk") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Ldtk.decode(Bytes.reader(b), opts) +end + +t:eq(Ldtk.name, "ldtk", "name") +t:eq(Ldtk.category, "vector", "category") +t:check(Ldtk.caps.decode and Ldtk.caps.encode, "caps") + +local function levelsOf(map: any): { { group: any, world: string } } + local out = {} + for _, l in map.layers do + if l.world then + for _, lv in l.layers do + table.insert(out, { group = lv, world = l.name }) + end + else + table.insert(out, { group = l, world = "" }) + end + end + return out +end + +-- our TileMap summarised like tools/fixtures/ldtk.py summarises the JSON +local function stats(map: any): any + local levels = {} + for _, it in levelsOf(map) do + local g = it.group + local layers = {} + for _, l in g.layers do + local tl = l.tiles or {} + local sum, flips = 0, 0 + for i, x in tl do + sum += x.tile * ((i - 1) % 7 + 1) + if x.flip ~= 0 then + flips += 1 + end + end + local ic, is = 0, 0 + for _, v in l.intGrid or {} do + if v ~= 0 then + ic += 1 + end + is += v + end + local names, epx = {}, 0 + for _, o in l.objects or {} do + table.insert(names, o.class) + epx += (o.x + o.pivot[1] * o.width) * 3 + (o.y + o.pivot[2] * o.height) + end + table.insert(layers, { + identifier = l.name, + type = l.ldtkType, + cWid = l.width or 0, + cHei = l.height or 0, + grid = l.gridSize, + tiles = #tl, + tileSum = sum, + flips = flips, + intCount = ic, + intSum = is, + entities = #(l.objects or {}), + entityNames = table.concat(names, ","), + entityPx = epx, + }) + end + local nf = 0 + for _ in g.properties do + nf += 1 + end + table.insert(levels, { identifier = g.name, worldX = g.offsetX, worldY = g.offsetY, pxWid = g.pxWidth, pxHei = g.pxHeight, world = it.world, fields = nf, layers = layers }) + end + local ts = {} + for i, x in map.tilesets do + ts[i] = x.name + end + return { levels = levels, tilesets = ts } +end + +local function diff(a: any, b: any, path: string, out: { string }) + if #out > 6 then + return + end + if type(a) == "table" and type(b) == "table" then + for k, v in a do + diff(v, b[k], path .. "." .. tostring(k), out) + end + for k, v in b do + if a[k] == nil then + diff(nil, v, path .. "." .. tostring(k), out) + end + end + elseif a ~= b then + table.insert(out, path .. ": " .. tostring(a) .. " vs " .. tostring(b)) + end +end + +local function sameStats(got: any, want: any, label: string) + local out = {} + -- entity-less layers report cWid 0 in ours when unknown: compare only layers' known widths + for _, lv in got.levels do + for _, l in lv.layers do + if l.type == "Entities" then + l.cWid, l.cHei = nil, nil + end + end + end + for _, lv in want.levels do + for _, l in lv.layers do + if l.type == "Entities" then + l.cWid, l.cHei = nil, nil + end + end + end + diff(got, want, "", out) + t:check(#out == 0, label .. ": " .. table.concat(out, "; ")) +end + +local maps: { [string]: any } = {} +local samples = {} +for _, c in Fx.cases do + local function resolve(p: string): buffer? + local f = c.files[p] + return if f then buffer.fromstring(f) else nil + end + local map, err = decode(c.data, { resolve = resolve }) + t:check(map, c.name .. ": decode: " .. tostring(err)) + if map then + maps[c.name] = map + t:eq(map.kind, "tilemap", c.name .. ": kind") + sameStats(stats(map), c.stats, c.name .. ": = LDtk's JSON") + end + t:check(Ldtk.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.8, c.name .. ": sniff") + if #c.data < 200000 then + table.insert(samples, c.data) + end +end + +-- Python's summary of our output = LDtk's +for _, o in Ours do + local want + for _, c in Fx.cases do + if c.name == o.name then + want = c.stats + end + end + sameStats(o.stats, want, o.name .. ": our LDtk output (Python)") +end + +-- details of the API sample +do + local m = maps["Test_file_for_API_showing_all_features.ldtk"] + t:eq(m.meta.source.version, "1.5.3", "json version") + local lv = m.layers[1] + t:check(lv.type == "group" and lv.level == true and lv.name ~= "", "level group") + local ents + for _, l in lv.layers do + if l.type == "objects" then + ents = l + end + end + t:check(ents and #ents.objects > 0, "entities layer") + local e = ents.objects[1] + t:eq(e.class, "EntityFieldsTest", "entity identifier") + t:eq(e.properties.Integer, 1, "Int field") + t:eq(e.properties.Float, 1.5, "Float field") + t:eq(e.properties.String_singleLine, "foo", "String field") + t:eq(e.propertyTypes.Enum, "LocalEnum.SomeEnum", "enum field type") + t:eq(e.properties.Color, "#D181E8", "Color field") + t:eq(e.x, 152 - 16, "entity x = px - pivot * width") + local top = lv.layers[#lv.layers] + t:eq(top.ldtkType, "Entities", "LDtk's first layer is drawn last") + local tiles + for _, l in lv.layers do + if l.ldtkType == "Tiles" then + tiles = l + end + end + local ts = m.tilesets[1] + t:eq(ts.imageSource, "atlas/Inca_front_by_Kronbits-extended.png", "tileset image path") + local first = tiles.tiles[1] + local cell = tiles.data[1 + first.x // 16 + (first.y // 16) * tiles.width] + t:check(bit32.band(cell, 0x0FFFFFFF) - ts.firstGid >= 0, "gid grid from the tile list") +end + +do + local m = maps["SeparateLevelFiles.ldtk"] + t:check(m.meta.source.externalLevels, "external levels flag") + t:check(m.layers[1].external and #m.layers[1].layers > 0, "external level loaded through resolve") + local c + for _, x in Fx.cases do + if x.name == "SeparateLevelFiles.ldtk" then + c = x + end + end + local nores = decode(c.data) + t:check(nores and nores.layers[1].unresolved and #nores.layers[1].layers == 0, "external level without resolve") +end + +do + local m = maps["multiworld.ldtk"] + t:check(m.meta.source.multiWorld and #m.layers == 2 and m.layers[1].world and m.layers[2].name == "Caves", "worlds") +end + +-- edits survive a save +do + local m = maps["Test_file_for_API_showing_all_features.ldtk"] + local lv = m.layers[1] + lv.properties = lv.properties or {} + local ents + for _, l in lv.layers do + if l.type == "objects" then + ents = l + end + end + ents.objects[1].properties.Integer = 42 + ents.objects[1].x += 16 + local out = assert(Ldtk.encode(m)) + local back = assert(decode(out)) + local e2 + for _, l in back.layers[1].layers do + if l.type == "objects" then + e2 = l.objects[1] + end + end + t:eq(e2.properties.Integer, 42, "edited field") + t:eq(e2.x, 152, "moved entity") + local s = buffer.tostring(out) + t:check(string.find(s, "\"V_Int\",%s*\"params\":%s*%[%s*42%s*%]") ~= nil, "realEditorValues updated") + t:check(F.detect(out) == "ldtk", "F.detect") +end + +-- a Tiled map as LDtk: a tile layer and objects +do + local map = Types.TileMap.new(3, 2, 16, 16) + table.insert(map.tilesets, { name = "terrain", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 4, count = 8, imageSource = "terrain.png", imageWidth = 64, imageHeight = 32 }) + table.insert(map.layers, { type = "tiles", name = "Ground", width = 3, height = 2, visible = true, opacity = 1, properties = {}, data = { 1, 2, 0, 0, 6, bit32.bor(8, 0x80000000) } }) + table.insert(map.layers, { type = "objects", name = "Things", visible = true, opacity = 1, properties = {}, objects = { { name = "spawn", class = "Spawn", x = 16, y = 0, width = 16, height = 16, properties = { hp = 3 } } } }) + local out = assert(F.save(map, nil, { format = "ldtk" })) + local back = assert(decode(out)) + local lv = back.layers[1] + t:eq(#lv.layers, 2, "tiled -> ldtk: one level, two layers") + local g = lv.layers[1] + t:eq(g.ldtkType, "Tiles", "tile layer") + t:eq(#g.tiles, 4, "tiles") + t:eq(g.data[6], bit32.bor(8, 0x80000000), "gid + flip") + t:eq(g.tiles[4].srcX, 48, "src x from the tileset columns") + local o = lv.layers[2].objects[1] + t:check(o.class == "Spawn" and o.x == 16 and o.properties.hp == 3, "entity with a made field definition") +end + +do + local _, e = decode("{\"jsonVersion\": \"1.5.3\"}") + t:check(e and e.code == Err.CORRUPT, "no defs") + local _, e2 = decode("{") + t:check(e2 ~= nil, "bad JSON") + local _, e3 = Ldtk.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode arg") +end + +t:fuzz("decode", function(b: buffer) + return decode(b) +end, samples, { mutations = 60, garbage = 20 }) +t:done() diff --git a/tools/fixtures/_ldtk_encode.luau b/tools/fixtures/_ldtk_encode.luau new file mode 100644 index 0000000..1dff7dd --- /dev/null +++ b/tools/fixtures/_ldtk_encode.luau @@ -0,0 +1,30 @@ +-- tools/fixtures/_ldtk_encode: run by tools/fixtures/ldtk.py (luau CLI, repo root): decodes every LDtk case (external +-- levels through resolve) and writes it with our encoder, printing "\t" lines for Python to summarise. +local Ldtk = require("@rosetta/vector/ldtk") +local Bytes = require("@rosetta/core/Bytes") +local Fx = require("@tests/gen/ldtk") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + return (string.gsub(s, ".", function(c: string): string + return HEX[string.byte(c)] + end)) +end + +for _, c in Fx.cases do + local map = Ldtk.decode(Bytes.reader(buffer.fromstring(c.data)), { + resolve = function(p: string): buffer? + local f = c.files[p] + return if f then buffer.fromstring(f) else nil + end, + }) + if map then + local out = Ldtk.encode(map) + if out then + print(c.name .. "\t" .. hex(buffer.tostring(out))) + end + end +end diff --git a/tools/fixtures/docs_engines.py b/tools/fixtures/docs_engines.py index 4a998f0..ad8ae97 100644 --- a/tools/fixtures/docs_engines.py +++ b/tools/fixtures/docs_engines.py @@ -1,9 +1,9 @@ # Docs inputs for the engine / level-editor sections of the scene, tile map, archive and data pages (tools/fixtures.py, -# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py. +# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py). # tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } } import importlib.util, os -INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py"] +INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py"] def mod(ctx, name): @@ -16,5 +16,6 @@ def mod(ctx, name): def generate(ctx): check = mod(ctx, "../docs_check") files = {"hand.ase": mod(ctx, "ase").HAND.encode()} - vars = {"aseText": "hand.ase"} + files["stamps.ldtk"] = open(os.path.join(mod(ctx, "ldtk").samples_dir(ctx), "AutoLayers_2_stamps.ldtk"), "rb").read() + vars = {"aseText": "hand.ase", "ldtkText": "stamps.ldtk"} check.emit_inputs(ctx, files, vars) diff --git a/tools/fixtures/ldtk.py b/tools/fixtures/ldtk.py new file mode 100644 index 0000000..fce702e --- /dev/null +++ b/tools/fixtures/ldtk.py @@ -0,0 +1,111 @@ +# LDtk fixtures (tools/fixtures.py): the sample projects shipped with LDtk 1.5.3 (MIT; extraFiles/samples inside +# the nixpkgs ldtk AppImage, read there and never committed), including SeparateLevelFiles (.ldtkl external levels), +# plus a multi-world project made here from Typical_TopDown_example (its levels split over two worlds). Reference +# values are read from the LDtk JSON by Python (the editor's own export: __cWid / __identifier / tile and entity +# lists). Then our encoder's output (tools/fixtures/_ldtk_encode.luau) is summarised the same way. +# tests/gen/ldtk.luau { cases = { { name, data, files = { [relPath] = bytes }, stats } } } +# tests/gen/ldtk_ours.luau { { name, stats } } +# stats: { levels = { { identifier, worldX, worldY, pxWid, pxHei, world, fields, layers = { { identifier, type, cWid, +# cHei, grid, tiles, tileSum, flips, intCount, intSum, entities, entityNames, entityPx } } } }, tilesets = { names } } +import copy, importlib.util, json, os, subprocess, tempfile, zlib + +INPUTS = ["src/Rosetta/vector/ldtk", "tools/fixtures/_ldtk_encode.luau", "tools/fixtures/_model_ref.py"] + +SAMPLES = ["Test_file_for_API_showing_all_features.ldtk", "Typical_2D_platformer_example.ldtk", "Typical_TopDown_example.ldtk", + "Entities.ldtk", "AutoLayers_1_basic.ldtk", "AutoLayers_2_stamps.ldtk", "AutoLayers_4_Assistant.ldtk", + "AutoLayers_5_Advanced.ldtk", "SeparateLevelFiles.ldtk", "WorldMap_Free_layout.ldtk"] + + +def samples_dir(ctx): + store = subprocess.run(["nix", "build", "nixpkgs#ldtk", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().split()[-1] + image = os.path.join(store, "share", "ldtk.AppImage") + out = os.path.join(tempfile.gettempdir(), "rosetta-ldtk-" + os.path.basename(store)) + target = os.path.join(out, "sq", "extraFiles", "samples") + if os.path.isdir(target): + return target + os.makedirs(out, exist_ok=True) + data = open(image, "rb").read() + at = 0 + while True: + at = data.find(b"hsqs", at + 1) + if at < 0: + raise RuntimeError("no squashfs in the LDtk AppImage") + try: + ctx.nix("squashfsTools", ["unsquashfs", "-q", "-f", "-o", str(at), "-d", os.path.join(out, "sq"), image, "extraFiles/samples"]) + if os.path.isdir(target): + return target + except subprocess.CalledProcessError: + pass + + +def stats(project, files): + def levels_of(p): + if p.get("worlds"): + for w in p["worlds"]: + for lv in w["levels"]: + yield w["identifier"], lv + else: + for lv in p["levels"]: + yield "", lv + + out = [] + for world, lv in levels_of(project): + if lv.get("layerInstances") is None and lv.get("externalRelPath"): + lv = json.loads(files[lv["externalRelPath"]]) + layers = [] + for li in reversed(lv["layerInstances"] or []): + tl = li["gridTiles"] if li["__type"] == "Tiles" else li["autoLayerTiles"] + ents = li["entityInstances"] + ints = li["intGridCsv"] + layers.append({ + "identifier": li["__identifier"], "type": li["__type"], "cWid": li["__cWid"], "cHei": li["__cHei"], + "grid": li["__gridSize"], "tiles": len(tl), "tileSum": sum(t["t"] * (i % 7 + 1) for i, t in enumerate(tl)), + "flips": sum(1 for t in tl if t["f"]), "intCount": sum(1 for v in ints if v), "intSum": sum(ints), + "entities": len(ents), "entityNames": ",".join(e["__identifier"] for e in ents), + "entityPx": sum(e["px"][0] * 3 + e["px"][1] for e in ents), + }) + out.append({"identifier": lv["identifier"], "worldX": lv["worldX"], "worldY": lv["worldY"], "pxWid": lv["pxWid"], + "pxHei": lv["pxHei"], "world": world, "fields": len(lv["fieldInstances"]), "layers": layers}) + return {"levels": out, "tilesets": [t["identifier"] for t in project["defs"]["tilesets"]]} + + +def multiworld(project): + p = copy.deepcopy(project) + lv = p["levels"] + half = max(1, len(lv) // 2) + p["worlds"] = [ + {"iid": "a0000000-0000-4000-8000-000000000001", "identifier": "Overworld", "worldGridWidth": 256, "worldGridHeight": 256, + "worldLayout": "Free", "levels": lv[:half]}, + {"iid": "a0000000-0000-4000-8000-000000000002", "identifier": "Caves", "worldGridWidth": 256, "worldGridHeight": 256, + "worldLayout": "Free", "levels": lv[half:]}, + ] + p["levels"] = [] + p["flags"] = sorted(set(p.get("flags", [])) | {"MultiWorlds"}) + p["worldLayout"] = None + return p + + +def generate(ctx): + d = samples_dir(ctx) + cases = [] + for name in SAMPLES: + raw = open(os.path.join(d, name), "rb").read() + project = json.loads(raw) + files = {} + for lv in project["levels"]: + rel = lv.get("externalRelPath") + if rel: + files[rel] = open(os.path.join(d, rel), "rb").read() + cases.append({"name": name, "data": raw, "files": files, "stats": stats(project, files)}) + top = json.loads(open(os.path.join(d, "Typical_TopDown_example.ldtk"), "rb").read()) + mw = multiworld(top) + cases.append({"name": "multiworld.ldtk", "data": json.dumps(mw, indent=1).encode(), "files": {}, "stats": stats(mw, {})}) + ctx.emit("ldtk", {"cases": cases}) + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + M = importlib.util.module_from_spec(spec) + spec.loader.exec_module(M) + ours = [] + for name, data in sorted(M.luau_encode(ctx, "tools/fixtures/_ldtk_encode.luau").items()): + p = json.loads(data) + ours.append({"name": name, "stats": stats(p, {})}) + ctx.emit("ldtk_ours", ours)