Files
rosetta/src/Rosetta/vector/tiled/Tmj.luau
T

630 lines
18 KiB
Luau

--!strict
-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap.
local Types = require("@rosetta/Types")
local Data = require("@rosetta/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", nil
end
table.insert(out, g)
end
return out, nil, 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
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
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
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
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