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 c371839331
commit 738bf0e078
13 files changed
+2239 -3

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
| vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` |
| layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` |
| layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` |
| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
+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
+25
View File
@@ -0,0 +1,25 @@
-- core/Base64 tests: the RFC 4648 vectors, whitespace / missing padding / URL-safe input, bad characters, random
-- round trips.
local T = require("@tests/T")
local Base64 = require("@formats/core/Base64")
local t = T.suite("base64")
for _, v in { { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, { "foobar", "Zm9vYmFy" } } do
t:eq(Base64.encode(v[1]), v[2], "encode " .. v[1])
t:eq(buffer.tostring(Base64.decode(v[2]) :: buffer), v[1], "decode " .. v[2])
end
t:eq(buffer.tostring(Base64.decode(" Zm9v\nYmE ") :: buffer), "fooba", "whitespace and no padding")
t:eq(buffer.tostring(Base64.decode("-_8=") :: buffer), "\251\255", "URL-safe alphabet")
local b, err = Base64.decode("Zm9v!")
t:check(b == nil and err, "bad character")
local b2 = Base64.decode("Zg==Zg")
t:check(b2 == nil, "data after padding")
local rand = T.rng(5)
for n = 0, 40 do
local s = buffer.create(n)
for i = 0, n - 1 do
buffer.writeu8(s, i, rand(256))
end
t:eq(buffer.tostring(Base64.decode(Base64.encode(s)) :: buffer), buffer.tostring(s), "round trip " .. n)
end
t:done()
+184
View File
@@ -0,0 +1,184 @@
-- vector/tiled tests: hand-written TMX maps (CSV / base64 zlib / gzip / raw / XML tile data, flip bits, infinite
-- chunks, hexagonal attributes, groups, image layers, every object shape, text, typed properties, embedded and
-- external tilesets with per-tile data) against Tiled's own TMJ export and TMX re-save of them (the same TileMap from
-- all three), a TSX tileset against Tiled's TSJ, our encoder's TMX / TMJ read back by Tiled (tools/fixtures/_ours.luau),
-- round trips in every data encoding, errors, and the fuzz pass. Fixtures: tools/fixtures/tiled.py.
local T = require("@tests/T")
local Tiled = require("@formats/vector/tiled")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tiled")
local Ours = require("@tests/gen/tiled_ours")
local t = T.suite("tiled")
local function decode(s: string | buffer): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
return Tiled.decode(Bytes.reader(b))
end
-- deep comparison of decoded maps, without the fields that only say who wrote the file
local SKIP = { version = true, tiledVersion = true, encoding = true, compression = true, meta = true }
local function same(a: any, b: any, path: string, out: { string })
if #out > 8 then
return
end
if type(a) == "table" and type(b) == "table" then
local keys = {}
for k in pairs(a) do
keys[k] = true
end
for k in pairs(b) do
keys[k] = true
end
for k in pairs(keys) do
if not SKIP[k] then
same(a[k], b[k], path .. "." .. tostring(k), out)
end
end
elseif type(a) == "number" and type(b) == "number" then
if math.abs(a - b) > 1e-9 then
table.insert(out, path .. ": " .. a .. " vs " .. b)
end
elseif a ~= b then
table.insert(out, path .. ": " .. tostring(a) .. " vs " .. tostring(b))
end
end
local function eqMap(a: any, b: any, label: string)
local out = {}
same(a, b, "", out)
t:check(#out == 0, label .. ": " .. table.concat(out, "; "))
end
t:eq(Tiled.name, "tiled", "name")
t:eq(Tiled.category, "vector", "category")
t:check(Tiled.caps.decode and Tiled.caps.encode, "caps")
local samples = {}
local maps = {}
for _, c in Fx.cases do
local m, err = decode(c.tmx)
t:check(m, c.name .. ": tmx: " .. tostring(err))
t:eq(m.kind, "tilemap", c.name .. ": kind")
local j, jerr = decode(c.tmj)
t:check(j, c.name .. ": Tiled's tmj: " .. tostring(jerr))
local x, xerr = decode(c.tiled_tmx)
t:check(x, c.name .. ": Tiled's tmx: " .. tostring(xerr))
eqMap(m, j, c.name .. ": hand TMX = Tiled's TMJ")
eqMap(m, x, c.name .. ": hand TMX = Tiled's TMX")
t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmx))), 0.9, c.name .. ": sniff tmx")
t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmj))), 0.8, c.name .. ": sniff tmj")
maps[c.name] = m
table.insert(samples, c.tmx)
table.insert(samples, c.tmj)
end
-- details of the orthogonal map
do
local m = maps.ortho
t:eq(m.class, "Level", "map class")
t:eq(m.renderOrder, "left-up", "render order")
t:eq(m.backgroundColor, "#102030", "background (canonical: opaque alpha dropped)")
t:eq(m.properties.title, "\u{dc}n\u{ef}code & more", "string property")
t:eq(m.properties.count, 42, "int property")
t:eq(m.properties.ratio, 1.5, "float property")
t:eq(m.properties.on, true, "bool property")
t:eq(m.propertyTypes.tint, "color", "color type")
t:eq(m.properties.target, 3, "object property")
t:eq(m.properties.notes, "line one\nline two", "multi-line property")
t:eq(#m.tilesets, 2, "tilesets")
t:eq(m.tilesets[1].imageSource, "tiles.png", "tileset image stays a path")
t:eq(m.tilesets[1].tiles[2].class, "Door", "tile class")
t:eq(m.tilesets[2].source, "ext.tsx", "external tileset reference")
t:eq(m.tilesets[2].firstGid, 9, "firstgid")
local L = m.layers
t:eq(L[1].data[4], 0x80000000 + 3, "horizontal flip bit kept")
t:eq(L[1].opacity, 0.75, "opacity")
t:eq(L[1].tintColor, "#ff00ff", "tint")
t:eq(L[2].visible, false, "hidden layer")
t:eq(L[2].data[8], 1, "zlib data")
t:eq(L[3].locked, true, "locked")
t:eq(#L[4].data, 24, "raw base64 data")
t:eq(L[5].type, "group", "group")
t:eq(L[5].layers[1].type, "image", "image layer")
t:eq(L[5].layers[1].imageSource, "sky.png", "image layer path")
t:eq(L[5].layers[1].repeatX, true, "repeatx")
local objs = L[5].layers[2].objects
t:eq(#objs, 7, "objects")
t:check(objs[1].class == "Crate" and objs[1].rotation == 45 and objs[1].properties.weight == 2.25, "rectangle")
t:eq(objs[2].shape, "ellipse", "ellipse")
t:eq(objs[3].shape, "point", "point")
t:check(objs[4].shape == "polygon" and #objs[4].points == 3 and objs[4].points[3][2] == -12.5, "polygon")
t:check(objs[5].shape == "polyline" and objs[5].visible == false, "polyline")
t:check(objs[6].shape == "text" and objs[6].text.text == "Hello <Tiled>" and objs[6].text.bold and objs[6].text.halign == "center", "text")
t:eq(objs[7].gid, 2147483651, "tile object gid with flip")
t:eq(maps.hex.hexSideLength, 14, "hex side")
t:eq(maps.hex.layers[1].data[5], 2, "XML tile data")
t:eq(#maps.infinite.layers[1].chunks, 3, "chunks")
t:eq(maps.infinite.layers[1].chunks[2].x, -16, "chunk position")
end
-- the external tileset, TSX vs Tiled's TSJ
do
local a = decode(Fx.tsx)
local b = decode(Fx.tsj)
t:check(a and a.meta.tileset and b and b.meta.tileset, "tileset files")
local ta, tb = a.tilesets[1], b.tilesets[1]
ta.firstGid, tb.firstGid = nil, nil
eqMap(ta, tb, "TSX = Tiled's TSJ")
t:eq(ta.tiles[1].animation[2].duration, 150, "animation")
t:eq(ta.tiles[2].objectGroup.objects[2].shape, "ellipse", "collision shapes")
t:eq(ta.tileOffset.y, -3, "tile offset")
for _, fmt in { "tsx", "tsj" } do
local back = decode(Tiled.encode(a, { format = fmt }) :: buffer)
back.tilesets[1].firstGid = nil
eqMap(back.tilesets[1], ta, "tileset round trip " .. fmt)
end
end
-- round trips through every flavour and data encoding
for name, m in maps do
for _, o in { { format = "tmx" }, { format = "tmx", encoding = "base64" }, { format = "tmx", encoding = "base64", compression = "zlib" }, { format = "tmx", encoding = "base64", compression = "gzip" }, { format = "tmx", encoding = "xml" }, { format = "tmj" }, { format = "tmj", encoding = "base64", compression = "zlib" }, { format = "json", indent = 0 } } do
local out, err = Tiled.encode(m, o :: any)
local label = name .. " " .. o.format .. " " .. tostring(o.encoding) .. " " .. tostring(o.compression)
t:check(out, label .. ": " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, label .. ": decode: " .. tostring(berr))
eqMap(back, m, label .. ": round trip")
table.insert(samples, buffer.tostring(out :: buffer))
end
end
do
local m = maps.ortho
t:eq(m.meta.source.format, "tmx", "source flavour")
t:eq(string.sub(buffer.tostring(Tiled.encode(m) :: buffer), 1, 5), "<?xml", "default: the source flavour")
local j = decode(Fx.cases[1].tmj)
t:eq(string.sub(buffer.tostring(Tiled.encode(j) :: buffer), 1, 1), "{", "a TMJ source writes TMJ")
end
-- Tiled read our TMX and TMJ (checked when the fixtures were made)
for _, c in Ours.checks do
t:check(c.ok, c.label)
end
-- errors
do
local zstd = string.gsub(Fx.cases[1].tmx, "compression=\"zlib\"", "compression=\"zstd\"")
local _, e = decode(zstd)
t:check(e and e.code == Err.UNSUPPORTED, "zstd: " .. tostring(e))
local _, e2 = decode("<map><layer><data encoding=\"csv\">1,x,2</data></layer></map>")
t:check(e2 and e2.code == Err.CORRUPT, "bad csv: " .. tostring(e2))
local _, e3 = decode("<notmap/>")
t:check(e3 and e3.code == Err.CORRUPT, "not a map")
local _, e4 = decode("{\"type\":\"map\",\"layers\":[{\"type\":\"weird\"}]}")
t:check(e4 and e4.code == Err.CORRUPT, "unknown layer type")
local _, e5 = Tiled.encode(maps.ortho, { format = "png" } :: any)
t:check(e5 and e5.code == Err.ARG, "unknown flavour")
local _, e6 = Tiled.encode({} :: any)
t:check(e6 and e6.code == Err.ARG, "not a TileMap")
end
t:fuzz("decode", function(b: buffer)
return Tiled.decode(Bytes.reader(b))
end, samples, { mutations = 6 })
t:done()
+32
View File
@@ -111,6 +111,32 @@ local function aseDoc(): Types.Layered
return doc
end
-- a Tiled map (tools/fixtures/tiled.py has Tiled read our TMX and TMJ of it)
local function tiledMap(): Types.TileMap
local m: any = Types.TileMap.new(5, 4, 16, 16)
m.nextLayerId, m.nextObjectId = 5, 4
m.properties = { name = "ours", n = 7, f = 0.5, ok = false, c = "#ff112233" }
m.propertyTypes = { c = "color" }
m.tilesets = { { firstGid = 1, name = "tiles", tileWidth = 16, tileHeight = 16, columns = 4, count = 8, spacing = 0, margin = 0, imageSource = "tiles.png", imageWidth = 64, imageHeight = 32, properties = {}, tiles = { { id = 2, class = "Wall", properties = { hard = true } }, { id = 4, properties = {}, animation = { { tileId = 4, duration = 120 }, { tileId = 5, duration = 80 } } } } } }
local data = {}
for i = 1, 20 do
data[i] = (i * 3) % 9
end
data[2] += 0x80000000
data[10] += 0x40000000
local tiles = { type = "tiles", id = 1, name = "ground", width = 5, height = 4, data = data, visible = true, opacity = 0.8, offsetX = 2, offsetY = 0, properties = { deep = 3 }, encoding = "base64", compression = "zlib" }
local objs = {
{ id = 1, name = "a", class = "Spawn", x = 4, y = 5.5, width = 8, height = 8, rotation = 30, visible = true, shape = "rectangle", properties = { team = "red" } },
{ id = 2, name = "b", class = "", x = 20, y = 10, width = 0, height = 0, rotation = 0, visible = true, shape = "polyline", points = { { 0, 0 }, { 8, 4 }, { 16, 0 } }, properties = {} },
{ id = 3, name = "c", class = "", x = 30, y = 30, width = 60, height = 14, rotation = 0, visible = false, shape = "text", text = { text = "hi there", fontFamily = "sans-serif", pixelSize = 14, wrap = true, color = "#00ff00", bold = false, italic = true, underline = false, strikeout = false, kerning = true, halign = "right", valign = "top" }, properties = {} },
}
local og = { type = "objects", id = 3, name = "things", visible = true, opacity = 1, drawOrder = "topdown", objects = objs, properties = {} }
local img = { type = "image", id = 4, name = "sky", visible = true, opacity = 1, imageSource = "sky.png", imageWidth = 40, imageHeight = 20, repeatX = true, repeatY = false, properties = {} }
local group = { type = "group", id = 2, name = "grp", visible = true, opacity = 0.5, layers = { og, img }, properties = {} }
m.layers = { tiles, group }
return m
end
local which = ...
if which == "psd" then
local Psd = require("@formats/layered/psd")
@@ -132,4 +158,10 @@ elseif which == "aseprite" then
frames[f] = hex((LayerOps.flatten(doc, { frame = f }) :: Types.Image).pixels)
end
print(json({ data = hex(data), nframes = 3, frames = frames }))
elseif which == "tiled" then
local Tiled = require("@formats/vector/tiled")
local m = tiledMap()
local tmx = Tiled.encode(m, { format = "tmx" }) :: buffer
local tmj = Tiled.encode(m, { format = "tmj" }) :: buffer
print(json({ tmx = hex(tmx), tmj = hex(tmj) }))
end
+279
View File
@@ -0,0 +1,279 @@
# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference:
# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } },
# tsx, tsj (an external tileset and Tiled's JSON export of it) }
# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with
# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and
# compared with our own TMJ
import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/vector/tiled", "tools/fixtures/_ours.luau"]
TSX = """<?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<tileoffset x="2" y="-3"/>
<properties>
<property name="kind" value="terrain"/>
</properties>
<image source="tiles.png" width="64" height="32"/>
<tile id="1" type="Water" probability="0.5">
<properties>
<property name="speed" type="float" value="0.25"/>
</properties>
<animation>
<frame tileid="1" duration="100"/>
<frame tileid="2" duration="150"/>
</animation>
</tile>
<tile id="5">
<objectgroup draworder="index" id="2">
<object id="1" x="1" y="2" width="10" height="12"/>
<object id="2" x="3" y="3">
<ellipse/>
</object>
</objectgroup>
</tile>
</tileset>
"""
def layer_bytes(gids):
return b"".join(struct.pack("<I", g) for g in gids)
def ortho():
W, H = 6, 4
g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)]
g1[3] |= 0x80000000
g1[7] |= 0x40000000
g1[11] |= 0x20000000
g2 = [(x * y) % 5 for y in range(H) for x in range(W)]
g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)]
g4 = [1 + (x % 2) for y in range(H) for x in range(W)]
csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H))
z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode()
gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode()
raw = base64.b64encode(layer_bytes(g4)).decode()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10">
<properties>
<property name="title" value="Ünïcode &amp; more"/>
<property name="count" type="int" value="42"/>
<property name="ratio" type="float" value="1.5"/>
<property name="on" type="bool" value="true"/>
<property name="tint" type="color" value="#80ff0000"/>
<property name="file" type="file" value="other.tmx"/>
<property name="target" type="object" value="3"/>
<property name="notes">line one
line two</property>
</properties>
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
<tile id="0">
<properties>
<property name="solid" type="bool" value="true"/>
</properties>
</tile>
<tile id="3" type="Door"/>
</tileset>
<tileset firstgid="9" source="ext.tsx"/>
<layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff">
<properties>
<property name="layerprop" value="x"/>
</properties>
<data encoding="csv">
{csv}
</data>
</layer>
<layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5">
<data encoding="base64" compression="zlib">
{z}
</data>
</layer>
<layer id="3" name="gzip" width="{W}" height="{H}" locked="1">
<data encoding="base64" compression="gzip">
{gz}
</data>
</layer>
<layer id="4" name="raw" class="Deco" width="{W}" height="{H}">
<data encoding="base64">
{raw}
</data>
</layer>
<group id="5" name="group" opacity="0.5" offsetx="1">
<imagelayer id="6" name="sky" repeatx="1">
<image source="sky.png" width="40" height="20"/>
</imagelayer>
<objectgroup id="7" name="things" color="#a0a0a4" draworder="index">
<object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45">
<properties>
<property name="weight" type="float" value="2.25"/>
</properties>
</object>
<object id="2" name="ring" x="40" y="5" width="10" height="10">
<ellipse/>
</object>
<object id="3" name="spot" x="7" y="9">
<point/>
</object>
<object id="4" name="poly" x="20" y="20">
<polygon points="0,0 16,0 8,-12.5"/>
</object>
<object id="5" name="line" x="30" y="30" visible="0">
<polyline points="0,0 5,5 10,0 15,5"/>
</object>
<object id="6" name="label" x="2" y="40" width="80" height="20">
<text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello &lt;Tiled&gt;</text>
</object>
<object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/>
</objectgroup>
</group>
</map>
"""
def iso():
W, H = 3, 3
tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="xmltiles" width="{W}" height="{H}">
<data>
{tiles}
</data>
</layer>
</map>
"""
def infinite():
def chunk(cx, cy):
g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)]
rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16))
return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>'
# Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds
chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0)))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="chunks" width="48" height="32">
<data encoding="csv">
{chunks}
</data>
</layer>
</map>
"""
def tiled(ctx, argv, cwd):
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
if shutil.which("tiled"):
subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
else:
subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
def magick(ctx, argv):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
def workdir(ctx, d):
magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")])
magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")])
open(os.path.join(d, "ext.tsx"), "w").write(TSX)
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gids(layer):
"""a JSON tile layer's gids (arrays, or base64 with compression) -> list"""
d = layer.get("data")
if isinstance(d, str):
raw = base64.b64decode(d)
c = layer.get("compression", "")
raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw
return list(struct.unpack("<%dI" % (len(raw) // 4), raw))
return d
IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"}
DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False}
def norm(v, obj=False):
"""a JSON map without the fields that only say which Tiled wrote it, or that hold defaults"""
if isinstance(v, dict):
out = {}
if v.get("type") == "tilelayer" and "data" in v:
v = dict(v, data=gids(v))
for k, x in v.items():
if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"):
continue
out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x)
return out
if isinstance(v, list):
return [norm(x) for x in v]
if isinstance(v, float) and v.is_integer():
return int(v)
return v
def diff(a, b, path="", out=None):
out = [] if out is None else out
if isinstance(a, dict) and isinstance(b, dict):
for k in sorted(set(a) | set(b)):
if k not in a or k not in b:
out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>")))
else:
diff(a[k], b[k], path + "." + k, out)
elif isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
out.append("%s: length %d vs %d" % (path, len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
diff(x, y, "%s[%d]" % (path, i), out)
elif a != b:
out.append("%s: %r vs %r" % (path, a, b))
return out
def generate(ctx):
cases = []
with tempfile.TemporaryDirectory() as d:
workdir(ctx, d)
for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())):
open(os.path.join(d, name + ".tmx"), "w").write(text)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d)
cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(),
"tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()})
tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d)
tsj = open(os.path.join(d, "ext.tsj"), "rb").read()
ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj})
# our encoder's files, read by Tiled
o = run_ours(ctx, "tiled")
open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"]))
open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"]))
tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d)
tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d)
mine = norm(json.loads(bytes.fromhex(o["tmj"])))
checks = []
for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")):
theirs = norm(json.load(open(os.path.join(d, f))))
dd = diff(mine, theirs)
checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd})
ctx.emit("tiled_ours", {"checks": checks})