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:
1 parent
63294e13bd
commit
a762554f2c
13 files changed
+2239
-3
No files matched your search
@@ -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
|
||||
@@ -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 & 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 <Tiled></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})
|
||||
Reference in new issue
Block a user