vector/ldtk: LDtk projects read + write as a TileMap (levels as groups, worlds, IntGrid / auto / tile / entity layers, fields, external levels through resolve)
This commit is contained in:
1 parent
524179ec67
commit
1f74419ccf
11 files changed
+1557
-6
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user