166 lines
11 KiB
Python
166 lines
11 KiB
Python
# Ogmo Editor 3 fixtures (tools/fixtures.py): the HaxeFlixel TurnBasedRPG project + level (tests/fixtures/ogmo, MIT,
|
|
# saved by Ogmo 3.3), and a project + levels written here in the shapes OgmoEditor3-CE 3.4 saves (src/modules/*/
|
|
# *Layer.hx save(): tile layers as ids / coords in 1D / 2D arrays with tileFlags, grid layers 1D / 2D, entities with
|
|
# origin, rotation (radians), flips, nodes and values, decals). Reference values come from a Python reading of the
|
|
# same layouts (what the editor's load() does). Then our encoder's output (tools/fixtures/_ogmo_encode.luau) is read
|
|
# by the same Python reader.
|
|
# tests/gen/ogmo.luau { cases = { { name, data, project, stats } }, projects = { { name, data } } }
|
|
# tests/gen/ogmo_ours.luau { { name, stats } }
|
|
import base64, importlib.util, json, math, os, struct, zlib
|
|
|
|
INPUTS = ["tests/fixtures/ogmo", "src/Rosetta/vector/ogmo", "tools/fixtures/_ogmo_encode.luau", "tools/fixtures/_model_ref.py"]
|
|
|
|
|
|
def png(w, h):
|
|
def chunk(t, d):
|
|
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
|
raw = b"".join(b"\0" + bytes((x * 7 + y * 3) & 255 for x in range(w * 3)) for y in range(h))
|
|
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
|
|
|
|
|
def project():
|
|
uri = "data:image/png;base64," + base64.b64encode(png(64, 32)).decode()
|
|
uri2 = "data:image/png;base64," + base64.b64encode(png(36, 20)).decode()
|
|
return {
|
|
"name": "Rosetta test", "ogmoVersion": "3.4.0", "levelPaths": ["."], "backgroundColor": "#282c34ff",
|
|
"gridColor": "#3c4049cc", "anglesRadians": True, "directoryDepth": 5, "layerGridDefaultSize": {"x": 8, "y": 8},
|
|
"levelDefaultSize": {"x": 64, "y": 48}, "levelMinSize": {"x": 8, "y": 8}, "levelMaxSize": {"x": 4096, "y": 4096},
|
|
"levelValues": [{"name": "music", "definition": "String", "display": 0, "defaults": ""},
|
|
{"name": "gravity", "definition": "Float", "display": 0, "defaults": 1, "bounded": False, "min": 0, "max": 100}],
|
|
"defaultExportMode": ".json", "compactExport": False, "externalScript": "", "playCommand": "", "entityTags": [],
|
|
"layers": [
|
|
{"definition": "entity", "name": "things", "gridSize": {"x": 8, "y": 8}, "exportID": "11", "requiredTags": [], "excludedTags": []},
|
|
{"definition": "decal", "name": "decor", "gridSize": {"x": 8, "y": 8}, "exportID": "12", "folder": "decals", "includeImageSequence": True, "scaleable": True, "rotatable": True, "values": []},
|
|
{"definition": "tile", "name": "front", "gridSize": {"x": 8, "y": 8}, "exportID": "13", "exportMode": 1, "arrayMode": 1, "defaultTileset": "small"},
|
|
{"definition": "grid", "name": "solid", "gridSize": {"x": 16, "y": 16}, "exportID": "14", "arrayMode": 1, "legend": {"0": "#00000000", "1": "#ffffffff", "w": "#0000ffff"}},
|
|
{"definition": "grid", "name": "zones", "gridSize": {"x": 8, "y": 8}, "exportID": "15", "arrayMode": 0, "legend": {"0": "#00000000", "1": "#ff0000ff"}},
|
|
{"definition": "tile", "name": "back", "gridSize": {"x": 8, "y": 8}, "exportID": "16", "exportMode": 0, "arrayMode": 0, "defaultTileset": "main"},
|
|
],
|
|
"entities": [
|
|
{"exportID": "21", "name": "player", "limit": 1, "size": {"x": 8, "y": 16}, "origin": {"x": 4, "y": 16}, "originAnchored": True,
|
|
"shape": {"label": "Rectangle", "points": []}, "color": "#ff0000ff", "tileX": False, "tileY": False, "tileSize": {"x": 8, "y": 8},
|
|
"resizeableX": False, "resizeableY": False, "rotatable": True, "rotationDegrees": 360, "canFlipX": True, "canFlipY": False,
|
|
"canSetColor": False, "hasNodes": True, "nodeLimit": 0, "nodeDisplay": 0, "nodeGhost": True, "tags": [],
|
|
"values": [{"name": "hp", "definition": "Integer", "display": 0, "defaults": 3, "bounded": False, "min": 0, "max": 100},
|
|
{"name": "boss", "definition": "Boolean", "display": 0, "defaults": False}]},
|
|
{"exportID": "22", "name": "door", "limit": -1, "size": {"x": 8, "y": 8}, "origin": {"x": 0, "y": 0}, "originAnchored": True,
|
|
"shape": {"label": "Rectangle", "points": []}, "color": "#00ff00ff", "tileX": False, "tileY": False, "tileSize": {"x": 8, "y": 8},
|
|
"resizeableX": True, "resizeableY": True, "rotatable": False, "rotationDegrees": 360, "canFlipX": False, "canFlipY": False,
|
|
"canSetColor": False, "hasNodes": False, "nodeLimit": 0, "nodeDisplay": 0, "nodeGhost": True, "tags": [], "values": []},
|
|
],
|
|
"tilesets": [
|
|
{"label": "main", "path": "tiles/main.png", "image": uri, "tileWidth": 8, "tileHeight": 8, "tileSeparationX": 0, "tileSeparationY": 0, "tileMarginX": 0, "tileMarginY": 0},
|
|
{"label": "small", "path": "tiles/small.png", "image": uri2, "tileWidth": 8, "tileHeight": 8, "tileSeparationX": 1, "tileSeparationY": 1, "tileMarginX": 1, "tileMarginY": 1},
|
|
],
|
|
}
|
|
|
|
|
|
def level(rng, w, h):
|
|
cx, cy = w // 8, h // 8
|
|
ids = [(-1 if rng.random() < 0.3 else rng.randrange(32)) for _ in range(cx * cy)]
|
|
flags = [(rng.choice([0, 0, 0, 4, 2, 1, 6]) if t >= 0 else 0) for t in ids]
|
|
# "small": (36 - 2 + 1) // 9 = 3 columns, 2 rows
|
|
coords = [[-1] if rng.random() < 0.5 else [rng.randrange(3), rng.randrange(2)] for _ in range(cx * cy)]
|
|
rows = lambda flat, n: [flat[i * n:(i + 1) * n] for i in range(len(flat) // n)]
|
|
gx, gy = w // 16, h // 16
|
|
solid = [rng.choice("001w") for _ in range(gx * gy)]
|
|
zones = [rng.choice("0001") for _ in range(cx * cy)]
|
|
base = {"offsetX": 0, "offsetY": 0}
|
|
return {
|
|
"ogmoVersion": "3.4.0", "width": w, "height": h, "offsetX": 0, "offsetY": 0,
|
|
"values": {"music": "cave.ogg", "gravity": 9.5},
|
|
"layers": [
|
|
dict(name="things", _eid="11", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, entities=[
|
|
{"name": "player", "id": 0, "_eid": "21", "x": 20, "y": 32, "originX": 4, "originY": 16, "rotation": math.pi / 2,
|
|
"flippedX": True, "nodes": [{"x": 40, "y": 32}, {"x": 48, "y": 8}], "values": {"hp": 5, "boss": False}},
|
|
{"name": "door", "id": 1, "_eid": "22", "x": 8, "y": 0, "width": 16, "height": 24, "originX": 0, "originY": 0},
|
|
]),
|
|
dict(name="decor", _eid="12", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, decals=[
|
|
{"x": 12, "y": 14, "scaleX": 2, "scaleY": 1, "rotation": math.pi, "texture": "tree.png", "originX": 0.5, "originY": 1},
|
|
], folder="decals"),
|
|
dict(name="front", _eid="13", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, tileset="small",
|
|
dataCoords2D=rows(coords, cx), exportMode=1, arrayMode=1),
|
|
dict(name="solid", _eid="14", gridCellWidth=16, gridCellHeight=16, gridCellsX=gx, gridCellsY=gy, **base, grid2D=rows(solid, gx), arrayMode=1),
|
|
dict(name="zones", _eid="15", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, grid=zones, arrayMode=0),
|
|
dict(name="back", _eid="16", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, tileset="main", data=ids,
|
|
tileFlags=flags, exportMode=0, arrayMode=0),
|
|
],
|
|
}
|
|
|
|
|
|
def flat(v2):
|
|
return [c for row in v2 for c in row]
|
|
|
|
|
|
def stats(lv, proj):
|
|
"""what Ogmo's load() reads, summarised; layers bottom first"""
|
|
radians = proj.get("anglesRadians", True) if proj else True
|
|
tsets = {t["label"]: t for t in (proj or {}).get("tilesets", [])}
|
|
defs = {e["name"]: e for e in (proj or {}).get("entities", [])}
|
|
out = []
|
|
for li in reversed(lv["layers"]):
|
|
d = {"name": li["name"], "w": li["gridCellsX"], "h": li["gridCellsY"]}
|
|
if "entities" in li:
|
|
ents = []
|
|
for e in li["entities"]:
|
|
t = defs.get(e["name"], {})
|
|
rot = e.get("rotation", 0)
|
|
ents.append("%s@%g,%g %gx%g r%d n%d %s" % (e["name"], e["x"] - e.get("originX", 0), e["y"] - e.get("originY", 0),
|
|
e.get("width", t.get("size", {}).get("x", 16)), e.get("height", t.get("size", {}).get("y", 16)),
|
|
round(math.degrees(rot) if radians else rot), len(e.get("nodes", [])),
|
|
",".join("%s=%s" % (k, json.dumps(v)) for k, v in sorted(e.get("values", {}).items()))))
|
|
d["kind"], d["items"] = "entity", ents
|
|
elif "decals" in li:
|
|
d["kind"] = "decal"
|
|
d["items"] = ["%s@%g,%g s%g,%g r%d" % (x["texture"], x["x"], x["y"], x.get("scaleX", 1), x.get("scaleY", 1),
|
|
round(math.degrees(x.get("rotation", 0)) if radians else x.get("rotation", 0))) for x in li["decals"]]
|
|
elif "grid" in li or "grid2D" in li:
|
|
d["kind"] = "grid"
|
|
d["cells"] = "".join(str(c) for c in (li["grid"] if "grid" in li else flat(li["grid2D"])))
|
|
else:
|
|
d["kind"] = "tile"
|
|
ts = tsets.get(li.get("tileset"))
|
|
cols = 1
|
|
if ts:
|
|
img = base64.b64decode(ts["image"].split(",", 1)[1])
|
|
iw = struct.unpack(">I", img[16:20])[0]
|
|
sx, mx = ts.get("tileSeparationX", 0), ts.get("tileMarginX", 0)
|
|
cols = max(1, (iw - 2 * mx + sx) // (ts["tileWidth"] + sx))
|
|
if li.get("exportMode", 0) == 1:
|
|
cells = li["dataCoords"] if li.get("arrayMode", 0) == 0 else flat(li["dataCoords2D"])
|
|
ids = [-1 if c[0] == -1 else c[1] * cols + c[0] for c in cells]
|
|
else:
|
|
ids = li["data"] if li.get("arrayMode", 0) == 0 else flat(li["data2D"])
|
|
fl = li.get("tileFlags") or (flat(li["tileFlags2D"]) if "tileFlags2D" in li else [0] * len(ids))
|
|
d["tileset"] = li.get("tileset", "")
|
|
d["nonEmpty"] = sum(1 for i in ids if i >= 0)
|
|
d["idSum"] = sum((i + 1) * (k % 7 + 1) for k, i in enumerate(ids))
|
|
d["flagSum"] = sum(f * (k % 5 + 1) for k, f in enumerate(fl))
|
|
out.append(d)
|
|
return {"width": lv["width"], "height": lv["height"], "values": ",".join("%s=%s" % (k, json.dumps(v)) for k, v in sorted(lv.get("values", {}).items())), "layers": out}
|
|
|
|
|
|
def generate(ctx):
|
|
rng = ctx.rng(11)
|
|
src = os.path.join(ctx.root, "tests", "fixtures", "ogmo")
|
|
rpg_proj = open(os.path.join(src, "turnBasedRPG.ogmo"), "rb").read()
|
|
rpg_lvl = open(os.path.join(src, "room-001.json"), "rb").read()
|
|
proj = project()
|
|
proj_bytes = json.dumps(proj, indent=2).encode()
|
|
cases = [{"name": "turnBasedRPG/room-001", "data": rpg_lvl, "project": rpg_proj, "stats": stats(json.loads(rpg_lvl), json.loads(rpg_proj))}]
|
|
for i, (w, h) in enumerate([(64, 48), (128, 32)]):
|
|
lv = level(rng, w, h)
|
|
cases.append({"name": "made/level%d" % i, "data": json.dumps(lv).encode(), "project": proj_bytes, "stats": stats(lv, proj)})
|
|
projects = [{"name": "turnBasedRPG.ogmo", "data": rpg_proj}, {"name": "made.ogmo", "data": proj_bytes}]
|
|
ctx.emit("ogmo", {"cases": cases, "projects": projects})
|
|
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
|
M = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(M)
|
|
ours = []
|
|
out = M.luau_encode(ctx, "tools/fixtures/_ogmo_encode.luau")
|
|
for c in cases:
|
|
lv, pj = out.get(c["name"] + ".json"), out.get(c["name"] + ".ogmo")
|
|
if lv and pj:
|
|
ours.append({"name": c["name"], "stats": stats(json.loads(lv), json.loads(pj))})
|
|
ctx.emit("ogmo_ours", ours)
|