vec: vector/tiled (TMX + TMJ + TSX/TSJ read/write into TileMap: all data encodings, chunks, objects, typed properties, tilesets as references); core/Base64 (new, small); Types: TileMap.new + open TileMap/Tileset/TileLayer fields; api: F.save passes the destination extension as opts.format when none is given (tmx vs tmj). Tests vs Tiled exports and Tiled reading our files

This commit is contained in:
4DBug committed 2026-10-31 08:54:35 -05:00
1 parent 63294e13bd
commit a762554f2c
13 files changed
+2239 -3

No files matched your search

+12
View File
@@ -50,6 +50,18 @@ local list: { Entry } = {
return require("@formats/data/xml")
end,
},
{
name = "tiled",
category = "vector",
path = "vector/tiled",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
load = function()
return require("@formats/vector/tiled")
end,
},
{
name = "aseprite",
category = "layered",
+12 -2
View File
@@ -681,8 +681,12 @@ end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string? }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any } }
-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept).
-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller
-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite
-- maps, objects' shapes, per-tile data, ...: see vector/tiled).
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any }
export type TileMap = {
kind: "tilemap",
width: number,
@@ -694,7 +698,13 @@ export type TileMap = {
layers: { TileLayer },
properties: { [string]: any },
meta: { [string]: any },
[string]: any,
}
local TileMap = {}
function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap
return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} }
end
Types.TileMap = TileMap
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
+89
View File
@@ -0,0 +1,89 @@
--!strict
--!native
-- core/Base64: RFC 4648 base64 (standard alphabet, and the URL-safe one on decode). Tiled map data, data: URIs, ...
-- decode skips whitespace and accepts missing padding; other bad characters fail. Never throws.
--
-- local s = Base64.encode(buf) -- buffer | string -> string
-- local b, err = Base64.decode(s) -- string -> buffer | nil, "message"
local Base64 = {}
local ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local ENC = buffer.create(64)
buffer.writestring(ENC, 0, ALPHABET)
local DEC = buffer.create(256)
buffer.fill(DEC, 0, 255)
for i = 0, 63 do
buffer.writeu8(DEC, string.byte(ALPHABET, i + 1), i)
end
buffer.writeu8(DEC, string.byte("-"), 62)
buffer.writeu8(DEC, string.byte("_"), 63)
for _, c in { 9, 10, 13, 32 } do
buffer.writeu8(DEC, c, 254) -- whitespace: skipped
end
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- encode(data) -> base64 text with padding
function Base64.encode(data: buffer | string): string
local src: buffer = if type(data) == "string" then buffer.fromstring(data) else data
local n = buffer.len(src)
local out = buffer.create((n + 2) // 3 * 4)
local o = 0
local i = 0
while i + 2 < n do
local v = readu8(src, i) * 65536 + readu8(src, i + 1) * 256 + readu8(src, i + 2)
writeu8(out, o, readu8(ENC, v // 262144))
writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
writeu8(out, o + 2, readu8(ENC, v // 64 % 64))
writeu8(out, o + 3, readu8(ENC, v % 64))
i += 3
o += 4
end
local rest = n - i
if rest > 0 then
local v = readu8(src, i) * 65536 + (if rest == 2 then readu8(src, i + 1) * 256 else 0)
writeu8(out, o, readu8(ENC, v // 262144))
writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
writeu8(out, o + 2, if rest == 2 then readu8(ENC, v // 64 % 64) else 61)
writeu8(out, o + 3, 61)
end
return buffer.tostring(out)
end
-- decode(text) -> buffer | nil, message
function Base64.decode(text: string | buffer): (buffer?, string?)
local src: buffer = if type(text) == "string" then buffer.fromstring(text) else text
local n = buffer.len(src)
local out = buffer.create(n // 4 * 3 + 3)
local o = 0
local acc, bits = 0, 0
local pad = false
for i = 0, n - 1 do
local c = readu8(src, i)
local v = readu8(DEC, c)
if v == 254 then
continue
end
if c == 61 then -- '='
pad = true
continue
end
if v == 255 or pad then
return nil, string.format("bad base64 character at %d", i)
end
acc = acc * 64 + v
bits += 6
if bits >= 8 then
bits -= 8
local p = 2 ^ bits
writeu8(out, o, acc // p)
acc %= p
o += 1
end
end
local res = buffer.create(o)
buffer.copy(res, 0, out, 0, o)
return res, nil
end
return Base64
+8 -1
View File
@@ -274,7 +274,14 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
if not entry then
return nil, err
end
local ok, buf, e = pcall(m.encode, value, o)
-- a format with several flavours (vector/tiled: tmx / tmj) picks one from opts.format: give it the destination's
-- extension when the caller named none
local eo = o
if o.format == nil and dest ~= nil then
eo = table.clone(o)
eo.format = Input.extension(dest)
end
local ok, buf, e = pcall(m.encode, value, eo)
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
end
+156
View File
@@ -0,0 +1,156 @@
--!strict
-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip)
-- to gids and back; property values and their types; number formatting. Never throws.
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/Deflate")
local Data = {}
-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message
function Data.csv(text: string): ({ number }?, string?)
local out = {}
for tok in string.gmatch(text, "[^,%s]+") do
local v = tonumber(tok)
if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then
return nil, "bad gid " .. string.sub(tok, 1, 20)
end
table.insert(out, v)
end
return out, nil
end
-- base64(text, compression) -> { gid } | nil, message, unsupported?
function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?)
local raw, err = Base64.decode(text)
if not raw then
return nil, err
end
local bytes: buffer = raw
if compression == "zlib" then
local z, zerr = Deflate.zlib(bytes)
if not z then
return nil, "zlib: " .. tostring(zerr)
end
bytes = z
elseif compression == "gzip" then
local z, zerr = Deflate.gunzip(bytes)
if not z then
return nil, "gzip: " .. tostring(zerr)
end
bytes = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported", true
end
local n = buffer.len(bytes) // 4
local out = table.create(n)
for i = 0, n - 1 do
out[i + 1] = buffer.readu32(bytes, i * 4)
end
return out, nil
end
-- toBase64(gids, compression?, level?) -> text | nil, message
function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?)
local b = buffer.create(#gids * 4)
for i, g in gids do
buffer.writeu32(b, (i - 1) * 4, g % 4294967296)
end
if compression == "zlib" then
local z = Deflate.zlibCompress(b, { level = level or 6 })
if not z then
return nil, "zlib failed"
end
b = z
elseif compression == "gzip" then
local z = Deflate.gzip(b, { level = level or 6 })
if not z then
return nil, "gzip failed"
end
b = z
elseif compression ~= nil and compression ~= "" then
return nil, "compression " .. compression .. " is not supported"
end
return Base64.encode(b), nil
end
-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print
function Data.num(v: number): string
if v % 1 == 0 and math.abs(v) < 2 ^ 53 then
return string.format("%.0f", v)
end
local s = string.format("%.15g", v)
if tonumber(s) ~= v then
s = string.format("%.17g", v)
end
return s
end
-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line)
function Data.csvText(gids: { number }, width: number): string
local rows = {}
local row = {}
for i, g in gids do
table.insert(row, Data.num(g))
if width > 0 and i % width == 0 then
table.insert(rows, table.concat(row, ","))
row = {}
end
end
if #row > 0 then
table.insert(rows, table.concat(row, ","))
end
return "\n" .. table.concat(rows, ",\n") .. "\n"
end
-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil)
function Data.color(s: string?): string?
if type(s) ~= "string" then
return nil
end
local h = string.lower((string.gsub(s, "^#", "")))
if #h == 8 and string.sub(h, 1, 2) == "ff" then
h = string.sub(h, 3)
end
return "#" .. h
end
-- property values: TMX / TMJ type names -> a Luau value from text
function Data.value(typ: string, text: string): any
if typ == "int" or typ == "float" or typ == "object" then
return tonumber(text) or 0
elseif typ == "bool" then
return text == "true" or text == "1"
elseif typ == "color" then
return Data.color(text) or ""
end
return text
end
-- typeOf(v, declared?) -> the Tiled type to write for v
function Data.typeOf(v: any, declared: string?): string
if declared then
return declared
end
if type(v) == "boolean" then
return "bool"
elseif type(v) == "number" then
return if v % 1 == 0 then "int" else "float"
elseif type(v) == "table" then
return "class"
end
return "string"
end
-- sortedKeys(t) -> its string keys, sorted
function Data.sortedKeys(t: { [any]: any }): { string }
local out = {}
for k in pairs(t) do
if type(k) == "string" then
table.insert(out, k)
end
end
table.sort(out)
return out
end
return Data
+634
View File
@@ -0,0 +1,634 @@
--!strict
-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ
-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
local Types = require("@formats/Types")
local Data = require("@formats/vector/tiled/Data")
local Tmj = {}
local function n(v: any, default: number?): number?
if type(v) == "number" then
return v
end
return default
end
local function b(v: any, default: boolean): boolean
if type(v) == "boolean" then
return v
end
return default
end
local function s(v: any): string?
if type(v) == "string" then
return v
end
return nil
end
local function list(v: any): { any }
if type(v) == "table" then
return v
end
return {}
end
-- ------------------------------------------------------------------------------------------------ read
local function properties(v: any): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
for _, p in list(v) do
if type(p) == "table" and type(p.name) == "string" then
local typ = s(p.type) or "string"
local val: any = p.value
if typ == "class" then
local inner, innerTypes = {}, nil
if type(val) == "table" then
-- a class value is an object of member -> value (types come from the project): keep them as they are
for k, x in pairs(val) do
if type(k) == "string" then
inner[k] = x
end
end
end
val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes }
elseif typ == "int" or typ == "float" or typ == "object" then
val = n(val, 0)
elseif typ == "bool" then
val = val == true
elseif typ == "color" then
val = Data.color(s(val)) or ""
elseif type(val) ~= "string" then
val = if val == nil then "" else tostring(val)
end
props[p.name] = val
if typ ~= "string" then
types = types or {}
;(types :: any)[p.name] = typ
end
end
end
return props, types
end
local function withProps(t: any, v: any)
local props, types = properties(v.properties)
t.properties = props
if types then
t.propertyTypes = types
end
end
local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if type(v) == "string" then
if encoding == "base64" or encoding == nil then
return Data.base64(v, compression)
end
return nil, "unknown encoding " .. tostring(encoding), true
end
local out = {}
for _, g in list(v) do
if type(g) ~= "number" or g < 0 or g >= 4294967296 then
return nil, "bad gid"
end
table.insert(out, g)
end
return out, nil
end
local function object(o: any): any
local obj: any = {
id = n(o.id),
name = s(o.name) or "",
class = s(o.class) or s(o.type) or "",
x = n(o.x, 0),
y = n(o.y, 0),
width = n(o.width, 0),
height = n(o.height, 0),
rotation = n(o.rotation, 0),
gid = n(o.gid),
visible = b(o.visible, true),
template = s(o.template),
shape = "rectangle",
}
withProps(obj, o)
if o.ellipse == true then
obj.shape = "ellipse"
elseif o.point == true then
obj.shape = "point"
end
for _, kind in { "polygon", "polyline" } do
if type(o[kind]) == "table" then
obj.shape = kind
local pts = {}
for _, p in o[kind] do
if type(p) == "table" then
table.insert(pts, { n(p.x, 0), n(p.y, 0) })
end
end
obj.points = pts
end
end
if type(o.text) == "table" then
local t = o.text
obj.shape = "text"
obj.text = {
text = s(t.text) or "",
fontFamily = s(t.fontfamily) or "sans-serif",
pixelSize = n(t.pixelsize, 16),
wrap = b(t.wrap, false),
color = Data.color(s(t.color)) or "#000000",
bold = b(t.bold, false),
italic = b(t.italic, false),
underline = b(t.underline, false),
strikeout = b(t.strikeout, false),
kerning = b(t.kerning, true),
halign = s(t.halign) or "left",
valign = s(t.valign) or "top",
}
end
return obj
end
local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" }
local layer: (v: any, depth: number) -> (any, string?, boolean?)
local function common(v: any, typ: string): any
local l: any = {
type = typ,
id = n(v.id),
name = s(v.name) or "",
visible = b(v.visible, true),
opacity = n(v.opacity, 1),
x = n(v.x, 0),
y = n(v.y, 0),
offsetX = n(v.offsetx, 0),
offsetY = n(v.offsety, 0),
parallaxX = n(v.parallaxx, 1),
parallaxY = n(v.parallaxy, 1),
tintColor = Data.color(s(v.tintcolor)),
class = s(v.class) or "",
locked = b(v.locked, false),
}
withProps(l, v)
return l
end
local function objectGroup(v: any): any
local l = common(v, "objects")
l.drawOrder = s(v.draworder) or "topdown"
l.color = Data.color(s(v.color))
l.objects = {}
for _, o in list(v.objects) do
if type(o) == "table" then
table.insert(l.objects, object(o))
end
end
return l
end
layer = function(v: any, depth: number): (any, string?, boolean?)
if type(v) ~= "table" then
return nil, "a layer is not an object"
end
if depth > 100 then
return nil, "groups nested too deep"
end
local typ = TYPES[v.type]
if typ == "tiles" then
local l = common(v, "tiles")
l.width = n(v.width, 0)
l.height = n(v.height, 0)
l.encoding = s(v.encoding)
l.compression = s(v.compression)
if type(v.chunks) == "table" then
l.chunks = {}
for _, c in v.chunks do
if type(c) == "table" then
local g, err, uns = gids(c.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g })
end
end
elseif v.data ~= nil then
local g, err, uns = gids(v.data, l.encoding, l.compression)
if not g then
return nil, err, uns
end
l.data = g
end
return l
elseif typ == "objects" then
return objectGroup(v)
elseif typ == "image" then
local l = common(v, "image")
l.imageSource = s(v.image)
l.imageWidth = n(v.imagewidth)
l.imageHeight = n(v.imageheight)
l.transparentColor = Data.color(s(v.transparentcolor))
l.repeatX = b(v.repeatx, false)
l.repeatY = b(v.repeaty, false)
return l
elseif typ == "group" then
local l = common(v, "group")
l.layers = {}
for _, c in list(v.layers) do
local sub, err, uns = layer(c, depth + 1)
if not sub then
return nil, err, uns
end
table.insert(l.layers, sub)
end
return l
end
return nil, "unknown layer type " .. tostring(v.type)
end
-- tileset(v) -> Tileset (a map's entry, or a .tsj root)
function Tmj.tileset(v: any): any
local ts: any = {
firstGid = n(v.firstgid, 1),
source = s(v.source),
name = s(v.name) or "",
tileWidth = n(v.tilewidth, 0),
tileHeight = n(v.tileheight, 0),
spacing = n(v.spacing, 0),
margin = n(v.margin, 0),
count = n(v.tilecount, 0),
columns = n(v.columns, 0),
objectAlignment = s(v.objectalignment),
class = s(v.class) or "",
imageSource = s(v.image),
imageWidth = n(v.imagewidth),
imageHeight = n(v.imageheight),
transparentColor = Data.color(s(v.transparentcolor)),
}
withProps(ts, v)
if type(v.tileoffset) == "table" then
ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) }
end
local tiles = {}
for _, t in list(v.tiles) do
if type(t) == "table" then
local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) }
withProps(tile, t)
tile.imageSource = s(t.image)
tile.imageWidth = n(t.imagewidth)
tile.imageHeight = n(t.imageheight)
if type(t.animation) == "table" then
tile.animation = {}
for _, f in t.animation do
if type(f) == "table" then
table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) })
end
end
end
if type(t.objectgroup) == "table" then
tile.objectGroup = objectGroup(t.objectgroup)
end
table.insert(tiles, tile)
end
end
table.sort(tiles, function(x: any, y: any): boolean
return x.id < y.id
end)
ts.tiles = tiles
return ts
end
-- read(value) -> TileMap | nil, message, unsupported?
function Tmj.read(v: any): (any, string?, boolean?)
if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then
return nil, "not a Tiled map (type is not \"map\")"
end
local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number)
map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version)
map.tiledVersion = s(v.tiledversion)
map.orientation = s(v.orientation) or "orthogonal"
map.renderOrder = s(v.renderorder) or "right-down"
map.infinite = b(v.infinite, false)
map.nextLayerId = n(v.nextlayerid)
map.nextObjectId = n(v.nextobjectid)
map.backgroundColor = Data.color(s(v.backgroundcolor))
map.hexSideLength = n(v.hexsidelength)
map.staggerAxis = s(v.staggeraxis)
map.staggerIndex = s(v.staggerindex)
map.class = s(v.class) or ""
map.parallaxOriginX = n(v.parallaxoriginx, 0)
map.parallaxOriginY = n(v.parallaxoriginy, 0)
withProps(map, v)
for _, ts in list(v.tilesets) do
if type(ts) == "table" then
table.insert(map.tilesets, Tmj.tileset(ts))
end
end
for _, l in list(v.layers) do
local x, err, uns = layer(l, 0)
if not x then
return nil, err, uns
end
table.insert(map.layers, x)
end
return map, nil
end
-- ------------------------------------------------------------------------------------------------ write
local function obj(pairs_: { { any } }): any
local o = Types.object()
for _, kv in pairs_ do
if kv[2] ~= nil then
Types.set(o, kv[1], kv[2])
end
end
return o
end
local function nz(v: any, default: any): any
if v == nil or v == default then
return nil
end
return v
end
local function str(v: any): string?
if type(v) == "string" and v ~= "" then
return v
end
return nil
end
local function propList(props: any, types: any): { any }?
if type(props) ~= "table" or next(props) == nil then
return nil
end
local out = {}
for _, k in Data.sortedKeys(props) do
local v = props[k]
local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil)
if typ == "class" and type(v) == "table" then
local members = Types.object()
if type(v.properties) == "table" then
for _, mk in Data.sortedKeys(v.properties) do
Types.set(members, mk, v.properties[mk])
end
end
table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } }))
else
table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } }))
end
end
return out
end
local function writeObject(o: any): any
local t: any = nil
if o.shape == "text" and type(o.text) == "table" then
local x = o.text
t = obj({
{ "bold", nz(x.bold, false) },
{ "color", nz(x.color, "#000000") },
{ "fontfamily", nz(x.fontFamily, "sans-serif") },
{ "halign", nz(x.halign, "left") },
{ "italic", nz(x.italic, false) },
{ "kerning", nz(x.kerning, true) },
{ "pixelsize", nz(x.pixelSize, 16) },
{ "strikeout", nz(x.strikeout, false) },
{ "text", tostring(x.text or "") },
{ "underline", nz(x.underline, false) },
{ "valign", nz(x.valign, "top") },
{ "wrap", nz(x.wrap, false) },
})
end
local pts: any = nil
if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then
pts = {}
for _, p in o.points do
table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } }))
end
end
return obj({
{ "ellipse", if o.shape == "ellipse" then true else nil },
{ "gid", o.gid },
{ "height", o.height or 0 },
{ "id", o.id },
{ "name", o.name or "" },
{ "point", if o.shape == "point" then true else nil },
{ "polygon", if o.shape == "polygon" then pts else nil },
{ "polyline", if o.shape == "polyline" then pts else nil },
{ "properties", propList(o.properties, o.propertyTypes) },
{ "rotation", o.rotation or 0 },
{ "template", o.template },
{ "text", t },
{ "type", o.class or "" },
{ "visible", o.visible ~= false },
{ "width", o.width or 0 },
{ "x", o.x or 0 },
{ "y", o.y or 0 },
})
end
export type WriteOptions = { encoding: string?, compression: string?, level: number? }
local function writeObjectGroup(l: any): any
local objs = {}
for _, o in (if type(l.objects) == "table" then l.objects else {}) do
table.insert(objs, writeObject(o))
end
return objs
end
local writeLayer: (l: any, o: WriteOptions) -> (any, string?)
writeLayer = function(l: any, o: WriteOptions): (any, string?)
local t = l.type
local fields: { { any } } = {}
local function add(k: string, v: any)
table.insert(fields, { k, v })
end
if t == "tiles" then
local enc = o.encoding or l.encoding
if enc ~= "base64" then
enc = nil
end
local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil
local function payload(g: { number }): (any, string?)
if enc == "base64" then
return Data.toBase64(g, comp, o.level)
end
return g, nil
end
if type(l.chunks) == "table" then
local chunks = {}
for _, c in l.chunks do
local d, err = payload(c.data or {})
if d == nil then
return nil, err
end
table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } }))
end
add("chunks", chunks)
local sx, sy = math.huge, math.huge
for _, c in l.chunks do
sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0)
end
if #l.chunks > 0 then
add("startx", sx)
add("starty", sy)
end
elseif type(l.data) == "table" then
local d, err = payload(l.data)
if d == nil then
return nil, err
end
add("data", d)
end
add("compression", comp)
add("encoding", enc)
add("height", l.height or 0)
elseif t == "objects" then
add("color", l.color)
add("draworder", l.drawOrder or "topdown")
elseif t == "image" then
add("image", l.imageSource or "")
add("imageheight", l.imageHeight)
add("imagewidth", l.imageWidth)
elseif t == "group" then
local kids = {}
for _, c in (if type(l.layers) == "table" then l.layers else {}) do
local x, err = writeLayer(c, o)
if x == nil then
return nil, err
end
table.insert(kids, x)
end
add("layers", kids)
else
return nil, "unknown layer type " .. tostring(t)
end
add("class", str(l.class))
add("id", l.id)
add("locked", nz(l.locked, false))
add("name", l.name or "")
if t == "objects" then
add("objects", writeObjectGroup(l))
end
add("offsetx", nz(l.offsetX, 0))
add("offsety", nz(l.offsetY, 0))
add("opacity", l.opacity or 1)
add("parallaxx", nz(l.parallaxX, 1))
add("parallaxy", nz(l.parallaxY, 1))
add("properties", propList(l.properties, l.propertyTypes))
if t == "image" then
add("repeatx", nz(l.repeatX, false))
add("repeaty", nz(l.repeatY, false))
end
add("tintcolor", l.tintColor)
if t == "image" then
add("transparentcolor", l.transparentColor)
end
add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group")
add("visible", l.visible ~= false)
if t == "tiles" then
add("width", l.width or 0)
end
add("x", l.x or 0)
add("y", l.y or 0)
return obj(fields), nil
end
-- tilesetValue(ts, inMap) -> a JSON object
function Tmj.tilesetValue(ts: any, inMap: boolean): any
if inMap and type(ts.source) == "string" then
return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
end
local tiles: any = nil
if type(ts.tiles) == "table" and #ts.tiles > 0 then
tiles = {}
for _, tile in ts.tiles do
local anim: any = nil
if type(tile.animation) == "table" then
anim = {}
for _, f in tile.animation do
table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } }))
end
end
local og: any = nil
if type(tile.objectGroup) == "table" then
og = writeLayer(tile.objectGroup, {})
end
table.insert(tiles, obj({
{ "animation", anim },
{ "id", tile.id or 0 },
{ "image", tile.imageSource },
{ "imageheight", tile.imageHeight },
{ "imagewidth", tile.imageWidth },
{ "objectgroup", og },
{ "probability", tile.probability },
{ "properties", propList(tile.properties, tile.propertyTypes) },
{ "type", str(tile.class) },
}))
end
end
return obj({
{ "class", str(ts.class) },
{ "columns", ts.columns or 0 },
{ "firstgid", if inMap then ts.firstGid or 1 else nil },
{ "image", ts.imageSource },
{ "imageheight", ts.imageHeight },
{ "imagewidth", ts.imageWidth },
{ "margin", ts.margin or 0 },
{ "name", ts.name or "" },
{ "objectalignment", ts.objectAlignment },
{ "properties", propList(ts.properties, ts.propertyTypes) },
{ "spacing", ts.spacing or 0 },
{ "tilecount", ts.count or 0 },
{ "tileheight", ts.tileHeight or 0 },
{ "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil },
{ "tiles", tiles },
{ "tilewidth", ts.tileWidth or 0 },
{ "transparentcolor", ts.transparentColor },
{ "type", if inMap then nil else "tileset" },
})
end
-- write(map, opts) -> a JSON value | nil, message
function Tmj.write(map: any, o: WriteOptions): (any, string?)
local layers = {}
for _, l in map.layers do
local x, err = writeLayer(l, o)
if x == nil then
return nil, err
end
table.insert(layers, x)
end
local tilesets = {}
for _, ts in map.tilesets do
table.insert(tilesets, Tmj.tilesetValue(ts, true))
end
return obj({
{ "backgroundcolor", map.backgroundColor },
{ "class", str(map.class) },
{ "compressionlevel", -1 },
{ "height", map.height },
{ "hexsidelength", map.hexSideLength },
{ "infinite", map.infinite == true },
{ "layers", layers },
{ "nextlayerid", map.nextLayerId },
{ "nextobjectid", map.nextObjectId },
{ "orientation", map.orientation or "orthogonal" },
{ "parallaxoriginx", nz(map.parallaxOriginX, 0) },
{ "parallaxoriginy", nz(map.parallaxOriginY, 0) },
{ "properties", propList(map.properties, map.propertyTypes) },
{ "renderorder", map.renderOrder or "right-down" },
{ "staggeraxis", map.staggerAxis },
{ "staggerindex", map.staggerIndex },
{ "tiledversion", map.tiledVersion },
{ "tileheight", map.tileHeight },
{ "tilesets", tilesets },
{ "tilewidth", map.tileWidth },
{ "type", "map" },
{ "version", map.version or "1.10" },
{ "width", map.width },
}), nil
end
return Tmj
+618
View File
@@ -0,0 +1,618 @@
--!strict
-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/Xml tree <-> a Types.TileMap, and TSX tilesets.
-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local Data = require("@formats/vector/tiled/Data")
local Tmx = {}
type Node = Types.XmlNode
local function a(n: Node, k: string): string?
return (n.attrs :: any)[k]
end
local function num(n: Node, k: string, default: number?): number?
local v = a(n, k)
if v == nil then
return default
end
return tonumber(v) or default
end
local function flag(n: Node, k: string, default: boolean): boolean
local v = a(n, k)
if v == nil then
return default
end
return v == "1" or v == "true"
end
-- ------------------------------------------------------------------------------------------------ read
-- <properties> -> values, types (types only for the non-string ones)
local function properties(n: Node?): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
if n == nil then
return props, nil
end
for _, p in Xml.children(n, "property") do
local name = a(p, "name")
if name then
local typ = a(p, "type") or "string"
local v: any
if typ == "class" then
local inner, innerTypes = properties(Xml.child(p, "properties"))
v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes }
else
local text = a(p, "value")
if text == nil then
text = Xml.text(p) -- multi-line strings
end
v = Data.value(typ, text :: string)
end
props[name] = v
if typ ~= "string" then
types = types or {}
;(types :: any)[name] = typ
end
end
end
return props, types
end
local function withProps(t: any, n: Node)
local props, types = properties(Xml.child(n, "properties"))
t.properties = props
if types then
t.propertyTypes = types
end
end
-- the gids of a <data> (or <chunk>) node
local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if encoding == "csv" then
return Data.csv(Xml.text(d))
elseif encoding == "base64" then
return Data.base64(Xml.text(d), compression)
elseif encoding == nil or encoding == "" then
local out = {}
for _, t in Xml.children(d, "tile") do
table.insert(out, num(t, "gid", 0) :: number)
end
return out, nil
end
return nil, "unknown encoding " .. encoding, true
end
local function object(o: Node): any
local obj: any = {
id = num(o, "id"),
name = a(o, "name") or "",
class = a(o, "class") or a(o, "type") or "",
x = num(o, "x", 0),
y = num(o, "y", 0),
width = num(o, "width", 0),
height = num(o, "height", 0),
rotation = num(o, "rotation", 0),
gid = num(o, "gid"),
visible = flag(o, "visible", true),
template = a(o, "template"),
shape = "rectangle",
}
withProps(obj, o)
if Xml.child(o, "ellipse") then
obj.shape = "ellipse"
elseif Xml.child(o, "point") then
obj.shape = "point"
end
for _, kind in { "polygon", "polyline" } do
local p = Xml.child(o, kind)
if p then
obj.shape = kind
local pts = {}
for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do
table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 })
end
obj.points = pts
end
end
local t = Xml.child(o, "text")
if t then
obj.shape = "text"
obj.text = {
text = Xml.text(t),
fontFamily = a(t, "fontfamily") or "sans-serif",
pixelSize = num(t, "pixelsize", 16),
wrap = flag(t, "wrap", false),
color = Data.color(a(t, "color")) or "#000000",
bold = flag(t, "bold", false),
italic = flag(t, "italic", false),
underline = flag(t, "underline", false),
strikeout = flag(t, "strikeout", false),
kerning = flag(t, "kerning", true),
halign = a(t, "halign") or "left",
valign = a(t, "valign") or "top",
}
end
return obj
end
local layer: (n: Node) -> (any, string?, boolean?)
local function common(n: Node, typ: string): any
local l: any = {
type = typ,
id = num(n, "id"),
name = a(n, "name") or "",
visible = flag(n, "visible", true),
opacity = num(n, "opacity", 1),
x = num(n, "x", 0),
y = num(n, "y", 0),
offsetX = num(n, "offsetx", 0),
offsetY = num(n, "offsety", 0),
parallaxX = num(n, "parallaxx", 1),
parallaxY = num(n, "parallaxy", 1),
tintColor = Data.color(a(n, "tintcolor")),
class = a(n, "class") or "",
locked = flag(n, "locked", false),
}
withProps(l, n)
return l
end
local function objectGroup(n: Node): any
local l = common(n, "objects")
l.drawOrder = a(n, "draworder") or "topdown"
l.color = Data.color(a(n, "color"))
l.objects = {}
for _, o in Xml.children(n, "object") do
table.insert(l.objects, object(o))
end
return l
end
layer = function(n: Node): (any, string?, boolean?)
local name = n.name
if name == "layer" then
local l = common(n, "tiles")
l.width = num(n, "width", 0)
l.height = num(n, "height", 0)
local d = Xml.child(n, "data")
if d then
local enc, comp = a(d, "encoding"), a(d, "compression")
l.encoding, l.compression = enc, comp
local chunks = Xml.children(d, "chunk")
if #chunks > 0 then
l.chunks = {}
for _, c in chunks do
local g, err, uns = gids(c, enc, comp)
if not g then
return nil, err, uns
end
table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g })
end
else
local g, err, uns = gids(d, enc, comp)
if not g then
return nil, err, uns
end
l.data = g
end
end
return l
elseif name == "objectgroup" then
return objectGroup(n)
elseif name == "imagelayer" then
local l = common(n, "image")
l.repeatX = flag(n, "repeatx", false)
l.repeatY = flag(n, "repeaty", false)
local img = Xml.child(n, "image")
if img then
l.imageSource = a(img, "source")
l.imageWidth = num(img, "width")
l.imageHeight = num(img, "height")
l.transparentColor = Data.color(a(img, "trans"))
end
return l
elseif name == "group" then
local l = common(n, "group")
l.layers = {}
for _, c in n.children do
if type(c) == "table" then
local sub, err, uns = layer(c)
if err then
return nil, err, uns
end
if sub then
table.insert(l.layers, sub)
end
end
end
return l
end
return nil
end
-- a <tileset> element (in a map, or a .tsx root) -> Tileset
function Tmx.tileset(n: Node): any
local ts: any = {
firstGid = num(n, "firstgid", 1),
source = a(n, "source"),
name = a(n, "name") or "",
tileWidth = num(n, "tilewidth", 0),
tileHeight = num(n, "tileheight", 0),
spacing = num(n, "spacing", 0),
margin = num(n, "margin", 0),
count = num(n, "tilecount", 0),
columns = num(n, "columns", 0),
objectAlignment = a(n, "objectalignment"),
class = a(n, "class") or "",
}
withProps(ts, n)
local off = Xml.child(n, "tileoffset")
if off then
ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) }
end
local img = Xml.child(n, "image")
if img then
ts.imageSource = a(img, "source")
ts.imageWidth = num(img, "width")
ts.imageHeight = num(img, "height")
ts.transparentColor = Data.color(a(img, "trans"))
end
local tiles = {}
for _, t in Xml.children(n, "tile") do
local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") }
withProps(tile, t)
local ti = Xml.child(t, "image")
if ti then
tile.imageSource = a(ti, "source")
tile.imageWidth = num(ti, "width")
tile.imageHeight = num(ti, "height")
end
local anim = Xml.child(t, "animation")
if anim then
tile.animation = {}
for _, f in Xml.children(anim, "frame") do
table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) })
end
end
local og = Xml.child(t, "objectgroup")
if og then
tile.objectGroup = objectGroup(og)
end
table.insert(tiles, tile)
end
ts.tiles = tiles
return ts
end
-- read(root) -> TileMap | nil, message, unsupported?
function Tmx.read(root: Node): (any, string?, boolean?)
if root.name ~= "map" then
return nil, "the root element is <" .. root.name .. ">, not <map>"
end
local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number)
map.version = a(root, "version")
map.tiledVersion = a(root, "tiledversion")
map.orientation = a(root, "orientation") or "orthogonal"
map.renderOrder = a(root, "renderorder") or "right-down"
map.infinite = flag(root, "infinite", false)
map.nextLayerId = num(root, "nextlayerid")
map.nextObjectId = num(root, "nextobjectid")
map.backgroundColor = Data.color(a(root, "backgroundcolor"))
map.hexSideLength = num(root, "hexsidelength")
map.staggerAxis = a(root, "staggeraxis")
map.staggerIndex = a(root, "staggerindex")
map.class = a(root, "class") or ""
map.parallaxOriginX = num(root, "parallaxoriginx", 0)
map.parallaxOriginY = num(root, "parallaxoriginy", 0)
withProps(map, root)
for _, c in root.children do
if type(c) == "table" then
if c.name == "tileset" then
table.insert(map.tilesets, Tmx.tileset(c))
else
local l, err, uns = layer(c)
if err then
return nil, err, uns
end
if l then
table.insert(map.layers, l)
end
end
end
end
return map, nil
end
-- ------------------------------------------------------------------------------------------------ write
type Attrs = { [string]: string }
local function el(name: string, attrs: { { any } }, children: { any }?): Node
-- attrs in order; nil / default values dropped by the caller
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
local v = kv[2]
Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v))
end
end
return Xml.element(name, o :: any, children)
end
local function nz(v: any, default: any): any
if v == nil or v == default then
return nil
end
return v
end
local function str(v: any): string?
if type(v) == "string" and v ~= "" then
return v
end
return nil
end
local function propsNode(props: any, types: any): Node?
if type(props) ~= "table" or next(props) == nil then
return nil
end
local list = {}
for _, k in Data.sortedKeys(props) do
local v = props[k]
local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil)
if typ == "class" and type(v) == "table" then
local inner = propsNode(v.properties, v.propertyTypes)
table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil))
else
local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v)
if string.find(text, "\n", 1, true) then
table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text }))
else
table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } }))
end
end
end
return el("properties", {}, list)
end
local function addProps(children: { any }, t: any)
local p = propsNode(t.properties, t.propertyTypes)
if p then
table.insert(children, p)
end
end
local function writeObject(o: any): Node
local kids = {}
addProps(kids, o)
local shape = o.shape
if shape == "ellipse" then
table.insert(kids, el("ellipse", {}))
elseif shape == "point" then
table.insert(kids, el("point", {}))
elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then
local pts = {}
for _, p in o.points do
table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0))
end
table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } }))
elseif shape == "text" and type(o.text) == "table" then
local t = o.text
table.insert(kids, el("text", {
{ "fontfamily", nz(t.fontFamily, "sans-serif") },
{ "pixelsize", nz(t.pixelSize, 16) },
{ "wrap", nz(t.wrap, false) },
{ "color", nz(t.color, "#000000") },
{ "bold", nz(t.bold, false) },
{ "italic", nz(t.italic, false) },
{ "underline", nz(t.underline, false) },
{ "strikeout", nz(t.strikeout, false) },
{ "kerning", nz(t.kerning, true) },
{ "halign", nz(t.halign, "left") },
{ "valign", nz(t.valign, "top") },
}, { tostring(t.text or "") }))
end
return el("object", {
{ "id", o.id },
{ "name", str(o.name) },
{ "type", str(o.class) },
{ "gid", o.gid },
{ "x", o.x or 0 },
{ "y", o.y or 0 },
{ "width", nz(o.width, 0) },
{ "height", nz(o.height, 0) },
{ "rotation", nz(o.rotation, 0) },
{ "visible", nz(o.visible, true) },
{ "template", o.template },
}, kids)
end
local function commonAttrs(l: any, extra: { { any } }): { { any } }
local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } }
table.move(extra, 1, #extra, #out + 1, out)
local tail = {
{ "visible", nz(l.visible, true) },
{ "locked", nz(l.locked, false) },
{ "opacity", nz(l.opacity, 1) },
{ "tintcolor", l.tintColor },
{ "offsetx", nz(l.offsetX, 0) },
{ "offsety", nz(l.offsetY, 0) },
{ "parallaxx", nz(l.parallaxX, 1) },
{ "parallaxy", nz(l.parallaxY, 1) },
}
table.move(tail, 1, #tail, #out + 1, out)
return out
end
local function writeObjectGroup(l: any, tag: string?): Node
local kids = {}
addProps(kids, l)
for _, o in (if type(l.objects) == "table" then l.objects else {}) do
table.insert(kids, writeObject(o))
end
return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids)
end
export type WriteOptions = { encoding: string?, compression: string?, level: number? }
local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?)
writeLayer = function(l: any, o: WriteOptions): (Node?, string?)
local t = l.type
if t == "tiles" then
local kids = {}
addProps(kids, l)
local enc = o.encoding or l.encoding or "csv"
local comp = if o.encoding then o.compression else (o.compression or l.compression)
if enc ~= "base64" then
comp = nil
end
local function payload(g: { number }, width: number): (string?, string?)
if enc == "csv" then
return Data.csvText(g, width), nil
end
local s, err = Data.toBase64(g, comp, o.level)
if not s then
return nil, err
end
return "\n " .. s .. "\n ", nil
end
local dataKids = {}
if type(l.chunks) == "table" then
for _, c in l.chunks do
local kids: { any } = {}
if enc == "xml" then
for _, g in (c.data or {}) do
table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } }))
end
else
local s, err = payload(c.data or {}, c.width or 0)
if not s then
return nil, err
end
kids = { s }
end
table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids))
end
elseif type(l.data) == "table" and enc == "xml" then
for _, g in l.data do
table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } }))
end
elseif type(l.data) == "table" then
local s, err = payload(l.data, l.width or 0)
if not s then
return nil, err
end
dataKids = { s }
end
table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids))
return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil
elseif t == "objects" then
return writeObjectGroup(l), nil
elseif t == "image" then
local kids = {}
addProps(kids, l)
if l.imageSource then
table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } }))
end
return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil
elseif t == "group" then
local kids = {}
addProps(kids, l)
for _, c in (if type(l.layers) == "table" then l.layers else {}) do
local n, err = writeLayer(c, o)
if not n then
return nil, err
end
table.insert(kids, n)
end
return el("group", commonAttrs(l, {}), kids), nil
end
return nil, "unknown layer type " .. tostring(t)
end
-- tilesetNode(ts, inMap) -> <tileset>
function Tmx.tilesetNode(ts: any, inMap: boolean): Node
if inMap and type(ts.source) == "string" then
return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
end
local kids = {}
if type(ts.tileOffset) == "table" then
table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }))
end
addProps(kids, ts)
if ts.imageSource then
table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } }))
end
for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do
local tk = {}
addProps(tk, tile)
if tile.imageSource then
table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } }))
end
if type(tile.objectGroup) == "table" then
table.insert(tk, writeObjectGroup(tile.objectGroup))
end
if type(tile.animation) == "table" then
local frames = {}
for _, f in tile.animation do
table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } }))
end
table.insert(tk, el("animation", {}, frames))
end
table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk))
end
return el("tileset", {
{ "firstgid", if inMap then ts.firstGid or 1 else nil },
{ "name", ts.name or "" },
{ "class", str(ts.class) },
{ "tilewidth", ts.tileWidth or 0 },
{ "tileheight", ts.tileHeight or 0 },
{ "spacing", nz(ts.spacing, 0) },
{ "margin", nz(ts.margin, 0) },
{ "tilecount", ts.count or 0 },
{ "columns", ts.columns or 0 },
{ "objectalignment", ts.objectAlignment },
}, kids)
end
-- write(map, opts) -> an XML document node | nil, message
function Tmx.write(map: any, o: WriteOptions): (Node?, string?)
local kids = {}
addProps(kids, map)
for _, ts in map.tilesets do
table.insert(kids, Tmx.tilesetNode(ts, true))
end
for _, l in map.layers do
local n, err = writeLayer(l, o)
if not n then
return nil, err
end
table.insert(kids, n)
end
local root = el("map", {
{ "version", map.version or "1.10" },
{ "tiledversion", map.tiledVersion },
{ "class", str(map.class) },
{ "orientation", map.orientation or "orthogonal" },
{ "renderorder", map.renderOrder or "right-down" },
{ "width", map.width },
{ "height", map.height },
{ "tilewidth", map.tileWidth },
{ "tileheight", map.tileHeight },
{ "hexsidelength", map.hexSideLength },
{ "staggeraxis", map.staggerAxis },
{ "staggerindex", map.staggerIndex },
{ "parallaxoriginx", nz(map.parallaxOriginX, 0) },
{ "parallaxoriginy", nz(map.parallaxOriginY, 0) },
{ "backgroundcolor", map.backgroundColor },
{ "infinite", map.infinite == true },
{ "nextlayerid", map.nextLayerId },
{ "nextobjectid", map.nextObjectId },
}, kids)
return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil
end
return Tmx
+189
View File
@@ -0,0 +1,189 @@
--!strict
-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map
-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib /
-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles,
-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers,
-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets
-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay
-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the
-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json".
-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external
-- tilesets or images (callers resolve `source` / `imageSource` paths themselves).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Json = require("@formats/codecs/Json")
local Tmx = require("@formats/vector/tiled/Tmx")
local Tmj = require("@formats/vector/tiled/Tmj")
-- ------------------------------------------------------------------------------------------------ contract
local Tiled = {
name = "tiled",
category = "vector",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 256 MB)
}
export type EncodeOptions = {
format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx
encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64"
compression: string?, -- base64 data: nil | "zlib" | "gzip"
level: number?, -- deflate level for compressed data (default 6)
indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON)
}
-- ------------------------------------------------------------------------------------------------ sniff
local function head(r: Bytes.Reader): string
local h = r:peek(1024)
if string.sub(h, 1, 3) == "\239\187\191" then
h = string.sub(h, 4)
end
return h
end
function Tiled.sniff(r: Bytes.Reader): number
local h = head(r)
if string.match(h, "^%s*<") then
if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then
return 0.9
end
return 0
end
if string.match(h, "^%s*{") then
-- Tiled writes its keys sorted: "type" comes last, so look at the tail too
local n = r:remaining()
local tail = if n > 1024 then r:peek(1024, n - 1024) else ""
for _, part in { h, tail } do
if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then
return 0.8
end
end
if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then
return 0.6
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its
-- meta.tileset is true) | nil, Err
function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
end
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local h = head(r)
local map: any, msg: string?, unsupported: boolean?
local flavour
if string.match(h, "^%s*<") then
local doc, xerr = Xml.decode(text)
if not doc then
return nil, xerr
end
local root = (doc :: any).root
if root == nil then
return nil, Err.new(Err.CORRUPT, "no root element")
end
if root.name == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmx.tileset(root) }
map.meta.tileset = true
flavour = "tsx"
else
map, msg, unsupported = Tmx.read(root)
flavour = "tmx"
end
else
local v, jerr = Json.decode(text)
if v == nil then
return nil, jerr
end
if type(v) == "table" and v.type == "tileset" then
map = Types.TileMap.new(0, 0, 0, 0)
map.tilesets = { Tmj.tileset(v) }
map.meta.tileset = true
flavour = "tsj"
else
map, msg, unsupported = Tmj.read(v)
flavour = "tmj"
end
end
if not map then
return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map")
end
map.meta.source = { format = flavour }
return map, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Tiled.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 o: EncodeOptions = opts or {}
local meta: any = if type(map.meta) == "table" then map.meta else {}
local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx"
fmt = string.lower(fmt)
if fmt == "tiled" then
fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx"
end
local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj"
if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then
return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml")
end
if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then
return nil, Err.new(Err.ARG, "compression must be zlib or gzip")
end
local wo = { encoding = o.encoding, compression = o.compression, level = o.level }
if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then
local doc: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" })
else
doc, err = Tmx.write(map, wo)
end
if not doc then
return nil, Err.new(Err.ARG, err or "bad map")
end
local s, xerr = Xml.encode(doc, { indent = o.indent or 1 })
if not s then
return nil, xerr
end
return buffer.fromstring(s .. "\n"), nil
elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then
local v: any, err: string?
if tilesetOnly then
if not map.tilesets[1] then
return nil, Err.new(Err.ARG, "no tileset to write")
end
v = Tmj.tilesetValue(map.tilesets[1], false)
else
v, err = Tmj.write(map, wo)
end
if v == nil then
return nil, Err.new(Err.ARG, err or "bad map")
end
local indent = if o.indent == 0 then nil else (o.indent or 2)
local s, jerr = Json.encode(v, { indent = indent })
if not s then
return nil, jerr
end
return buffer.fromstring(s .. "\n"), nil
end
return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)")
end
return Tiled